context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * 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> /// ApplyLibraryItemResponse /// </summary> [DataContract] public partial class ApplyLibraryItemResponse : IEquatable<ApplyLibraryItemResponse>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ApplyLibraryItemResponse" /> class. /// </summary> /// <param name="attributes">Attributes from the library item.</param> /// <param name="cjson">Cjson from library item, only populated if this library item was a cjson snippet or marketing email (not transactional).</param> /// <param name="contentType">flow, campaign, cjson, upsell, postcard, transactional_email or email.</param> /// <param name="emailTemplateVmPath">If a marketing email was applied, this is the path to the template encapsulating the cjson. This is needed for the UltraCart UI..</param> /// <param name="error">error.</param> /// <param name="metadata">metadata.</param> /// <param name="storefrontOid">StoreFront oid where content originates necessary for tracking down relative assets.</param> /// <param name="success">Indicates if API call was successful.</param> /// <param name="title">title of library item, usually the name of the flow or campaign, or description of cjson.</param> /// <param name="uuid">UUID of marketing email or communication flow/campaign if this library item was an email, campaign or flow.</param> /// <param name="warning">warning.</param> public ApplyLibraryItemResponse(List<LibraryItemAttribute> attributes = default(List<LibraryItemAttribute>), string cjson = default(string), string contentType = default(string), string emailTemplateVmPath = default(string), Error error = default(Error), ResponseMetadata metadata = default(ResponseMetadata), int? storefrontOid = default(int?), bool? success = default(bool?), string title = default(string), string uuid = default(string), Warning warning = default(Warning)) { this.Attributes = attributes; this.Cjson = cjson; this.ContentType = contentType; this.EmailTemplateVmPath = emailTemplateVmPath; this.Error = error; this.Metadata = metadata; this.StorefrontOid = storefrontOid; this.Success = success; this.Title = title; this.Uuid = uuid; this.Warning = warning; } /// <summary> /// Attributes from the library item /// </summary> /// <value>Attributes from the library item</value> [DataMember(Name="attributes", EmitDefaultValue=false)] public List<LibraryItemAttribute> Attributes { get; set; } /// <summary> /// Cjson from library item, only populated if this library item was a cjson snippet or marketing email (not transactional) /// </summary> /// <value>Cjson from library item, only populated if this library item was a cjson snippet or marketing email (not transactional)</value> [DataMember(Name="cjson", EmitDefaultValue=false)] public string Cjson { get; set; } /// <summary> /// flow, campaign, cjson, upsell, postcard, transactional_email or email /// </summary> /// <value>flow, campaign, cjson, upsell, postcard, transactional_email or email</value> [DataMember(Name="content_type", EmitDefaultValue=false)] public string ContentType { get; set; } /// <summary> /// If a marketing email was applied, this is the path to the template encapsulating the cjson. This is needed for the UltraCart UI. /// </summary> /// <value>If a marketing email was applied, this is the path to the template encapsulating the cjson. This is needed for the UltraCart UI.</value> [DataMember(Name="email_template_vm_path", EmitDefaultValue=false)] public string EmailTemplateVmPath { get; set; } /// <summary> /// Gets or Sets Error /// </summary> [DataMember(Name="error", EmitDefaultValue=false)] public Error Error { get; set; } /// <summary> /// Gets or Sets Metadata /// </summary> [DataMember(Name="metadata", EmitDefaultValue=false)] public ResponseMetadata Metadata { get; set; } /// <summary> /// StoreFront oid where content originates necessary for tracking down relative assets /// </summary> /// <value>StoreFront oid where content originates necessary for tracking down relative assets</value> [DataMember(Name="storefront_oid", EmitDefaultValue=false)] public int? StorefrontOid { get; set; } /// <summary> /// Indicates if API call was successful /// </summary> /// <value>Indicates if API call was successful</value> [DataMember(Name="success", EmitDefaultValue=false)] public bool? Success { get; set; } /// <summary> /// title of library item, usually the name of the flow or campaign, or description of cjson /// </summary> /// <value>title of library item, usually the name of the flow or campaign, or description of cjson</value> [DataMember(Name="title", EmitDefaultValue=false)] public string Title { get; set; } /// <summary> /// UUID of marketing email or communication flow/campaign if this library item was an email, campaign or flow /// </summary> /// <value>UUID of marketing email or communication flow/campaign if this library item was an email, campaign or flow</value> [DataMember(Name="uuid", EmitDefaultValue=false)] public string Uuid { get; set; } /// <summary> /// Gets or Sets Warning /// </summary> [DataMember(Name="warning", EmitDefaultValue=false)] public Warning Warning { 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 ApplyLibraryItemResponse {\n"); sb.Append(" Attributes: ").Append(Attributes).Append("\n"); sb.Append(" Cjson: ").Append(Cjson).Append("\n"); sb.Append(" ContentType: ").Append(ContentType).Append("\n"); sb.Append(" EmailTemplateVmPath: ").Append(EmailTemplateVmPath).Append("\n"); sb.Append(" Error: ").Append(Error).Append("\n"); sb.Append(" Metadata: ").Append(Metadata).Append("\n"); sb.Append(" StorefrontOid: ").Append(StorefrontOid).Append("\n"); sb.Append(" Success: ").Append(Success).Append("\n"); sb.Append(" Title: ").Append(Title).Append("\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Warning: ").Append(Warning).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 ApplyLibraryItemResponse); } /// <summary> /// Returns true if ApplyLibraryItemResponse instances are equal /// </summary> /// <param name="input">Instance of ApplyLibraryItemResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(ApplyLibraryItemResponse input) { if (input == null) return false; return ( this.Attributes == input.Attributes || this.Attributes != null && this.Attributes.SequenceEqual(input.Attributes) ) && ( this.Cjson == input.Cjson || (this.Cjson != null && this.Cjson.Equals(input.Cjson)) ) && ( this.ContentType == input.ContentType || (this.ContentType != null && this.ContentType.Equals(input.ContentType)) ) && ( this.EmailTemplateVmPath == input.EmailTemplateVmPath || (this.EmailTemplateVmPath != null && this.EmailTemplateVmPath.Equals(input.EmailTemplateVmPath)) ) && ( this.Error == input.Error || (this.Error != null && this.Error.Equals(input.Error)) ) && ( this.Metadata == input.Metadata || (this.Metadata != null && this.Metadata.Equals(input.Metadata)) ) && ( this.StorefrontOid == input.StorefrontOid || (this.StorefrontOid != null && this.StorefrontOid.Equals(input.StorefrontOid)) ) && ( this.Success == input.Success || (this.Success != null && this.Success.Equals(input.Success)) ) && ( this.Title == input.Title || (this.Title != null && this.Title.Equals(input.Title)) ) && ( this.Uuid == input.Uuid || (this.Uuid != null && this.Uuid.Equals(input.Uuid)) ) && ( this.Warning == input.Warning || (this.Warning != null && this.Warning.Equals(input.Warning)) ); } /// <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.Attributes != null) hashCode = hashCode * 59 + this.Attributes.GetHashCode(); if (this.Cjson != null) hashCode = hashCode * 59 + this.Cjson.GetHashCode(); if (this.ContentType != null) hashCode = hashCode * 59 + this.ContentType.GetHashCode(); if (this.EmailTemplateVmPath != null) hashCode = hashCode * 59 + this.EmailTemplateVmPath.GetHashCode(); if (this.Error != null) hashCode = hashCode * 59 + this.Error.GetHashCode(); if (this.Metadata != null) hashCode = hashCode * 59 + this.Metadata.GetHashCode(); if (this.StorefrontOid != null) hashCode = hashCode * 59 + this.StorefrontOid.GetHashCode(); if (this.Success != null) hashCode = hashCode * 59 + this.Success.GetHashCode(); if (this.Title != null) hashCode = hashCode * 59 + this.Title.GetHashCode(); if (this.Uuid != null) hashCode = hashCode * 59 + this.Uuid.GetHashCode(); if (this.Warning != null) hashCode = hashCode * 59 + this.Warning.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) { yield break; } } }
// Copyright (c) 2014 Christian Crowhurst. All rights reserved. // see LICENSE using System; using System.Threading.Tasks; using NUnit.Framework; // ReSharper disable ExpressionIsAlwaysNull namespace CcAcca.CacheAbstraction.Test { /// <summary> /// Defines and asserts the detailed behaviour / contract that a <see cref="ICache"/> implementation is /// expected to implement /// </summary> /// <remarks> /// When writing a new <see cref="ICache"/> implementation, you should create a test class that inherits from /// this class. Doing so ensures that your <see cref="ICache"/> implementation is checked for compliance to /// the <see cref="ICache"/> contract /// </remarks> public abstract class CacheExamplesBase { #region Member Variables private ICache _cache; #endregion #region Properties public ICache Cache { get { return _cache; } } #endregion #region Setup / Teardown [SetUp] public void TestInitialise() { _cache = CreateCache(); } [TearDown] public void TestCleanup() { if (_cache != null) { _cache.Flush(); } _cache = null; } #endregion [Test] public void AddOrUpdate_Should_Add() { Cache.AddOrUpdate("key", 5); Assert.That(Cache.GetData<int>("key"), Is.EqualTo(5)); Assert.That(Cache.Contains("key"), Is.True); } [Test] public void AddOrUpdate_ShouldUpdateExistingItem() { Cache.AddOrUpdate("key", 5); Cache.AddOrUpdate("key", 6); Assert.That(Cache.GetData<int>("key"), Is.EqualTo(6)); } [Test] public void AddOrUpdate_UpdateShouldThrowWhenNullValueSupplied() { Cache.AddOrUpdate("key", 5); Assert.Throws<ArgumentNullException>(() => { Cache.AddOrUpdate<object>("key", null); }); } [Test] public void AddOrUpdate_AddShouldThrowWhenNullSupplied() { Assert.Throws<ArgumentNullException>(() => { Cache.AddOrUpdate<object>("whatever", null); }); } [Test] public void AddOrUpdateFactory_UpdateShouldThrowWhenNullValueSupplied() { // given Cache.AddOrUpdate("key", 5); // when, then Assert.Throws<ArgumentNullException>(() => { this.Cache.AddOrUpdate<int?>("key", 5, (k, v) => null); }); } [Test] public void AddOrUpdateFactory_AddShouldThrowWhenNullSupplied() { int? value = null; Assert.Throws<ArgumentNullException>(() => { Cache.AddOrUpdate("whatever", value, (k, v) => 5); }); } [Test] public void AddOrUpdateFactory_Should_Add() { Cache.AddOrUpdate("key", 5, (k, existingValue) => existingValue + 1); Assert.That(Cache.GetData<int>("key"), Is.EqualTo(5)); Assert.That(Cache.Contains("key"), Is.True); } [Test] public void AddOrUpdateFactory_ShouldUpdateExistingItem() { Cache.AddOrUpdate("key", 5); Cache.AddOrUpdate("key", 5, (key, existingValue) => existingValue + 1); Assert.That(Cache.GetData<int>("key"), Is.EqualTo(6)); } protected abstract ICache CreateCache(); [Test] public void GetCacheItem_ShouldReturnNullIfItemMissing() { Assert.That(Cache.GetCacheItem<int>("missingkey"), Is.Null); } [Test] public void GetData_ShouldReturnDefaultValueIfItemMissing() { Assert.That(Cache.GetData<object>("missingkey"), Is.Null); } [Test] public void GetData_ShouldReturnDefaultValueIfItemMissing_NullableInt() { Assert.That(Cache.GetData<int?>("missingkey"), Is.Null); } [Test] public void GetData_ShouldReturnDefaultValueIfItemMissing_Int() { Assert.That(Cache.GetData<int>("missingkey"), Is.EqualTo(0)); } [Test] public void GetOrAdd_ShouldThrowWhenNullAdded() { Assert.Throws<ArgumentNullException>(() => { Cache.GetOrAdd<object>("whatever", _ => null); }); } [Test] public void GetOrAdd_ShouldReturnExistingCachedItem() { //given var v1 = new TestValue(); var v2 = new TestValue(); Cache.GetOrAdd("someKey", _ => v1); //when var itemFromCache = Cache.GetOrAdd("someKey", _ => v2); //then Assert.That(itemFromCache, Is.EqualTo(v1), "previously cached item not returned"); } [Test] public void GetOrAdd_WhereItemAlreadyExistsInCache_ShouldNotExecuteConstructorDelegate() { //given Cache.GetOrAdd("someKey", _ => new object()); //when bool constructorExecuted = false; Func<string, object> constructor = delegate { constructorExecuted = true; return new object(); }; Cache.GetOrAdd("someKey", constructor); //then Assert.That(constructorExecuted, Is.False); } [Test] public void GetOrAdd_WhereItemNotAlreadyCached_ShouldAddItemToCache() { var v1 = new TestValue(); var cachedItem = Cache.GetOrAdd("someKey", _ => v1); //then Assert.That(cachedItem, Is.EqualTo(v1)); } [Test] public async Task GetOrAdd_WhereItemNotAlreadyCached_UnderRaceCondition_ShouldReturnFirstValueAdded() { Task<int> t1 = Task.Run(async () => { await Task.Delay(TimeSpan.FromMilliseconds(100)); return Cache.GetOrAdd("Key", _ => 1); }); Task<int> t2 = Task.Run(async () => { await Task.Delay(TimeSpan.FromMilliseconds(5)); return Cache.GetOrAdd("Key", _ => 2); }); Task<int[]> ts = Task.WhenAll(t1, t2); Assert.That(await ts, Is.EqualTo(new[] {2, 2})); } [Test] public void Remove_ShouldSilentlyIgnoreMissingItem() { Assert.DoesNotThrow(() => Cache.Remove("missingkey")); } [Test] public void WhenItemExpiresFromCache_GetOrAdd_WillAddNewItemToCache() { //given var v1 = new TestValue(); var v2 = new TestValue(); var v3 = new TestValue(); Cache.GetOrAdd("someKey", _ => v1); Cache.Flush(); //simulate item expiring from the cache //when, then Assert.That(Cache.GetOrAdd("someKey", _ => v2), Is.EqualTo(v2), "expired item was not replaced"); Assert.That(Cache.GetOrAdd("someKey", _ => v3), Is.EqualTo(v2), "v2 still expected"); } [Serializable] public class TestValue : IEquatable<TestValue> { private readonly Guid _id = Guid.NewGuid(); public bool Equals(TestValue other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return _id.Equals(other._id); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((TestValue)obj); } public override int GetHashCode() { return _id.GetHashCode(); } } } }
#region License /* * WebSocketFrame.cs * * The MIT License * * Copyright (c) 2012-2019 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contributors /* * Contributors: * - Chris Swiedler */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace WebSocketSharp { internal class WebSocketFrame : IEnumerable<byte> { #region Private Fields private byte[] _extPayloadLength; private Fin _fin; private Mask _mask; private byte[] _maskingKey; private Opcode _opcode; private PayloadData _payloadData; private byte _payloadLength; private Rsv _rsv1; private Rsv _rsv2; private Rsv _rsv3; #endregion #region Internal Fields /// <summary> /// Represents the ping frame without the payload data as an array of /// <see cref="byte"/>. /// </summary> /// <remarks> /// The value of this field is created from a non masked ping frame, /// so it can only be used to send a ping from the server. /// </remarks> internal static readonly byte[] EmptyPingBytes; #endregion #region Static Constructor static WebSocketFrame () { EmptyPingBytes = CreatePingFrame (false).ToArray (); } #endregion #region Private Constructors private WebSocketFrame () { } #endregion #region Internal Constructors internal WebSocketFrame (Opcode opcode, PayloadData payloadData, bool mask) : this (Fin.Final, opcode, payloadData, false, mask) { } internal WebSocketFrame ( Fin fin, Opcode opcode, byte[] data, bool compressed, bool mask ) : this (fin, opcode, new PayloadData (data), compressed, mask) { } internal WebSocketFrame ( Fin fin, Opcode opcode, PayloadData payloadData, bool compressed, bool mask ) { _fin = fin; _opcode = opcode; _rsv1 = opcode.IsData () && compressed ? Rsv.On : Rsv.Off; _rsv2 = Rsv.Off; _rsv3 = Rsv.Off; var len = payloadData.Length; if (len < 126) { _payloadLength = (byte) len; _extPayloadLength = WebSocket.EmptyBytes; } else if (len < 0x010000) { _payloadLength = (byte) 126; _extPayloadLength = ((ushort) len).InternalToByteArray (ByteOrder.Big); } else { _payloadLength = (byte) 127; _extPayloadLength = len.InternalToByteArray (ByteOrder.Big); } if (mask) { _mask = Mask.On; _maskingKey = createMaskingKey (); payloadData.Mask (_maskingKey); } else { _mask = Mask.Off; _maskingKey = WebSocket.EmptyBytes; } _payloadData = payloadData; } #endregion #region Internal Properties internal ulong ExactPayloadLength { get { return _payloadLength < 126 ? _payloadLength : _payloadLength == 126 ? _extPayloadLength.ToUInt16 (ByteOrder.Big) : _extPayloadLength.ToUInt64 (ByteOrder.Big); } } internal int ExtendedPayloadLengthWidth { get { return _payloadLength < 126 ? 0 : _payloadLength == 126 ? 2 : 8; } } #endregion #region Public Properties public byte[] ExtendedPayloadLength { get { return _extPayloadLength; } } public Fin Fin { get { return _fin; } } public bool IsBinary { get { return _opcode == Opcode.Binary; } } public bool IsClose { get { return _opcode == Opcode.Close; } } public bool IsCompressed { get { return _rsv1 == Rsv.On; } } public bool IsContinuation { get { return _opcode == Opcode.Cont; } } public bool IsControl { get { return _opcode >= Opcode.Close; } } public bool IsData { get { return _opcode == Opcode.Text || _opcode == Opcode.Binary; } } public bool IsFinal { get { return _fin == Fin.Final; } } public bool IsFragment { get { return _fin == Fin.More || _opcode == Opcode.Cont; } } public bool IsMasked { get { return _mask == Mask.On; } } public bool IsPing { get { return _opcode == Opcode.Ping; } } public bool IsPong { get { return _opcode == Opcode.Pong; } } public bool IsText { get { return _opcode == Opcode.Text; } } public ulong Length { get { return 2 + (ulong) (_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length; } } public Mask Mask { get { return _mask; } } public byte[] MaskingKey { get { return _maskingKey; } } public Opcode Opcode { get { return _opcode; } } public PayloadData PayloadData { get { return _payloadData; } } public byte PayloadLength { get { return _payloadLength; } } public Rsv Rsv1 { get { return _rsv1; } } public Rsv Rsv2 { get { return _rsv2; } } public Rsv Rsv3 { get { return _rsv3; } } #endregion #region Private Methods private static byte[] createMaskingKey () { var key = new byte[4]; WebSocket.RandomNumber.GetBytes (key); return key; } private static string dump (WebSocketFrame frame) { var len = frame.Length; var cnt = (long) (len / 4); var rem = (int) (len % 4); int cntDigit; string cntFmt; if (cnt < 10000) { cntDigit = 4; cntFmt = "{0,4}"; } else if (cnt < 0x010000) { cntDigit = 4; cntFmt = "{0,4:X}"; } else if (cnt < 0x0100000000) { cntDigit = 8; cntFmt = "{0,8:X}"; } else { cntDigit = 16; cntFmt = "{0,16:X}"; } var spFmt = String.Format ("{{0,{0}}}", cntDigit); var headerFmt = String.Format ( @" {0} 01234567 89ABCDEF 01234567 89ABCDEF {0}+--------+--------+--------+--------+\n", spFmt ); var lineFmt = String.Format ( "{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", cntFmt ); var footerFmt = String.Format ( "{0}+--------+--------+--------+--------+", spFmt ); var buff = new StringBuilder (64); Func<Action<string, string, string, string>> linePrinter = () => { long lineCnt = 0; return (arg1, arg2, arg3, arg4) => { buff.AppendFormat ( lineFmt, ++lineCnt, arg1, arg2, arg3, arg4 ); }; }; var printLine = linePrinter (); var bytes = frame.ToArray (); buff.AppendFormat (headerFmt, String.Empty); for (long i = 0; i <= cnt; i++) { var j = i * 4; if (i < cnt) { printLine ( Convert.ToString (bytes[j], 2).PadLeft (8, '0'), Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0'), Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0'), Convert.ToString (bytes[j + 3], 2).PadLeft (8, '0') ); continue; } if (rem > 0) { printLine ( Convert.ToString (bytes[j], 2).PadLeft (8, '0'), rem >= 2 ? Convert.ToString (bytes[j + 1], 2).PadLeft (8, '0') : String.Empty, rem == 3 ? Convert.ToString (bytes[j + 2], 2).PadLeft (8, '0') : String.Empty, String.Empty ); } } buff.AppendFormat (footerFmt, String.Empty); return buff.ToString (); } private static string print (WebSocketFrame frame) { // Payload Length var payloadLen = frame._payloadLength; // Extended Payload Length var extPayloadLen = payloadLen > 125 ? frame.ExactPayloadLength.ToString () : String.Empty; // Masking Key var maskingKey = BitConverter.ToString (frame._maskingKey); // Payload Data var payload = payloadLen == 0 ? String.Empty : payloadLen > 125 ? "---" : !frame.IsText || frame.IsFragment || frame.IsMasked || frame.IsCompressed ? frame._payloadData.ToString () : utf8Decode (frame._payloadData.ApplicationData); var fmt = @" FIN: {0} RSV1: {1} RSV2: {2} RSV3: {3} Opcode: {4} MASK: {5} Payload Length: {6} Extended Payload Length: {7} Masking Key: {8} Payload Data: {9}"; return String.Format ( fmt, frame._fin, frame._rsv1, frame._rsv2, frame._rsv3, frame._opcode, frame._mask, payloadLen, extPayloadLen, maskingKey, payload ); } private static WebSocketFrame processHeader (byte[] header) { if (header.Length != 2) { var msg = "The header part of a frame could not be read."; throw new WebSocketException (msg); } // FIN var fin = (header[0] & 0x80) == 0x80 ? Fin.Final : Fin.More; // RSV1 var rsv1 = (header[0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off; // RSV2 var rsv2 = (header[0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off; // RSV3 var rsv3 = (header[0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off; // Opcode var opcode = (byte) (header[0] & 0x0f); // MASK var mask = (header[1] & 0x80) == 0x80 ? Mask.On : Mask.Off; // Payload Length var payloadLen = (byte) (header[1] & 0x7f); if (!opcode.IsSupported ()) { var msg = "A frame has an unsupported opcode."; throw new WebSocketException (CloseStatusCode.ProtocolError, msg); } if (!opcode.IsData () && rsv1 == Rsv.On) { var msg = "A non data frame is compressed."; throw new WebSocketException (CloseStatusCode.ProtocolError, msg); } if (opcode.IsControl ()) { if (fin == Fin.More) { var msg = "A control frame is fragmented."; throw new WebSocketException (CloseStatusCode.ProtocolError, msg); } if (payloadLen > 125) { var msg = "A control frame has too long payload length."; throw new WebSocketException (CloseStatusCode.ProtocolError, msg); } } var frame = new WebSocketFrame (); frame._fin = fin; frame._rsv1 = rsv1; frame._rsv2 = rsv2; frame._rsv3 = rsv3; frame._opcode = (Opcode) opcode; frame._mask = mask; frame._payloadLength = payloadLen; return frame; } private static WebSocketFrame readExtendedPayloadLength ( Stream stream, WebSocketFrame frame ) { var len = frame.ExtendedPayloadLengthWidth; if (len == 0) { frame._extPayloadLength = WebSocket.EmptyBytes; return frame; } var bytes = stream.ReadBytes (len); if (bytes.Length != len) { var msg = "The extended payload length of a frame could not be read."; throw new WebSocketException (msg); } frame._extPayloadLength = bytes; return frame; } private static void readExtendedPayloadLengthAsync ( Stream stream, WebSocketFrame frame, Action<WebSocketFrame> completed, Action<Exception> error ) { var len = frame.ExtendedPayloadLengthWidth; if (len == 0) { frame._extPayloadLength = WebSocket.EmptyBytes; completed (frame); return; } stream.ReadBytesAsync ( len, bytes => { if (bytes.Length != len) { var msg = "The extended payload length of a frame could not be read."; throw new WebSocketException (msg); } frame._extPayloadLength = bytes; completed (frame); }, error ); } private static WebSocketFrame readHeader (Stream stream) { return processHeader (stream.ReadBytes (2)); } private static void readHeaderAsync ( Stream stream, Action<WebSocketFrame> completed, Action<Exception> error ) { stream.ReadBytesAsync ( 2, bytes => completed (processHeader (bytes)), error ); } private static WebSocketFrame readMaskingKey ( Stream stream, WebSocketFrame frame ) { if (!frame.IsMasked) { frame._maskingKey = WebSocket.EmptyBytes; return frame; } var len = 4; var bytes = stream.ReadBytes (len); if (bytes.Length != len) { var msg = "The masking key of a frame could not be read."; throw new WebSocketException (msg); } frame._maskingKey = bytes; return frame; } private static void readMaskingKeyAsync ( Stream stream, WebSocketFrame frame, Action<WebSocketFrame> completed, Action<Exception> error ) { if (!frame.IsMasked) { frame._maskingKey = WebSocket.EmptyBytes; completed (frame); return; } var len = 4; stream.ReadBytesAsync ( len, bytes => { if (bytes.Length != len) { var msg = "The masking key of a frame could not be read."; throw new WebSocketException (msg); } frame._maskingKey = bytes; completed (frame); }, error ); } private static WebSocketFrame readPayloadData ( Stream stream, WebSocketFrame frame ) { var exactLen = frame.ExactPayloadLength; if (exactLen > PayloadData.MaxLength) { var msg = "A frame has too long payload length."; throw new WebSocketException (CloseStatusCode.TooBig, msg); } if (exactLen == 0) { frame._payloadData = PayloadData.Empty; return frame; } var len = (long) exactLen; var bytes = frame._payloadLength < 127 ? stream.ReadBytes ((int) exactLen) : stream.ReadBytes (len, 1024); if (bytes.LongLength != len) { var msg = "The payload data of a frame could not be read."; throw new WebSocketException (msg); } frame._payloadData = new PayloadData (bytes, len); return frame; } private static void readPayloadDataAsync ( Stream stream, WebSocketFrame frame, Action<WebSocketFrame> completed, Action<Exception> error ) { var exactLen = frame.ExactPayloadLength; if (exactLen > PayloadData.MaxLength) { var msg = "A frame has too long payload length."; throw new WebSocketException (CloseStatusCode.TooBig, msg); } if (exactLen == 0) { frame._payloadData = PayloadData.Empty; completed (frame); return; } var len = (long) exactLen; Action<byte[]> comp = bytes => { if (bytes.LongLength != len) { var msg = "The payload data of a frame could not be read."; throw new WebSocketException (msg); } frame._payloadData = new PayloadData (bytes, len); completed (frame); }; if (frame._payloadLength < 127) { stream.ReadBytesAsync ((int) exactLen, comp, error); return; } stream.ReadBytesAsync (len, 1024, comp, error); } private static string utf8Decode (byte[] bytes) { try { return Encoding.UTF8.GetString (bytes); } catch { return null; } } #endregion #region Internal Methods internal static WebSocketFrame CreateCloseFrame ( PayloadData payloadData, bool mask ) { return new WebSocketFrame ( Fin.Final, Opcode.Close, payloadData, false, mask ); } internal static WebSocketFrame CreatePingFrame (bool mask) { return new WebSocketFrame ( Fin.Final, Opcode.Ping, PayloadData.Empty, false, mask ); } internal static WebSocketFrame CreatePingFrame (byte[] data, bool mask) { return new WebSocketFrame ( Fin.Final, Opcode.Ping, new PayloadData (data), false, mask ); } internal static WebSocketFrame CreatePongFrame ( PayloadData payloadData, bool mask ) { return new WebSocketFrame ( Fin.Final, Opcode.Pong, payloadData, false, mask ); } internal static WebSocketFrame ReadFrame (Stream stream, bool unmask) { var frame = readHeader (stream); readExtendedPayloadLength (stream, frame); readMaskingKey (stream, frame); readPayloadData (stream, frame); if (unmask) frame.Unmask (); return frame; } internal static void ReadFrameAsync ( Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error ) { readHeaderAsync ( stream, frame => readExtendedPayloadLengthAsync ( stream, frame, frame1 => readMaskingKeyAsync ( stream, frame1, frame2 => readPayloadDataAsync ( stream, frame2, frame3 => { if (unmask) frame3.Unmask (); completed (frame3); }, error ), error ), error ), error ); } internal void Unmask () { if (_mask == Mask.Off) return; _mask = Mask.Off; _payloadData.Mask (_maskingKey); _maskingKey = WebSocket.EmptyBytes; } #endregion #region Public Methods public IEnumerator<byte> GetEnumerator () { foreach (var b in ToArray ()) yield return b; } public void Print (bool dumped) { Console.WriteLine (dumped ? dump (this) : print (this)); } public string PrintToString (bool dumped) { return dumped ? dump (this) : print (this); } public byte[] ToArray () { using (var buff = new MemoryStream ()) { var header = (int) _fin; header = (header << 1) + (int) _rsv1; header = (header << 1) + (int) _rsv2; header = (header << 1) + (int) _rsv3; header = (header << 4) + (int) _opcode; header = (header << 1) + (int) _mask; header = (header << 7) + (int) _payloadLength; buff.Write ( ((ushort) header).InternalToByteArray (ByteOrder.Big), 0, 2 ); if (_payloadLength > 125) buff.Write (_extPayloadLength, 0, _payloadLength == 126 ? 2 : 8); if (_mask == Mask.On) buff.Write (_maskingKey, 0, 4); if (_payloadLength > 0) { var bytes = _payloadData.ToArray (); if (_payloadLength < 127) buff.Write (bytes, 0, bytes.Length); else buff.WriteBytes (bytes, 1024); } buff.Close (); return buff.ToArray (); } } public override string ToString () { return BitConverter.ToString (ToArray ()); } #endregion #region Explicit Interface Implementations IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } #endregion } }
namespace KabMan.Client { partial class VTPort { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar1 = new DevExpress.XtraBars.Bar(); this.barButtonItem1 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem2 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem3 = new DevExpress.XtraBars.BarButtonItem(); this.barButtonItem4 = new DevExpress.XtraBars.BarButtonItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.gridControl1 = new DevExpress.XtraGrid.GridControl(); this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.ServerId = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.Room = new DevExpress.XtraGrid.Columns.GridColumn(); this.Coordinate = new DevExpress.XtraGrid.Columns.GridColumn(); this.OPSys = new DevExpress.XtraGrid.Columns.GridColumn(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); this.SuspendLayout(); // // barManager1 // this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar1}); this.barManager1.DockControls.Add(this.barDockControlTop); this.barManager1.DockControls.Add(this.barDockControlBottom); this.barManager1.DockControls.Add(this.barDockControlLeft); this.barManager1.DockControls.Add(this.barDockControlRight); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.barButtonItem1, this.barButtonItem2, this.barButtonItem3, this.barButtonItem4}); this.barManager1.MaxItemId = 4; // // bar1 // this.bar1.Appearance.BackColor = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BackColor2 = System.Drawing.Color.WhiteSmoke; this.bar1.Appearance.BorderColor = System.Drawing.Color.Gainsboro; this.bar1.Appearance.Options.UseBackColor = true; this.bar1.Appearance.Options.UseBorderColor = true; this.bar1.BarName = "Tools"; this.bar1.DockCol = 0; this.bar1.DockRow = 0; this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem1), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem2), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem3), new DevExpress.XtraBars.LinkPersistInfo(this.barButtonItem4)}); this.bar1.OptionsBar.AllowQuickCustomization = false; this.bar1.OptionsBar.DrawDragBorder = false; this.bar1.OptionsBar.UseWholeRow = true; this.bar1.Text = "Tools"; // // barButtonItem1 // this.barButtonItem1.Caption = "Add"; this.barButtonItem1.Glyph = global::KabMan.Client.Properties.Resources.neu; this.barButtonItem1.Id = 0; this.barButtonItem1.Name = "barButtonItem1"; this.barButtonItem1.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem1_ItemClick); // // barButtonItem2 // this.barButtonItem2.Caption = "Detail"; this.barButtonItem2.Glyph = global::KabMan.Client.Properties.Resources.detail; this.barButtonItem2.Id = 1; this.barButtonItem2.Name = "barButtonItem2"; this.barButtonItem2.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem2_ItemClick); // // barButtonItem3 // this.barButtonItem3.Caption = "Delete"; this.barButtonItem3.Glyph = global::KabMan.Client.Properties.Resources.loeschen; this.barButtonItem3.Id = 2; this.barButtonItem3.Name = "barButtonItem3"; this.barButtonItem3.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem3_ItemClick); // // barButtonItem4 // this.barButtonItem4.Caption = "Close"; this.barButtonItem4.Glyph = global::KabMan.Client.Properties.Resources.exit; this.barButtonItem4.Id = 3; this.barButtonItem4.Name = "barButtonItem4"; this.barButtonItem4.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.barButtonItem4_ItemClick); // // layoutControl1 // this.layoutControl1.Controls.Add(this.gridControl1); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 26); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(494, 325); this.layoutControl1.TabIndex = 4; this.layoutControl1.Text = "layoutControl1"; // // gridControl1 // this.gridControl1.EmbeddedNavigator.Name = ""; this.gridControl1.Location = new System.Drawing.Point(7, 7); this.gridControl1.MainView = this.gridView1; this.gridControl1.Name = "gridControl1"; this.gridControl1.Size = new System.Drawing.Size(481, 312); this.gridControl1.TabIndex = 7; this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.gridView1}); this.gridControl1.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.gridControl1_MouseDoubleClick); // // gridView1 // this.gridView1.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.gridView1.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.gridView1.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.gridView1.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.gridView1.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.Empty.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.gridView1.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.gridView1.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.EvenRow.Options.UseBackColor = true; this.gridView1.Appearance.EvenRow.Options.UseForeColor = true; this.gridView1.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterCloseButton.Options.UseBackColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.gridView1.Appearance.FilterCloseButton.Options.UseForeColor = true; this.gridView1.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.gridView1.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.gridView1.Appearance.FilterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FilterPanel.Options.UseForeColor = true; this.gridView1.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.gridView1.Appearance.FixedLine.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.gridView1.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FocusedCell.Options.UseBackColor = true; this.gridView1.Appearance.FocusedCell.Options.UseForeColor = true; this.gridView1.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.gridView1.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.gridView1.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.FocusedRow.Options.UseBackColor = true; this.gridView1.Appearance.FocusedRow.Options.UseForeColor = true; this.gridView1.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.FooterPanel.Options.UseBackColor = true; this.gridView1.Appearance.FooterPanel.Options.UseBorderColor = true; this.gridView1.Appearance.FooterPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupButton.Options.UseBackColor = true; this.gridView1.Appearance.GroupButton.Options.UseBorderColor = true; this.gridView1.Appearance.GroupButton.Options.UseForeColor = true; this.gridView1.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.gridView1.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.GroupFooter.Options.UseBackColor = true; this.gridView1.Appearance.GroupFooter.Options.UseBorderColor = true; this.gridView1.Appearance.GroupFooter.Options.UseForeColor = true; this.gridView1.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.gridView1.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.GroupPanel.Options.UseBackColor = true; this.gridView1.Appearance.GroupPanel.Options.UseFont = true; this.gridView1.Appearance.GroupPanel.Options.UseForeColor = true; this.gridView1.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.gridView1.Appearance.GroupRow.Options.UseBackColor = true; this.gridView1.Appearance.GroupRow.Options.UseForeColor = true; this.gridView1.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.gridView1.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.HeaderPanel.Options.UseBackColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseBorderColor = true; this.gridView1.Appearance.HeaderPanel.Options.UseFont = true; this.gridView1.Appearance.HeaderPanel.Options.UseForeColor = true; this.gridView1.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.gridView1.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.gridView1.Appearance.HideSelectionRow.Options.UseBackColor = true; this.gridView1.Appearance.HideSelectionRow.Options.UseForeColor = true; this.gridView1.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.HorzLine.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.gridView1.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.gridView1.Appearance.OddRow.Options.UseBackColor = true; this.gridView1.Appearance.OddRow.Options.UseForeColor = true; this.gridView1.Appearance.Preview.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.gridView1.Appearance.Preview.Options.UseBackColor = true; this.gridView1.Appearance.Preview.Options.UseForeColor = true; this.gridView1.Appearance.Row.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.gridView1.Appearance.Row.Options.UseBackColor = true; this.gridView1.Appearance.Row.Options.UseForeColor = true; this.gridView1.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.gridView1.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.gridView1.Appearance.RowSeparator.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.gridView1.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.gridView1.Appearance.SelectedRow.Options.UseBackColor = true; this.gridView1.Appearance.SelectedRow.Options.UseForeColor = true; this.gridView1.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.gridView1.Appearance.VertLine.Options.UseBackColor = true; this.gridView1.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.ServerId, this.gridColumn4, this.gridColumn1, this.Room, this.Coordinate, this.OPSys}); this.gridView1.GridControl = this.gridControl1; this.gridView1.Name = "gridView1"; this.gridView1.OptionsBehavior.AllowIncrementalSearch = true; this.gridView1.OptionsBehavior.Editable = false; this.gridView1.OptionsCustomization.AllowFilter = false; this.gridView1.OptionsMenu.EnableColumnMenu = false; this.gridView1.OptionsMenu.EnableFooterMenu = false; this.gridView1.OptionsMenu.EnableGroupPanelMenu = false; this.gridView1.OptionsView.EnableAppearanceEvenRow = true; this.gridView1.OptionsView.EnableAppearanceOddRow = true; this.gridView1.OptionsView.ShowAutoFilterRow = true; this.gridView1.OptionsView.ShowGroupPanel = false; this.gridView1.OptionsView.ShowIndicator = false; // // ServerId // this.ServerId.Caption = "Id"; this.ServerId.FieldName = "Id"; this.ServerId.Name = "ServerId"; // // gridColumn4 // this.gridColumn4.Caption = "VT Port Name"; this.gridColumn4.FieldName = "Name"; this.gridColumn4.Name = "gridColumn4"; this.gridColumn4.Visible = true; this.gridColumn4.VisibleIndex = 0; // // gridColumn1 // this.gridColumn1.Caption = "Location"; this.gridColumn1.FieldName = "Location"; this.gridColumn1.Name = "gridColumn1"; this.gridColumn1.Visible = true; this.gridColumn1.VisibleIndex = 1; // // Room // this.Room.Caption = "Data Center"; this.Room.FieldName = "Room"; this.Room.Name = "Room"; this.Room.Visible = true; this.Room.VisibleIndex = 2; this.Room.Width = 108; // // Coordinate // this.Coordinate.Caption = "San"; this.Coordinate.FieldName = "San"; this.Coordinate.Name = "Coordinate"; this.Coordinate.Visible = true; this.Coordinate.VisibleIndex = 3; this.Coordinate.Width = 108; // // OPSys // this.OPSys.Caption = "Visible"; this.OPSys.FieldName = "Visible"; this.OPSys.Name = "OPSys"; this.OPSys.Visible = true; this.OPSys.VisibleIndex = 4; this.OPSys.Width = 84; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(494, 325); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.gridControl1; this.layoutControlItem1.CustomizationFormText = "layoutControlItem1"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(492, 323); this.layoutControlItem1.Text = "layoutControlItem1"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // VTPort // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(494, 351); this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Name = "VTPort"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "VTPort"; this.Load += new System.EventHandler(this.VTPort_Load); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar1; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.BarButtonItem barButtonItem1; private DevExpress.XtraBars.BarButtonItem barButtonItem2; private DevExpress.XtraBars.BarButtonItem barButtonItem3; private DevExpress.XtraBars.BarButtonItem barButtonItem4; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraGrid.GridControl gridControl1; private DevExpress.XtraGrid.Views.Grid.GridView gridView1; private DevExpress.XtraGrid.Columns.GridColumn ServerId; private DevExpress.XtraGrid.Columns.GridColumn gridColumn4; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn Room; private DevExpress.XtraGrid.Columns.GridColumn Coordinate; private DevExpress.XtraGrid.Columns.GridColumn OPSys; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Linq; using UnityEditor; namespace PrefabEvolution { [InitializeOnLoad] static internal class PEUtils { static PEUtils() { EditorUtility.ClearProgressBar();// EditorApplication.hierarchyWindowItemOnGUI += OnItemGUI; } #region ReplaceReference static internal void ReplaceReference(Object root, Object from, Object to) { ReplaceReference(EditorUtility.CollectDeepHierarchy(new [] { root }), from, to); } static internal void ReplaceReference(Object[] roots, Object from, Object to) { var dict = new Dictionary<Object, Object>(); dict.Add(from, to); ReplaceReference(roots, dict); } static internal void ReplaceReference(Object root, IDictionary<Object, Object> dict) { ReplaceReference(EditorUtility.CollectDeepHierarchy(new [] { root }), dict); } static internal void ReplaceReference(Object[] roots, IDictionary<Object, Object> dict) { foreach (var obj in roots) { if (obj == null) continue; var so = new SerializedObject(obj); var property = so.GetIterator(); while (property.Next(true)) { if (property.propertyType != SerializedPropertyType.ObjectReference) continue; if (PropertyFilter(property)) continue; if (property.objectReferenceValue == null) continue; Object result; if (!dict.TryGetValue(property.objectReferenceValue, out result)) continue; property.objectReferenceValue = result; property.serializedObject.ApplyModifiedProperties(); } } } #endregion #region etc static public void Foreach<T>(this IEnumerable<T> targets, System.Action<T> action) { foreach (var t in targets) { action(t); } } static internal void SetParentAndSaveLocalTransform(Transform child, Transform parent) { var lp = child.localPosition; var lr = child.localRotation; var ls = child.localScale; #if UNITY_4_6 || UNITY_5_0 || UNITY_5 Vector2 sizeDelta = Vector2.zero; var rectTransform = child as RectTransform; if (rectTransform) sizeDelta = rectTransform.sizeDelta; child.parent = parent; if (rectTransform) rectTransform.sizeDelta = sizeDelta; #else child.parent = parent; #endif child.localPosition = lp; child.localRotation = lr; child.localScale = ls; } static internal IEnumerable<PEPrefabScript> GetNestedInstances(GameObject gameObject) { var instances = gameObject.GetComponentsInChildren<PEPrefabScript>(true); var rootInstance = gameObject.GetComponent<PEPrefabScript>(); foreach (var instance in instances) { if (instance == rootInstance) continue; var parentInstance = instance.gameObject.GetInParent<PEPrefabScript>(); if (parentInstance == null) { yield return instance; } else if (parentInstance == rootInstance) { if (rootInstance.ParentPrefab == null) yield return instance; else if (rootInstance.ParentPrefab.GetComponent<PEPrefabScript>().Links[parentInstance.Links[instance]] == null) yield return instance; } else { if (parentInstance.IsNonPrefabObject(instance)) yield return instance; } } } private static T GetInParent<T>(this GameObject obj) where T : MonoBehaviour { var item = obj.transform.parent; while (item != null) { var result = item.GetComponent<T>(); if (result != null) return result; item = item.parent; } return null; } static internal void ExecuteOnEditorUpdate(this IEnumerator enumerator) { EditorApplication.CallbackFunction self = null; EditorApplication.CallbackFunction func = () => { if (!enumerator.MoveNext()) EditorApplication.update -= self; }; self = func; EditorApplication.update += func; } #endregion #region GUI static internal GUIStyle emptyStyle = new GUIStyle(); static void OnItemGUI(int instanceID, Rect rect) { var instance = EditorUtility.InstanceIDToObject(instanceID) as GameObject; if (instance == null) return; var prefabInstance = instance.GetComponent<PEPrefabScript>(); var isPrefab = PrefabUtility.GetPrefabParent(instance) && PrefabUtility.FindPrefabRoot(instance) == instance; if (prefabInstance) { bool rootPrefab = PrefabUtility.GetPrefabParent(prefabInstance.gameObject) == prefabInstance.Prefab; var color = GUI.color; GUI.color = rootPrefab ? Color.green : (Color.yellow); if (!prefabInstance.enabled) GUI.color = Color.white; if (prefabInstance.Prefab == null) GUI.color = Color.red; const int width = 15; var br = rect; br.height -= 2; br.y += 2 / 2; br.x += br.width - width; br.width = width; var content = new GUIContent(PEResources.icon, prefabInstance.Prefab ? prefabInstance.Prefab.name : "Missiog prefab with guid: " + prefabInstance.PrefabGUID); var click = GUI.Button(br, content, emptyStyle); GUI.color = color; var evt = Event.current; if (prefabInstance.Prefab && (evt.type == EventType.ContextClick || click || evt.type == EventType.MouseUp)) { var mousePos = evt.mousePosition; if (br.Contains(mousePos)) { var menu = new GenericMenu(); BuildMenu(menu, prefabInstance, rootPrefab); menu.ShowAsContext(); evt.Use(); } } } else if (isPrefab) { var click = PEPrefs.AutoPrefabs; if (click) MakeNested(instance); } } static private LinkedList<GameObject> buildMenuRecursionList = new LinkedList<GameObject>(); static internal void BuildMenu(GenericMenu menu, PEPrefabScript prefabInstance, bool rootPrefab, string path = "", bool showParent = true, bool showInstances = true) { if (buildMenuRecursionList.Contains(prefabInstance.Prefab)) { buildMenuRecursionList.AddLast(prefabInstance.Prefab); var prefabsArray = buildMenuRecursionList.Select(p => AssetDatabase.GetAssetPath(p)).ToArray(); buildMenuRecursionList.Clear(); throw new System.Exception("Prefab recursion detected:\n" + string.Join("\n", prefabsArray)); } buildMenuRecursionList.AddLast(prefabInstance.Prefab); if (prefabInstance.ParentPrefab == null || !showParent) menu.AddItem(new GUIContent(path + prefabInstance.Prefab.name), false, () => { }); else { BuildMenu(menu, prefabInstance.ParentPrefab.GetComponent<PEPrefabScript>(), false, path + prefabInstance.Prefab.name + "/", true, false); menu.AddItem(new GUIContent(path + prefabInstance.Prefab.name), false, () => { }); } menu.AddSeparator(path + ""); var isPrefab = prefabInstance.gameObject == prefabInstance.Prefab.gameObject; menu.AddItem(new GUIContent(path + "Select"), false, SelectPrefab, prefabInstance); var prefabType = PrefabUtility.GetPrefabType(prefabInstance.gameObject); var canApply = rootPrefab && prefabType != PrefabType.ModelPrefab && prefabType != PrefabType.ModelPrefabInstance && prefabType != PrefabType.DisconnectedModelPrefabInstance; if (canApply) { menu.AddItem(new GUIContent(path + "Apply"), false, Apply, prefabInstance); } if (!AssetDatabase.Contains(prefabInstance) || !isPrefab) { menu.AddItem(new GUIContent(path + "Revert"), false, Revert, prefabInstance); if (prefabInstance.ParentPrefab != null) menu.AddItem(new GUIContent(path + "Revert To Parent"), false, RevertToParent, prefabInstance); } menu.AddSeparator(path + ""); menu.AddItem(new GUIContent(path + "Create Child"), false, CreateChild, prefabInstance); #if INJECTION if (prefabInstance.ParentPrefab != null) menu.AddItem(new GUIContent(path + "Insert Parent"), false, InjectParent, prefabInstance); #endif if (!rootPrefab && !AssetDatabase.Contains(prefabInstance)) { menu.AddSeparator(path); if (prefabInstance.enabled) menu.AddItem(new GUIContent(path + "Disable"), false, obj => (obj as PEPrefabScript).enabled = false, prefabInstance); else menu.AddItem(new GUIContent(path + "Enable"), false, obj => (obj as PEPrefabScript).enabled = true, prefabInstance); } menu.AddSeparator(path); if (prefabInstance.GetPrefabsWithInstances().Any()) menu.AddItem(new GUIContent(path + "Instances/Select All Instances"), false, SelectInstances, prefabInstance); if (showInstances) foreach (var prefab in prefabInstance.GetPrefabsWithInstances()) { if (prefab == null) continue; var pi = prefab.GetComponent<PEPrefabScript>(); var name = prefab.name; name = (pi != null && pi.ParentPrefab == prefabInstance.Prefab) ? "Child: " + name : "Contains in: " + name; if (pi != null) BuildMenu(menu, prefab.GetComponent<PEPrefabScript>(), false, path + "Instances/" + name + "/", false); var current = prefab; menu.AddItem(new GUIContent(path + "Instances/" + name), false, () => { Selection.activeObject = current; }); } menu.AddItem(new GUIContent(path + "Instantiate"), false, pi => Selection.activeObject = PrefabUtility.InstantiatePrefab(((PEPrefabScript)pi).Prefab), prefabInstance); if (!AssetDatabase.Contains(prefabInstance)) menu.AddItem(new GUIContent(path + "Replace"), false, Replace, prefabInstance); buildMenuRecursionList.Remove(prefabInstance.Prefab); } static internal void Replace(object prefabInstance) { SelectObjectRoutine(prefabInstance as PEPrefabScript).ExecuteOnEditorUpdate(); } static IEnumerator SelectObjectRoutine(PEPrefabScript prefabInstance) { EditorGUIUtility.ShowObjectPicker<GameObject>(null, false, "t:Prefab", 1); Object obj = null; while (EditorGUIUtility.GetObjectPickerControlID() == 1) { obj = EditorGUIUtility.GetObjectPickerObject(); yield return null; } if (obj != null && EditorUtility.DisplayDialog("Replace", string.Format("Do you want to replace {0} with {1}", prefabInstance.gameObject.name, obj.name), "Replace", "Cancel")) { prefabInstance.ReplaceInPlace(obj as GameObject, EditorUtility.DisplayDialog("Replace", "Apply modifications from current instance?", "Apply", "Don't apply"), false); } } static internal bool IsCousin(GameObject b, GameObject c) { if (b == null || c == null) return false; var bi = b.GetComponent<PEPrefabScript>(); var ci = c.GetComponent<PEPrefabScript>(); return bi != null && ci != null && (ci.ParentPrefab == bi.Prefab || IsCousin(b, ci.ParentPrefab)); } static internal void MakeNested(GameObject instance) { var parent = PrefabUtility.GetPrefabParent(instance); var prefab = parent == null ? instance : parent as GameObject; if (prefab.GetComponent<EvolvePrefab>() != null) return; var pi = (PEPrefabScript)prefab.AddComponent<EvolvePrefab>(); pi.Prefab = prefab; pi.BuildLinks(); } static void SelectInstances(object obj) { Selection.objects = ((PEPrefabScript)obj).GetPrefabsWithInstances().ToArray(); } static void Apply(object obj) { DoApply((PEPrefabScript)obj); } static internal void DoApply(PEPrefabScript script) { if (PEPrefs.DebugLevel > 0) Debug.Log("DoApply Start"); script.ApplyChanges(true); if (PEPrefs.DebugLevel > 0) Debug.Log("DoApply Completed"); DoAutoSave(); } static internal void DoAutoSave() { EditorUtility.ClearProgressBar(); if (PEPrefs.AutoSaveAfterApply) EditorApplication.delayCall += AssetDatabase.SaveAssets; } static internal void RevertToParent(object obj) { ((PEPrefabScript)obj).RevertToParent(); } static internal void Revert(object obj) { ((PEPrefabScript)obj).Revert(); } static internal void CreateChild(object obj) { var pi = (PEPrefabScript)obj; var path = AssetDatabase.GenerateUniqueAssetPath(System.IO.Path.ChangeExtension(AssetDatabase.GUIDToAssetPath(pi.PrefabGUID), null) + "_Child.prefab"); var go = PrefabUtility.CreatePrefab(path, pi.gameObject, ReplacePrefabOptions.Default); var prefabInstance = go.GetComponent<PEPrefabScript>(); prefabInstance.Prefab = go; prefabInstance.ParentPrefab = pi.Prefab; prefabInstance.ParentPrefabGUID = pi.PrefabGUID; prefabInstance.BuildModifications(); Selection.activeObject = PrefabUtility.InstantiatePrefab(go); AssetDatabase.ImportAsset(path); PECache.Instance.CheckPrefab(path); } static internal void InjectChild(PEPrefabScript obj, GameObject[] children) { var path = AssetDatabase.GenerateUniqueAssetPath(System.IO.Path.ChangeExtension(AssetDatabase.GUIDToAssetPath(obj.PrefabGUID), null) + "_Child_Injected.prefab"); var go = PrefabUtility.CreatePrefab(path, obj.gameObject, ReplacePrefabOptions.Default); var prefabInstance = go.GetComponent<PEPrefabScript>(); prefabInstance.Prefab = go; prefabInstance.ParentPrefabGUID = obj.PrefabGUID; prefabInstance.BuildModifications(); Selection.activeObject = PrefabUtility.InstantiatePrefab(go); AssetDatabase.ImportAsset(path); PECache.Instance.CheckPrefab(path); foreach (var child in children) { child.GetComponent<PEPrefabScript>().ParentPrefabGUID = AssetDatabase.AssetPathToGUID(path); PECache.Instance.CheckPrefab(AssetDatabase.GUIDToAssetPath(child.GetComponent<PEPrefabScript>().PrefabGUID)); } } static internal void InjectParent(object obj) { var pi = (PEPrefabScript)obj; var path = AssetDatabase.GenerateUniqueAssetPath(System.IO.Path.ChangeExtension(AssetDatabase.GUIDToAssetPath(pi.PrefabGUID), null) + "_Parent_Inserted.prefab"); var go = PrefabUtility.CreatePrefab(path, pi.gameObject, ReplacePrefabOptions.Default); var prefabInstance = go.GetComponent<PEPrefabScript>(); prefabInstance.Prefab = go; prefabInstance.ParentPrefabGUID = pi.ParentPrefabGUID; prefabInstance.BuildModifications(); Selection.activeObject = PrefabUtility.InstantiatePrefab(go); AssetDatabase.ImportAsset(path); PECache.Instance.CheckPrefab(path); pi.ParentPrefabGUID = prefabInstance.PrefabGUID; PECache.Instance.CheckPrefab(AssetDatabase.GUIDToAssetPath(pi.PrefabGUID)); } static void SelectPrefab(object obj) { Selection.activeObject = ((PEPrefabScript)obj).Prefab; } static internal IEnumerable<GameObject> GetPrefabsWithInstance(string guid) { return PECache.Instance.GetPrefabsWithInstances(guid); } #endregion #region Assets static internal T GetAssetByGUID<T>(string GUID) where T : Object { return GetAssetByPath<T>(AssetDatabase.GUIDToAssetPath(GUID)); } static internal string GetAssetGUID(Object asset) { return AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(asset)); } static internal T GetAssetByPath<T>(string assetPath) where T : Object { return AssetDatabase.LoadAssetAtPath(assetPath, typeof(T)) as T; } #endregion static internal T GetInstance<T>(this SerializedProperty property) { return (T)GetInstance(property); } static internal object GetInstance(object obj, string path) { path = path.Replace(".Array.data", ""); var split = path.Split('.'); var stack = split; object v = obj; try { foreach (var name in stack) { if (name.Contains("[")) { var n = name.Split('[', ']'); v = GetField(v, n[0], int.Parse(n[1])); } else v = GetField(v, name); } } catch (System.Exception e) { Debug.LogException(e); return null; } return v; } static internal object GetInstance(this SerializedProperty property) { var obj = property.serializedObject.targetObject; var path = property.propertyPath; return GetInstance(obj, path); } private static object GetField(object obj, string field, int index = -1) { try { var obj2 = obj.GetType().GetField(field).GetValue(obj); return index == -1 ? obj2 : (obj2 as IList)[index]; } catch (System.Exception) { return null; } } #region Serialization static internal bool PropertyFilter(SerializedProperty property) { return property.propertyPath.Contains("m_Prefab") || property.propertyPath.Contains("m_FileID") || property.propertyPath.Contains("m_PathID") || property.propertyPath.Contains("m_ObjectHideFlags") || property.propertyPath.Contains("m_Children") || property.propertyPath.Contains("m_Father") || property.propertyPath.Contains("m_GameObject") || property.propertyPath.Contains("m_Component"); } static internal object GetPropertyValue(this SerializedProperty prop) { switch (prop.propertyType) { case SerializedPropertyType.Integer: return prop.intValue; case SerializedPropertyType.Boolean: return prop.boolValue; case SerializedPropertyType.Float: return prop.floatValue; case SerializedPropertyType.String: return prop.stringValue; case SerializedPropertyType.Color: return prop.colorValue; case SerializedPropertyType.ObjectReference: return prop.objectReferenceValue; case SerializedPropertyType.LayerMask: return prop.intValue; case SerializedPropertyType.Enum: return prop.enumValueIndex; case SerializedPropertyType.Vector2: return prop.vector2Value; case SerializedPropertyType.Vector3: return prop.vector3Value; case SerializedPropertyType.Quaternion: return prop.quaternionValue; case SerializedPropertyType.Rect: return prop.rectValue; case SerializedPropertyType.ArraySize: return prop.intValue; case SerializedPropertyType.Character: return prop.intValue; case SerializedPropertyType.AnimationCurve: return prop.animationCurveValue; case SerializedPropertyType.Bounds: return prop.boundsValue; case SerializedPropertyType.Gradient: break; } return null; } static internal void SetPropertyValue(this SerializedProperty prop, object value) { if(SetInternalPropertyValue(prop, value)) return; switch (prop.propertyType) { case SerializedPropertyType.Integer: prop.intValue = (int)value; break; case SerializedPropertyType.Boolean: prop.boolValue = (bool)value; break; case SerializedPropertyType.Float: prop.floatValue = (float)value; break; case SerializedPropertyType.String: prop.stringValue = (string)value; break; case SerializedPropertyType.Color: prop.colorValue = (Color)value; break; case SerializedPropertyType.ObjectReference: prop.objectReferenceValue = (Object)value; break; case SerializedPropertyType.LayerMask: prop.intValue = (int)value; break; case SerializedPropertyType.Enum: prop.enumValueIndex = (int)value; break; case SerializedPropertyType.Vector2: prop.vector2Value = (Vector2)value; break; case SerializedPropertyType.Vector3: prop.vector3Value = (Vector3)value; break; case SerializedPropertyType.Quaternion: prop.quaternionValue = (Quaternion)value; break; case SerializedPropertyType.Rect: prop.rectValue = (Rect)value; break; case SerializedPropertyType.ArraySize: prop.intValue = (int)value; break; case SerializedPropertyType.Character: prop.intValue = (int)value; break; case SerializedPropertyType.AnimationCurve: prop.animationCurveValue = (AnimationCurve)value; break; case SerializedPropertyType.Bounds: prop.boundsValue = (Bounds)value; break; case SerializedPropertyType.Gradient: break; } } static private bool SetInternalPropertyValue(this SerializedProperty prop, object value) { var targetTransform = prop.serializedObject.targetObject as Transform; if (targetTransform != null) { switch (prop.propertyPath) { case "m_RootOrder": targetTransform.SetSiblingIndex((int)value); return false; case "m_Father": SetParentAndSaveLocalTransform(targetTransform, (Transform)value); return true; default: return false; } } return false; } static internal void CopyPrefabInternalData(Object src, Object dest) { if (src == null || dest == null) { if (PEPrefs.DebugLevel > 0) Debug.LogError(string.Format("Failed to copy internal prefab data src:{0} dst:{1}", src, dest)); return; } var destSO = new SerializedObject(dest); var srcSO = new SerializedObject(src); destSO.FindProperty("m_PrefabParentObject").SetPropertyValue(srcSO.FindProperty("m_PrefabParentObject").GetPropertyValue()); destSO.FindProperty("m_PrefabInternal").SetPropertyValue(srcSO.FindProperty("m_PrefabInternal").GetPropertyValue()); destSO.ApplyModifiedProperties(); } static internal bool Compare(AnimationCurve c0, AnimationCurve c1) { if (c0 == null && c1 != null || c0 != null && c1 == null) return false; if (c0 == c1) return true; if (c0.postWrapMode != c1.postWrapMode) return false; if (c0.preWrapMode != c1.preWrapMode) return false; if (c0.keys == null && c1.keys != null) return false; if (c0.keys != null && c1.keys == null) return false; if (c0.keys != null && c1.keys != null) { if (c0.keys.Length != c1.keys.Length) return false; return !c0.keys.Where((t, i) => !Compare(t, c1.keys[i])).Any(); } return true; } static internal bool Compare(Keyframe c0, Keyframe c1) { return c0.inTangent == c1.inTangent && c0.outTangent == c1.outTangent && c0.tangentMode == c1.tangentMode && c0.time == c1.time && c0.value == c1.value; } static internal Component CopyComponentTo(this Component component, GameObject gameObject) { if (component == null) { if (PEPrefs.DebugLevel > 0) Debug.Log("Trying to copy null component"); return null; } if (PEPrefs.DebugLevel > 0) Debug.Log(string.Format("Add component {0} to {1}", component, gameObject)); var newComponent = gameObject.AddComponent(component.GetType()); if (!newComponent) { if (PEPrefs.DebugLevel > 0) Debug.LogWarning(string.Format("Failed to copy component of type {0}", component.GetType())); return null; } EditorUtility.CopySerialized(component, newComponent); return newComponent; } #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. #pragma warning disable 0420 // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A lock-free, concurrent stack primitive, and its associated debugger view type. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization; using System.Security; using System.Threading; namespace System.Collections.Concurrent { // A stack that uses CAS operations internally to maintain thread-safety in a lock-free // manner. Attempting to push or pop concurrently from the stack will not trigger waiting, // although some optimistic concurrency and retry is used, possibly leading to lack of // fairness and/or livelock. The stack uses spinning and backoff to add some randomization, // in hopes of statistically decreasing the possibility of livelock. // // Note that we currently allocate a new node on every push. This avoids having to worry // about potential ABA issues, since the CLR GC ensures that a memory address cannot be // reused before all references to it have died. /// <summary> /// Represents a thread-safe last-in, first-out collection of objects. /// </summary> /// <typeparam name="T">Specifies the type of elements in the stack.</typeparam> /// <remarks> /// All public and protected members of <see cref="ConcurrentStack{T}"/> are thread-safe and may be used /// concurrently from multiple threads. /// </remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<>))] internal class ConcurrentStack<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T> { /// <summary> /// A simple (internal) node type used to store elements of concurrent stacks and queues. /// </summary> private class Node { internal readonly T m_value; // Value of the node. internal Node m_next; // Next pointer. /// <summary> /// Constructs a new node with the specified value and no next node. /// </summary> /// <param name="value">The value of the node.</param> internal Node(T value) { m_value = value; m_next = null; } } private volatile Node m_head; // The stack is a singly linked list, and only remembers the head. private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff. /// <summary> /// Initializes a new instance of the <see cref="ConcurrentStack{T}"/> /// class. /// </summary> public ConcurrentStack() { } /// <summary> /// Gets the number of elements contained in the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <value>The number of elements contained in the <see cref="ConcurrentStack{T}"/>.</value> /// <remarks> /// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/> /// property is recommended rather than retrieving the number of items from the <see cref="Count"/> /// property and comparing it to 0. /// </remarks> public int Count { // Counts the number of entries in the stack. This is an O(n) operation. The answer may be out // of date before returning, but guarantees to return a count that was once valid. Conceptually, // the implementation snaps a copy of the list and then counts the entries, though physically // this is not what actually happens. get { int count = 0; // Just whip through the list and tally up the number of nodes. We rely on the fact that // node next pointers are immutable after being enqueued for the first time, even as // they are being dequeued. If we ever changed this (e.g. to pool nodes somehow), // we'd need to revisit this implementation. for (Node curr = m_head; curr != null; curr = curr.m_next) { count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR } return count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is /// synchronized with the SyncRoot. /// </summary> /// <value>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized /// with the SyncRoot; otherwise, false. For <see cref="ConcurrentStack{T}"/>, this property always /// returns false.</value> bool ICollection.IsSynchronized { // Gets a value indicating whether access to this collection is synchronized. Always returns // false. The reason is subtle. While access is in face thread safe, it's not the case that // locking on the SyncRoot would have prevented concurrent pushes and pops, as this property // would typically indicate; that's because we internally use CAS operations vs. true locks. get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see /// cref="T:System.Collections.ICollection"/>. This property is not supported. /// </summary> /// <exception cref="T:System.NotSupportedException">The SyncRoot property is not supported</exception> object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see /// cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must /// have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"> /// <paramref name="array"/> is multidimensional. -or- /// <paramref name="array"/> does not have zero-based indexing. -or- /// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. -or- The type of the source <see /// cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the /// destination <paramref name="array"/>. /// </exception> void ICollection.CopyTo(Array array, int index) { // Validate arguments. if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ((ICollection)ToList()).CopyTo(array, index); } /// <summary> /// Copies the <see cref="ConcurrentStack{T}"/> elements to an existing one-dimensional <see /// cref="T:System.Array"/>, starting at the specified array index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of /// the elements copied from the /// <see cref="ConcurrentStack{T}"/>. The <see cref="T:System.Array"/> must have zero-based /// indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying /// begins.</param> /// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in /// Visual Basic).</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than /// zero.</exception> /// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the /// length of the <paramref name="array"/> /// -or- The number of elements in the source <see cref="ConcurrentStack{T}"/> is greater than the /// available space from <paramref name="index"/> to the end of the destination <paramref /// name="array"/>. /// </exception> public void CopyTo(T[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } // We must be careful not to corrupt the array, so we will first accumulate an // internal list of elements that we will then copy to the array. This requires // some extra allocation, but is necessary since we don't know up front whether // the array is sufficiently large to hold the stack's contents. ToList().CopyTo(array, index); } /// <summary> /// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="item">The object to push onto the <see cref="ConcurrentStack{T}"/>. The value can be /// a null reference (Nothing in Visual Basic) for reference types. /// </param> public void Push(T item) { // Pushes a node onto the front of the stack thread-safely. Internally, this simply // swaps the current head pointer using a (thread safe) CAS operation to accomplish // lock freedom. If the CAS fails, we add some back off to statistically decrease // contention at the head, and then go back around and retry. Node newNode = new Node(item); newNode.m_next = m_head; if (Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next) { return; } // If we failed, go to the slow path and loop around until we succeed. PushCore(newNode, newNode); } /// <summary> /// Push one or many nodes into the stack, if head and tails are equal then push one node to the stack other wise push the list between head /// and tail to the stack /// </summary> /// <param name="head">The head pointer to the new list</param> /// <param name="tail">The tail pointer to the new list</param> private void PushCore(Node head, Node tail) { SpinWait spin = new SpinWait(); // Keep trying to CAS the exising head with the new node until we succeed. do { spin.SpinOnce(); // Reread the head and link our new node. tail.m_next = m_head; } while (Interlocked.CompareExchange( ref m_head, head, tail.m_next) != tail.m_next); } /// <summary> /// Attempts to pop and return the object at the top of the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <param name="result"> /// When this method returns, if the operation was successful, <paramref name="result"/> contains the /// object removed. If no object was available to be removed, the value is unspecified. /// </param> /// <returns>true if an element was removed and returned from the top of the <see /// cref="ConcurrentStack{T}"/> /// succesfully; otherwise, false.</returns> public bool TryPop(out T result) { Node head = m_head; //stack is empty if (head == null) { result = default(T); return false; } if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head) { result = head.m_value; return true; } // Fall through to the slow path. return TryPopCore(out result); } /// <summary> /// Local helper function to Pop an item from the stack, slow path /// </summary> /// <param name="result">The popped item</param> /// <returns>True if succeeded, false otherwise</returns> private bool TryPopCore(out T result) { Node poppedNode; if (TryPopCore(1, out poppedNode) == 1) { result = poppedNode.m_value; return true; } result = default(T); return false; } /// <summary> /// Slow path helper for TryPop. This method assumes an initial attempt to pop an element /// has already occurred and failed, so it begins spinning right away. /// </summary> /// <param name="count">The number of items to pop.</param> /// <param name="poppedHead"> /// When this method returns, if the pop succeeded, contains the removed object. If no object was /// available to be removed, the value is unspecified. This parameter is passed uninitialized. /// </param> /// <returns>True if an element was removed and returned; otherwise, false.</returns> private int TryPopCore(int count, out Node poppedHead) { SpinWait spin = new SpinWait(); // Try to CAS the head with its current next. We stop when we succeed or // when we notice that the stack is empty, whichever comes first. Node head; Node next; int backoff = 1; Random r = null; while (true) { head = m_head; // Is the stack empty? if (head == null) { poppedHead = null; return 0; } next = head; int nodesCount = 1; for (; nodesCount < count && next.m_next != null; nodesCount++) { next = next.m_next; } // Try to swap the new head. If we succeed, break out of the loop. if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head) { // Return the popped Node. poppedHead = head; return nodesCount; } // We failed to CAS the new head. Spin briefly and retry. for (int i = 0; i < backoff; i++) { spin.SpinOnce(); } if (spin.NextSpinWillYield) { if (r == null) { r = new Random(); } backoff = r.Next(1, BACKOFF_MAX_YIELDS); } else { backoff *= 2; } } } /// <summary> /// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array. /// </summary> /// <returns>A new array containing a snapshot of elements copied from the <see /// cref="ConcurrentStack{T}"/>.</returns> public T[] ToArray() { return ToList().ToArray(); } /// <summary> /// Returns an array containing a snapshot of the list's contents, using /// the target list node as the head of a region in the list. /// </summary> /// <returns>An array of the list's contents.</returns> private List<T> ToList() { List<T> list = new List<T>(); Node curr = m_head; while (curr != null) { list.Add(curr.m_value); curr = curr.m_next; } return list; } /// <summary> /// Returns an enumerator that iterates through the <see cref="ConcurrentStack{T}"/>. /// </summary> /// <returns>An enumerator for the <see cref="ConcurrentStack{T}"/>.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents /// of the stack. It does not reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use /// concurrently with reads from and writes to the stack. /// </remarks> public IEnumerator<T> GetEnumerator() { // Returns an enumerator for the stack. This effectively takes a snapshot // of the stack's contents at the time of the call, i.e. subsequent modifications // (pushes or pops) will not be reflected in the enumerator's contents. //If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of //the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called. //This is inconsistent with existing generic collections. In order to prevent it, we capture the //value of m_head in a buffer and call out to a helper method return GetEnumerator(m_head); } private IEnumerator<T> GetEnumerator(Node head) { Node current = head; while (current != null) { yield return current.m_value; current = current.m_next; } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An <see cref="T:System.Collections.IEnumerator"/> that can be used to iterate through /// the collection.</returns> /// <remarks> /// The enumeration represents a moment-in-time snapshot of the contents of the stack. It does not /// reflect any updates to the collection after /// <see cref="GetEnumerator"/> was called. The enumerator is safe to use concurrently with reads /// from and writes to the stack. /// </remarks> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } }
// // Copyright (C) Microsoft. All rights reserved. // namespace System.Management.Automation { using System; using System.Collections; using System.Reflection; using System.Xml; using System.Management.Automation.Internal; using System.Collections.Generic; using Dbg = System.Management.Automation.Diagnostics; /// <summary> /// This class provides functionality for serializing a PSObject /// </summary> internal class CustomSerialization { #region constructor /// <summary> /// depth of serialization /// </summary> private int _depth; /// <summary> /// XmlWriter to be used for writing. /// </summary> private XmlWriter _writer; /// <summary> /// Whether type information should be included in the xml /// </summary> private bool _notypeinformation; /// <summary> /// CustomerSerializer used for formatting the output for _writer /// </summary> private CustomInternalSerializer _serializer; /// <summary> /// Constructor /// </summary> /// <param name="writer"> /// writer to be used for serialization. /// </param> /// <param name="notypeinformation"> /// should the type information to be shown. /// </param> /// <param name="depth"> /// depth to be used for serialization. If this value is specified, /// depth from types.xml is not used. /// </param> internal CustomSerialization(XmlWriter writer, bool notypeinformation, int depth) { if (writer == null) { throw PSTraceSource.NewArgumentException("writer"); } if (depth < 1) { throw PSTraceSource.NewArgumentException("writer", Serialization.DepthOfOneRequired); } _depth = depth; _writer = writer; _notypeinformation = notypeinformation; _serializer = null; } /// <summary> /// Default depth of serialization /// </summary> public static int MshDefaultSerializationDepth { get; } = 1; /// <summary> /// Constructor /// </summary> /// <param name="writer"> /// writer to be used for serialization. /// </param> /// <param name="notypeinformation"> /// should the type information to be shown. /// </param> internal CustomSerialization(XmlWriter writer, bool notypeinformation) : this(writer, notypeinformation, MshDefaultSerializationDepth) { } #endregion constructor #region public methods private bool _firstCall = true; /// <summary> /// Serializes passed in object /// </summary> /// <param name="source"> /// object to be serialized /// </param> internal void Serialize(object source) { //Write the root element tag before writing first object. if (_firstCall) { _firstCall = false; Start(); } _serializer = new CustomInternalSerializer ( _writer, _notypeinformation, true ); _serializer.WriteOneObject(source, null, _depth); _serializer = null; } /// <summary> /// Serializes passed in object /// </summary> /// <param name="source"> /// object to be serialized /// </param> internal void SerializeAsStream(object source) { _serializer = new CustomInternalSerializer ( _writer, _notypeinformation, true ); _serializer.WriteOneObject(source, null, _depth); _serializer = null; } /// <summary> /// Writes the start of root element /// </summary> private void Start() { CustomInternalSerializer.WriteStartElement(_writer, CustomSerializationStrings.RootElementTag); } /// <summary> /// Write the end of root element /// </summary> internal void Done() { if (_firstCall) { _firstCall = false; Start(); } _writer.WriteEndElement(); _writer.Flush(); } /// <summary> /// Flush the writer /// </summary> internal void DoneAsStream() { _writer.Flush(); } internal void Stop() { CustomInternalSerializer serializer = _serializer; if (serializer != null) { serializer.Stop(); } } #endregion } /// <summary> /// This internal helper class provides methods for serializing mshObject. /// </summary> internal class CustomInternalSerializer { #region constructor /// <summary> /// Xml writer to be used /// </summary> private XmlWriter _writer; /// <summary> /// check first call for every pipeline object to write Object tag else property tag /// </summary> private bool _firstcall; /// <summary> /// should the type information to be shown /// </summary> private bool _notypeinformation; /// <summary> /// check object call /// </summary> private bool _firstobjectcall = true; /// <summary> /// Constructor /// </summary> /// <param name="writer"> /// Xml writer to be used /// </param> /// <param name="notypeinformation"> /// Xml writer to be used /// </param> /// <param name="isfirstcallforObject"> /// check first call for every pipeline object to write Object tag else property tag /// </param> internal CustomInternalSerializer(XmlWriter writer, bool notypeinformation, bool isfirstcallforObject) { Dbg.Assert(writer != null, "caller should validate the parameter"); _writer = writer; _notypeinformation = notypeinformation; _firstcall = isfirstcallforObject; } #endregion #region Stopping private bool _isStopping = false; /// <summary> /// Called from a separate thread will stop the serialization process /// </summary> internal void Stop() { _isStopping = true; } private void CheckIfStopping() { if (_isStopping) { throw PSTraceSource.NewInvalidOperationException(Serialization.Stopping); } } #endregion Stopping /// <summary> /// This writes one object. /// </summary> /// <param name="source"> /// source to be serialized. /// </param> /// <param name="property"> /// name of property. If null, name attribute is not written. /// </param> /// <param name="depth"> /// depth to which this object should be serialized. /// </param> internal void WriteOneObject(object source, string property, int depth) { Dbg.Assert(depth >= 0, "depth should always be greater or equal to zero"); CheckIfStopping(); if (source == null) { WriteNull(property); return; } if (HandlePrimitiveKnownType(source, property)) { return; } if (HandlePrimitiveKnownTypePSObject(source, property, depth)) { return; } //Note: We donot use containers in depth calculation. i.e even if the //current depth is zero, we serialize the container. All contained items will //get serialized with depth zero. if (HandleKnownContainerTypes(source, property, depth)) { return; } PSObject mshSource = PSObject.AsPSObject(source); //If depth is zero, complex type should be serialized as string. if (depth == 0 || SerializeAsString(mshSource)) { HandlePSObjectAsString(mshSource, property, depth); return; } HandleComplexTypePSObject(mshSource, property, depth); return; } /// <summary> /// Serializes Primitive Known Types. /// </summary> /// <returns> /// true if source is handled, else false. /// </returns> private bool HandlePrimitiveKnownType(object source, string property) { Dbg.Assert(source != null, "caller should validate the parameter"); //Check if source is of primitive known type TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(source.GetType()); if (pktInfo != null) { WriteOnePrimitiveKnownType(_writer, property, source, pktInfo); return true; } return false; } /// <summary> /// Serializes PSObject whose base objects are of primitive known type /// </summary> /// <param name="source"></param> /// <param name="property"></param> /// <param name="depth"></param> /// <returns> /// true if source is handled, else false. /// </returns> private bool HandlePrimitiveKnownTypePSObject(object source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the parameter"); bool sourceHandled = false; PSObject moSource = source as PSObject; if (moSource != null && !moSource.immediateBaseObjectIsEmpty) { //Check if baseObject is primitive known type object baseObject = moSource.ImmediateBaseObject; TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(baseObject.GetType()); if (pktInfo != null) { WriteOnePrimitiveKnownType(_writer, property, baseObject, pktInfo); sourceHandled = true; } } return sourceHandled; } private bool HandleKnownContainerTypes(object source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the parameter"); ContainerType ct = ContainerType.None; PSObject mshSource = source as PSObject; IEnumerable enumerable = null; IDictionary dictionary = null; //If passed in object is PSObject with no baseobject, return false. if (mshSource != null && mshSource.immediateBaseObjectIsEmpty) { return false; } //Check if source (or baseobject in mshSource) is known container type GetKnownContainerTypeInfo(mshSource != null ? mshSource.ImmediateBaseObject : source, out ct, out dictionary, out enumerable); if (ct == ContainerType.None) return false; WriteStartOfPSObject(mshSource ?? PSObject.AsPSObject(source), property, true); switch (ct) { case ContainerType.Dictionary: { WriteDictionary(dictionary, depth); } break; case ContainerType.Stack: case ContainerType.Queue: case ContainerType.List: case ContainerType.Enumerable: { WriteEnumerable(enumerable, depth); } break; default: { Dbg.Assert(false, "All containers should be handled in the switch"); } break; } //An object which is original enumerable becomes an PSObject //with arraylist on deserialization. So on roundtrip it will show up //as List. //We serialize properties of enumerable and on deserialization mark the object //as Deserialized. So if object is marked deserialized, we should write properties. //Note: we do not serialize the properties of IEnumerable if depth is zero. if (depth != 0 && (ct == ContainerType.Enumerable || (mshSource != null && mshSource.isDeserialized))) { //Note:Depth is the depth for serialization of baseObject. //Depth for serialization of each property is one less. WritePSObjectProperties(PSObject.AsPSObject(source), depth); } //If source is PSObject, serialize notes if (mshSource != null) { //Serialize instanceMembers PSMemberInfoCollection<PSMemberInfo> instanceMembers = mshSource.InstanceMembers; if (instanceMembers != null) { WriteMemberInfoCollection(instanceMembers, depth, true); } } _writer.WriteEndElement(); return true; } /// <summary> /// Checks if source is known container type and returns appropriate /// information /// </summary> /// <param name="source"></param> /// <param name="ct"></param> /// <param name="dictionary"></param> /// <param name="enumerable"></param> private void GetKnownContainerTypeInfo( object source, out ContainerType ct, out IDictionary dictionary, out IEnumerable enumerable) { Dbg.Assert(source != null, "caller should validate the parameter"); ct = ContainerType.None; dictionary = null; enumerable = null; dictionary = source as IDictionary; if (dictionary != null) { ct = ContainerType.Dictionary; return; } if (source is Stack) { ct = ContainerType.Stack; enumerable = LanguagePrimitives.GetEnumerable(source); Dbg.Assert(enumerable != null, "Stack is enumerable"); } else if (source is Queue) { ct = ContainerType.Queue; enumerable = LanguagePrimitives.GetEnumerable(source); Dbg.Assert(enumerable != null, "Queue is enumerable"); } else if (source is IList) { ct = ContainerType.List; enumerable = LanguagePrimitives.GetEnumerable(source); Dbg.Assert(enumerable != null, "IList is enumerable"); } else { Type gt = source.GetType(); if (gt.GetTypeInfo().IsGenericType) { if (DerivesFromGenericType(gt, typeof(Stack<>))) { ct = ContainerType.Stack; enumerable = LanguagePrimitives.GetEnumerable(source); Dbg.Assert(enumerable != null, "Stack is enumerable"); } else if (DerivesFromGenericType(gt, typeof(Queue<>))) { ct = ContainerType.Queue; enumerable = LanguagePrimitives.GetEnumerable(source); Dbg.Assert(enumerable != null, "Queue is enumerable"); } else if (DerivesFromGenericType(gt, typeof(List<>))) { ct = ContainerType.List; enumerable = LanguagePrimitives.GetEnumerable(source); Dbg.Assert(enumerable != null, "Queue is enumerable"); } } } //Check if type is IEnumerable if (ct == ContainerType.None) { enumerable = LanguagePrimitives.GetEnumerable(source); if (enumerable != null) { ct = ContainerType.Enumerable; } } } /// <summary> /// Checks if derived is of type baseType or a type derived from baseType /// </summary> /// <param name="derived"></param> /// <param name="baseType"></param> /// <returns></returns> private static bool DerivesFromGenericType(Type derived, Type baseType) { Dbg.Assert(derived != null, "caller should validate the parameter"); Dbg.Assert(baseType != null, "caller should validate the parameter"); while (derived != null) { if (derived.GetTypeInfo().IsGenericType) derived = derived.GetGenericTypeDefinition(); if (derived == baseType) { return true; } derived = derived.GetTypeInfo().BaseType; } return false; } #region Write PSObject /// <summary> /// Serializes an PSObject whose baseobject is of primitive type /// and which has notes. /// </summary> /// <param name="source"> /// source from which notes are written /// </param> /// <param name="primitive"> /// primitive object which is written as base object. In most cases it /// is same source.ImmediateBaseObject. When PSObject is serialized as string, /// it can be different. <see cref="HandlePSObjectAsString"/> for more info. /// </param> /// <param name="pktInfo"> /// TypeSerializationInfo for the primitive. /// </param> /// <param name="property"></param> /// <param name="depth"></param> private void WritePrimitiveTypePSObjectWithNotes( PSObject source, object primitive, TypeSerializationInfo pktInfo, string property, int depth) { Dbg.Assert(source != null, "caller should validate the parameter"); //Write start of PSObject. Since baseobject is primitive known //type, we do not need TypeName information. WriteStartOfPSObject(source, property, source.ToStringFromDeserialization != null); if (pktInfo != null) { WriteOnePrimitiveKnownType(_writer, null, primitive, pktInfo); } //Serialize instanceMembers PSMemberInfoCollection<PSMemberInfo> instanceMembers = source.InstanceMembers; if (instanceMembers != null) { WriteMemberInfoCollection(instanceMembers, depth, true); } _writer.WriteEndElement(); } private void HandleComplexTypePSObject(PSObject source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the parameter"); WriteStartOfPSObject(source, property, true); // Figure out what kind of object we are dealing with bool isEnum = false; bool isPSObject = false; if (!source.immediateBaseObjectIsEmpty) { isEnum = source.ImmediateBaseObject is Enum; isPSObject = source.ImmediateBaseObject is PSObject; } if (isEnum) { object baseObject = source.ImmediateBaseObject; foreach (PSPropertyInfo prop in source.Properties) { WriteOneObject(System.Convert.ChangeType(baseObject, Enum.GetUnderlyingType(baseObject.GetType()), System.Globalization.CultureInfo.InvariantCulture), prop.Name, depth); } } else if (isPSObject) { if (_firstobjectcall) { _firstobjectcall = false; WritePSObjectProperties(source, depth); } else { WriteOneObject(source.ImmediateBaseObject, null, depth); } } else { WritePSObjectProperties(source, depth); } _writer.WriteEndElement(); } /// <summary> /// Writes start element, attributes and typeNames for PSObject. /// </summary> /// <param name="mshObject"></param> /// <param name="property"></param> /// <param name="writeTNH"> /// if true, TypeName information is written, else not. /// </param> private void WriteStartOfPSObject( PSObject mshObject, string property, bool writeTNH) { Dbg.Assert(mshObject != null, "caller should validate the parameter"); if (property != null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property.ToString()); } else { if (_firstcall) { WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag); _firstcall = false; } else { WriteStartElement(_writer, CustomSerializationStrings.Properties); } } Object baseObject = mshObject.BaseObject; if (!_notypeinformation) WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, baseObject.GetType().ToString()); } #region membersets /// <summary> /// Returns true if PSObject has notes. /// </summary> /// <param name="source"></param> /// <returns> /// </returns> private bool PSObjectHasNotes(PSObject source) { if (source.InstanceMembers != null && source.InstanceMembers.Count > 0) { return true; } return false; } /// <summary> /// Serialize member set. This method serializes without writing /// enclosing tags and attributes. /// </summary> /// <param name="me"> /// enumerable containing members /// </param> /// <param name="depth"></param> /// <param name="writeEnclosingMemberSetElementTag"> /// if this is true, write an enclosing "<memberset></memberset>" tag. /// </param> /// <returns></returns> private void WriteMemberInfoCollection( PSMemberInfoCollection<PSMemberInfo> me, int depth, bool writeEnclosingMemberSetElementTag) { Dbg.Assert(me != null, "caller should validate the parameter"); bool enclosingTagWritten = false; foreach (PSMemberInfo info in me) { if (!info.ShouldSerialize) { continue; } PSPropertyInfo property = info as PSPropertyInfo; if (property == null) { continue; } enclosingTagWritten = true; WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, info.Name); if (!_notypeinformation) WriteAttribute(_writer, CustomSerializationStrings.TypeAttribute, info.GetType().ToString()); _writer.WriteString(property.Value.ToString()); } if (enclosingTagWritten) { _writer.WriteEndElement(); } } #endregion membersets #region properties /// <summary> /// Serializes properties of PSObject /// </summary> private void WritePSObjectProperties(PSObject source, int depth) { Dbg.Assert(source != null, "caller should validate the information"); depth = GetDepthOfSerialization(source, depth); //Depth available for each property is one less --depth; Dbg.Assert(depth >= 0, "depth should be greater or equal to zero"); if (source.GetSerializationMethod(null) == SerializationMethod.SpecificProperties) { PSMemberInfoInternalCollection<PSPropertyInfo> specificProperties = new PSMemberInfoInternalCollection<PSPropertyInfo>(); foreach (string propertyName in source.GetSpecificPropertiesToSerialize(null)) { PSPropertyInfo property = source.Properties[propertyName]; if (property != null) { specificProperties.Add(property); } } SerializeProperties(specificProperties, CustomSerializationStrings.Properties, depth); return; } foreach (PSPropertyInfo prop in source.Properties) { Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); object value = AutomationNull.Value; //PSObject throws GetValueException if it cannot //get value for a property. try { value = prop.Value; } catch (GetValueException) { WritePropertyWithNullValue(_writer, prop, depth); continue; } //Write the property if (value == null) { WritePropertyWithNullValue(_writer, prop, depth); } else { WriteOneObject(value, prop.Name, depth); } } } /// <summary> /// Serializes properties from collection /// </summary> /// <param name="propertyCollection"> /// Collection of properties to serialize /// </param> /// <param name="name"> /// Name for enclosing element tag /// </param> /// <param name="depth"> /// depth to which each property should be /// serialized /// </param> private void SerializeProperties( PSMemberInfoInternalCollection<PSPropertyInfo> propertyCollection, string name, int depth) { Dbg.Assert(propertyCollection != null, "caller should validate the parameter"); if (propertyCollection.Count == 0) return; foreach (PSMemberInfo info in propertyCollection) { PSPropertyInfo prop = info as PSPropertyInfo; Dbg.Assert(prop != null, "propertyCollection should only have member of type PSProperty"); object value = AutomationNull.Value; //PSObject throws GetValueException if it cannot //get value for a property. try { value = prop.Value; } catch (GetValueException) { continue; } //Write the property WriteOneObject(value, prop.Name, depth); } } #endregion base properties #endregion WritePSObject #region enumerable and dictionary /// <summary> /// Serializes IEnumerable /// </summary> /// <param name="enumerable"> /// enumerable which is serialized /// </param> /// <param name="depth"></param> private void WriteEnumerable(IEnumerable enumerable, int depth) { Dbg.Assert(enumerable != null, "caller should validate the parameter"); IEnumerator enumerator = null; try { enumerator = enumerable.GetEnumerator(); enumerator.Reset(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); enumerator = null; } //AD has incorrect implementation of IEnumerable where they returned null //for GetEnumerator instead of empty enumerator if (enumerator != null) { while (true) { object item = null; try { if (!enumerator.MoveNext()) { break; } else { item = enumerator.Current; } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); break; } WriteOneObject(item, null, depth); } } } /// <summary> /// Serializes IDictionary /// </summary> /// <param name="dictionary">dictionary which is serialized</param> /// <param name="depth"></param> private void WriteDictionary(IDictionary dictionary, int depth) { IDictionaryEnumerator dictionaryEnum = null; try { dictionaryEnum = (IDictionaryEnumerator)dictionary.GetEnumerator(); } catch (Exception e) // ignore non-severe exceptions { CommandProcessorBase.CheckForSevereException(e); } if (dictionaryEnum != null) { while (dictionaryEnum.MoveNext()) { //Write Key WriteOneObject(dictionaryEnum.Key, CustomSerializationStrings.DictionaryKey, depth); //Write Value WriteOneObject(dictionaryEnum.Value, CustomSerializationStrings.DictionaryValue, depth); } } } #endregion enumerable and dictionary #region serialize as string private void HandlePSObjectAsString(PSObject source, string property, int depth) { Dbg.Assert(source != null, "caller should validate the information"); bool hasNotes = PSObjectHasNotes(source); string value = GetStringFromPSObject(source); if (value != null) { TypeSerializationInfo pktInfo = KnownTypes.GetTypeSerializationInfo(value.GetType()); Dbg.Assert(pktInfo != null, "TypeSerializationInfo should be present for string"); if (hasNotes) { WritePrimitiveTypePSObjectWithNotes(source, value, pktInfo, property, depth); } else { WriteOnePrimitiveKnownType(_writer, property, source.BaseObject, pktInfo); } } else { if (hasNotes) { WritePrimitiveTypePSObjectWithNotes(source, null, null, property, depth); } else { WriteNull(property); } } } /// <summary> /// Gets the string from PSObject using the information from /// types.ps1xml. This string is used for serializing the PSObject. /// </summary> /// /// <param name="source"> /// PSObject to be converted to string /// </param> /// /// <returns> /// string value to use for serializing this PSObject. /// </returns> private string GetStringFromPSObject(PSObject source) { Dbg.Assert(source != null, "caller should have validated the information"); // check if we have a well known string serialization source PSPropertyInfo serializationProperty = source.GetStringSerializationSource(null); string result = null; if (serializationProperty != null) { object val = serializationProperty.Value; if (val != null) { try { // if we have a string serialization value, return it result = val.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } } else { try { // fall back value result = source.ToString(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } } return result; } /// <summary> /// Reads the information the PSObject /// and returns true if this object should be serialized as /// string /// </summary> /// <param name="source">PSObject to be serialized</param> /// <returns>true if the object needs to be serialized as a string</returns> private static bool SerializeAsString(PSObject source) { return source.GetSerializationMethod(null) == SerializationMethod.String; } #endregion serialize as string /// <summary> /// compute the serialization depth for an PSObject instance subtree /// </summary> /// <param name="source">PSObject whose serialization depth has to be computed</param> /// <param name="depth">current depth</param> /// <returns></returns> private static int GetDepthOfSerialization(PSObject source, int depth) { if (source == null) return depth; // get the depth from the PSObject // NOTE: we assume that the depth out of the PSObject is > 0 // else we consider it not set in types.ps1xml int objectLevelDepth = source.GetSerializationDepth(null); if (objectLevelDepth <= 0) { // no override at the type level return depth; } return objectLevelDepth; } /// <summary> /// Writes null /// </summary> /// <param name="property"></param> private void WriteNull(string property) { if (property != null) { WriteStartElement(_writer, CustomSerializationStrings.Properties); WriteAttribute(_writer, CustomSerializationStrings.NameAttribute, property); } else { if (_firstcall) { WriteStartElement(_writer, CustomSerializationStrings.PSObjectTag); _firstcall = false; } else { WriteStartElement(_writer, CustomSerializationStrings.Properties); } } _writer.WriteEndElement(); } #region known type serialization private void WritePropertyWithNullValue( XmlWriter writer, PSPropertyInfo source, int depth) { WriteStartElement(writer, CustomSerializationStrings.Properties); WriteAttribute(writer, CustomSerializationStrings.NameAttribute, ((PSPropertyInfo)source).Name.ToString()); if (!_notypeinformation) WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, ((PSPropertyInfo)source).TypeNameOfValue.ToString()); writer.WriteEndElement(); } private void WriteObjectString( XmlWriter writer, string property, object source, TypeSerializationInfo entry) { if (property != null) { WriteStartElement(writer, CustomSerializationStrings.Properties); WriteAttribute(writer, CustomSerializationStrings.NameAttribute, property.ToString()); } else { if (_firstcall) { WriteStartElement(writer, CustomSerializationStrings.PSObjectTag); _firstcall = false; } else { WriteStartElement(writer, CustomSerializationStrings.Properties); } } if (!_notypeinformation) WriteAttribute(writer, CustomSerializationStrings.TypeAttribute, source.GetType().ToString()); writer.WriteString(source.ToString()); writer.WriteEndElement(); } /// <summary> /// Writes an item or property in Monad namespace /// </summary> /// <param name="writer">The XmlWriter stream to which the object is serialized.</param> /// <param name="property">name of property. Pass null for item</param> /// <param name="source">object to be written</param> /// <param name="entry">serialization information about source</param> private void WriteOnePrimitiveKnownType( XmlWriter writer, string property, object source, TypeSerializationInfo entry) { WriteObjectString(writer, property, source, entry); } #endregion known type serialization #region misc /// <summary> /// Writes start element in Monad namespace /// </summary> /// <param name="writer"></param> /// <param name="elementTag">tag of element</param> internal static void WriteStartElement(XmlWriter writer, string elementTag) { writer.WriteStartElement(elementTag); } /// <summary> /// Writes attribute in monad namespace /// </summary> /// <param name="writer"></param> /// <param name="name">name of attribute</param> /// <param name="value">value of attribute</param> internal static void WriteAttribute(XmlWriter writer, string name, string value) { writer.WriteAttributeString(name, value); } #endregion misc } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Security; using Xunit; using Xunit.NetCore.Extensions; namespace System.Diagnostics.Tests { public partial class ProcessTests : ProcessTestBase { [Fact] private void TestWindowApisUnix() { // This tests the hardcoded implementations of these APIs on Unix. using (Process p = Process.GetCurrentProcess()) { Assert.True(p.Responding); Assert.Equal(string.Empty, p.MainWindowTitle); Assert.False(p.CloseMainWindow()); Assert.Throws<InvalidOperationException>(()=>p.WaitForInputIdle()); } } [Fact] public void MainWindowHandle_GetUnix_ThrowsPlatformNotSupportedException() { CreateDefaultProcess(); Assert.Equal(IntPtr.Zero, _process.MainWindowHandle); } [Fact] public void TestProcessOnRemoteMachineUnix() { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1")); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1")); } [Theory] [MemberData(nameof(MachineName_Remote_TestData))] public void GetProcessesByName_RemoteMachineNameUnix_ThrowsPlatformNotSupportedException(string machineName) { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, machineName)); } [Fact] public void TestRootGetProcessById() { Process p = Process.GetProcessById(1); Assert.Equal(1, p.Id); } [Fact] [PlatformSpecific(TestPlatforms.Linux)] public void ProcessStart_UseShellExecute_OnLinux_ThrowsIfNoProgramInstalled() { if (!s_allowedProgramsToRun.Any(program => IsProgramInstalled(program))) { Console.WriteLine($"None of the following programs were installed on this machine: {string.Join(",", s_allowedProgramsToRun)}."); Assert.Throws<Win32Exception>(() => Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = Environment.CurrentDirectory })); } } [Fact] [OuterLoop("Opens program")] public void ProcessStart_DirectoryNameInCurDirectorySameAsFileNameInExecDirectory_Success() { string fileToOpen = "dotnet"; string curDir = Environment.CurrentDirectory; string dotnetFolder = Path.Combine(Path.GetTempPath(),"dotnet"); bool shouldDelete = !Directory.Exists(dotnetFolder); try { Directory.SetCurrentDirectory(Path.GetTempPath()); Directory.CreateDirectory(dotnetFolder); using (var px = Process.Start(fileToOpen)) { Assert.NotNull(px); } } finally { if (shouldDelete) { Directory.Delete(dotnetFolder); } Directory.SetCurrentDirectory(curDir); } } [Theory, InlineData(true), InlineData(false)] [OuterLoop("Opens program")] public void ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled(bool isFolder) { string programToOpen = s_allowedProgramsToRun.FirstOrDefault(program => IsProgramInstalled(program)); string fileToOpen; if (isFolder) { fileToOpen = Environment.CurrentDirectory; } else { fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_UseShellExecute_OnUnix_SuccessWhenProgramInstalled)}"); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || programToOpen != null) { using (var px = Process.Start(new ProcessStartInfo { UseShellExecute = true, FileName = fileToOpen })) { Assert.NotNull(px); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) // on OSX, process name is dotnet for some reason. Refer to #23972 { Assert.Equal(programToOpen, px.ProcessName); } px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } } [Theory, InlineData("nano"), InlineData("vi")] [PlatformSpecific(TestPlatforms.Linux)] [OuterLoop("Opens program")] public void ProcessStart_OpenFileOnLinux_UsesSpecifiedProgram(string programToOpenWith) { if (IsProgramInstalled(programToOpenWith)) { string fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnLinux_UsesSpecifiedProgram)}"); using (var px = Process.Start(programToOpenWith, fileToOpen)) { Assert.Equal(programToOpenWith, px.ProcessName); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } else { Console.WriteLine($"Program specified to open file with {programToOpenWith} is not installed on this machine."); } } [Theory, InlineData("/usr/bin/open"), InlineData("/usr/bin/nano")] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens program")] public void ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram(string programToOpenWith) { string fileToOpen = GetTestFilePath() + ".txt"; File.WriteAllText(fileToOpen, $"{nameof(ProcessStart_OpenFileOnOsx_UsesSpecifiedProgram)}"); using (var px = Process.Start(programToOpenWith, fileToOpen)) { // Assert.Equal(programToOpenWith, px.ProcessName); // on OSX, process name is dotnet for some reason. Refer to #23972 Console.WriteLine($"in OSX, {nameof(programToOpenWith)} is {programToOpenWith}, while {nameof(px.ProcessName)} is {px.ProcessName}."); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Theory, InlineData("Safari"), InlineData("\"Google Chrome\"")] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens browser")] public void ProcessStart_OpenUrl_UsesSpecifiedApplication(string applicationToOpenWith) { using (var px = Process.Start("/usr/bin/open", "https://github.com/dotnet/corefx -a " + applicationToOpenWith)) { Assert.NotNull(px); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Theory, InlineData("-a Safari"), InlineData("-a \"Google Chrome\"")] [PlatformSpecific(TestPlatforms.OSX)] [OuterLoop("Opens browser")] public void ProcessStart_UseShellExecuteTrue_OpenUrl_SuccessfullyReadsArgument(string arguments) { var startInfo = new ProcessStartInfo { UseShellExecute = true, FileName = "https://github.com/dotnet/corefx", Arguments = arguments }; using (var px = Process.Start(startInfo)) { Assert.NotNull(px); px.Kill(); px.WaitForExit(); Assert.True(px.HasExited); } } [Fact] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestPriorityClassUnix() { CreateDefaultProcess(); ProcessPriorityClass priorityClass = _process.PriorityClass; _process.PriorityClass = ProcessPriorityClass.Idle; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Idle); try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); _process.PriorityClass = priorityClass; } catch (Win32Exception ex) { Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}"); } } [Fact] [Trait(XunitConstants.Category, XunitConstants.RequiresElevation)] public void TestBasePriorityOnUnix() { CreateDefaultProcess(); ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19); try { SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0); SetAndCheckBasePriority(ProcessPriorityClass.High, -11); _process.PriorityClass = originalPriority; } catch (Win32Exception ex) { Assert.True(!PlatformDetection.IsSuperUser, $"Failed even though superuser {ex.ToString()}"); } } [Fact] public void TestStartOnUnixWithBadPermissions() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Equal(0, chmod(path, 644)); // no execute permissions Win32Exception e = Assert.Throws<Win32Exception>(() => Process.Start(path)); Assert.NotEqual(0, e.NativeErrorCode); } [Fact] public void TestStartOnUnixWithBadFormat() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Equal(0, chmod(path, 744)); // execute permissions using (Process p = Process.Start(path)) { p.WaitForExit(); Assert.NotEqual(0, p.ExitCode); } } [DllImport("libc")] private static extern int chmod(string path, int mode); private readonly string[] s_allowedProgramsToRun = new string[] { "xdg-open", "gnome-open", "kfmclient" }; /// <summary> /// Checks if the program is installed /// </summary> /// <param name="program"></param> /// <returns></returns> private bool IsProgramInstalled(string program) { string path; string pathEnvVar = Environment.GetEnvironmentVariable("PATH"); if (pathEnvVar != null) { var pathParser = new StringParser(pathEnvVar, ':', skipEmpty: true); while (pathParser.MoveNext()) { string subPath = pathParser.ExtractCurrent(); path = Path.Combine(subPath, program); if (File.Exists(path)) { return true; } } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Xml; using System.Collections; using System.Diagnostics; namespace System.Data.Common { internal sealed class ByteStorage : DataStorage { private const byte defaultValue = 0; private byte[] _values; internal ByteStorage(DataColumn column) : base(column, typeof(byte), defaultValue, StorageType.Byte) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: ulong sum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += _values[record]; } hasData = true; } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: long meanSum = defaultValue; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += _values[record]; } meanCount++; hasData = true; } if (hasData) { byte mean; checked { mean = (byte)(meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = defaultValue; double prec = defaultValue; double dsum = defaultValue; double sqrsum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; dsum += _values[record]; sqrsum += _values[record] * (double)_values[record]; count++; } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return _nullValue; case AggregateType.Min: byte min = byte.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; min = Math.Min(_values[record], min); hasData = true; } if (hasData) { return min; } return _nullValue; case AggregateType.Max: byte max = byte.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; max = Math.Max(_values[record], max); hasData = true; } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null; case AggregateType.Count: return base.Aggregate(records, kind); } } catch (OverflowException) { throw ExprException.Overflow(typeof(byte)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { byte valueNo1 = _values[recordNo1]; byte valueNo2 = _values[recordNo2]; if (valueNo1 == defaultValue || valueNo2 == defaultValue) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) return bitCheck; } return valueNo1.CompareTo(valueNo2); } public override int CompareValueTo(int recordNo, object value) { Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { if (IsNull(recordNo)) { return 0; } return 1; } byte valueNo1 = _values[recordNo]; if ((defaultValue == valueNo1) && IsNull(recordNo)) { return -1; } return valueNo1.CompareTo((byte)value); } public override object ConvertValue(object value) { if (_nullValue != value) { if (null != value) { value = ((IConvertible)value).ToByte(FormatProvider); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { byte value = _values[record]; if (value != defaultValue) { return value; } return GetBits(record); } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = defaultValue; SetNullBit(record, true); } else { _values[record] = ((IConvertible)value).ToByte(FormatProvider); SetNullBit(record, false); } } public override void SetCapacity(int capacity) { byte[] newValues = new byte[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } public override object ConvertXmlToObject(string s) { return XmlConvert.ToByte(s); } public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((byte)value); } protected override object GetEmptyStorage(int recordCount) { return new byte[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { byte[] typedStore = (byte[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (byte[])store; SetNullStorage(nullbits); } } }
using System.Collections.Generic; using System.Linq; using Reference.Lib.DataStructures.Trees; namespace Reference.Lib.DataStructures.Heaps { public abstract class BinaryHeap<T> : ArrayBasedBinaryTree<T> { /// <summary> /// Initialize empty heap /// </summary> /// <returns></returns> protected BinaryHeap() { } /// <summary> /// Initialize heap using data, and invoke BuildHeap /// </summary> /// <param name="data"></param> /// <returns></returns> protected BinaryHeap(params T[] data) : base(data) { HeapSize = Store.Count; BuildHeap(); } protected BinaryHeap(IList<T> data) : base(data) { HeapSize = Store.Count; BuildHeap(); } public bool IsValidHeap => HasHeapProperty(0); public int HeapSize { get; internal set; } /// <summary> /// Because a heap is a complete binary tree, /// the index of the first non-leaf node is /// given by the below formula /// </summary> /// <returns></returns> private int IndexOfFirstNonLeafNode => HeapSize / 2 - 1; /// <summary> /// O(n log n) /// </summary> private void BuildHeap() { for (var i = IndexOfFirstNonLeafNode; i >= 0; --i) Heapify(i); } /// <summary> /// Heap property comparison method. Should be /// overridden according to the type of heap desired /// </summary> /// <param name="root"></param> /// <param name="child"></param> /// <returns>true if the Heap property is maintained for root -> child</returns> internal abstract bool HeapProperty(T root, T child); /// <summary> /// Recursively determine if a sub-tree maintains /// the heap property /// </summary> /// <param name="root"></param> /// <returns>true if the sub-tree maintains the heap property</returns> private bool HasHeapProperty(int root) { if (!ElementExists(root)) return true; var leftIdx = GetLeftIndex(root); var rightIdx = GetRightIndex(root); var value = GetElement(root); if (HasLeftChild(root)) if (!HeapProperty(value, GetElement(leftIdx))) return false; if (HasRightChild(root)) if (!HeapProperty(value, GetElement(rightIdx))) return false; return HasHeapProperty(leftIdx) && HasHeapProperty(rightIdx); } private bool HasLeftChild(int root) { return ElementExists(GetLeftIndex(root)); } private bool HasRightChild(int root) { return ElementExists(GetRightIndex(root)); } private bool ElementExists(int idx) { if (idx >= HeapSize || idx < 0) return false; return true; } public void Add(params T[] values) { foreach (var value in values) Add(value); } public void Add(T value) { // add to end of the store Store.Add(value); // heap has increased in size ++HeapSize; // ensure our added value occupies it's // correct position in the heap BubbleUp(HeapSize - 1); } /// <summary> /// O(log n) /// </summary> public void Heapify() { Heapify(0); } /// <summary> /// O(log n) /// </summary> /// <param name="index"></param> public void Heapify(int index) { if (!ElementExists(index)) return; var rootIndex = index; var rootValue = GetElement(index); if (HasLeftChild(index)) { var left = GetElement(GetLeftIndex(index)); if (HeapProperty(left, rootValue)) { rootIndex = GetLeftIndex(index); rootValue = left; } } if (HasRightChild(index)) { var right = GetElement(GetRightIndex(index)); if (HeapProperty(right, rootValue)) rootIndex = GetRightIndex(index); } if (rootIndex == index) return; Swap(index, rootIndex); Heapify(rootIndex); } private void BubbleUp(int idx) { if (!ElementExists(idx)) return; var parent = GetParentIndex(idx); if (!ElementExists(parent)) return; if (HeapProperty(GetElement(parent), GetElement(idx))) return; // heap property not maintained Swap(parent, idx); BubbleUp(parent); } public void Swap(int x, int y) { var buffer = GetElement(x); Store[x] = Store[y]; Store[y] = buffer; } public T[] ToArray() { return Store.ToArray(); } } }
using IntuiLab.Kinect.DataUserTracking; using IntuiLab.Kinect.DataUserTracking.Events; using IntuiLab.Kinect.TUIO; using Microsoft.Kinect; using Microsoft.Kinect.Toolkit.Interaction; using System; using System.Collections.Generic; using System.Windows; namespace IntuiLab.Kinect { /// <summary> /// Mange the user in front of the kinect sensor /// </summary> public partial class KinectModule { #region Fields /// <summary> /// User list tracked by the kinect sensor /// </summary> private Dictionary<int, UserData> m_refListUsers; /// <summary> /// Insatnce of TuioManager for send message to the MGRE /// </summary> private TuioManager m_refTuioManager; #endregion #region Events #region NewHandActive /// <summary> /// Event triggered when a new hand is active /// </summary> public event EventHandler<HandActiveEventArgs> NewHandActive; /// <summary> /// Raise event NewHandActive /// </summary> protected void RaiseNewHandActive(object sender, HandActiveEventArgs e) { if (NewHandActive != null) { NewHandActive(this,e); } } #endregion #region UserHandMove /// <summary> /// Event triggered when user's hand moved /// </summary> public event EventHandler<HandMoveEventArgs> UserHandMove; /// <summary> /// Raise event UserHandMove /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void RaiseUserHandMove(object sender, HandMoveEventArgs e) { if (UserHandMove != null) { UserHandMove(this, e); } } #endregion #region UserHandGripStateChanged /// <summary> /// Event triggered when user's hand grip state changed /// </summary> public event EventHandler<HandGripStateChangeEventArgs> UserHandGripStateChanged; /// <summary> /// Raise event UserHandGripStateChanged /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void RaiseUserHandGripStateChanged(object sender, HandGripStateChangeEventArgs e) { if (UserHandGripStateChanged != null) { UserHandGripStateChanged(this, e); } } #endregion #region NewUserPointing /// <summary> /// Event triggered when a new user in pointing mode is detected. /// This event permit to attribute the hand's feedback id in the Pointingfacade class. /// </summary> public event EventHandler<NewUserPointingEventArgs> NewUserPointing; /// <summary> /// Raise event NewUserPointing /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void RaiseNewUserPointing(object sender, NewUserPointingEventArgs e) { if (NewUserPointing != null) { NewUserPointing(this, e); } } #endregion #region DeleteUserPointing /// <summary> /// Event triggered when a user in pointing mode is deleted. /// This event permit to liberate the hand's feedback id in the Pointingfacade class. /// </summary> public event EventHandler<DeleteUserPointingEventArgs> DeleteUserPointing; /// <summary> /// Raise event DeleteUserPointing /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void RaiseDeleteUserPointing(object sender, DeleteUserPointingEventArgs e) { if (DeleteUserPointing != null) { DeleteUserPointing(this, e); } } #endregion #endregion #region Add User Data /// <summary> /// Add a User /// </summary> /// <param name="refSkeleton">New User's Skeleton</param> /// <param name="depth">Distance User/sensor Kinect</param> /// <param name="timesTamp">Skeleton TimesTamp</param> private void AddUserData(Skeleton refSkeleton, double depth, long timesTamp) { UserDataPointing refNewUser = new UserDataPointing(refSkeleton.TrackingId, refSkeleton, depth, timesTamp); if (PropertiesPluginKinect.Instance.KinectPointingModeEnabled) { // If the user is the first, create the TuioManager if (m_refListUsers.Count == 0) { m_refTuioManager = new TuioManager(); } RaiseNewUserPointing(this, new NewUserPointingEventArgs { UserID = refSkeleton.TrackingId }); refNewUser.UserHandActive += OnUserHandActive; refNewUser.UserHandMove += OnUserHandMove; refNewUser.UserHandGripStateChanged += OnUserHandGripStateChanged; } else { // Grip is also used for Gesture Recognition refNewUser.UserHandGripStateChanged += OnUserHandGripStateChanged; // If recording mode is activated, send the user to the DataUserRecorder if (m_bRecData) { lock (this) { m_refDataUserRecorder.RecordData(refNewUser); } } } // Connect events refNewUser.UserGestureDetected += OnUserGestureDetected; refNewUser.UserGestureProgress += OnUsergestureProgress; refNewUser.UserGestureLost += OnUserGestureLost; refNewUser.UserPositionInColorFrame = SkeletonPointToColorImage(refSkeleton.Joints[JointType.ShoulderCenter].Position); refNewUser.UserPositionInDepthFrame = SkeletonPointToDepthImage(refSkeleton.Joints[JointType.ShoulderCenter].Position); // Add User in system lock (m_refListUsers) { m_refListUsers.Add(refSkeleton.TrackingId, refNewUser); } // Notify new user PropertiesPluginKinect.Instance.UserCounter++; } #endregion #region Modify User Data /// <summary> /// Modify a User /// </summary> /// <param name="nUserID">User ID</param> /// <param name="refSkeleton">New User's Skeleton</param> /// <param name="depth">Distance User/sensor Kinect</param> /// <param name="timesTamp">Skeleton TimesTamp</param> private void ModifyUserData(int nUserID, Skeleton refSkeleton, double depth, long timesTamp) { // Update the DataUser m_refListUsers[nUserID].AddSkeleton(refSkeleton, timesTamp); m_refListUsers[nUserID].UserPositionInColorFrame = SkeletonPointToColorImage(refSkeleton.Joints[JointType.ShoulderCenter].Position); m_refListUsers[nUserID].UserPositionInDepthFrame = SkeletonPointToDepthImage(refSkeleton.Joints[JointType.ShoulderCenter].Position); m_refListUsers[nUserID].UserDepth = depth; // If recording mode is activating, send the user to the DataUserRecorder if (m_bRecData) { lock (this) { m_refDataUserRecorder.RecordData(m_refListUsers[nUserID]); } } } #endregion #region Delete User Data /// <summary> /// Delete a User /// </summary> /// <param name="nUserID">User ID</param> private void DeleteUserData(int nUserID) { // Disconect user events m_refListUsers[nUserID].UserGestureDetected -= OnUserGestureDetected; m_refListUsers[nUserID].UserGestureProgress -= OnUsergestureProgress; m_refListUsers[nUserID].UserGestureLost -= OnUserGestureLost; // If the Pointing mode is enabled, disconnect event of tjis mode if ((m_refListUsers[nUserID] as UserDataPointing) != null) { (m_refListUsers[nUserID] as UserDataPointing).UserHandActive -= OnUserHandActive; (m_refListUsers[nUserID] as UserDataPointing).UserHandMove -= OnUserHandMove; (m_refListUsers[nUserID] as UserDataPointing).UserHandGripStateChanged -= OnUserHandGripStateChanged; (m_refListUsers[nUserID] as UserDataPointing).DisposeUserDataPointing(); // If this user is the last in fornt of the Kinect sensor, destroy the TuioManager if (m_refListUsers.Count == 1) { if (m_refTuioManager != null) { m_refTuioManager.Dispose(); } } RaiseDeleteUserPointing(this, new DeleteUserPointingEventArgs { UserID = nUserID }); } else { // Dispose the UserData m_refListUsers[nUserID].Dispose(); } // Remove user in system lock (m_refListUsers) { m_refListUsers.Remove(nUserID); } // Notify remove user PropertiesPluginKinect.Instance.UserCounter--; } #endregion #region Skeleton Point Converter /// <summary> /// Get back the SkeletonPoint position in the ColorFrame /// </summary> /// <param name="point">The SkeletonPoint to treat</param> /// <returns></returns> private Point SkeletonPointToColorImage(SkeletonPoint point) { ColorImagePoint colorPoint = m_refKinectsensor.CoordinateMapper.MapSkeletonPointToColorPoint(point, ColorImageFormat.RgbResolution640x480Fps30); return new Point(colorPoint.X, colorPoint.Y); } /// <summary> /// Get back the SkeletonPoint position in the DepthFrame /// </summary> /// <param name="point">The SkeletonPoint to treat</param> /// <returns></returns> private Point SkeletonPointToDepthImage(SkeletonPoint point) { DepthImagePoint depthPoint = m_refKinectsensor.CoordinateMapper.MapSkeletonPointToDepthPoint(point, DepthImageFormat.Resolution640x480Fps30); return new Point(depthPoint.X, depthPoint.Y); } #endregion #region Event's Handler /// <summary> /// Callback when a hand's user is active. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnUserHandActive(object sender, HandActiveEventArgs e) { RaiseNewHandActive(this, e); // If the hand is became inactive and it's in grip state, // we delete the hand in TuioManager if (!e.IsActive) { if (e.HandType == InteractionHandType.Left) { m_refTuioManager.DeleteHandTuioKinect(e.userID); } else if (e.HandType == InteractionHandType.Right) { m_refTuioManager.DeleteHandTuioKinect(e.userID * 100); } } } /// <summary> /// Callback when an user's hand moved /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnUserHandMove(object sender, HandMoveEventArgs e) { RaiseUserHandMove(this, e); // If the hand is in grip state, send TuioMessage for the MGRE if (m_refTuioManager != null && e.IsGrip) { if(e.HandType == InteractionHandType.Left) { m_refTuioManager.UpdateHandTuioKinect(e.userID, e.RawPosition); } else if (e.HandType == InteractionHandType.Right) { m_refTuioManager.UpdateHandTuioKinect(e.userID * 100, e.RawPosition); } } } /// <summary> /// Callback when an user's hand grip state changed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnUserHandGripStateChanged(object sender, HandGripStateChangeEventArgs e) { RaiseUserHandGripStateChanged(this, e); if (m_refTuioManager != null) { // If the the hand is grip, send message to MGRE for update the data if (e.IsGrip) { if (e.HandType == InteractionHandType.Left) { m_refTuioManager.AddTuioHandKinect(e.userID, e.RawPosition); } else if (e.HandType == InteractionHandType.Right) { m_refTuioManager.AddTuioHandKinect(e.userID * 100, e.RawPosition); } } else // if the hand is not grip, send message to MGRE for stop the interaction { if (e.HandType == InteractionHandType.Left) { m_refTuioManager.DeleteHandTuioKinect(e.userID); } else if (e.HandType == InteractionHandType.Right) { m_refTuioManager.DeleteHandTuioKinect(e.userID * 100); } } } } #endregion } }
using System; using System.Diagnostics; namespace Lucene.Net.Util.Packed { /* * 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. */ /// <summary> /// Common functionality shared by <see cref="AppendingDeltaPackedInt64Buffer"/> and <see cref="MonotonicAppendingInt64Buffer"/>. /// <para/> /// NOTE: This was AbstractAppendingLongBuffer in Lucene /// </summary> public abstract class AbstractAppendingInt64Buffer : Int64Values // LUCENENET NOTE: made public rather than internal because has public subclasses { internal const int MIN_PAGE_SIZE = 64; // More than 1M doesn't really makes sense with these appending buffers // since their goal is to try to have small numbers of bits per value internal static readonly int MAX_PAGE_SIZE = 1 << 20; internal readonly int pageShift, pageMask; internal PackedInt32s.Reader[] values; private long valuesBytes; internal int valuesOff; internal long[] pending; internal int pendingOff; internal float acceptableOverheadRatio; internal AbstractAppendingInt64Buffer(int initialBlockCount, int pageSize, float acceptableOverheadRatio) { values = new PackedInt32s.Reader[initialBlockCount]; pending = new long[pageSize]; pageShift = PackedInt32s.CheckBlockSize(pageSize, MIN_PAGE_SIZE, MAX_PAGE_SIZE); pageMask = pageSize - 1; valuesOff = 0; pendingOff = 0; this.acceptableOverheadRatio = acceptableOverheadRatio; } public int PageSize => pageMask + 1; /// <summary> /// Get the number of values that have been added to the buffer. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> public long Count { get { long size = pendingOff; if (valuesOff > 0) { size += values[valuesOff - 1].Count; } if (valuesOff > 1) { size += (long)(valuesOff - 1) * PageSize; } return size; } } /// <summary> /// Append a value to this buffer. </summary> public void Add(long l) { if (pending == null) { throw new Exception("this buffer is frozen"); } if (pendingOff == pending.Length) { // check size if (values.Length == valuesOff) { int newLength = ArrayUtil.Oversize(valuesOff + 1, 8); Grow(newLength); } PackPendingValues(); valuesBytes += values[valuesOff].RamBytesUsed(); ++valuesOff; // reset pending buffer pendingOff = 0; } pending[pendingOff++] = l; } internal virtual void Grow(int newBlockCount) { Array.Resize<PackedInt32s.Reader>(ref values, newBlockCount); } internal abstract void PackPendingValues(); public override sealed long Get(long index) { Debug.Assert(index >= 0 && index < Count); int block = (int)(index >> pageShift); int element = (int)(index & pageMask); return Get(block, element); } /// <summary> /// Bulk get: read at least one and at most <paramref name="len"/> <see cref="long"/>s starting /// from <paramref name="index"/> into <c>arr[off:off+len]</c> and return /// the actual number of values that have been read. /// </summary> public int Get(long index, long[] arr, int off, int len) { Debug.Assert(len > 0, "len must be > 0 (got " + len + ")"); Debug.Assert(index >= 0 && index < Count); Debug.Assert(off + len <= arr.Length); int block = (int)(index >> pageShift); int element = (int)(index & pageMask); return Get(block, element, arr, off, len); } internal abstract long Get(int block, int element); internal abstract int Get(int block, int element, long[] arr, int off, int len); /// <summary> /// Return an iterator over the values of this buffer. /// </summary> public virtual Iterator GetIterator() { return new Iterator(this); } public sealed class Iterator { private readonly AbstractAppendingInt64Buffer outerInstance; internal long[] currentValues; internal int vOff, pOff; internal int currentCount; // number of entries of the current page internal Iterator(AbstractAppendingInt64Buffer outerInstance) { this.outerInstance = outerInstance; vOff = pOff = 0; if (outerInstance.valuesOff == 0) { currentValues = outerInstance.pending; currentCount = outerInstance.pendingOff; } else { currentValues = new long[outerInstance.values[0].Count]; FillValues(); } } internal void FillValues() { if (vOff == outerInstance.valuesOff) { currentValues = outerInstance.pending; currentCount = outerInstance.pendingOff; } else { currentCount = outerInstance.values[vOff].Count; for (int k = 0; k < currentCount; ) { k += outerInstance.Get(vOff, k, currentValues, k, currentCount - k); } } } /// <summary> /// Whether or not there are remaining values. </summary> public bool HasNext => pOff < currentCount; /// <summary> /// Return the next long in the buffer. </summary> public long Next() { Debug.Assert(HasNext); long result = currentValues[pOff++]; if (pOff == currentCount) { vOff += 1; pOff = 0; if (vOff <= outerInstance.valuesOff) { FillValues(); } else { currentCount = 0; } } return result; } } internal virtual long BaseRamBytesUsed() { return RamUsageEstimator.NUM_BYTES_OBJECT_HEADER + 2 * RamUsageEstimator.NUM_BYTES_OBJECT_REF + 2 * RamUsageEstimator.NUM_BYTES_INT32 + 2 * RamUsageEstimator.NUM_BYTES_INT32 + RamUsageEstimator.NUM_BYTES_SINGLE + RamUsageEstimator.NUM_BYTES_INT64; // valuesBytes - acceptable overhead - pageShift, pageMask - the 2 offsets - the 2 arrays } /// <summary> /// Return the number of bytes used by this instance. </summary> public virtual long RamBytesUsed() { // TODO: this is called per-doc-per-norms/dv-field, can we optimize this? long bytesUsed = RamUsageEstimator.AlignObjectSize(BaseRamBytesUsed()) + (pending != null ? RamUsageEstimator.SizeOf(pending) : 0L) + RamUsageEstimator.AlignObjectSize(RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + (long)RamUsageEstimator.NUM_BYTES_OBJECT_REF * values.Length); // values return bytesUsed + valuesBytes; } /// <summary> /// Pack all pending values in this buffer. Subsequent calls to <see cref="Add(long)"/> will fail. </summary> public virtual void Freeze() { if (pendingOff > 0) { if (values.Length == valuesOff) { Grow(valuesOff + 1); // don't oversize! } PackPendingValues(); valuesBytes += values[valuesOff].RamBytesUsed(); ++valuesOff; pendingOff = 0; } pending = null; } } }
/* * 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 OpenMetaverse; using System; using System.Reflection; using System.Xml.Serialization; namespace OpenSim.Framework { [Flags] public enum AssetFlags : int { Normal = 0, // Immutable asset Maptile = 1, // What it says Rewritable = 2, // Content can be rewritten Collectable = 4 // Can be GC'ed after some time } /// <summary> /// Asset class. All Assets are reference by this class or a class derived from this class /// </summary> [Serializable] public class AssetBase { public static readonly int MAX_ASSET_DESC = 64; public static readonly int MAX_ASSET_NAME = 64; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Data of the Asset /// </summary> private byte[] m_data; /// <summary> /// Meta Data of the Asset /// </summary> private AssetMetadata m_metadata; // This is needed for .NET serialization!!! // Do NOT "Optimize" away! public AssetBase() { m_metadata = new AssetMetadata(); m_metadata.FullID = UUID.Zero; m_metadata.ID = UUID.Zero.ToString(); m_metadata.Type = (sbyte)AssetType.Unknown; m_metadata.CreatorID = String.Empty; } public AssetBase(UUID assetID, string name, sbyte assetType, string creatorID) { if (assetType == (sbyte)AssetType.Unknown) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true); m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace.ToString()); } m_metadata = new AssetMetadata(); m_metadata.FullID = assetID; m_metadata.Name = name; m_metadata.Type = assetType; m_metadata.CreatorID = creatorID; } public AssetBase(string assetID, string name, sbyte assetType, string creatorID) { if (assetType == (sbyte)AssetType.Unknown) { System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(true); m_log.ErrorFormat("[ASSETBASE]: Creating asset '{0}' ({1}) with an unknown asset type\n{2}", name, assetID, trace.ToString()); } m_metadata = new AssetMetadata(); m_metadata.ID = assetID; m_metadata.Name = name; m_metadata.Type = assetType; m_metadata.CreatorID = creatorID; } public bool ContainsReferences { get { return IsTextualAsset && ( Type != (sbyte)AssetType.Notecard && Type != (sbyte)AssetType.CallingCard && Type != (sbyte)AssetType.LSLText && Type != (sbyte)AssetType.Landmark); } } public string CreatorID { get { return m_metadata.CreatorID; } set { m_metadata.CreatorID = value; } } public virtual byte[] Data { get { return m_data; } set { m_data = value; } } public string Description { get { return m_metadata.Description; } set { m_metadata.Description = value; } } public AssetFlags Flags { get { return m_metadata.Flags; } set { m_metadata.Flags = value; } } /// <summary> /// Asset UUID /// </summary> public UUID FullID { get { return m_metadata.FullID; } set { m_metadata.FullID = value; } } /// <summary> /// Asset MetaData ID (transferring from UUID to string ID) /// </summary> public string ID { get { return m_metadata.ID; } set { m_metadata.ID = value; } } /// <summary> /// Checks if this asset is a binary or text asset /// </summary> public bool IsBinaryAsset { get { return (Type == (sbyte)AssetType.Animation || Type == (sbyte)AssetType.Gesture || Type == (sbyte)AssetType.Simstate || Type == (sbyte)AssetType.Unknown || Type == (sbyte)AssetType.Object || Type == (sbyte)AssetType.Sound || Type == (sbyte)AssetType.SoundWAV || Type == (sbyte)AssetType.Texture || Type == (sbyte)AssetType.TextureTGA || Type == (sbyte)AssetType.Folder || Type == (sbyte)AssetType.RootFolder || Type == (sbyte)AssetType.LostAndFoundFolder || Type == (sbyte)AssetType.SnapshotFolder || Type == (sbyte)AssetType.TrashFolder || Type == (sbyte)AssetType.ImageJPEG || Type == (sbyte)AssetType.ImageTGA || Type == (sbyte)AssetType.LSLBytecode); } } public bool IsTextualAsset { get { return !IsBinaryAsset; } } /// <summary> /// Is this a region only asset, or does this exist on the asset server also /// </summary> public bool Local { get { return m_metadata.Local; } set { m_metadata.Local = value; } } [XmlIgnore] public AssetMetadata Metadata { get { return m_metadata; } set { m_metadata = value; } } public string Name { get { return m_metadata.Name; } set { m_metadata.Name = value; } } /// <summary> /// Is this asset going to be saved to the asset database? /// </summary> public bool Temporary { get { return m_metadata.Temporary; } set { m_metadata.Temporary = value; } } /// <summary> /// (sbyte) AssetType enum /// </summary> public sbyte Type { get { return m_metadata.Type; } set { m_metadata.Type = value; } } public override string ToString() { return FullID.ToString(); } } [Serializable] public class AssetMetadata { private string m_content_type; private DateTime m_creation_date; private string m_creatorid; private string m_description = String.Empty; private AssetFlags m_flags; private UUID m_fullid; private string m_id; private bool m_local; private string m_name = String.Empty; private byte[] m_sha1; private bool m_temporary; private sbyte m_type = (sbyte)AssetType.Unknown; public string ContentType { get { if (!String.IsNullOrEmpty(m_content_type)) return m_content_type; else return SLUtil.SLAssetTypeToContentType(m_type); } set { m_content_type = value; sbyte type = (sbyte)SLUtil.ContentTypeToSLAssetType(value); if (type != -1) m_type = type; } } public DateTime CreationDate { get { return m_creation_date; } set { m_creation_date = value; } } public string CreatorID { get { return m_creatorid; } set { m_creatorid = value; } } public string Description { get { return m_description; } set { m_description = value; } } public AssetFlags Flags { get { return m_flags; } set { m_flags = value; } } public UUID FullID { get { return m_fullid; } set { m_fullid = value; m_id = m_fullid.ToString(); } } public string ID { //get { return m_fullid.ToString(); } //set { m_fullid = new UUID(value); } get { if (String.IsNullOrEmpty(m_id)) m_id = m_fullid.ToString(); return m_id; } set { UUID uuid = UUID.Zero; if (UUID.TryParse(value, out uuid)) { m_fullid = uuid; m_id = m_fullid.ToString(); } else m_id = value; } } public bool Local { get { return m_local; } set { m_local = value; } } public string Name { get { return m_name; } set { m_name = value; } } public byte[] SHA1 { get { return m_sha1; } set { m_sha1 = value; } } public bool Temporary { get { return m_temporary; } set { m_temporary = value; } } public sbyte Type { get { return m_type; } set { m_type = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Fonts.cs // // Authors: // Alexandre Pigolkine (pigolkine@gmx.de) // Miguel de Icaza (miguel@ximian.com) // Todd Berman (tberman@sevenl.com) // Jordi Mas i Hernandez (jordi@ximian.com) // Ravindra (rkumar@novell.com) // // Copyright (C) 2004 Ximian, Inc. (http://www.ximian.com) // Copyright (C) 2004, 2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Reflection; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.ComponentModel; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { #if !NETCORE [Editor ("System.Drawing.Design.FontEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))] [TypeConverter (typeof (FontConverter))] #endif public sealed partial class Font { private const byte DefaultCharSet = 1; private static int CharSetOffset = -1; private void CreateFont(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte charSet, bool isVertical) { _originalFontName = familyName; FontFamily family; // NOTE: If family name is null, empty or invalid, // MS creates Microsoft Sans Serif font. try { family = new FontFamily(familyName); } catch (Exception) { family = FontFamily.GenericSansSerif; } setProperties(family, emSize, style, unit, charSet, isVertical); int status = Gdip.GdipCreateFont(new HandleRef(this, family.NativeFamily), emSize, style, unit, out _nativeFont); if (status == Gdip.FontStyleNotFound) throw new ArgumentException(string.Format("Style {0} isn't supported by font {1}.", style.ToString(), familyName)); Gdip.CheckStatus(status); } internal void unitConversion(GraphicsUnit fromUnit, GraphicsUnit toUnit, float nSrc, out float nTrg) { float inchs = 0; nTrg = 0; switch (fromUnit) { case GraphicsUnit.Display: inchs = nSrc / 75f; break; case GraphicsUnit.Document: inchs = nSrc / 300f; break; case GraphicsUnit.Inch: inchs = nSrc; break; case GraphicsUnit.Millimeter: inchs = nSrc / 25.4f; break; case GraphicsUnit.Pixel: case GraphicsUnit.World: inchs = nSrc / Graphics.systemDpiX; break; case GraphicsUnit.Point: inchs = nSrc / 72f; break; default: throw new ArgumentException("Invalid GraphicsUnit"); } switch (toUnit) { case GraphicsUnit.Display: nTrg = inchs * 75; break; case GraphicsUnit.Document: nTrg = inchs * 300; break; case GraphicsUnit.Inch: nTrg = inchs; break; case GraphicsUnit.Millimeter: nTrg = inchs * 25.4f; break; case GraphicsUnit.Pixel: case GraphicsUnit.World: nTrg = inchs * Graphics.systemDpiX; break; case GraphicsUnit.Point: nTrg = inchs * 72; break; default: throw new ArgumentException("Invalid GraphicsUnit"); } } void setProperties(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte charSet, bool isVertical) { _fontFamily = family; _fontSize = emSize; // MS throws ArgumentException, if unit is set to GraphicsUnit.Display _fontUnit = unit; _fontStyle = style; _gdiCharSet = charSet; _gdiVerticalFont = isVertical; unitConversion(unit, GraphicsUnit.Point, emSize, out _fontSizeInPoints); } public static Font FromHfont(IntPtr hfont) { IntPtr newObject; FontStyle newStyle = FontStyle.Regular; float newSize; SafeNativeMethods.LOGFONT lf = new SafeNativeMethods.LOGFONT(); // Sanity. Should we throw an exception? if (hfont == IntPtr.Zero) { Font result = new Font("Arial", (float)10.0, FontStyle.Regular); return (result); } // If we're on Unix we use our private gdiplus API to avoid Wine // dependencies in S.D int s = Gdip.GdipCreateFontFromHfont(hfont, out newObject, ref lf); Gdip.CheckStatus(s); if (lf.lfItalic != 0) { newStyle |= FontStyle.Italic; } if (lf.lfUnderline != 0) { newStyle |= FontStyle.Underline; } if (lf.lfStrikeOut != 0) { newStyle |= FontStyle.Strikeout; } if (lf.lfWeight > 400) { newStyle |= FontStyle.Bold; } if (lf.lfHeight < 0) { newSize = lf.lfHeight * -1; } else { newSize = lf.lfHeight; } return (new Font(newObject, lf.lfFaceName, newStyle, newSize)); } public IntPtr ToHfont() { if (_nativeFont == IntPtr.Zero) throw new ArgumentException("Object has been disposed."); return _nativeFont; } internal Font(IntPtr nativeFont, string familyName, FontStyle style, float size) { FontFamily fontFamily; try { fontFamily = new FontFamily(familyName); } catch (Exception) { fontFamily = FontFamily.GenericSansSerif; } setProperties(fontFamily, size, style, GraphicsUnit.Pixel, 0, false); _nativeFont = nativeFont; } public Font(Font prototype, FontStyle newStyle) { // no null checks, MS throws a NullReferenceException if original is null setProperties(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, prototype.GdiCharSet, prototype.GdiVerticalFont); int status = Gdip.GdipCreateFont(new HandleRef(_fontFamily, _fontFamily.NativeFamily), Size, Style, Unit, out _nativeFont); Gdip.CheckStatus(status); } public Font(FontFamily family, float emSize, GraphicsUnit unit) : this(family, emSize, FontStyle.Regular, unit, DefaultCharSet, false) { } public Font(string familyName, float emSize, GraphicsUnit unit) : this(new FontFamily(familyName), emSize, FontStyle.Regular, unit, DefaultCharSet, false) { } public Font(FontFamily family, float emSize) : this(family, emSize, FontStyle.Regular, GraphicsUnit.Point, DefaultCharSet, false) { } public Font(FontFamily family, float emSize, FontStyle style) : this(family, emSize, style, GraphicsUnit.Point, DefaultCharSet, false) { } public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit) : this(family, emSize, style, unit, DefaultCharSet, false) { } public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) : this(family, emSize, style, unit, gdiCharSet, false) { } public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (family == null) throw new ArgumentNullException(nameof(family)); int status; setProperties(family, emSize, style, unit, gdiCharSet, gdiVerticalFont); status = Gdip.GdipCreateFont(new HandleRef(this, family.NativeFamily), emSize, style, unit, out _nativeFont); Gdip.CheckStatus(status); } public Font(string familyName, float emSize) : this(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, DefaultCharSet, false) { } public Font(string familyName, float emSize, FontStyle style) : this(familyName, emSize, style, GraphicsUnit.Point, DefaultCharSet, false) { } public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit) : this(familyName, emSize, style, unit, DefaultCharSet, false) { } public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) : this(familyName, emSize, style, unit, gdiCharSet, false) { } public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { CreateFont(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont); } internal Font(string familyName, float emSize, string systemName) : this(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, DefaultCharSet, false) { _systemFontName = systemName; } public object Clone() { return new Font(this, Style); } private float _fontSizeInPoints; [Browsable(false)] public float SizeInPoints => _fontSizeInPoints; public static Font FromHdc(IntPtr hdc) { throw new NotImplementedException(); } public static Font FromLogFont(object lf, IntPtr hdc) { IntPtr newObject; SafeNativeMethods.LOGFONT o = (SafeNativeMethods.LOGFONT)lf; int status = Gdip.GdipCreateFontFromLogfont(hdc, ref o, out newObject); Gdip.CheckStatus(status); return new Font(newObject, "Microsoft Sans Serif", FontStyle.Regular, 10); } public float GetHeight() { return GetHeight(Graphics.systemDpiY); } public static Font FromLogFont(object lf) { return FromLogFont(lf, IntPtr.Zero); } public void ToLogFont(object logFont) { // Unix - We don't have a window we could associate the DC with // so we use an image instead using (Bitmap img = new Bitmap(1, 1, Imaging.PixelFormat.Format32bppArgb)) { using (Graphics g = Graphics.FromImage(img)) { ToLogFont(logFont, g); } } } public void ToLogFont(object logFont, Graphics graphics) { if (graphics == null) throw new ArgumentNullException(nameof(graphics)); if (logFont == null) { throw new AccessViolationException(nameof(logFont)); } Type st = logFont.GetType(); if (!st.GetTypeInfo().IsLayoutSequential) throw new ArgumentException(nameof(logFont), "Layout must be sequential."); // note: there is no exception if 'logFont' isn't big enough Type lf = typeof(LOGFONT); int size = Marshal.SizeOf(logFont); if (size >= Marshal.SizeOf(lf)) { int status; IntPtr copy = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(logFont, copy, false); status = Gdip.GdipGetLogFontW(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), logFont); if (status != Gdip.Ok) { // reset to original values Marshal.PtrToStructure(copy, logFont); } } finally { Marshal.FreeHGlobal(copy); } if (CharSetOffset == -1) { // not sure why this methods returns an IntPtr since it's an offset // anyway there's no issue in downcasting the result into an int32 CharSetOffset = (int)Marshal.OffsetOf(lf, "lfCharSet"); } // note: Marshal.WriteByte(object,*) methods are unimplemented on Mono GCHandle gch = GCHandle.Alloc(logFont, GCHandleType.Pinned); try { IntPtr ptr = gch.AddrOfPinnedObject(); // if GDI+ lfCharSet is 0, then we return (S.D.) 1, otherwise the value is unchanged if (Marshal.ReadByte(ptr, CharSetOffset) == 0) { // set lfCharSet to 1 Marshal.WriteByte(ptr, CharSetOffset, 1); } } finally { gch.Free(); } // now we can throw, if required Gdip.CheckStatus(status); } } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.MasterSetup.DS { public class MST_DepartmentDS { public MST_DepartmentDS() { } private const string THIS = "PCSComUtils.MasterSetup.DS.MST_DepartmentDS"; //************************************************************************** /// <Description> /// This method uses to add data to MST_Department /// </Description> /// <Inputs> /// MST_DepartmentVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { MST_DepartmentVO objObject = (MST_DepartmentVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO MST_Department(" + MST_DepartmentTable.CODE_FLD + "," + MST_DepartmentTable.NAME_FLD + ")" + "VALUES(?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DepartmentTable.CODE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DepartmentTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DepartmentTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DepartmentTable.NAME_FLD].Value = objObject.Name; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from MST_Department /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + MST_DepartmentTable.TABLE_NAME + " WHERE " + "DepartmentID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from MST_Department /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// MST_DepartmentVO /// </Outputs> /// <Returns> /// MST_DepartmentVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MST_DepartmentTable.DEPARTMENTID_FLD + "," + MST_DepartmentTable.CODE_FLD + "," + MST_DepartmentTable.NAME_FLD + " FROM " + MST_DepartmentTable.TABLE_NAME +" WHERE " + MST_DepartmentTable.DEPARTMENTID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); MST_DepartmentVO objObject = new MST_DepartmentVO(); while (odrPCS.Read()) { objObject.DepartmentID = int.Parse(odrPCS[MST_DepartmentTable.DEPARTMENTID_FLD].ToString().Trim()); objObject.Code = odrPCS[MST_DepartmentTable.CODE_FLD].ToString().Trim(); objObject.Name = odrPCS[MST_DepartmentTable.NAME_FLD].ToString().Trim(); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to MST_Department /// </Description> /// <Inputs> /// MST_DepartmentVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; MST_DepartmentVO objObject = (MST_DepartmentVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE MST_Department SET " + MST_DepartmentTable.CODE_FLD + "= ?" + "," + MST_DepartmentTable.NAME_FLD + "= ?" +" WHERE " + MST_DepartmentTable.DEPARTMENTID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DepartmentTable.CODE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DepartmentTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DepartmentTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_DepartmentTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(MST_DepartmentTable.DEPARTMENTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_DepartmentTable.DEPARTMENTID_FLD].Value = objObject.DepartmentID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from MST_Department /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MST_DepartmentTable.DEPARTMENTID_FLD + "," + MST_DepartmentTable.CODE_FLD + "," + MST_DepartmentTable.NAME_FLD + " FROM " + MST_DepartmentTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,MST_DepartmentTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + MST_DepartmentTable.DEPARTMENTID_FLD + "," + MST_DepartmentTable.CODE_FLD + "," + MST_DepartmentTable.NAME_FLD + " FROM " + MST_DepartmentTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,MST_DepartmentTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using SquaredEngine.Common; using SquaredEngine.Diagnostics.Debug; using SquaredEngine.GameBoard.Components; using SquaredEngine.Graphics; using SquaredEngine.Input; using SquaredEngine.Utils.Trees.QuadTree; using SquaredEngine.Diagnostics.Log; using IDrawable = SquaredEngine.Graphics.IDrawable; namespace Squared { public class GameStart : Game { private readonly GraphicsDeviceManager graphics; public String ID { get; private set; } private LoggerInstance log; private Camera2D camera; private CameraDebuger cameraDebuger; private GraphicsDrawer graphicsDrawer; private MouseState prevState; private KeyboardController keyboardController; private GamePadController gamePadController; private int previousZoom; private TimeController time; private TimeDebuger timeDebuger; public GameStart() { ID = Guid.NewGuid().ToString(); this.log = new LoggerInstance(typeof(GameStart), ID); graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Data"; IsFixedTimeStep = false; graphics.SynchronizeWithVerticalRetrace = false; graphics.PreferredBackBufferHeight = 768; graphics.PreferredBackBufferWidth = 1024; graphics.ApplyChanges(); } protected override void Initialize() { this.log.WriteInformation("Initializing..."); GraphicsDevice.DeviceReset += (s, e) => LoadContent(); IsMouseVisible = true; time = new TimeController(this); timeDebuger = new TimeDebuger(this); camera = new Camera2D(this); camera.OnMoveStarted += (s, e) => this.log.WriteDebugInformation("Camera move started..."); camera.OnMoveEnded += (s, e) => this.log.WriteDebugInformation("Camera move ended!"); cameraDebuger = new CameraDebuger(this, camera, new Range(5000, 5000)); keyboardController = new KeyboardController(this); gamePadController = new GamePadController(this); // ------------ TEST -------------- GenerateCurve(); // ------------ TEST -------------- RegisterComponents(); base.Initialize(); this.log.WriteInformation("Initialized..."); } private void RegisterComponents() { Components.Add(time); Components.Add(timeDebuger); Components.Add(camera); Components.Add(cameraDebuger); Components.Add(keyboardController); Components.Add(gamePadController); } protected override void LoadContent() { graphicsDrawer = new GraphicsDrawer(GraphicsDevice) { DebugFont = Content.Load<SpriteFont>("Fonts/DebugFont") }; timeDebuger.Position = new Vector3(0f, GraphicsDevice.Viewport.Height - TimeDebuger.GraphHeight, 0f); cameraDebuger.Position = new Vector2(GraphicsDevice.Viewport.Width - CameraDebuger.ComponentWidth, 0f); } protected override void Update(GameTime gameTime) { // TODO: Dodati InputController za mis // TODO: Objediniti kontrolere za mis i tipkovnicu // NOTE: Kasnije bi trebalo dodati InputManager.Touch za WP7 platformu if (keyboardController.Keyboard.IsKeyDown(Keys.Escape)) { Exit(); } MouseState state = Mouse.GetState(); int delta = previousZoom - state.ScrollWheelValue; previousZoom = state.ScrollWheelValue; prevState = state; #if DEBUG if (keyboardController.IsClicked(Keys.F11)) { if (graphics.IsFullScreen) { graphics.PreferredBackBufferHeight = 768; graphics.PreferredBackBufferWidth = 1024; } else { graphics.PreferredBackBufferHeight = GraphicsDevice.Adapter.CurrentDisplayMode.Height; graphics.PreferredBackBufferWidth = GraphicsDevice.Adapter.CurrentDisplayMode.Width; } graphics.IsFullScreen = !graphics.IsFullScreen; graphics.ApplyChanges(); } if (keyboardController.IsHeld(Keys.F12)) { if (keyboardController.IsClicked(Keys.C)) { cameraDebuger.Enabled = !cameraDebuger.Enabled; } if (keyboardController.IsClicked(Keys.T)) { timeDebuger.Enabled = !timeDebuger.Enabled; } } #endif base.Update(gameTime); #if DEBUG //Console.WriteLine(gamePadController.ToString(true)); #endif } List<Vector3> points = new List<Vector3>() { new Vector3(50, 50, 0), new Vector3(50, 50, 0), new Vector3(70, 70, 0), new Vector3(120, 120, 0), new Vector3(300, 25, 0), new Vector3(500, 125, 0), new Vector3(500, 125, 0) }; private Vector3 GetNextPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float amt) { return new Vector3( MathHelper.CatmullRom(p0.X, p1.X, p2.X, p3.X, amt), MathHelper.CatmullRom(p0.Y, p1.Y, p2.Y, p3.Y, amt), MathHelper.CatmullRom(p0.Z, p1.Z, p2.Z, p3.Z, amt)); } List<Vector3> curvedPoints = new List<Vector3>(); private void GenerateCurve() { //curvedPoints.AddRange(points); for (int m = 0; m < points.Count - 3; m++) { Vector3 a = points[m + 1]; Vector3 b = points[m + 2]; float amount; Vector3.Distance(ref a, ref b, out amount); amount = 1 / (amount / 10) / 1.5f; Console.WriteLine(amount); for (float i = 0; i < 1; i += amount) { curvedPoints.Add(GetNextPoint(points[m], points[m + 1], points[m + 2], points[m + 3], i)); } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // TODO: Dodati GetDebug za svaku komponentu graphicsDrawer.Begin(); Vector2 position; String text; position = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); text = (new Vector2(Mouse.GetState().X, Mouse.GetState().Y)).ToString(); graphicsDrawer.Write(text, position); graphicsDrawer.End(); graphicsDrawer.Begin(); foreach (var point in curvedPoints) { graphicsDrawer.Draw(new Ellipse(point, 3f, 3f, Color.Red)); } for (int i = 0; i < curvedPoints.Count - 1; i++) { graphicsDrawer.Draw(new GraphicsDrawer.Line(curvedPoints[i], curvedPoints[i + 1], Color.Red)); } foreach (var point in points) { graphicsDrawer.Draw(new Ellipse(point, 2f, 2f, Color.Blue)); } for (int i = 0; i < points.Count - 1; i++) { graphicsDrawer.Draw(new GraphicsDrawer.Line(points[i], points[i + 1], Color.Blue)); } //x DrawChildren(graphicsDrawer, groundBoard.RootNode); graphicsDrawer.End(); graphicsDrawer.Begin(); graphicsDrawer.Write(gamePadController.ToString(true), new Vector2(20)); graphicsDrawer.End(); base.Draw(gameTime); } private static void DrawChildren<K>(GraphicsDrawer gd, INode<K> node) where K : IComponent { int mult = 32; IDrawable nodeQuad = new RectangleOutline(node.Range.UpperLeft * mult, node.Range.Width * mult, node.HasComponents ? Color.Blue : Color.Red); gd.Draw(nodeQuad); foreach (var child in node.Children) { DrawChildren<K>(gd, child); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Specialized; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; 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.UserInterface; using osuTK; namespace osu.Game.Collections { /// <summary> /// A dropdown to select the <see cref="CollectionFilterMenuItem"/> to filter beatmaps using. /// </summary> public class CollectionFilterDropdown : OsuDropdown<CollectionFilterMenuItem> { /// <summary> /// Whether to show the "manage collections..." menu item in the dropdown. /// </summary> protected virtual bool ShowManageCollectionsItem => true; private readonly BindableWithCurrent<CollectionFilterMenuItem> current = new BindableWithCurrent<CollectionFilterMenuItem>(); public new Bindable<CollectionFilterMenuItem> Current { get => current.Current; set => current.Current = value; } private readonly IBindableList<BeatmapCollection> collections = new BindableList<BeatmapCollection>(); private readonly IBindableList<BeatmapInfo> beatmaps = new BindableList<BeatmapInfo>(); private readonly BindableList<CollectionFilterMenuItem> filters = new BindableList<CollectionFilterMenuItem>(); [Resolved(CanBeNull = true)] private ManageCollectionsDialog manageCollectionsDialog { get; set; } [Resolved(CanBeNull = true)] private CollectionManager collectionManager { get; set; } public CollectionFilterDropdown() { ItemSource = filters; Current.Value = new AllBeatmapsCollectionFilterMenuItem(); } protected override void LoadComplete() { base.LoadComplete(); if (collectionManager != null) collections.BindTo(collectionManager.Collections); // Dropdown has logic which triggers a change on the bindable with every change to the contained items. // This is not desirable here, as it leads to multiple filter operations running even though nothing has changed. // An extra bindable is enough to subvert this behaviour. base.Current = Current; collections.BindCollectionChanged((_, __) => collectionsChanged(), true); Current.BindValueChanged(filterChanged, true); } /// <summary> /// Occurs when a collection has been added or removed. /// </summary> private void collectionsChanged() { var selectedItem = SelectedItem?.Value?.Collection; filters.Clear(); filters.Add(new AllBeatmapsCollectionFilterMenuItem()); filters.AddRange(collections.Select(c => new CollectionFilterMenuItem(c))); if (ShowManageCollectionsItem) filters.Add(new ManageCollectionsFilterMenuItem()); Current.Value = filters.SingleOrDefault(f => f.Collection != null && f.Collection == selectedItem) ?? filters[0]; } /// <summary> /// Occurs when the <see cref="CollectionFilterMenuItem"/> selection has changed. /// </summary> private void filterChanged(ValueChangedEvent<CollectionFilterMenuItem> filter) { // Binding the beatmaps will trigger a collection change event, which results in an infinite-loop. This is rebound later, when it's safe to do so. beatmaps.CollectionChanged -= filterBeatmapsChanged; if (filter.OldValue?.Collection != null) beatmaps.UnbindFrom(filter.OldValue.Collection.Beatmaps); if (filter.NewValue?.Collection != null) beatmaps.BindTo(filter.NewValue.Collection.Beatmaps); beatmaps.CollectionChanged += filterBeatmapsChanged; // Never select the manage collection filter - rollback to the previous filter. // This is done after the above since it is important that bindable is unbound from OldValue, which is lost after forcing it back to the old value. if (filter.NewValue is ManageCollectionsFilterMenuItem) { Current.Value = filter.OldValue; manageCollectionsDialog?.Show(); } } /// <summary> /// Occurs when the beatmaps contained by a <see cref="BeatmapCollection"/> have changed. /// </summary> private void filterBeatmapsChanged(object sender, NotifyCollectionChangedEventArgs e) { // The filtered beatmaps have changed, without the filter having changed itself. So a change in filter must be notified. // Note that this does NOT propagate to bound bindables, so the FilterControl must bind directly to the value change event of this bindable. Current.TriggerChange(); } protected override LocalisableString GenerateItemText(CollectionFilterMenuItem item) => item.CollectionName.Value; protected sealed override DropdownHeader CreateHeader() => CreateCollectionHeader().With(d => { d.SelectedItem.BindTarget = Current; }); protected sealed override DropdownMenu CreateMenu() => CreateCollectionMenu(); protected virtual CollectionDropdownHeader CreateCollectionHeader() => new CollectionDropdownHeader(); protected virtual CollectionDropdownMenu CreateCollectionMenu() => new CollectionDropdownMenu(); public class CollectionDropdownHeader : OsuDropdownHeader { public readonly Bindable<CollectionFilterMenuItem> SelectedItem = new Bindable<CollectionFilterMenuItem>(); private readonly Bindable<string> collectionName = new Bindable<string>(); protected override LocalisableString Label { get => base.Label; set { } // See updateText(). } public CollectionDropdownHeader() { Height = 25; Icon.Size = new Vector2(16); Foreground.Padding = new MarginPadding { Top = 4, Bottom = 4, Left = 8, Right = 4 }; } protected override void LoadComplete() { base.LoadComplete(); SelectedItem.BindValueChanged(_ => updateBindable(), true); } private void updateBindable() { collectionName.UnbindAll(); if (SelectedItem.Value != null) collectionName.BindTo(SelectedItem.Value.CollectionName); collectionName.BindValueChanged(_ => updateText(), true); } // Dropdowns don't bind to value changes, so the real name is copied directly from the selected item here. private void updateText() => base.Label = collectionName.Value; } protected class CollectionDropdownMenu : OsuDropdownMenu { public CollectionDropdownMenu() { MaxHeight = 200; } protected override DrawableDropdownMenuItem CreateDrawableDropdownMenuItem(MenuItem item) => new CollectionDropdownMenuItem(item) { BackgroundColourHover = HoverColour, BackgroundColourSelected = SelectionColour }; } protected class CollectionDropdownMenuItem : OsuDropdownMenu.DrawableOsuDropdownMenuItem { [NotNull] protected new CollectionFilterMenuItem Item => ((DropdownMenuItem<CollectionFilterMenuItem>)base.Item).Value; [Resolved] private OsuColour colours { get; set; } [Resolved] private IBindable<WorkingBeatmap> beatmap { get; set; } [CanBeNull] private readonly BindableList<BeatmapInfo> collectionBeatmaps; [NotNull] private readonly Bindable<string> collectionName; private IconButton addOrRemoveButton; private Content content; private bool beatmapInCollection; public CollectionDropdownMenuItem(MenuItem item) : base(item) { collectionBeatmaps = Item.Collection?.Beatmaps.GetBoundCopy(); collectionName = Item.CollectionName.GetBoundCopy(); } [BackgroundDependencyLoader] private void load() { AddInternal(addOrRemoveButton = new IconButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, X = -OsuScrollContainer.SCROLL_BAR_HEIGHT, Scale = new Vector2(0.65f), Action = addOrRemove, }); } protected override void LoadComplete() { base.LoadComplete(); if (collectionBeatmaps != null) { collectionBeatmaps.CollectionChanged += (_, __) => collectionChanged(); beatmap.BindValueChanged(_ => collectionChanged(), true); } // Although the DrawableMenuItem binds to value changes of the item's text, the item is an internal implementation detail of Dropdown that has no knowledge // of the underlying CollectionFilter value and its accompanying name, so the real name has to be copied here. Without this, the collection name wouldn't update when changed. collectionName.BindValueChanged(name => content.Text = name.NewValue, true); updateButtonVisibility(); } protected override bool OnHover(HoverEvent e) { updateButtonVisibility(); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { updateButtonVisibility(); base.OnHoverLost(e); } private void collectionChanged() { Debug.Assert(collectionBeatmaps != null); beatmapInCollection = collectionBeatmaps.Contains(beatmap.Value.BeatmapInfo); addOrRemoveButton.Enabled.Value = !beatmap.IsDefault; addOrRemoveButton.Icon = beatmapInCollection ? FontAwesome.Solid.MinusSquare : FontAwesome.Solid.PlusSquare; addOrRemoveButton.TooltipText = beatmapInCollection ? "Remove selected beatmap" : "Add selected beatmap"; updateButtonVisibility(); } protected override void OnSelectChange() { base.OnSelectChange(); updateButtonVisibility(); } private void updateButtonVisibility() { if (collectionBeatmaps == null) addOrRemoveButton.Alpha = 0; else addOrRemoveButton.Alpha = IsHovered || IsPreSelected || beatmapInCollection ? 1 : 0; } private void addOrRemove() { Debug.Assert(collectionBeatmaps != null); if (!collectionBeatmaps.Remove(beatmap.Value.BeatmapInfo)) collectionBeatmaps.Add(beatmap.Value.BeatmapInfo); } protected override Drawable CreateContent() => content = (Content)base.CreateContent(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Specialized.Tests { public static class StringCollectionTests { private const string ElementNotPresent = "element-not-present"; /// <summary> /// Data used for testing with Insert. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. data to insert (ElementNotPresent or null) /// 4. location to insert (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> Insert_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); foreach (string element in new[] { ElementNotPresent, null }) { foreach (int location in new[] { 0, d.Length / 2, d.Length }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, element, location }; } } } }/// <summary> /// Data used for testing with RemoveAt. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. location to remove (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> RemoveAt_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); if (d.Length > 0) { foreach (int location in new[] { 0, d.Length / 2, d.Length - 1 }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, location }; } } } } /// <summary> /// Data used for testing with a set of collections. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Data() { yield return ConstructRow(new string[] { /* empty */ }); yield return ConstructRow(new string[] { null }); yield return ConstructRow(new string[] { "single" }); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x.ToString()).ToArray()); for (int index = 0; index < 100; index += 25) { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x == index ? null : x.ToString()).ToArray()); } } /// <summary> /// Data used for testing with a set of collections, where the data has duplicates. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Duplicates_Data() { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (string)null).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x % 10 == 0 ? null : (x % 10).ToString()).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (x % 10).ToString()).ToArray()); } private static object[] ConstructRow(string[] data) { if (data.Contains(ElementNotPresent)) throw new ArgumentException("Do not include \"" + ElementNotPresent + "\" in data."); StringCollection col = new StringCollection(); col.AddRange(data); return new object[] { col, data }; } [Fact] public static void Constructor_DefaultTest() { StringCollection sc = new StringCollection(); Assert.Equal(0, sc.Count); Assert.False(sc.Contains(null)); Assert.False(sc.Contains("")); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data) { IList added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddRangeTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); added.AddRange(data); Assert.Equal(collection, added); added.AddRange(new string[] { /*empty*/}); Assert.Equal(collection, added); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void AddRange_NullTest(StringCollection collection, string[] data) { AssertExtensions.Throws<ArgumentNullException>("value", () => collection.AddRange(null)); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void ClearTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyToTest(StringCollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyTo_ExplicitInterface_Test(ICollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1)); if (data.Length > 0) { AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(new string[0], data.Length - 1)); AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(new string[data.Length - 1], 0)); } // As explicit interface implementation Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1)); if (data.Length > 0) { AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => ((ICollection)collection).CopyTo(new string[0], data.Length - 1)); AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0)); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void CountTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); collection.Add("one"); Assert.Equal(1, collection.Count); collection.AddRange(data); Assert.Equal(1 + data.Length, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void ContainsTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.True(collection.Contains(element))); Assert.All(data, element => Assert.True(((IList)collection).Contains(element))); Assert.False(collection.Contains(ElementNotPresent)); Assert.False(((IList)collection).Contains(ElementNotPresent)); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetEnumeratorTest(StringCollection collection, string[] data) { bool repeat = true; StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); while (repeat) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); foreach (string element in data) { Assert.True(enumerator.MoveNext()); Assert.Equal(element, enumerator.Current); Assert.Equal(element, enumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator.Reset(); enumerator.Reset(); repeat = false; } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data) { StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); if (data.Length > 0) { Assert.True(enumerator.MoveNext()); string current = enumerator.Current; Assert.Equal(data[0], current); collection.RemoveAt(0); if (data.Length > 1 && data[0] != data[1]) { Assert.NotEqual(current, collection[0]); } Assert.Equal(current, enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { collection.Add("newValue"); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSetTest(StringCollection collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { string temp = collection[i]; collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSet_ExplicitInterface_Test(IList collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { object temp = collection[i]; if (temp != null) { Assert.IsType<string>(temp); } collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void GetSet_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length]); // As explicitly implementing the interface Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length]); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void IndexOfTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void IndexOf_DuplicateTest(StringCollection collection, string[] data) { // Only the index of the first element will be returned. data = data.Distinct().ToArray(); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData(nameof(Insert_Data))] public static void InsertTest(StringCollection collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData(nameof(Insert_Data))] public static void Insert_ExplicitInterface_Test(IList collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Insert_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(data.Length + 1, ElementNotPresent)); // And as explicit interface implementation Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(data.Length + 1, ElementNotPresent)); } [Fact] public static void IsFixedSizeTest() { Assert.False(((IList)new StringCollection()).IsFixedSize); } [Fact] public static void IsReadOnlyTest() { Assert.False(new StringCollection().IsReadOnly); Assert.False(((IList)new StringCollection()).IsReadOnly); } [Fact] public static void IsSynchronizedTest() { Assert.False(new StringCollection().IsSynchronized); Assert.False(((IList)new StringCollection()).IsSynchronized); } [Theory] [MemberData(nameof(StringCollection_Data))] public static void RemoveTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] public static void Remove_IListTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_NotPresentTest(StringCollection collection, string[] data) { collection.Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); ((IList)collection).Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_DuplicateTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(RemoveAt_Data))] public static void RemoveAtTest(StringCollection collection, string[] data, int location) { collection.RemoveAt(location); Assert.Equal(data.Length - 1, collection.Count); for (int i = 0; i < data.Length - 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i >= location) { Assert.Equal(data[i + 1], collection[i]); } } } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void RemoveAt_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(data.Length)); } [Theory] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData(nameof(StringCollection_Data))] [MemberData(nameof(StringCollection_Duplicates_Data))] public static void SyncRootTest(StringCollection collection, string[] data) { object syncRoot = collection.SyncRoot; Assert.NotNull(syncRoot); Assert.IsType<object>(syncRoot); Assert.Same(syncRoot, collection.SyncRoot); Assert.NotSame(syncRoot, new StringCollection().SyncRoot); StringCollection other = new StringCollection(); other.AddRange(data); Assert.NotSame(syncRoot, other.SyncRoot); } } }
//------------------------------------------------------------------------------ // <copyright file="DiscoveryClientProtocol.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Services.Discovery { using System.Xml.Serialization; using System.IO; using System; using System.Web.Services; using System.Web.Services.Protocols; using System.Net; using System.Collections; using System.Diagnostics; using System.Web.Services.Configuration; using System.Text; using System.Security.Permissions; using System.Globalization; using System.Threading; using System.Runtime.InteropServices; using System.Web.Services.Diagnostics; /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class DiscoveryClientProtocol : HttpWebClientProtocol { private DiscoveryClientReferenceCollection references = new DiscoveryClientReferenceCollection(); private DiscoveryClientDocumentCollection documents = new DiscoveryClientDocumentCollection(); private Hashtable inlinedSchemas = new Hashtable(); private ArrayList additionalInformation = new ArrayList(); private DiscoveryExceptionDictionary errors = new DiscoveryExceptionDictionary(); /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.DiscoveryClientProtocol"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientProtocol() : base() { } internal DiscoveryClientProtocol(HttpWebClientProtocol protocol) : base(protocol) { } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.AdditionalInformation"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IList AdditionalInformation { get { return additionalInformation; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.Documents"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientDocumentCollection Documents { get { return documents; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.Errors"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryExceptionDictionary Errors { get { return errors; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.References"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientReferenceCollection References { get { return references; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.References"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal Hashtable InlinedSchemas { get { return inlinedSchemas; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.Discover"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public DiscoveryDocument Discover(string url) { DiscoveryDocument doc = Documents[url] as DiscoveryDocument; if (doc != null) return doc; DiscoveryDocumentReference docRef = new DiscoveryDocumentReference(url); docRef.ClientProtocol = this; References[url] = docRef; Errors.Clear(); // this will auto-resolve and place the document in the Documents hashtable. return docRef.Document; } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.DiscoverAny"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public DiscoveryDocument DiscoverAny(string url) { Type[] refTypes = WebServicesSection.Current.DiscoveryReferenceTypes; DiscoveryReference discoRef = null; string contentType = null; Stream stream = Download(ref url, ref contentType); Errors.Clear(); bool allErrorsAreHtmlContentType = true; Exception errorInValidDocument = null; ArrayList specialErrorMessages = new ArrayList(); foreach (Type type in refTypes) { if (!typeof(DiscoveryReference).IsAssignableFrom(type)) continue; discoRef = (DiscoveryReference) Activator.CreateInstance(type); discoRef.Url = url; discoRef.ClientProtocol = this; stream.Position = 0; Exception e = discoRef.AttemptResolve(contentType, stream); if (e == null) break; Errors[type.FullName] = e; discoRef = null; InvalidContentTypeException e2 = e as InvalidContentTypeException; if (e2 == null || !ContentType.MatchesBase(e2.ContentType, "text/html")) allErrorsAreHtmlContentType = false; InvalidDocumentContentsException e3 = e as InvalidDocumentContentsException; if (e3 != null) { errorInValidDocument = e; break; } if (e.InnerException != null && e.InnerException.InnerException == null) specialErrorMessages.Add(e.InnerException.Message); } if (discoRef == null) { if (errorInValidDocument != null) { StringBuilder errorMessage = new StringBuilder(Res.GetString(Res.TheDocumentWasUnderstoodButContainsErrors)); while (errorInValidDocument != null) { errorMessage.Append("\n - ").Append(errorInValidDocument.Message); errorInValidDocument = errorInValidDocument.InnerException; } throw new InvalidOperationException(errorMessage.ToString()); } else if (allErrorsAreHtmlContentType) { throw new InvalidOperationException(Res.GetString(Res.TheHTMLDocumentDoesNotContainDiscoveryInformation)); } else { bool same = specialErrorMessages.Count == Errors.Count && Errors.Count > 0; for (int i = 1; same && i < specialErrorMessages.Count; i++) { if ((string) specialErrorMessages[i - 1] != (string) specialErrorMessages[i]) same = false; } if (same) throw new InvalidOperationException(Res.GetString(Res.TheDocumentWasNotRecognizedAsAKnownDocumentType, specialErrorMessages[0])); else { Exception e; StringBuilder errorMessage = new StringBuilder(Res.GetString(Res.WebMissingResource, url)); foreach (DictionaryEntry entry in Errors) { e = (Exception)(entry.Value); string refType = (string)(entry.Key); if (0 == string.Compare(refType, typeof(ContractReference).FullName, StringComparison.Ordinal)) { refType = Res.GetString(Res.WebContractReferenceName); } else if (0 == string.Compare(refType, typeof(SchemaReference).FullName, StringComparison.Ordinal)) { refType = Res.GetString(Res.WebShemaReferenceName); } else if (0 == string.Compare(refType, typeof(DiscoveryDocumentReference).FullName, StringComparison.Ordinal)) { refType = Res.GetString(Res.WebDiscoveryDocumentReferenceName); } errorMessage.Append("\n- ").Append(Res.GetString(Res.WebDiscoRefReport, refType, e.Message)); while (e.InnerException != null) { errorMessage.Append("\n - ").Append(e.InnerException.Message); e = e.InnerException; } } throw new InvalidOperationException(errorMessage.ToString()); } } } if (discoRef is DiscoveryDocumentReference) return ((DiscoveryDocumentReference) discoRef).Document; References[discoRef.Url] = discoRef; DiscoveryDocument doc = new DiscoveryDocument(); doc.References.Add(discoRef); return doc; } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.Download"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public Stream Download(ref string url) { string contentType = null; return Download(ref url, ref contentType); } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.Download1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public Stream Download(ref string url, ref string contentType) { WebRequest request = GetWebRequest(new Uri(url)); request.Method = "GET"; #if DEBUG // HttpWebRequest httpRequest = request as HttpWebRequest; if (httpRequest != null) { httpRequest.Timeout = httpRequest.Timeout * 2; } #endif WebResponse response = null; try { response = GetWebResponse(request); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } throw new WebException(Res.GetString(Res.ThereWasAnErrorDownloading0, url), e); } HttpWebResponse httpResponse = response as HttpWebResponse; if (httpResponse != null) { if (httpResponse.StatusCode != HttpStatusCode.OK) { string errorMessage = RequestResponseUtils.CreateResponseExceptionString(httpResponse); throw new WebException(Res.GetString(Res.ThereWasAnErrorDownloading0, url), new WebException(errorMessage, null, WebExceptionStatus.ProtocolError, response)); } } Stream responseStream = response.GetResponseStream(); try { // Uri.ToString() returns the unescaped version url = response.ResponseUri.ToString(); contentType = response.ContentType; if (response.ResponseUri.Scheme == Uri.UriSchemeFtp || response.ResponseUri.Scheme == Uri.UriSchemeFile) { int dotIndex = response.ResponseUri.AbsolutePath.LastIndexOf('.'); if (dotIndex != -1) { switch (response.ResponseUri.AbsolutePath.Substring(dotIndex + 1).ToLower(CultureInfo.InvariantCulture)) { case "xml": case "wsdl": case "xsd": case "disco": contentType = ContentType.TextXml; break; default: break; } } } // need to return a buffered stream (one that supports CanSeek) return RequestResponseUtils.StreamToMemoryStream(responseStream); } finally { responseStream.Close(); } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.LoadExternals"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// <internalonly/> /// </devdoc> [Obsolete("This method will be removed from a future version. The method call is no longer required for resource discovery", false)] [ComVisible(false)] public void LoadExternals() { } internal void FixupReferences() { foreach (DiscoveryReference reference in References.Values) { reference.LoadExternals(InlinedSchemas); } foreach (string url in InlinedSchemas.Keys) { Documents.Remove(url); } } private static bool IsFilenameInUse(Hashtable filenames, string path) { return filenames[path.ToLower(CultureInfo.InvariantCulture)] != null; } private static void AddFilename(Hashtable filenames, string path) { filenames.Add(path.ToLower(CultureInfo.InvariantCulture), path); } private static string GetUniqueFilename(Hashtable filenames, string path) { if (IsFilenameInUse(filenames, path)) { string extension = Path.GetExtension(path); string allElse = path.Substring(0, path.Length - extension.Length); int append = 0; do { path = allElse + append.ToString(CultureInfo.InvariantCulture) + extension; append++; } while (IsFilenameInUse(filenames, path)); } AddFilename(filenames, path); return path; } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.ReadAll"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public DiscoveryClientResultCollection ReadAll(string topLevelFilename) { XmlSerializer ser = new XmlSerializer(typeof(DiscoveryClientResultsFile)); Stream file = File.OpenRead(topLevelFilename); string topLevelPath = Path.GetDirectoryName(topLevelFilename); DiscoveryClientResultsFile results = null; try { results = (DiscoveryClientResultsFile) ser.Deserialize(file); for (int i = 0; i < results.Results.Count; i++) { if (results.Results[i] == null) throw new InvalidOperationException(Res.GetString(Res.WebNullRef)); string typeName = results.Results[i].ReferenceTypeName; if (typeName == null || typeName.Length == 0) throw new InvalidOperationException(Res.GetString(Res.WebRefInvalidAttribute, "referenceType")); DiscoveryReference reference = (DiscoveryReference) Activator.CreateInstance(Type.GetType(typeName)); reference.ClientProtocol = this; string url = results.Results[i].Url; if (url == null || url.Length == 0) throw new InvalidOperationException(Res.GetString(Res.WebRefInvalidAttribute2, reference.GetType().FullName, "url")); reference.Url = url; string fileName = results.Results[i].Filename; if (fileName == null || fileName.Length == 0) throw new InvalidOperationException(Res.GetString(Res.WebRefInvalidAttribute2, reference.GetType().FullName, "filename")); Stream docFile = File.OpenRead(Path.Combine(topLevelPath, results.Results[i].Filename)); try { Documents[reference.Url] = reference.ReadDocument(docFile); Debug.Assert(Documents[reference.Url] != null, "Couldn't deserialize file " + results.Results[i].Filename); } finally { docFile.Close(); } References[reference.Url] = reference; } ResolveAll(); } finally { file.Close(); } return results.Results; } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.ResolveAll"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public void ResolveAll() { // Resolve until we reach a 'steady state' (no more references added) Errors.Clear(); int resolvedCount = InlinedSchemas.Keys.Count; while (resolvedCount != References.Count) { resolvedCount = References.Count; DiscoveryReference[] refs = new DiscoveryReference[References.Count]; References.Values.CopyTo(refs, 0); for (int i = 0; i < refs.Length; i++) { DiscoveryReference discoRef = refs[i]; if (discoRef is DiscoveryDocumentReference) { try { // Resolve discovery document references deeply ((DiscoveryDocumentReference)discoRef).ResolveAll(true); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } // don't let the exception out - keep going. Just add it to the list of errors. Errors[discoRef.Url] = e; if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, this, "ResolveAll", e); } } else { try { discoRef.Resolve(); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } // don't let the exception out - keep going. Just add it to the list of errors. Errors[discoRef.Url] = e; if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, this, "ResolveAll", e); } } } } FixupReferences(); } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.ResolveOneLevel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public void ResolveOneLevel() { // download everything we have a reference to, but don't recurse. Errors.Clear(); DiscoveryReference[] refs = new DiscoveryReference[References.Count]; References.Values.CopyTo(refs, 0); for (int i = 0; i < refs.Length; i++) { try { refs[i].Resolve(); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } // don't let the exception out - keep going. Just add it to the list of errors. Errors[refs[i].Url] = e; if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Warning, this, "ResolveOneLevel", e); } } } private static string GetRelativePath(string fullPath, string relativeTo) { string currentDir = Path.GetDirectoryName(Path.GetFullPath(relativeTo)); string answer = ""; while (currentDir.Length > 0) { if (currentDir.Length <= fullPath.Length && string.Compare(currentDir, fullPath.Substring(0, currentDir.Length), StringComparison.OrdinalIgnoreCase) == 0) { answer += fullPath.Substring(currentDir.Length); if (answer.StartsWith("\\", StringComparison.Ordinal)) answer = answer.Substring(1); return answer; } answer += "..\\"; if (currentDir.Length < 2) break; else { int lastSlash = currentDir.LastIndexOf('\\', currentDir.Length - 2); currentDir = currentDir.Substring(0, lastSlash + 1); } } return fullPath; } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.WriteAll"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public DiscoveryClientResultCollection WriteAll(string directory, string topLevelFilename) { DiscoveryClientResultsFile results = new DiscoveryClientResultsFile(); Hashtable filenames = new Hashtable(); string topLevelFullPath = Path.Combine(directory, topLevelFilename); // write out each of the documents DictionaryEntry[] entries = new DictionaryEntry[Documents.Count + InlinedSchemas.Keys.Count]; int i = 0; foreach (DictionaryEntry entry in Documents) { entries[i++] = entry; } foreach (DictionaryEntry entry in InlinedSchemas) { entries[i++] = entry; } foreach (DictionaryEntry entry in entries) { string url = (string) entry.Key; object document = entry.Value; if (document == null) continue; DiscoveryReference reference = References[url]; string filename = reference == null ? DiscoveryReference.FilenameFromUrl(Url) : reference.DefaultFilename; filename = GetUniqueFilename(filenames, Path.GetFullPath(Path.Combine(directory, filename))); results.Results.Add(new DiscoveryClientResult(reference == null ? null : reference.GetType(), url, GetRelativePath(filename, topLevelFullPath))); Stream file = File.Create(filename); try { reference.WriteDocument(document, file); } finally { file.Close(); } } // write out the file that points to all those documents. XmlSerializer ser = new XmlSerializer(typeof(DiscoveryClientResultsFile)); Stream topLevelFile = File.Create(topLevelFullPath); try { ser.Serialize(new StreamWriter(topLevelFile, new UTF8Encoding(false)), results); } finally { topLevelFile.Close(); } return results.Results; } // public sealed class DiscoveryClientResultsFile { private DiscoveryClientResultCollection results = new DiscoveryClientResultCollection(); /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientProtocol.DiscoveryClientResultsFile.Results"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientResultCollection Results { get { return results; } } } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResultCollection"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public sealed class DiscoveryClientResultCollection : CollectionBase { /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResultCollection.this"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientResult this[int i] { get { return (DiscoveryClientResult) List[i]; } set { List[i] = value; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResultCollection.Add"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(DiscoveryClientResult value) { return List.Add(value); } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResultCollection.Contains"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(DiscoveryClientResult value) { return List.Contains(value); } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResultCollection.Remove"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(DiscoveryClientResult value) { List.Remove(value); } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResult"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public sealed class DiscoveryClientResult { string referenceTypeName; string url; string filename; /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResult.DiscoveryClientResult"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientResult() { } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResult.DiscoveryClientResult1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public DiscoveryClientResult(Type referenceType, string url, string filename) { this.referenceTypeName = referenceType == null ? string.Empty : referenceType.FullName; this.url = url; this.filename = filename; } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResult.ReferenceTypeName"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("referenceType")] public string ReferenceTypeName { get { return referenceTypeName; } set { referenceTypeName = value; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResult.Url"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("url")] public string Url { get { return url; } set { url = value; } } /// <include file='doc\DiscoveryClientProtocol.uex' path='docs/doc[@for="DiscoveryClientResult.Filename"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("filename")] public string Filename { get { return filename; } set { filename = value; } } } }
// 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.ObjectModel; using System.Dynamic.Utils; using System.Runtime.CompilerServices; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents a visitor or rewriter for expression trees. /// </summary> /// <remarks> /// This class is designed to be inherited to create more specialized /// classes whose functionality requires traversing, examining or copying /// an expression tree. /// </remarks> public abstract partial class ExpressionVisitor { /// <summary> /// Initializes a new instance of <see cref="ExpressionVisitor"/>. /// </summary> protected ExpressionVisitor() { } /// <summary> /// Dispatches the expression to one of the more specialized visit methods in this class. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> public virtual Expression Visit(Expression node) => node?.Accept(this); /// <summary> /// Dispatches the list of expressions to one of the more specialized visit methods in this class. /// </summary> /// <param name="nodes">The expressions to visit.</param> /// <returns>The modified expression list, if any of the elements were modified; /// otherwise, returns the original expression list.</returns> public ReadOnlyCollection<Expression> Visit(ReadOnlyCollection<Expression> nodes) { ContractUtils.RequiresNotNull(nodes, nameof(nodes)); Expression[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { Expression node = Visit(nodes[i]); if (newNodes != null) { newNodes[i] = node; } else if (!object.ReferenceEquals(node, nodes[i])) { newNodes = new Expression[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new TrueReadOnlyCollection<Expression>(newNodes); } private Expression[] VisitArguments(IArgumentProvider nodes) { return ExpressionVisitorUtils.VisitArguments(this, nodes); } private ParameterExpression[] VisitParameters(IParameterProvider nodes, string callerName) { return ExpressionVisitorUtils.VisitParameters(this, nodes, callerName); } /// <summary> /// Visits all nodes in the collection using a specified element visitor. /// </summary> /// <typeparam name="T">The type of the nodes.</typeparam> /// <param name="nodes">The nodes to visit.</param> /// <param name="elementVisitor">A delegate that visits a single element, /// optionally replacing it with a new element.</param> /// <returns>The modified node list, if any of the elements were modified; /// otherwise, returns the original node list.</returns> public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor) { ContractUtils.RequiresNotNull(nodes, nameof(nodes)); ContractUtils.RequiresNotNull(elementVisitor, nameof(elementVisitor)); T[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { T node = elementVisitor(nodes[i]); if (newNodes != null) { newNodes[i] = node; } else if (!object.ReferenceEquals(node, nodes[i])) { newNodes = new T[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new TrueReadOnlyCollection<T>(newNodes); } /// <summary> /// Visits an expression, casting the result back to the original expression type. /// </summary> /// <typeparam name="T">The type of the expression.</typeparam> /// <param name="node">The expression to visit.</param> /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception> public T VisitAndConvert<T>(T node, string callerName) where T : Expression { if (node == null) { return null; } node = Visit(node) as T; if (node == null) { throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName); } return node; } /// <summary> /// Visits an expression, casting the result back to the original expression type. /// </summary> /// <typeparam name="T">The type of the expression.</typeparam> /// <param name="nodes">The expression to visit.</param> /// <param name="callerName">The name of the calling method; used to report to report a better error message.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> /// <exception cref="InvalidOperationException">The visit method for this node returned a different type.</exception> public ReadOnlyCollection<T> VisitAndConvert<T>(ReadOnlyCollection<T> nodes, string callerName) where T : Expression { ContractUtils.RequiresNotNull(nodes, nameof(nodes)); T[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { T node = Visit(nodes[i]) as T; if (node == null) { throw Error.MustRewriteToSameNode(callerName, typeof(T), callerName); } if (newNodes != null) { newNodes[i] = node; } else if (!object.ReferenceEquals(node, nodes[i])) { newNodes = new T[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new TrueReadOnlyCollection<T>(newNodes); } /// <summary> /// Visits the children of the <see cref="BinaryExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitBinary(BinaryExpression node) { // Walk children in evaluation order: left, conversion, right return ValidateBinary( node, node.Update( Visit(node.Left), VisitAndConvert(node.Conversion, nameof(VisitBinary)), Visit(node.Right) ) ); } /// <summary> /// Visits the children of the <see cref="BlockExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitBlock(BlockExpression node) { Expression[] nodes = ExpressionVisitorUtils.VisitBlockExpressions(this, node); ReadOnlyCollection<ParameterExpression> v = VisitAndConvert(node.Variables, "VisitBlock"); if (v == node.Variables && nodes == null) { return node; } return node.Rewrite(v, nodes); } /// <summary> /// Visits the children of the <see cref="ConditionalExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitConditional(ConditionalExpression node) { return node.Update(Visit(node.Test), Visit(node.IfTrue), Visit(node.IfFalse)); } /// <summary> /// Visits the <see cref="ConstantExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitConstant(ConstantExpression node) { return node; } /// <summary> /// Visits the <see cref="DebugInfoExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitDebugInfo(DebugInfoExpression node) { return node; } /// <summary> /// Visits the <see cref="DefaultExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitDefault(DefaultExpression node) { return node; } /// <summary> /// Visits the children of the extension expression. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> /// <remarks> /// This can be overridden to visit or rewrite specific extension nodes. /// If it is not overridden, this method will call <see cref="Expression.VisitChildren"/>, /// which gives the node a chance to walk its children. By default, /// <see cref="Expression.VisitChildren"/> will try to reduce the node. /// </remarks> protected internal virtual Expression VisitExtension(Expression node) { return node.VisitChildren(this); } /// <summary> /// Visits the children of the <see cref="GotoExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitGoto(GotoExpression node) { return node.Update(VisitLabelTarget(node.Target), Visit(node.Value)); } /// <summary> /// Visits the children of the <see cref="InvocationExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitInvocation(InvocationExpression node) { Expression e = Visit(node.Expression); Expression[] a = VisitArguments(node); if (e == node.Expression && a == null) { return node; } return node.Rewrite(e, a); } /// <summary> /// Visits the <see cref="LabelTarget"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual LabelTarget VisitLabelTarget(LabelTarget node) { return node; } /// <summary> /// Visits the children of the <see cref="LabelExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLabel(LabelExpression node) { return node.Update(VisitLabelTarget(node.Target), Visit(node.DefaultValue)); } /// <summary> /// Visits the children of the <see cref="Expression{T}"/>. /// </summary> /// <typeparam name="T">The type of the delegate.</typeparam> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLambda<T>(Expression<T> node) { Expression body = Visit(node.Body); ParameterExpression[] parameters = VisitParameters(node, nameof(VisitLambda)); if (body == node.Body && parameters == null) { return node; } return node.Rewrite(body, parameters); } /// <summary> /// Visits the children of the <see cref="LoopExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitLoop(LoopExpression node) { return node.Update(VisitLabelTarget(node.BreakLabel), VisitLabelTarget(node.ContinueLabel), Visit(node.Body)); } /// <summary> /// Visits the children of the <see cref="MemberExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitMember(MemberExpression node) { return node.Update(Visit(node.Expression)); } /// <summary> /// Visits the children of the <see cref="IndexExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitIndex(IndexExpression node) { Expression o = Visit(node.Object); Expression[] a = VisitArguments(node); if (o == node.Object && a == null) { return node; } return node.Rewrite(o, a); } /// <summary> /// Visits the children of the <see cref="MethodCallExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitMethodCall(MethodCallExpression node) { Expression o = Visit(node.Object); Expression[] a = VisitArguments(node); if (o == node.Object && a == null) { return node; } return node.Rewrite(o, a); } /// <summary> /// Visits the children of the <see cref="NewArrayExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitNewArray(NewArrayExpression node) { return node.Update(Visit(node.Expressions)); } /// <summary> /// Visits the children of the <see cref="NewExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] protected internal virtual Expression VisitNew(NewExpression node) { Expression[] a = VisitArguments(node); if (a == null) { return node; } return node.Update(a); } /// <summary> /// Visits the <see cref="ParameterExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitParameter(ParameterExpression node) { return node; } /// <summary> /// Visits the children of the <see cref="RuntimeVariablesExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { return node.Update(VisitAndConvert(node.Variables, nameof(VisitRuntimeVariables))); } /// <summary> /// Visits the children of the <see cref="SwitchCase"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual SwitchCase VisitSwitchCase(SwitchCase node) { return node.Update(Visit(node.TestValues), Visit(node.Body)); } /// <summary> /// Visits the children of the <see cref="SwitchExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitSwitch(SwitchExpression node) { return ValidateSwitch( node, node.Update( Visit(node.SwitchValue), Visit(node.Cases, VisitSwitchCase), Visit(node.DefaultBody) ) ); } /// <summary> /// Visits the children of the <see cref="CatchBlock"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual CatchBlock VisitCatchBlock(CatchBlock node) { return node.Update(VisitAndConvert(node.Variable, nameof(VisitCatchBlock)), Visit(node.Filter), Visit(node.Body)); } /// <summary> /// Visits the children of the <see cref="TryExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitTry(TryExpression node) { return node.Update( Visit(node.Body), Visit(node.Handlers, VisitCatchBlock), Visit(node.Finally), Visit(node.Fault) ); } /// <summary> /// Visits the children of the <see cref="TypeBinaryExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitTypeBinary(TypeBinaryExpression node) { return node.Update(Visit(node.Expression)); } /// <summary> /// Visits the children of the <see cref="UnaryExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitUnary(UnaryExpression node) { return ValidateUnary(node, node.Update(Visit(node.Operand))); } /// <summary> /// Visits the children of the <see cref="MemberInitExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitMemberInit(MemberInitExpression node) { return node.Update( VisitAndConvert(node.NewExpression, nameof(VisitMemberInit)), Visit(node.Bindings, VisitMemberBinding) ); } /// <summary> /// Visits the children of the <see cref="ListInitExpression"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitListInit(ListInitExpression node) { return node.Update( VisitAndConvert(node.NewExpression, nameof(VisitListInit)), Visit(node.Initializers, VisitElementInit) ); } /// <summary> /// Visits the children of the <see cref="ElementInit"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual ElementInit VisitElementInit(ElementInit node) { return node.Update(Visit(node.Arguments)); } /// <summary> /// Visits the children of the <see cref="MemberBinding"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberBinding VisitMemberBinding(MemberBinding node) { switch (node.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment)node); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding)node); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding)node); default: throw Error.UnhandledBindingType(node.BindingType); } } /// <summary> /// Visits the children of the <see cref="MemberAssignment"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment node) { return node.Update(Visit(node.Expression)); } /// <summary> /// Visits the children of the <see cref="MemberMemberBinding"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) { return node.Update(Visit(node.Bindings, VisitMemberBinding)); } /// <summary> /// Visits the children of the <see cref="MemberListBinding"/>. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding node) { return node.Update(Visit(node.Initializers, VisitElementInit)); } // // Prevent some common cases of invalid rewrites. // // Essentially, we don't want the rewritten node to be semantically // bound by the factory, which may do the wrong thing. Instead we // require derived classes to be explicit about what they want to do if // types change. // private static UnaryExpression ValidateUnary(UnaryExpression before, UnaryExpression after) { if (before != after && before.Method == null) { if (after.Method != null) { throw Error.MustRewriteWithoutMethod(after.Method, nameof(VisitUnary)); } // rethrow has null operand if (before.Operand != null && after.Operand != null) { ValidateChildType(before.Operand.Type, after.Operand.Type, nameof(VisitUnary)); } } return after; } private static BinaryExpression ValidateBinary(BinaryExpression before, BinaryExpression after) { if (before != after && before.Method == null) { if (after.Method != null) { throw Error.MustRewriteWithoutMethod(after.Method, nameof(VisitBinary)); } ValidateChildType(before.Left.Type, after.Left.Type, nameof(VisitBinary)); ValidateChildType(before.Right.Type, after.Right.Type, nameof(VisitBinary)); } return after; } // We wouldn't need this if switch didn't infer the method. private static SwitchExpression ValidateSwitch(SwitchExpression before, SwitchExpression after) { // If we did not have a method, we don't want to bind to one, // it might not be the right thing. if (before.Comparison == null && after.Comparison != null) { throw Error.MustRewriteWithoutMethod(after.Comparison, nameof(VisitSwitch)); } return after; } // Value types must stay as the same type, otherwise it's now a // different operation, e.g. adding two doubles vs adding two ints. private static void ValidateChildType(Type before, Type after, string methodName) { if (before.IsValueType) { if (TypeUtils.AreEquivalent(before, after)) { // types are the same value type return; } } else if (!after.IsValueType) { // both are reference types return; } // Otherwise, it's an invalid type change. throw Error.MustRewriteChildToSameType(before, after, methodName); } } }
using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Web; using System.Web.Caching; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Events; using umbraco.DataLayer; namespace umbraco.BusinessLogic { /// <summary> /// Represents a umbraco Usertype /// </summary> [Obsolete("Use the UserService instead")] public class UserType { internal Umbraco.Core.Models.Membership.IUserType UserTypeItem; /// <summary> /// Creates a new empty instance of a UserType /// </summary> public UserType() { UserTypeItem = new Umbraco.Core.Models.Membership.UserType(); } internal UserType(Umbraco.Core.Models.Membership.IUserType userType) { UserTypeItem = userType; } /// <summary> /// Creates a new instance of a UserType and attempts to /// load it's values from the database cache. /// </summary> /// <remarks> /// If the UserType is not found in the existing ID list, then this object /// will remain an empty object /// </remarks> /// <param name="id">The UserType id to find</param> public UserType(int id) { this.LoadByPrimaryKey(id); } /// <summary> /// Initializes a new instance of the <see cref="UserType"/> class. /// </summary> /// <param name="id">The user type id.</param> /// <param name="name">The name.</param> public UserType(int id, string name) { UserTypeItem = new Umbraco.Core.Models.Membership.UserType(); UserTypeItem.Id = id; UserTypeItem.Name = name; } /// <summary> /// Creates a new instance of UserType with all parameters /// </summary> /// <param name="id"></param> /// <param name="name"></param> /// <param name="defaultPermissions"></param> /// <param name="alias"></param> public UserType(int id, string name, string defaultPermissions, string alias) { UserTypeItem = new Umbraco.Core.Models.Membership.UserType(); UserTypeItem.Id = id; UserTypeItem.Name = name; UserTypeItem.Alias = alias; UserTypeItem.Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } /// <summary> /// The cache storage for all user types /// </summary> private static List<UserType> UserTypes { get { return ApplicationContext.Current.Services.UserService.GetAllUserTypes() .Select(x => new UserType(x)) .ToList(); } } #region Public Properties /// <summary> /// Gets or sets the user type alias. /// </summary> public string Alias { get { return UserTypeItem.Alias; } set { UserTypeItem.Alias = value; } } /// <summary> /// Gets the name of the user type. /// </summary> public string Name { get { return UserTypeItem.Name; } set { UserTypeItem.Name = value; } } /// <summary> /// Gets the id the user type /// </summary> public int Id { get { return UserTypeItem.Id; } } /// <summary> /// Gets the default permissions of the user type /// </summary> public string DefaultPermissions { get { return string.Join("", UserTypeItem.Permissions); } set { UserTypeItem.Permissions = value.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)); } } /// <summary> /// Returns an array of UserTypes /// </summary> [Obsolete("Use the GetAll method instead")] public static UserType[] getAll { get { return GetAllUserTypes().ToArray(); } } #endregion /// <summary> /// Saves this instance. /// </summary> public void Save() { //ensure that this object has an ID specified (it exists in the database) if (UserTypeItem.HasIdentity == false) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); ApplicationContext.Current.Services.UserService.SaveUserType(UserTypeItem); //raise event OnUpdated(this, new EventArgs()); } /// <summary> /// Deletes this instance. /// </summary> public void Delete() { //ensure that this object has an ID specified (it exists in the database) if (UserTypeItem.HasIdentity == false) throw new Exception("The current UserType object does not exist in the database. New UserTypes should be created with the MakeNew method"); ApplicationContext.Current.Services.UserService.DeleteUserType(UserTypeItem); //raise event OnDeleted(this, new EventArgs()); } /// <summary> /// Load the data for the current UserType by it's id /// </summary> /// <param name="id"></param> /// <returns>Returns true if the UserType id was found /// and the data was loaded, false if it wasn't</returns> public bool LoadByPrimaryKey(int id) { UserTypeItem = ApplicationContext.Current.Services.UserService.GetUserTypeById(id); return UserTypeItem != null; } /// <summary> /// Creates a new user type /// </summary> /// <param name="name"></param> /// <param name="defaultPermissions"></param> /// <param name="alias"></param> [MethodImpl(MethodImplOptions.Synchronized)] public static UserType MakeNew(string name, string defaultPermissions, string alias) { //ensure that the current alias does not exist //get the id for the new user type var existing = UserTypes.Find(ut => (ut.Alias == alias)); if (existing != null) throw new Exception("The UserType alias specified already exists"); var userType = new Umbraco.Core.Models.Membership.UserType { Alias = alias, Name = name, Permissions = defaultPermissions.ToCharArray().Select(x => x.ToString(CultureInfo.InvariantCulture)) }; ApplicationContext.Current.Services.UserService.SaveUserType(userType); var legacy = new UserType(userType); //raise event OnNew(legacy, new EventArgs()); return legacy; } /// <summary> /// Gets the user type with the specied ID /// </summary> /// <param name="id">The id.</param> /// <returns></returns> public static UserType GetUserType(int id) { return UserTypes.Find(ut => (ut.Id == id)); } /// <summary> /// Returns all UserType's /// </summary> /// <returns></returns> public static List<UserType> GetAllUserTypes() { return UserTypes; } internal static event TypedEventHandler<UserType, EventArgs> New; private static void OnNew(UserType userType, EventArgs args) { if (New != null) { New(userType, args); } } internal static event TypedEventHandler<UserType, EventArgs> Deleted; private static void OnDeleted(UserType userType, EventArgs args) { if (Deleted != null) { Deleted(userType, args); } } internal static event TypedEventHandler<UserType, EventArgs> Updated; private static void OnUpdated(UserType userType, EventArgs args) { if (Updated != null) { Updated(userType, args); } } } }
// 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 global::System; using global::System.Reflection; using global::System.Diagnostics; using global::System.Text; using global::System.Collections.Generic; using global::Internal.Metadata.NativeFormat; using global::Internal.Runtime.Augments; using global::Internal.Reflection.Core; using global::Internal.Reflection.Core.Execution; namespace Internal.Reflection.Execution.PayForPlayExperience { internal static class DiagnosticMappingTables { // Get the diagnostic name string for a type. This attempts to reformat the string into something that is essentially human readable. // Returns true if the function is successful. // runtimeTypeHandle represents the type to get a name for // diagnosticName is the name that is returned // // the genericParameterOffsets list is an optional parameter that contains the list of the locations of where generic parameters may be inserted // to make the string represent an instantiated generic. // // For example for Dictionary<K,V>, metadata names the type Dictionary`2, but this function will return Dictionary<,> // For consumers of this function that will be inserting generic arguments, the genericParameterOffsets list is used to find where to insert the generic parameter name. // // That isn't all that interesting for Dictionary, but it becomes substantially more interesting for nested generic types, or types which are compiler named as // those may contain embedded <> pairs and such. public static bool TryGetDiagnosticStringForNamedType(RuntimeTypeHandle runtimeTypeHandle, out String diagnosticName, List<int> genericParameterOffsets) { diagnosticName = null; ExecutionEnvironmentImplementation executionEnvironment = ReflectionExecution.ExecutionEnvironment; MetadataReader reader; TypeReferenceHandle typeReferenceHandle; if (executionEnvironment.TryGetTypeReferenceForNamedType(runtimeTypeHandle, out reader, out typeReferenceHandle)) { diagnosticName = GetTypeFullNameFromTypeRef(typeReferenceHandle, reader, genericParameterOffsets); return true; } TypeDefinitionHandle typeDefinitionHandle; if (executionEnvironment.TryGetMetadataForNamedType(runtimeTypeHandle, out reader, out typeDefinitionHandle)) { diagnosticName = GetTypeFullNameFromTypeDef(typeDefinitionHandle, reader, genericParameterOffsets); return true; } return false; } private static String GetTypeFullNameFromTypeRef(TypeReferenceHandle typeReferenceHandle, MetadataReader reader, List<int> genericParameterOffsets) { String s = ""; TypeReference typeReference = typeReferenceHandle.GetTypeReference(reader); s = typeReference.TypeName.GetString(reader); Handle parentHandle = typeReference.ParentNamespaceOrType; HandleType parentHandleType = parentHandle.HandleType; if (parentHandleType == HandleType.TypeReference) { String containingTypeName = GetTypeFullNameFromTypeRef(parentHandle.ToTypeReferenceHandle(reader), reader, genericParameterOffsets); s = containingTypeName + "." + s; } else if (parentHandleType == HandleType.NamespaceReference) { NamespaceReferenceHandle namespaceReferenceHandle = parentHandle.ToNamespaceReferenceHandle(reader); for (; ;) { NamespaceReference namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader); String namespacePart = namespaceReference.Name.GetStringOrNull(reader); if (namespacePart == null) break; // Reached the root namespace. s = namespacePart + "." + s; if (namespaceReference.ParentScopeOrNamespace.HandleType != HandleType.NamespaceReference) break; // Should have reached the root namespace first but this helper is for ToString() - better to // return partial information than crash. namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader); } } else { // If we got here, the metadata is illegal but this helper is for ToString() - better to // return something partial than throw. } return ConvertBackTickNameToNameWithReducerInputFormat(s, genericParameterOffsets); } public static String ConvertBackTickNameToNameWithReducerInputFormat(String typename, List<int> genericParameterOffsets) { int indexOfBackTick = typename.LastIndexOf('`'); if (indexOfBackTick != -1) { string typeNameSansBackTick = typename.Substring(0, indexOfBackTick); if ((indexOfBackTick + 1) < typename.Length) { string textAfterBackTick = typename.Substring(indexOfBackTick + 1); int genericParameterCount; if (Int32.TryParse(textAfterBackTick, out genericParameterCount) && (genericParameterCount > 0)) { // Replace the `Number with <,,,> where the count of ',' is one less than Number. StringBuilder genericTypeName = new StringBuilder(); genericTypeName.Append(typeNameSansBackTick); genericTypeName.Append('<'); if (genericParameterOffsets != null) { genericParameterOffsets.Add(genericTypeName.Length); } for (int i = 1; i < genericParameterCount; i++) { genericTypeName.Append(','); if (genericParameterOffsets != null) { genericParameterOffsets.Add(genericTypeName.Length); } } genericTypeName.Append('>'); return genericTypeName.ToString(); } } } return typename; } private static String GetTypeFullNameFromTypeDef(TypeDefinitionHandle typeDefinitionHandle, MetadataReader reader, List<int> genericParameterOffsets) { String s = ""; TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader); s = typeDefinition.Name.GetString(reader); TypeDefinitionHandle enclosingTypeDefHandle = typeDefinition.EnclosingType; if (!enclosingTypeDefHandle.IsNull(reader)) { String containingTypeName = GetTypeFullNameFromTypeDef(enclosingTypeDefHandle, reader, genericParameterOffsets); s = containingTypeName + "." + s; } else { NamespaceDefinitionHandle namespaceHandle = typeDefinition.NamespaceDefinition; for (; ;) { NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); String namespacePart = namespaceDefinition.Name.GetStringOrNull(reader); if (namespacePart == null) break; // Reached the root namespace. s = namespacePart + "." + s; if (namespaceDefinition.ParentScopeOrNamespace.HandleType != HandleType.NamespaceDefinition) break; // Should have reached the root namespace first but this helper is for ToString() - better to // return partial information than crash. namespaceHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader); } } return ConvertBackTickNameToNameWithReducerInputFormat(s, genericParameterOffsets); } public static bool TryGetArrayTypeElementType(RuntimeTypeHandle arrayTypeHandle, out RuntimeTypeHandle elementTypeHandle) { elementTypeHandle = RuntimeAugments.GetRelatedParameterTypeHandle(arrayTypeHandle); return true; } public static bool TryGetMultiDimArrayTypeElementType(RuntimeTypeHandle arrayTypeHandle, int rank, out RuntimeTypeHandle elementTypeHandle) { elementTypeHandle = default(RuntimeTypeHandle); if (rank != 2) return false; // Rank 2 arrays are really generic type of type MDArrayRank2<T>. RuntimeTypeHandle genericTypeDefinitionHandle; RuntimeTypeHandle[] genericTypeArgumentHandles; if (!DiagnosticMappingTables.TryGetConstructedGenericTypeComponents(arrayTypeHandle, out genericTypeDefinitionHandle, out genericTypeArgumentHandles)) return false; // This should really be an assert but this is used for generating diagnostic info so it's better to persevere and hope something useful gets printed out. if (genericTypeArgumentHandles.Length != 1) return false; elementTypeHandle = genericTypeArgumentHandles[0]; return true; } public static bool TryGetPointerTypeTargetType(RuntimeTypeHandle pointerTypeHandle, out RuntimeTypeHandle targetTypeHandle) { targetTypeHandle = RuntimeAugments.GetRelatedParameterTypeHandle(pointerTypeHandle); return true; } public static bool TryGetConstructedGenericTypeComponents(RuntimeTypeHandle runtimeTypeHandle, out RuntimeTypeHandle genericTypeDefinitionHandle, out RuntimeTypeHandle[] genericTypeArgumentHandles) { genericTypeDefinitionHandle = default(RuntimeTypeHandle); genericTypeArgumentHandles = null; // Check the regular tables first. if (ReflectionExecution.ExecutionEnvironment.TryGetConstructedGenericTypeComponents(runtimeTypeHandle, out genericTypeDefinitionHandle, out genericTypeArgumentHandles)) return true; // Now check the diagnostic tables. if (ReflectionExecution.ExecutionEnvironment.TryGetConstructedGenericTypeComponentsDiag(runtimeTypeHandle, out genericTypeDefinitionHandle, out genericTypeArgumentHandles)) return true; return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarTests { // GregorianCalendar.GetEra(DateTime) public class GregorianCalendarGetEra { private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private const int c_DAYS_IN_LEAP_YEAR = 366; private const int c_DAYS_IN_COMMON_YEAR = 365; private const int c_AD_ERA = 1; private const int c_CURRENT_ERA = 0; #region Positive tests // PosTest1: the speicified time is in leap year, February [Fact] public void PosTest1() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); DateTime time; int year, month; int expectedEra, actualEra; year = GetALeapYear(myCalendar); month = 2; time = myCalendar.ToDateTime(year, month, 29, 10, 30, 12, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest2: the speicified time is in leap year, any month other than February [Fact] public void PosTest2() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = GetALeapYear(myCalendar); //Get a random value beween 1 and 12 not including 2. do { month = _generator.GetInt32(-55) % 12 + 1; } while (2 == month); time = myCalendar.ToDateTime(year, month, 28, 10, 30, 20, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest3: the speicified time is in common year, February [Fact] public void PosTest3() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = GetACommonYear(myCalendar); month = 2; time = myCalendar.ToDateTime(year, month, 28, 10, 20, 30, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest4: the speicified time is in common year, any month other than February [Fact] public void PosTest4() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = GetACommonYear(myCalendar); //Get a random value beween 1 and 12 not including 2. do { month = _generator.GetInt32(-55) % 12 + 1; } while (2 == month); time = myCalendar.ToDateTime(year, month, 28, 10, 30, 20, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest5: the speicified time is in minimum supported year, any month [Fact] public void PosTest5() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = myCalendar.MinSupportedDateTime.Year; month = _generator.GetInt32(-55) % 12 + 1; time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest6: the speicified time is in maximum supported year, any month [Fact] public void PosTest6() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = myCalendar.MaxSupportedDateTime.Year; month = _generator.GetInt32(-55) % 12 + 1; time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest7: the speicified time is in any year, minimum month [Fact] public void PosTest7() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = myCalendar.MinSupportedDateTime.Year; month = 1; time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest8: the speicified time is in any year, maximum month [Fact] public void PosTest8() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = myCalendar.MaxSupportedDateTime.Year; month = 12; time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } // PosTest9: the speicified time is in any year, any month [Fact] public void PosTest9() { System.Globalization.Calendar myCalendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish); int year, month; DateTime time; int expectedEra, actualEra; year = GetAYear(myCalendar); month = _generator.GetInt32(-55) % 12 + 1; time = myCalendar.ToDateTime(year, month, 20, 8, 20, 30, 0); expectedEra = c_AD_ERA; actualEra = myCalendar.GetEra(time); Assert.Equal(expectedEra, actualEra); } #endregion #region Helper methods for all the tests //Indicate whether the specified year is leap year or not private bool IsLeapYear(int year) { if (0 == year % 400 || (0 != year % 100 && 0 == (year & 0x3))) { return true; } return false; } //Get a random year beween minmum supported year and maximum supported year of the specified calendar private int GetAYear(Calendar calendar) { int retVal; int maxYear, minYear; maxYear = calendar.MaxSupportedDateTime.Year; minYear = calendar.MinSupportedDateTime.Year; retVal = minYear + _generator.GetInt32(-55) % (maxYear + 1 - minYear); return retVal; } //Get a leap year of the specified calendar private int GetALeapYear(Calendar calendar) { int retVal; // A leap year is any year divisible by 4 except for centennial years(those ending in 00) // which are only leap years if they are divisible by 400. retVal = ~(~GetAYear(calendar) | 0x3); // retVal will be divisible by 4 since the 2 least significant bits will be 0 retVal = (0 != retVal % 100) ? retVal : (retVal - retVal % 400); // if retVal is divisible by 100 subtract years from it to make it divisible by 400 // if retVal was 100, 200, or 300 the above logic will result in 0 if (0 == retVal) { retVal = 400; } return retVal; } //Get a common year of the specified calendar private int GetACommonYear(Calendar calendar) { int retVal; do { retVal = GetAYear(calendar); } while ((0 == (retVal & 0x3) && 0 != retVal % 100) || 0 == retVal % 400); return retVal; } //Get text represntation of the input parmeters private string GetParamsInfo(int year) { string str; str = string.Format("\nThe specified year is {0:04}(yyyy).", year); return str; } //Get text represntation of the input parmeters private string GetParamsInfo(DateTime time) { string str; str = string.Format("\nThe specified time is ({0}).", time); return str; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace pltkw3msInventoryCatalog.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/11/2009 10:08:43 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; namespace DotSpatial.Symbology { /// <summary> /// Categorizable legend item. /// </summary> public abstract class Scheme : LegendItem { #region Private Variables #endregion #region Nested type: Break /// <summary> /// Breaks for value ranges /// </summary> protected class Break { /// <summary> /// A double value for the maximum value for the break /// </summary> public double? Maximum { get; set; } /// <summary> /// The string name /// </summary> public string Name { get; set; } /// <summary> /// Creates a new instance of a break /// </summary> public Break() { Name = string.Empty; Maximum = 0; } /// <summary> /// Creates a new instance of a break with a given name /// </summary> /// <param name="name">The string name for the break</param> public Break(string name) { Name = name; Maximum = 0; } } #endregion #region Constructors /// <summary> /// Creates a new instance of DrawingScheme /// </summary> protected Scheme() { base.LegendSymbolMode = SymbolMode.None; LegendType = LegendType.Scheme; Statistics = new Statistics(); } #endregion #region Methods /// <summary> /// Creates the category using a random fill color /// </summary> /// <param name="fillColor">The base color to use for creating the category</param> /// <param name="size">For points this is the larger dimension, for lines this is the largest width</param> /// <returns>A new IFeatureCategory that matches the type of this scheme</returns> public virtual ICategory CreateNewCategory(Color fillColor, double size) { // This method should be overridden in child classes return null; } /// <summary> /// Draws the regular symbolizer for the specified cateogry to the specified graphics /// surface in the specified bounding rectangle. /// </summary> /// <param name="index">The integer index of the feature to draw.</param> /// <param name="g">The Graphics object to draw to</param> /// <param name="bounds">The rectangular bounds to draw in</param> public abstract void DrawCategory(int index, Graphics g, Rectangle bounds); /// <summary> /// Adds a new scheme, assuming that the new scheme is the correct type. /// </summary> /// <param name="category">The category to add</param> public abstract void AddCategory(ICategory category); /// <summary> /// Reduces the index value of the specified category by 1 by /// exchaning it with the category before it. If there is no /// category before it, then this does nothing. /// </summary> /// <param name="category">The category to decrease the index of</param> public abstract bool DecreaseCategoryIndex(ICategory category); /// <summary> /// Removes the specified category /// </summary> /// <param name="category">The category to insert</param> public abstract void RemoveCategory(ICategory category); /// <summary> /// Inserts the category at the specified index /// </summary> /// <param name="index">The integer index where the category should be inserted</param> /// <param name="category">The category to insert</param> public abstract void InsertCategory(int index, ICategory category); /// <summary> /// Re-orders the specified member by attempting to exchange it with the next higher /// index category. If there is no higher index, this does nothing. /// </summary> /// <param name="category">The category to increase the index of</param> public abstract bool IncreaseCategoryIndex(ICategory category); /// <summary> /// Suspends the category events /// </summary> public abstract void SuspendEvents(); /// <summary> /// Resumes the category events /// </summary> public abstract void ResumeEvents(); /// <summary> /// Clears the categories /// </summary> public abstract void ClearCategories(); /// <summary> /// Generates the break categories for this scheme /// </summary> protected void CreateBreakCategories() { var count = EditorSettings.NumBreaks; switch (EditorSettings.IntervalMethod) { case IntervalMethod.EqualFrequency: Breaks = GetQuantileBreaks(count); break; case IntervalMethod.NaturalBreaks: Breaks = GetNaturalBreaks(count); break; default: Breaks = GetEqualBreaks(count); break; } ApplyBreakSnapping(); SetBreakNames(Breaks); var colorRamp = GetColorSet(count); var sizeRamp = GetSizeSet(count); ClearCategories(); var colorIndex = 0; Break prevBreak = null; foreach (var brk in Breaks) { //get the color for the category var randomColor = colorRamp[colorIndex]; var randomSize = sizeRamp[colorIndex]; var cat = CreateNewCategory(randomColor, randomSize); if (cat != null) { //cat.SelectionSymbolizer = _selectionSymbolizer.Copy(); cat.LegendText = brk.Name; if (prevBreak != null) cat.Minimum = prevBreak.Maximum; cat.Maximum = brk.Maximum; cat.Range.MaxIsInclusive = true; cat.ApplyMinMax(EditorSettings); AddCategory(cat); } prevBreak = brk; colorIndex++; } } /// <summary> /// THe defaul /// </summary> /// <param name="count"></param> /// <returns></returns> protected virtual List<double> GetSizeSet(int count) { var result = new List<double>(); for (var i = 0; i < count; i++) { result.Add(20); } return result; } /// <summary> /// Creates a list of generated colors according to the convention /// specified in the EditorSettings. /// </summary> /// <param name="count">The integer count of the number of colors to create.</param> /// <returns>The list of colors created.</returns> protected List<Color> GetColorSet(int count) { List<Color> colorRamp; if (EditorSettings.UseColorRange) { if (!EditorSettings.RampColors) { colorRamp = CreateRandomColors(count); } else if (!EditorSettings.HueSatLight) { colorRamp = CreateRampColors(count, EditorSettings.StartColor, EditorSettings.EndColor); } else { var cStart = EditorSettings.StartColor; var cEnd = EditorSettings.EndColor; colorRamp = CreateRampColors(count, cStart.GetSaturation(), cStart.GetBrightness(), (int)cStart.GetHue(), cEnd.GetSaturation(), cEnd.GetBrightness(), (int)cEnd.GetHue(), EditorSettings.HueShift, cStart.A, cEnd.A); } } else { colorRamp = GetDefaultColors(count); } return colorRamp; } /// <summary> /// Uses the settings on this scheme to create a random category. /// </summary> /// <returns>A new ICategory</returns> public abstract ICategory CreateRandomCategory(); /// <summary> /// Creates the colors in the case where the color range controls are not being used. /// This can be overriddend for handling special cases like ponit and line symbolizers /// that should be using the template colors. /// </summary> /// <param name="count">The integer count to use</param> /// <returns></returns> protected virtual List<Color> GetDefaultColors(int count) { return EditorSettings.RampColors ? CreateUnboundedRampColors(count) : CreateUnboundedRandomColors(count); } /// <summary> /// The default behavior for creating ramp colors is to create colors in the mid-range for /// both lightness and saturation, but to have the full range of hue /// </summary> /// <param name="numColors"></param> /// <returns></returns> private static List<Color> CreateUnboundedRampColors(int numColors) { return CreateRampColors(numColors, .25f, .25f, 0, .75f, .75f, 360, 0, 255, 255); } private static List<Color> CreateUnboundedRandomColors(int numColors) { var rnd = new Random(DateTime.Now.Millisecond); var result = new List<Color>(numColors); for (var i = 0; i < numColors; i++) { result.Add(rnd.NextColor()); } return result; } private List<Color> CreateRandomColors(int numColors) { var result = new List<Color>(numColors); var rnd = new Random(DateTime.Now.Millisecond); for (var i = 0; i < numColors; i++) { result.Add(CreateRandomColor(rnd)); } return result; } /// <summary> /// Creates a random color, but accepts a given random class instead of creating a new one. /// </summary> /// <param name="rnd"></param> /// <returns></returns> protected Color CreateRandomColor(Random rnd) { var startColor = EditorSettings.StartColor; var endColor = EditorSettings.EndColor; if (EditorSettings.HueSatLight) { double hLow = startColor.GetHue(); var dH = endColor.GetHue() - hLow; double sLow = startColor.GetSaturation(); var ds = endColor.GetSaturation() - sLow; double lLow = startColor.GetBrightness(); var dl = endColor.GetBrightness() - lLow; var aLow = (startColor.A) / 255.0; var da = (endColor.A - aLow) / 255.0; return SymbologyGlobal.ColorFromHsl(rnd.NextDouble() * dH + hLow, rnd.NextDouble() * ds + sLow, rnd.NextDouble() * dl + lLow).ToTransparent((float)(rnd.NextDouble() * da + aLow)); } int rLow = Math.Min(startColor.R, endColor.R); int rHigh = Math.Max(startColor.R, endColor.R); int gLow = Math.Min(startColor.G, endColor.G); int gHigh = Math.Max(startColor.G, endColor.G); int bLow = Math.Min(startColor.B, endColor.B); int bHigh = Math.Max(startColor.B, endColor.B); int iaLow = Math.Min(startColor.A, endColor.A); int aHigh = Math.Max(startColor.A, endColor.A); return Color.FromArgb(rnd.Next(iaLow, aHigh), rnd.Next(rLow, rHigh), rnd.Next(gLow, gHigh), rnd.Next(bLow, bHigh)); } private static List<Color> CreateRampColors(int numColors, Color startColor, Color endColor) { var result = new List<Color>(numColors); var dR = (endColor.R - (double)startColor.R) / numColors; var dG = (endColor.G - (double)startColor.G) / numColors; var dB = (endColor.B - (double)startColor.B) / numColors; var dA = (endColor.A - (double)startColor.A) / numColors; for (var i = 0; i < numColors; i++) { result.Add(Color.FromArgb((int)(startColor.A + dA * i), (int)(startColor.R + dR * i), (int)(startColor.G + dG * i), (int)(startColor.B + dB * i))); } return result; } /// <summary> /// Applies the snapping rule directly to the categories, based on the most recently /// collected set of values, and the current VectorEditorSettings. /// </summary> public void ApplySnapping(ICategory category) { category.ApplySnapping(EditorSettings.IntervalSnapMethod, EditorSettings.IntervalRoundingDigits, Values); } /// <summary> /// Uses the currently calculated Values in order to calculate a list of breaks /// that have equal separations. /// </summary> /// <param name="count"></param> /// <returns></returns> protected List<Break> GetEqualBreaks(int count) { var result = new List<Break>(); var min = Values[0]; var dx = (Values[Values.Count - 1] - min) / count; for (var i = 0; i < count; i++) { var brk = new Break(); // max if (i == count - 1) { brk.Maximum = null; } else { brk.Maximum = min + (i + 1) * dx; } result.Add(brk); } return result; } /// <summary> /// Applies the snapping type to the given breaks /// </summary> protected void ApplyBreakSnapping() { if (Values == null || Values.Count == 0) return; switch (EditorSettings.IntervalSnapMethod) { case IntervalSnapMethod.None: break; case IntervalSnapMethod.SignificantFigures: foreach (var item in Breaks) { if (item.Maximum == null) continue; var val = (double)item.Maximum; item.Maximum = Utils.SigFig(val, EditorSettings.IntervalRoundingDigits); } break; case IntervalSnapMethod.Rounding: foreach (var item in Breaks) { if (item.Maximum == null) continue; item.Maximum = Math.Round((double)item.Maximum, EditorSettings.IntervalRoundingDigits); } break; case IntervalSnapMethod.DataValue: foreach (var item in Breaks) { if (item.Maximum == null) continue; item.Maximum = Utils.GetNearestValue((double)item.Maximum, Values); } break; } } /// <summary> /// Attempts to create the specified number of breaks with equal numbers of members in each. /// </summary> /// <param name="count">The integer count.</param> /// <returns>A list of breaks.</returns> protected List<Break> GetQuantileBreaks(int count) { var result = new List<Break>(); var binSize = (int)Math.Ceiling(Values.Count / (double)count); for (var iBreak = 1; iBreak <= count; iBreak++) { if (binSize * iBreak < Values.Count) { var brk = new Break(); brk.Maximum = Values[binSize * iBreak]; result.Add(brk); } else { // if num breaks is larger than number of members, this can happen var brk = new Break(); brk.Maximum = null; result.Add(brk); break; } } return result; } /// <summary> /// Generates natural breaks. /// </summary> /// <param name="count">Count of breaks.</param> /// <returns>List with breaks.</returns> protected List<Break> GetNaturalBreaks(int count) { var breaks = new JenksBreaksCalcuation(Values, count); breaks.Optimize(); var results = breaks.GetResults(); var output = new List<Break>(count); output.AddRange(results.Select(result => new Break { Maximum = Values[result] })); // Set latest Maximum to null output.Last().Maximum = null; return output; } /// <summary> /// Sets the names for the break categories. /// </summary> protected static void SetBreakNames(IList<Break> breaks) { for (var i = 0; i < breaks.Count; i++) { var brk = breaks[i]; if (breaks.Count == 1) { brk.Name = "All Values"; } else if (i == 0) { brk.Name = "<= " + brk.Maximum; } else if (i == breaks.Count - 1) { brk.Name = "> " + breaks[i - 1].Maximum; } else { brk.Name = breaks[i - 1].Maximum + " - " + brk.Maximum; } } } private static List<Color> CreateRampColors(int numColors, float minSat, float minLight, int minHue, float maxSat, float maxLight, int maxHue, int hueShift, int minAlpha, int maxAlpha) { var result = new List<Color>(numColors); var ds = (maxSat - (double)minSat) / numColors; var dh = (maxHue - (double)minHue) / numColors; var dl = (maxLight - (double)minLight) / numColors; var dA = (maxAlpha - (double)minAlpha) / numColors; for (var i = 0; i < numColors; i++) { var h = (minHue + dh * i) + hueShift % 360; var s = minSat + ds * i; var l = minLight + dl * i; var a = (float)(minAlpha + dA * i) / 255f; result.Add(SymbologyGlobal.ColorFromHsl(h, s, l).ToTransparent(a)); } return result; } #endregion #region Properties /// <summary> /// Gets or sets the editor settings that control how this scheme operates. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public EditorSettings EditorSettings { get; set; } /// <summary> /// This is cached until a GetValues call is made, at which time the statistics will /// be re-calculated from the values. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Statistics Statistics { get; protected set; } /// <summary> /// Gets or sets the list of breaks for this scheme /// </summary> protected List<Break> Breaks { get; set; } /// <summary> /// Gets the current list of values calculated in the case of numeric breaks. /// This includes only members that are not excluded by the exclude expression, /// and have a valid numeric value. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public List<double> Values { get; protected set; } #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.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading.Tests; using Xunit; namespace System.Threading.Threads.Tests { public class DummyClass : RemoteExecutorTestBase { public static string HostRunnerTest = HostRunner; } public static class ThreadTests { private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds; private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds; [Fact] public static void ConstructorTest() { Action<Thread> startThreadAndJoin = t => { t.IsBackground = true; t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); }; Action<int> verifyStackSize = stackSizeBytes => { // Try to stack-allocate an array to verify that close to the expected amount of stack space is actually // available int bufferSizeBytes = Math.Max(16 << 10, stackSizeBytes - (64 << 10)); unsafe { byte* buffer = stackalloc byte[bufferSizeBytes]; Volatile.Write(ref buffer[0], 0xff); Volatile.Write(ref buffer[bufferSizeBytes - 1], 0xff); } }; startThreadAndJoin(new Thread(() => verifyStackSize(0))); startThreadAndJoin(new Thread(() => verifyStackSize(0), 0)); startThreadAndJoin(new Thread(() => verifyStackSize(64 << 10), 64 << 10)); // 64 KB startThreadAndJoin(new Thread(() => verifyStackSize(16 << 20), 16 << 20)); // 16 MB startThreadAndJoin(new Thread(state => verifyStackSize(0))); startThreadAndJoin(new Thread(state => verifyStackSize(0), 0)); startThreadAndJoin(new Thread(state => verifyStackSize(64 << 10), 64 << 10)); // 64 KB startThreadAndJoin(new Thread(state => verifyStackSize(16 << 20), 16 << 20)); // 16 MB Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null)); Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null, 0)); Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null)); Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(() => { }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(state => { }, -1)); } private static IEnumerable<object[]> ApartmentStateTest_MemberData() { yield return new object[] { #pragma warning disable 618 // Obsolete members new Func<Thread, ApartmentState>(t => t.ApartmentState), #pragma warning restore 618 // Obsolete members new Func<Thread, ApartmentState, int>( (t, value) => { try { #pragma warning disable 618 // Obsolete members t.ApartmentState = value; #pragma warning restore 618 // Obsolete members return 0; } catch (ArgumentOutOfRangeException) { return 1; } catch (PlatformNotSupportedException) { return 3; } }), 0 }; yield return new object[] { new Func<Thread, ApartmentState>(t => t.GetApartmentState()), new Func<Thread, ApartmentState, int>( (t, value) => { try { t.SetApartmentState(value); return 0; } catch (ArgumentOutOfRangeException) { return 1; } catch (InvalidOperationException) { return 2; } catch (PlatformNotSupportedException) { return 3; } }), 1 }; yield return new object[] { new Func<Thread, ApartmentState>(t => t.GetApartmentState()), new Func<Thread, ApartmentState, int>( (t, value) => { try { return t.TrySetApartmentState(value) ? 0 : 2; } catch (ArgumentOutOfRangeException) { return 1; } catch (PlatformNotSupportedException) { return 3; } }), 2 }; } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [InlineData("STAMain.exe", "GetApartmentState")] [InlineData("STAMain.exe", "SetApartmentState")] [InlineData("MTAMain.exe", "GetApartmentState")] [InlineData("MTAMain.exe", "SetApartmentState")] [ActiveIssue(20766, TargetFrameworkMonikers.Uap)] public static void ApartmentState_AttributePresent(string AppName, string mode) { var psi = new ProcessStartInfo(); if (PlatformDetection.IsFullFramework || PlatformDetection.IsNetNative) { psi.FileName = AppName; psi.Arguments = $"{mode}"; } else { psi.FileName = DummyClass.HostRunnerTest; psi.Arguments = $"{AppName} {mode}"; } using (Process p = Process.Start(psi)) { p.WaitForExit(); Assert.Equal(PlatformDetection.IsWindows ? 0 : 2, p.ExitCode); } } [Fact] [ActiveIssue(20766,TargetFrameworkMonikers.UapAot)] [PlatformSpecific(TestPlatforms.Windows)] public static void ApartmentState_NoAttributePresent_DefaultState_Windows() { DummyClass.RemoteInvoke(() => { Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState()); Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA)); Thread.CurrentThread.SetApartmentState(ApartmentState.MTA); }).Dispose(); } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] [ActiveIssue(20766,TargetFrameworkMonikers.UapAot)] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void ApartmentState_NoAttributePresent_STA_Windows_Core() { DummyClass.RemoteInvoke(() => { Thread.CurrentThread.SetApartmentState(ApartmentState.STA); Assert.Equal(ApartmentState.STA, Thread.CurrentThread.GetApartmentState()); Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.MTA)); }).Dispose(); } // The Thread Apartment State is set to MTA if attribute is not specified on main function [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public static void ApartmentState_NoAttributePresent_STA_Windows_Desktop() { DummyClass.RemoteInvoke(() => { Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA)); Thread.CurrentThread.SetApartmentState(ApartmentState.MTA); Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState()); }).Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public static void ApartmentState_NoAttributePresent_DefaultState_Unix() { DummyClass.RemoteInvoke(() => { Assert.Equal(ApartmentState.Unknown, Thread.CurrentThread.GetApartmentState()); Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.MTA)); }).Dispose(); } // Thread is always initialized as MTA irrespective of the attribute present. [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindowsNanoServer))] public static void ApartmentState_NoAttributePresent_DefaultState_Nano() { DummyClass.RemoteInvoke(() => { Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA)); Assert.Equal(ApartmentState.MTA, Thread.CurrentThread.GetApartmentState()); }).Dispose(); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public static void ApartmentState_NoAttributePresent_STA_Unix() { DummyClass.RemoteInvoke(() => { Assert.Throws<PlatformNotSupportedException>(() => Thread.CurrentThread.SetApartmentState(ApartmentState.STA)); }).Dispose(); } [Theory] [MemberData(nameof(ApartmentStateTest_MemberData))] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows [ActiveIssue(20766,TargetFrameworkMonikers.UapAot)] public static void GetSetApartmentStateTest_ChangeAfterThreadStarted_Windows( Func<Thread, ApartmentState> getApartmentState, Func<Thread, ApartmentState, int> setApartmentState, int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */) { ThreadTestHelpers.RunTestInBackgroundThread(() => { var t = Thread.CurrentThread; Assert.Equal(1, setApartmentState(t, ApartmentState.STA - 1)); Assert.Equal(1, setApartmentState(t, ApartmentState.Unknown + 1)); Assert.Equal(ApartmentState.MTA, getApartmentState(t)); Assert.Equal(0, setApartmentState(t, ApartmentState.MTA)); Assert.Equal(ApartmentState.MTA, getApartmentState(t)); Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.STA)); // cannot be changed after thread is started Assert.Equal(ApartmentState.MTA, getApartmentState(t)); }); } [Theory] [MemberData(nameof(ApartmentStateTest_MemberData))] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows [ActiveIssue(20766,TargetFrameworkMonikers.UapAot)] public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows( Func<Thread, ApartmentState> getApartmentState, Func<Thread, ApartmentState, int> setApartmentState, int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */) { ApartmentState apartmentStateInThread = ApartmentState.Unknown; Thread t = null; t = new Thread(() => apartmentStateInThread = getApartmentState(t)); t.IsBackground = true; Assert.Equal(0, setApartmentState(t, ApartmentState.STA)); Assert.Equal(ApartmentState.STA, getApartmentState(t)); Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once Assert.Equal(ApartmentState.STA, getApartmentState(t)); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); if (PlatformDetection.IsWindowsNanoServer) { // Nano server threads are always MTA. If you set the thread to STA // it will read back as STA but when the thread starts it will read back as MTA. Assert.Equal(ApartmentState.MTA, apartmentStateInThread); } else { Assert.Equal(ApartmentState.STA, apartmentStateInThread); } } [Theory] [MemberData(nameof(ApartmentStateTest_MemberData))] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior differs on Unix and Windows public static void ApartmentStateTest_Unix( Func<Thread, ApartmentState> getApartmentState, Func<Thread, ApartmentState, int> setApartmentState, int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */) { var t = new Thread(() => { }); Assert.Equal(ApartmentState.Unknown, getApartmentState(t)); Assert.Equal(0, setApartmentState(t, ApartmentState.Unknown)); int expectedFailure; switch (setType) { case 0: expectedFailure = 0; // ApartmentState setter - no exception, but value does not change break; case 1: expectedFailure = 3; // SetApartmentState - InvalidOperationException break; default: expectedFailure = 2; // TrySetApartmentState - returns false break; } Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.STA)); Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.MTA)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] public static void CurrentCultureTest_SkipOnDesktopFramework() { // Cannot access culture properties on a thread object from a different thread var t = new Thread(() => { }); Assert.Throws<InvalidOperationException>(() => t.CurrentCulture); Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture); } [Fact] public static void CurrentCultureTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var t = Thread.CurrentThread; var originalCulture = CultureInfo.CurrentCulture; var originalUICulture = CultureInfo.CurrentUICulture; var otherCulture = CultureInfo.InvariantCulture; // Culture properties return the same value as those on CultureInfo Assert.Equal(originalCulture, t.CurrentCulture); Assert.Equal(originalUICulture, t.CurrentUICulture); try { // Changing culture properties on CultureInfo causes the values of properties on the current thread to change CultureInfo.CurrentCulture = otherCulture; CultureInfo.CurrentUICulture = otherCulture; Assert.Equal(otherCulture, t.CurrentCulture); Assert.Equal(otherCulture, t.CurrentUICulture); // Changing culture properties on the current thread causes new values to be returned, and causes the values of // properties on CultureInfo to change t.CurrentCulture = originalCulture; t.CurrentUICulture = originalUICulture; Assert.Equal(originalCulture, t.CurrentCulture); Assert.Equal(originalUICulture, t.CurrentUICulture); Assert.Equal(originalCulture, CultureInfo.CurrentCulture); Assert.Equal(originalUICulture, CultureInfo.CurrentUICulture); } finally { CultureInfo.CurrentCulture = originalCulture; CultureInfo.CurrentUICulture = originalUICulture; } Assert.Throws<ArgumentNullException>(() => t.CurrentCulture = null); Assert.Throws<ArgumentNullException>(() => t.CurrentUICulture = null); }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] public static void CurrentPrincipalTest_SkipOnDesktopFramework() { ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Null(Thread.CurrentPrincipal)); } [Fact] public static void CurrentPrincipalTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var originalPrincipal = Thread.CurrentPrincipal; var otherPrincipal = new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[] { string.Empty }); Thread.CurrentPrincipal = otherPrincipal; Assert.Equal(otherPrincipal, Thread.CurrentPrincipal); Thread.CurrentPrincipal = originalPrincipal; Assert.Equal(originalPrincipal, Thread.CurrentPrincipal); }); } [Fact] public static void CurrentThreadTest() { Thread otherThread = null; var t = new Thread(() => otherThread = Thread.CurrentThread); t.IsBackground = true; t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.Equal(t, otherThread); var mainThread = Thread.CurrentThread; Assert.NotNull(mainThread); Assert.NotEqual(mainThread, otherThread); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] public static void ExecutionContextTest() { ThreadTestHelpers.RunTestInBackgroundThread( () => Assert.Equal(ExecutionContext.Capture(), Thread.CurrentThread.ExecutionContext)); } [Fact] public static void IsAliveTest() { var isAliveWhenRunning = false; Thread t = null; t = new Thread(() => isAliveWhenRunning = t.IsAlive); t.IsBackground = true; Assert.False(t.IsAlive); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.True(isAliveWhenRunning); Assert.False(t.IsAlive); } [Fact] public static void IsBackgroundTest() { var t = new Thread(() => { }); Assert.False(t.IsBackground); t.IsBackground = true; Assert.True(t.IsBackground); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); // Cannot use this property after the thread is dead Assert.Throws<ThreadStateException>(() => t.IsBackground); Assert.Throws<ThreadStateException>(() => t.IsBackground = false); Assert.Throws<ThreadStateException>(() => t.IsBackground = true); // Verify that the test process can shut down gracefully with a hung background thread t = new Thread(() => Thread.Sleep(Timeout.Infinite)); t.IsBackground = true; t.Start(); } [Fact] public static void IsThreadPoolThreadTest() { var isThreadPoolThread = false; Thread t = null; t = new Thread(() => { isThreadPoolThread = t.IsThreadPoolThread; }); t.IsBackground = true; Assert.False(t.IsThreadPoolThread); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.False(isThreadPoolThread); var e = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem( state => { isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread; e.Set(); }); e.CheckedWait(); Assert.True(isThreadPoolThread); } [Fact] public static void ManagedThreadIdTest() { var e = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; t.Start(); Assert.NotEqual(Thread.CurrentThread.ManagedThreadId, t.ManagedThreadId); e.Set(); waitForThread(); } [Fact] public static void NameTest() { var t = new Thread(() => { }); Assert.Null(t.Name); t.Name = "a"; Assert.Equal("a", t.Name); Assert.Throws<InvalidOperationException>(() => t.Name = "b"); Assert.Equal("a", t.Name); } [Fact] public static void PriorityTest() { var e = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; Assert.Equal(ThreadPriority.Normal, t.Priority); t.Priority = ThreadPriority.AboveNormal; Assert.Equal(ThreadPriority.AboveNormal, t.Priority); t.Start(); Assert.Equal(ThreadPriority.AboveNormal, t.Priority); t.Priority = ThreadPriority.Normal; Assert.Equal(ThreadPriority.Normal, t.Priority); e.Set(); waitForThread(); } [Fact] [ActiveIssue(20766, TargetFrameworkMonikers.UapAot)] public static void ThreadStateTest() { var e0 = new ManualResetEvent(false); var e1 = new AutoResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { e0.CheckedWait(); ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0)); }); Assert.Equal(ThreadState.Unstarted, t.ThreadState); t.IsBackground = true; Assert.Equal(ThreadState.Unstarted | ThreadState.Background, t.ThreadState); t.Start(); ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.WaitSleepJoin | ThreadState.Background)); e0.Set(); ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.Running | ThreadState.Background)); e1.Set(); waitForThread(); Assert.Equal(ThreadState.Stopped, t.ThreadState); t = ThreadTestHelpers.CreateGuardedThread( out waitForThread, () => ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0))); t.Start(); ThreadTestHelpers.WaitForCondition(() => t.ThreadState == ThreadState.Running); e1.Set(); waitForThread(); Assert.Equal(ThreadState.Stopped, t.ThreadState); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] public static void AbortSuspendTest() { var e = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; Action verify = () => { Assert.Throws<PlatformNotSupportedException>(() => t.Abort()); Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t)); #pragma warning disable 618 // Obsolete members Assert.Throws<PlatformNotSupportedException>(() => t.Suspend()); Assert.Throws<PlatformNotSupportedException>(() => t.Resume()); #pragma warning restore 618 // Obsolete members }; verify(); t.Start(); verify(); e.Set(); waitForThread(); Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort()); } private static void VerifyLocalDataSlot(LocalDataStoreSlot slot) { Assert.NotNull(slot); var waitForThreadArray = new Action[2]; var threadArray = new Thread[2]; var barrier = new Barrier(threadArray.Length); var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; Func<bool> barrierSignalAndWait = () => { try { Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken)); } catch (OperationCanceledException) { return false; } return true; }; Action<int> threadMain = threadIndex => { try { Assert.Null(Thread.GetData(slot)); if (!barrierSignalAndWait()) { return; } if (threadIndex == 0) { Thread.SetData(slot, threadIndex); } if (!barrierSignalAndWait()) { return; } if (threadIndex == 0) { Assert.Equal(threadIndex, Thread.GetData(slot)); } else { Assert.Null(Thread.GetData(slot)); } if (!barrierSignalAndWait()) { return; } if (threadIndex != 0) { Thread.SetData(slot, threadIndex); } if (!barrierSignalAndWait()) { return; } Assert.Equal(threadIndex, Thread.GetData(slot)); if (!barrierSignalAndWait()) { return; } } catch (Exception ex) { cancellationTokenSource.Cancel(); throw new TargetInvocationException(ex); } }; for (int i = 0; i < threadArray.Length; ++i) { threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i)); threadArray[i].IsBackground = true; threadArray[i].Start(); } foreach (var waitForThread in waitForThreadArray) { waitForThread(); } } [Fact] public static void LocalDataSlotTest() { var slot = Thread.AllocateDataSlot(); var slot2 = Thread.AllocateDataSlot(); Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); var slotName = "System.Threading.Threads.Tests.LocalDataSlotTest"; var slotName2 = slotName + ".2"; var invalidSlotName = slotName + ".Invalid"; try { // AllocateNamedDataSlot allocates slot = Thread.AllocateNamedDataSlot(slotName); AssertExtensions.Throws<ArgumentException>(null, () => Thread.AllocateNamedDataSlot(slotName)); slot2 = Thread.AllocateNamedDataSlot(slotName2); Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); // Free the same slot twice, should be fine Thread.FreeNamedDataSlot(slotName2); Thread.FreeNamedDataSlot(slotName2); } catch (Exception ex) { Thread.FreeNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName2); throw new TargetInvocationException(ex); } try { // GetNamedDataSlot gets or allocates var tempSlot = Thread.GetNamedDataSlot(slotName); Assert.Equal(slot, tempSlot); tempSlot = Thread.GetNamedDataSlot(slotName2); Assert.NotEqual(slot2, tempSlot); slot2 = tempSlot; Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); } finally { Thread.FreeNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName2); } try { // A named slot can be used after the name is freed, since only the name is freed, not the slot slot = Thread.AllocateNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName); slot2 = Thread.AllocateNamedDataSlot(slotName); // same name Thread.FreeNamedDataSlot(slotName); Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); } finally { Thread.FreeNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName2); } } [Fact] [ActiveIssue(20766, TargetFrameworkMonikers.UapAot)] public static void InterruptTest() { // Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets // interrupted and does not auto-reset the signaled event var threadReady = new AutoResetEvent(false); var continueThread = new AutoResetEvent(false); bool continueThreadBool = false; Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { threadReady.Set(); ThreadTestHelpers.WaitForConditionWithoutBlocking(() => Volatile.Read(ref continueThreadBool)); threadReady.Set(); Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()); }); t.IsBackground = true; t.Start(); threadReady.CheckedWait(); continueThread.Set(); t.Interrupt(); Assert.False(threadReady.WaitOne(ExpectedTimeoutMilliseconds)); Volatile.Write(ref continueThreadBool, true); waitForThread(); Assert.True(continueThread.WaitOne(0)); // Interrupting a dead thread does nothing t.Interrupt(); // Interrupting an unstarted thread causes the thread to be interrupted after it is started and starts blocking t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait())); t.IsBackground = true; t.Interrupt(); t.Start(); waitForThread(); // A thread that is already blocked on a synchronization primitive unblocks immediately continueThread.Reset(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait())); t.IsBackground = true; t.Start(); ThreadTestHelpers.WaitForCondition(() => (t.ThreadState & ThreadState.WaitSleepJoin) != 0); t.Interrupt(); waitForThread(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] [ActiveIssue(20766,TargetFrameworkMonikers.UapAot)] public static void InterruptInFinallyBlockTest_SkipOnDesktopFramework() { // A wait in a finally block can be interrupted. The desktop framework applies the same rules as thread abort, and // does not allow thread interrupt in a finally block. There is nothing special about thread interrupt that requires // not allowing it in finally blocks, so this behavior has changed in .NET Core. var continueThread = new AutoResetEvent(false); Action waitForThread; Thread t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { try { } finally { Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()); } }); t.IsBackground = true; t.Start(); t.Interrupt(); waitForThread(); } [Fact] public static void JoinTest() { var threadReady = new ManualResetEvent(false); var continueThread = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { threadReady.Set(); continueThread.CheckedWait(); Thread.Sleep(ExpectedTimeoutMilliseconds); }); t.IsBackground = true; Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds((double)int.MaxValue + 1))); Assert.Throws<ThreadStateException>(() => t.Join()); Assert.Throws<ThreadStateException>(() => t.Join(UnexpectedTimeoutMilliseconds)); Assert.Throws<ThreadStateException>(() => t.Join(TimeSpan.FromMilliseconds(UnexpectedTimeoutMilliseconds))); t.Start(); threadReady.CheckedWait(); Assert.False(t.Join(ExpectedTimeoutMilliseconds)); Assert.False(t.Join(TimeSpan.FromMilliseconds(ExpectedTimeoutMilliseconds))); continueThread.Set(); waitForThread(); Assert.True(t.Join(0)); Assert.True(t.Join(TimeSpan.Zero)); } [Fact] public static void SleepTest() { Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds((double)int.MaxValue + 1))); Thread.Sleep(0); var stopwatch = Stopwatch.StartNew(); Thread.Sleep(500); stopwatch.Stop(); Assert.InRange((int)stopwatch.ElapsedMilliseconds, 100, int.MaxValue); } [Fact] public static void StartTest() { var e = new AutoResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; Assert.Throws<InvalidOperationException>(() => t.Start(null)); Assert.Throws<InvalidOperationException>(() => t.Start(t)); t.Start(); Assert.Throws<ThreadStateException>(() => t.Start()); e.Set(); waitForThread(); Assert.Throws<ThreadStateException>(() => t.Start()); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => e.CheckedWait()); t.IsBackground = true; t.Start(); Assert.Throws<ThreadStateException>(() => t.Start()); Assert.Throws<ThreadStateException>(() => t.Start(null)); Assert.Throws<ThreadStateException>(() => t.Start(t)); e.Set(); waitForThread(); Assert.Throws<ThreadStateException>(() => t.Start()); Assert.Throws<ThreadStateException>(() => t.Start(null)); Assert.Throws<ThreadStateException>(() => t.Start(t)); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Null(parameter)); t.IsBackground = true; t.Start(); waitForThread(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Null(parameter)); t.IsBackground = true; t.Start(null); waitForThread(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Equal(t, parameter)); t.IsBackground = true; t.Start(t); waitForThread(); } [Fact] [ActiveIssue(20766,TargetFrameworkMonikers.UapAot)] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono)] public static void MiscellaneousTest() { Thread.BeginCriticalRegion(); Thread.EndCriticalRegion(); Thread.BeginThreadAffinity(); Thread.EndThreadAffinity(); ThreadTestHelpers.RunTestInBackgroundThread(() => { // TODO: Port tests for these once all of the necessary interop APIs are available Thread.CurrentThread.DisableComObjectEagerCleanup(); Marshal.CleanupUnusedObjectsInCurrentContext(); }); #pragma warning disable 618 // obsolete members Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack()); Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture())); #pragma warning restore 618 // obsolete members Thread.MemoryBarrier(); var ad = Thread.GetDomain(); Assert.NotNull(ad); Assert.Equal(AppDomain.CurrentDomain, ad); Assert.Equal(ad.Id, Thread.GetDomainID()); Thread.SpinWait(int.MinValue); Thread.SpinWait(-1); Thread.SpinWait(0); Thread.SpinWait(1); Thread.Yield(); } } }
/* * 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 log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; //using HyperGrid.Framework; //using OpenSim.Region.Communications.Hypergrid; namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { public class HGAssetMapper { #region Fields private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // This maps between inventory server urls and inventory server clients // private Dictionary<string, InventoryClient> m_inventoryServers = new Dictionary<string, InventoryClient>(); private Scene m_scene; #endregion #region Constructor public HGAssetMapper(Scene scene) { m_scene = scene; } #endregion #region Internal functions public AssetBase FetchAsset(string url, UUID assetID) { AssetBase asset = m_scene.AssetService.Get(url + "/" + assetID.ToString()); if (asset != null) { m_log.DebugFormat("[HG ASSET MAPPER]: Copied asset {0} from {1} to local asset server. ", asset.ID, url); return asset; } return null; } public bool PostAsset(string url, AssetBase asset) { if (asset != null) { // See long comment in AssetCache.AddAsset if (!asset.Temporary || asset.Local) { // We need to copy the asset into a new asset, because // we need to set its ID to be URL+UUID, so that the // HGAssetService dispatches it to the remote grid. // It's not pretty, but the best that can be done while // not having a global naming infrastructure AssetBase asset1 = new AssetBase(asset.FullID, asset.Name, asset.Type, asset.Metadata.CreatorID); Copy(asset, asset1); try { asset1.ID = url + "/" + asset.ID; // UUID temp = UUID.Zero; // TODO: if the creator is local, stick this grid's URL in front //if (UUID.TryParse(asset.Metadata.CreatorID, out temp)) // asset1.Metadata.CreatorID = ??? + "/" + asset.Metadata.CreatorID; } catch { m_log.Warn("[HG ASSET MAPPER]: Oops."); } m_scene.AssetService.Store(asset1); m_log.DebugFormat("[HG ASSET MAPPER]: Posted copy of asset {0} from local asset server to {1}", asset1.ID, url); } return true; } else m_log.Warn("[HG ASSET MAPPER]: Tried to post asset to remote server, but asset not in local cache."); return false; } private void Copy(AssetBase from, AssetBase to) { to.Data = from.Data; to.Description = from.Description; to.FullID = from.FullID; to.ID = from.ID; to.Local = from.Local; to.Name = from.Name; to.Temporary = from.Temporary; to.Type = from.Type; } // TODO: unused // private void Dump(Dictionary<UUID, bool> lst) // { // m_log.Debug("XXX -------- UUID DUMP ------- XXX"); // foreach (KeyValuePair<UUID, bool> kvp in lst) // m_log.Debug(" >> " + kvp.Key + " (texture? " + kvp.Value + ")"); // m_log.Debug("XXX -------- UUID DUMP ------- XXX"); // } #endregion #region Public interface public void Get(UUID assetID, UUID ownerID, string userAssetURL) { // Get the item from the remote asset server onto the local AssetCache // and place an entry in m_assetMap m_log.Debug("[HG ASSET MAPPER]: Fetching object " + assetID + " from asset server " + userAssetURL); AssetBase asset = FetchAsset(userAssetURL, assetID); if (asset != null) { // OK, now fetch the inside. Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>(); HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, userAssetURL); uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids); if (ids.ContainsKey(assetID)) ids.Remove(assetID); foreach (UUID uuid in ids.Keys) FetchAsset(userAssetURL, uuid); m_log.DebugFormat("[HG ASSET MAPPER]: Successfully fetched asset {0} from asset server {1}", asset.ID, userAssetURL); } else m_log.Warn("[HG ASSET MAPPER]: Could not fetch asset from remote asset server " + userAssetURL); } public void Post(UUID assetID, UUID ownerID, string userAssetURL) { // Post the item from the local AssetCache onto the remote asset server // and place an entry in m_assetMap m_log.Debug("[HG ASSET MAPPER]: Posting object " + assetID + " to asset server " + userAssetURL); AssetBase asset = m_scene.AssetService.Get(assetID.ToString()); if (asset != null) { Dictionary<UUID, AssetType> ids = new Dictionary<UUID, AssetType>(); HGUuidGatherer uuidGatherer = new HGUuidGatherer(this, m_scene.AssetService, string.Empty); uuidGatherer.GatherAssetUuids(asset.FullID, (AssetType)asset.Type, ids); foreach (UUID uuid in ids.Keys) { asset = m_scene.AssetService.Get(uuid.ToString()); if (asset == null) m_log.DebugFormat("[HG ASSET MAPPER]: Could not find asset {0}", uuid); else PostAsset(userAssetURL, asset); } // maybe all pieces got there... m_log.DebugFormat("[HG ASSET MAPPER]: Successfully posted item {0} to asset server {1}", assetID, userAssetURL); } else m_log.DebugFormat("[HG ASSET MAPPER]: Something wrong with asset {0}, it could not be found", assetID); } #endregion } }
#nullable enable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Abstractions.Constants; using BTCPayServer.Abstractions.Extensions; using BTCPayServer.Client; using BTCPayServer.Client.Models; using BTCPayServer.Configuration; using BTCPayServer.Data; using BTCPayServer.Events; using BTCPayServer.Logging; using BTCPayServer.Security; using BTCPayServer.Security.Greenfield; using BTCPayServer.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using NicolasDorier.RateLimits; namespace BTCPayServer.Controllers.Greenfield { [ApiController] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [EnableCors(CorsPolicies.All)] public class GreenfieldUsersController : ControllerBase { public Logs Logs { get; } private readonly UserManager<ApplicationUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly SettingsRepository _settingsRepository; private readonly EventAggregator _eventAggregator; private readonly IPasswordValidator<ApplicationUser> _passwordValidator; private readonly RateLimitService _throttleService; private readonly BTCPayServerOptions _options; private readonly IAuthorizationService _authorizationService; private readonly UserService _userService; public GreenfieldUsersController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, SettingsRepository settingsRepository, EventAggregator eventAggregator, IPasswordValidator<ApplicationUser> passwordValidator, RateLimitService throttleService, BTCPayServerOptions options, IAuthorizationService authorizationService, UserService userService, Logs logs) { this.Logs = logs; _userManager = userManager; _roleManager = roleManager; _settingsRepository = settingsRepository; _eventAggregator = eventAggregator; _passwordValidator = passwordValidator; _throttleService = throttleService; _options = options; _authorizationService = authorizationService; _userService = userService; } [Authorize(Policy = Policies.CanViewUsers, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/users/{idOrEmail}")] public async Task<IActionResult> GetUser(string idOrEmail) { var user = (await _userManager.FindByIdAsync(idOrEmail) ) ?? await _userManager.FindByEmailAsync(idOrEmail); if (user != null) { return Ok(await FromModel(user)); } return UserNotFound(); } [Authorize(Policy = Policies.CanViewUsers, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/users/")] public async Task<ActionResult<ApplicationUserData[]>> GetUsers() { return Ok(await _userService.GetUsersWithRoles()); } [Authorize(Policy = Policies.CanViewProfile, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpGet("~/api/v1/users/me")] public async Task<ActionResult<ApplicationUserData>> GetCurrentUser() { var user = await _userManager.GetUserAsync(User); return await FromModel(user); } [Authorize(Policy = Policies.CanDeleteUser, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] [HttpDelete("~/api/v1/users/me")] public async Task<IActionResult> DeleteCurrentUser() { return await DeleteUser(_userManager.GetUserId(User)); } [AllowAnonymous] [HttpPost("~/api/v1/users")] public async Task<IActionResult> CreateUser(CreateApplicationUserRequest request, CancellationToken cancellationToken = default) { if (request.Email is null) ModelState.AddModelError(nameof(request.Email), "Email is missing"); if (!string.IsNullOrEmpty(request.Email) && !Validation.EmailValidator.IsEmail(request.Email)) { ModelState.AddModelError(nameof(request.Email), "Invalid email"); } if (request.Password is null) ModelState.AddModelError(nameof(request.Password), "Password is missing"); if (!ModelState.IsValid) { return this.CreateValidationError(ModelState); } if (User.Identity is null) throw new JsonHttpException(this.StatusCode(401)); var anyAdmin = (await _userManager.GetUsersInRoleAsync(Roles.ServerAdmin)).Any(); var policies = await _settingsRepository.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings(); var isAuth = User.Identity.AuthenticationType == GreenfieldConstants.AuthenticationType; // If registration are locked and that an admin exists, don't accept unauthenticated connection if (anyAdmin && policies.LockSubscription && !isAuth) return this.CreateAPIError(401, "unauthenticated", "New user creation isn't authorized to users who are not admin"); // Even if subscription are unlocked, it is forbidden to create admin unauthenticated if (anyAdmin && request.IsAdministrator is true && !isAuth) return this.CreateAPIError(401, "unauthenticated", "New admin creation isn't authorized to users who are not admin"); // You are de-facto admin if there is no other admin, else you need to be auth and pass policy requirements bool isAdmin = anyAdmin ? (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanModifyServerSettings))).Succeeded && (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.Unrestricted))).Succeeded && isAuth : true; // You need to be admin to create an admin if (request.IsAdministrator is true && !isAdmin) return this.CreateAPIPermissionError(Policies.Unrestricted, $"Insufficient API Permissions. Please use an API key with permission: {Policies.Unrestricted} and be an admin."); if (!isAdmin && (policies.LockSubscription || (await _settingsRepository.GetPolicies()).DisableNonAdminCreateUserApi)) { // If we are not admin and subscriptions are locked, we need to check the Policies.CanCreateUser.Key permission var canCreateUser = (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanCreateUser))).Succeeded; if (!isAuth || !canCreateUser) return this.CreateAPIPermissionError(Policies.CanCreateUser); } var user = new ApplicationUser { UserName = request.Email, Email = request.Email, RequiresEmailConfirmation = policies.RequiresConfirmedEmail, Created = DateTimeOffset.UtcNow, }; var passwordValidation = await this._passwordValidator.ValidateAsync(_userManager, user, request.Password); if (!passwordValidation.Succeeded) { foreach (var error in passwordValidation.Errors) { ModelState.AddModelError(nameof(request.Password), error.Description); } return this.CreateValidationError(ModelState); } if (!isAdmin) { if (!await _throttleService.Throttle(ZoneLimits.Register, this.HttpContext.Connection.RemoteIpAddress, cancellationToken)) return new TooManyRequestsResult(ZoneLimits.Register); } var identityResult = await _userManager.CreateAsync(user, request.Password); if (!identityResult.Succeeded) { foreach (var error in identityResult.Errors) { if (error.Code == "DuplicateUserName") ModelState.AddModelError(nameof(request.Email), error.Description); else ModelState.AddModelError(string.Empty, error.Description); } return this.CreateValidationError(ModelState); } if (request.IsAdministrator is true) { if (!anyAdmin) { await _roleManager.CreateAsync(new IdentityRole(Roles.ServerAdmin)); } await _userManager.AddToRoleAsync(user, Roles.ServerAdmin); if (!anyAdmin) { var settings = await _settingsRepository.GetSettingAsync<ThemeSettings>(); if (settings != null) { settings.FirstRun = false; await _settingsRepository.UpdateSetting(settings); } await _settingsRepository.FirstAdminRegistered(policies, _options.UpdateUrl != null, _options.DisableRegistration, Logs); } } _eventAggregator.Publish(new UserRegisteredEvent() { RequestUri = Request.GetAbsoluteRootUri(), User = user, Admin = request.IsAdministrator is true }); var model = await FromModel(user); return CreatedAtAction(string.Empty, model); } [HttpDelete("~/api/v1/users/{userId}")] [Authorize(Policy = Policies.CanModifyServerSettings, AuthenticationSchemes = AuthenticationSchemes.Greenfield)] public async Task<IActionResult> DeleteUser(string userId) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { return UserNotFound(); } // We can safely delete the user if it's not an admin user if (!(await _userService.IsAdminUser(user))) { await _userService.DeleteUserAndAssociatedData(user); return Ok(); } // User shouldn't be deleted if it's the only admin if (await IsUserTheOnlyOneAdmin(user)) { return Forbid(AuthenticationSchemes.GreenfieldBasic); } // Ok, this user is an admin but there are other admins as well so safe to delete await _userService.DeleteUserAndAssociatedData(user); return Ok(); } private async Task<ApplicationUserData> FromModel(ApplicationUser data) { var roles = (await _userManager.GetRolesAsync(data)).ToArray(); return UserService.FromModel(data, roles); } private async Task<bool> IsUserTheOnlyOneAdmin() { return await IsUserTheOnlyOneAdmin(await _userManager.GetUserAsync(User)); } private async Task<bool> IsUserTheOnlyOneAdmin(ApplicationUser user) { var isUserAdmin = await _userService.IsAdminUser(user); if (!isUserAdmin) { return false; } return (await _userManager.GetUsersInRoleAsync(Roles.ServerAdmin)).Count == 1; } private IActionResult UserNotFound() { return this.CreateAPIError(404, "user-not-found", "The user was not found"); } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof (Rigidbody))] [RequireComponent(typeof (CapsuleCollider))] public class RigidbodyFirstPersonController : MonoBehaviour { [Serializable] public class MovementSettings { public float ForwardSpeed = 8.0f; // Speed when walking forward public float BackwardSpeed = 4.0f; // Speed when walking backwards public float StrafeSpeed = 4.0f; // Speed when walking sideways public float RunMultiplier = 2.0f; // Speed when sprinting public KeyCode RunKey = KeyCode.LeftShift; public float JumpForce = 30f; public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f)); [HideInInspector] public float CurrentTargetSpeed = 8f; #if !MOBILE_INPUT private bool m_Running; #endif public void UpdateDesiredTargetSpeed(Vector2 input) { if (input == Vector2.zero) return; if (input.x > 0 || input.x < 0) { //strafe CurrentTargetSpeed = StrafeSpeed; } if (input.y < 0) { //backwards CurrentTargetSpeed = BackwardSpeed; } if (input.y > 0) { //forwards //handled last as if strafing and moving forward at the same time forwards speed should take precedence CurrentTargetSpeed = ForwardSpeed; } #if !MOBILE_INPUT if (Input.GetKey(RunKey)) { CurrentTargetSpeed *= RunMultiplier; m_Running = true; } else { m_Running = false; } #endif } #if !MOBILE_INPUT public bool Running { get { return m_Running; } } #endif } [Serializable] public class AdvancedSettings { public float groundCheckDistance = 0.01f; // distance for checking if the controller is grounded ( 0.01f seems to work best for this ) public float stickToGroundHelperDistance = 0.5f; // stops the character public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input public bool airControl; // can the user control the direction that is being moved in the air } public Camera cam; public MovementSettings movementSettings = new MovementSettings(); public MouseLook mouseLook = new MouseLook(); public AdvancedSettings advancedSettings = new AdvancedSettings(); private Rigidbody m_RigidBody; private CapsuleCollider m_Capsule; private float m_YRotation; private Vector3 m_GroundContactNormal; private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded; public Vector3 Velocity { get { return m_RigidBody.velocity; } } public bool Grounded { get { return m_IsGrounded; } } public bool Jumping { get { return m_Jumping; } } public bool Running { get { #if !MOBILE_INPUT return movementSettings.Running; #else return false; #endif } } private void Start() { m_RigidBody = GetComponent<Rigidbody>(); m_Capsule = GetComponent<CapsuleCollider>(); mouseLook.Init (transform, cam.transform); } private void Update() { RotateView(); if (CrossPlatformInputManager.GetButtonDown("Jump") && !m_Jump) { m_Jump = true; } } private void FixedUpdate() { GroundCheck(); Vector2 input = GetInput(); if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded)) { // always move along the camera forward as it is the direction that it being aimed at Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x; desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized; desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed; desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed; desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed; if (m_RigidBody.velocity.sqrMagnitude < (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed)) { m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse); } } if (m_IsGrounded) { m_RigidBody.drag = 5f; if (m_Jump) { m_RigidBody.drag = 0f; m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z); m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse); m_Jumping = true; } if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f) { m_RigidBody.Sleep(); } } else { m_RigidBody.drag = 0f; if (m_PreviouslyGrounded && !m_Jumping) { StickToGroundHelper(); } } m_Jump = false; } private float SlopeMultiplier() { float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up); return movementSettings.SlopeCurveModifier.Evaluate(angle); } private void StickToGroundHelper() { RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo, ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.stickToGroundHelperDistance)) { if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f) { m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal); } } } private Vector2 GetInput() { Vector2 input = new Vector2 { x = CrossPlatformInputManager.GetAxis("Horizontal"), y = CrossPlatformInputManager.GetAxis("Vertical") }; movementSettings.UpdateDesiredTargetSpeed(input); return input; } private void RotateView() { //avoids the mouse looking if the game is effectively paused if (Mathf.Abs(Time.timeScale) < float.Epsilon) return; // get the rotation before it's changed float oldYRotation = transform.eulerAngles.y; mouseLook.LookRotation (transform, cam.transform); if (m_IsGrounded || advancedSettings.airControl) { // Rotate the rigidbody velocity to match the new direction that the character is looking Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up); m_RigidBody.velocity = velRotation*m_RigidBody.velocity; } } /// sphere cast down just beyond the bottom of the capsule to see if the capsule is colliding round the bottom private void GroundCheck() { m_PreviouslyGrounded = m_IsGrounded; RaycastHit hitInfo; if (Physics.SphereCast(transform.position, m_Capsule.radius, Vector3.down, out hitInfo, ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance)) { m_IsGrounded = true; m_GroundContactNormal = hitInfo.normal; } else { m_IsGrounded = false; m_GroundContactNormal = Vector3.up; } if (!m_PreviouslyGrounded && m_IsGrounded && m_Jumping) { m_Jumping = false; } } } }
// // DelegateSerializationCompiler.cs // // Author: // Scott Thomas <lunchtimemama@gmail.com> // // Copyright (c) 2009 Scott Thomas // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace Mono.Upnp.Xml.Compilation { public class DelegateSerializationCompiler<TContext> : SerializationCompiler<TContext> { public DelegateSerializationCompiler (XmlSerializer<TContext> xmlSerializer, Type type) : base (xmlSerializer, type) { } protected override Serializer<TContext> CreateTypeStartAutoSerializer () { var name = Type.Name; string @namespace = null; string prefix = null; XmlTypeAttribute type_attribute = null; var namespaces = new List<XmlNamespaceAttribute> (); foreach (var custom_attribute in Type.GetCustomAttributes (false)) { var xml_type = custom_attribute as XmlTypeAttribute; if (xml_type != null) { type_attribute = xml_type; continue; } else { var xml_namespace = custom_attribute as XmlNamespaceAttribute; if (xml_namespace != null) { namespaces.Add (xml_namespace); } } } if (type_attribute != null) { if (!string.IsNullOrEmpty (type_attribute.Name)) { name = type_attribute.Name; } @namespace = type_attribute.Namespace; prefix = type_attribute.Prefix; } return CreateTypeStartAutoSerializer ( name, @namespace, prefix, namespaces.Count == 0 ? null : namespaces.ToArray ()); } protected virtual Serializer<TContext> CreateTypeStartAutoSerializer (string name, string @namespace, string prefix, IEnumerable<XmlNamespaceAttribute> namespaces) { if (namespaces != null) { return (obj, context) => { context.Writer.WriteStartElement (prefix, name, @namespace); foreach (var ns in namespaces) { context.Writer.WriteAttributeString ("xmlns", ns.Prefix, null, ns.Namespace); } }; } else { return (obj, context) => { context.Writer.WriteStartElement (prefix, name, @namespace); }; } } protected override Serializer<TContext> CreateTypeEndAutoSerializer () { return (obj, context) => context.Writer.WriteEndElement (); } protected override Serializer<TContext> CreateMemberAutoSerializer () { var attribute_serializers = new List<Serializer<TContext>> (); var element_serializers = new List<Serializer<TContext>> (); foreach (var property in Properties) { ProcessProperty (property, attribute_serializers, element_serializers); } attribute_serializers.AddRange (element_serializers); if (attribute_serializers.Count == 0) { return (obj, context) => { if (obj != null) { context.Writer.WriteValue (obj.ToString ()); } }; } else { var serializers = attribute_serializers.ToArray (); return (obj, context) => { foreach (var serializer in serializers) { serializer (obj, context); } }; } } protected virtual void ProcessProperty (PropertyInfo property, ICollection<Serializer<TContext>> attributeSerializers, ICollection<Serializer<TContext>> elementSerializers) { XmlAttributeAttribute attribute_attribute = null; XmlElementAttribute element_attribute = null; XmlFlagAttribute flag_attribute = null; XmlArrayAttribute array_attribute = null; XmlArrayItemAttribute array_item_attribute = null; XmlValueAttribute value_attribute = null; foreach (var custom_attribute in property.GetCustomAttributes (false)) { if (custom_attribute is DoNotSerializeAttribute) { attribute_attribute = null; element_attribute = null; flag_attribute = null; array_attribute = null; value_attribute = null; break; } var attribute = custom_attribute as XmlAttributeAttribute; if(attribute != null) { attribute_attribute = attribute; continue; } var element = custom_attribute as XmlElementAttribute; if (element != null) { element_attribute = element; continue; } var flag = custom_attribute as XmlFlagAttribute; if (flag != null) { flag_attribute = flag; continue; } var array = custom_attribute as XmlArrayAttribute; if (array != null) { array_attribute = array; continue; } var array_item = custom_attribute as XmlArrayItemAttribute; if (array_item != null) { array_item_attribute = array_item; continue; } var value = custom_attribute as XmlValueAttribute; if (value != null) { value_attribute = value; continue; } } if (attribute_attribute != null) { attributeSerializers.Add ( CreateSerializer (property, CreateAttributeSerializer (property, attribute_attribute))); } else if (element_attribute != null) { elementSerializers.Add ( CreateSerializer (property, CreateElementSerializer (property, element_attribute))); } else if (flag_attribute != null) { elementSerializers.Add ( CreateSerializer (property, CreateFlagSerializer (property, flag_attribute))); } else if (array_attribute != null) { elementSerializers.Add ( CreateSerializer (property, CreateArraySerializer (property, array_attribute, array_item_attribute))); } else if (array_item_attribute != null) { elementSerializers.Add ( CreateSerializer (property, CreateArrayItemSerializer (property, array_item_attribute))); } else if (value_attribute != null) { elementSerializers.Add ( CreateSerializer (property, CreateValueSerializer (property))); } } protected virtual Serializer<TContext> CreateSerializer (PropertyInfo property, Serializer<TContext> serializer) { return (obj, context) => serializer (property.GetValue (obj, null), context); } static Serializer<TContext> CreateSerializer (Serializer<TContext> serializer, bool omitIfNull) { if (omitIfNull) { return (obj, writer) => { if (obj != null) { serializer (obj, writer); } }; } else { return serializer; } } protected virtual Serializer<TContext> CreateAttributeSerializer (PropertyInfo property, XmlAttributeAttribute attributeAttribute) { return CreateSerializer ( CreateAttributeSerializer ( property, string.IsNullOrEmpty (attributeAttribute.Name) ? property.Name : attributeAttribute.Name, attributeAttribute.Namespace, attributeAttribute.Prefix), attributeAttribute.OmitIfNull); } protected virtual Serializer<TContext> CreateAttributeSerializer (PropertyInfo property, string name, string @namespace, string prefix) { if (!property.CanRead) { // TODO throw } if (property.PropertyType.IsEnum) { var map = GetEnumMap (property.PropertyType); return (obj, context) => { context.Writer.WriteAttributeString (prefix, name, @namespace, map[obj]); }; } else { return (obj, context) => { context.Writer.WriteAttributeString ( prefix, name, @namespace, obj != null ? obj.ToString () : string.Empty); }; } } protected virtual Serializer<TContext> CreateElementSerializer (PropertyInfo property, XmlElementAttribute elementAttribute) { return CreateSerializer ( CreateElementSerializer ( property, string.IsNullOrEmpty (elementAttribute.Name) ? property.Name : elementAttribute.Name, elementAttribute.Namespace, elementAttribute.Prefix), elementAttribute.OmitIfNull); } protected virtual Serializer<TContext> CreateElementSerializer (PropertyInfo property, string name, string @namespace, string prefix) { if (!property.CanRead) { // TODO throw } var next = GetCompilerForType (property.PropertyType).MemberSerializer; return (obj, context) => { context.Writer.WriteStartElement (prefix, name, @namespace); next (obj, context); context.Writer.WriteEndElement (); }; } protected virtual Serializer<TContext> CreateArraySerializer (PropertyInfo property, XmlArrayAttribute arrayAttribute, XmlArrayItemAttribute arrayItemAttribute) { return CreateSerializer ( CreateArraySerializer ( property, string.IsNullOrEmpty (arrayAttribute.Name) ? property.Name : arrayAttribute.Name, arrayAttribute.Namespace, arrayAttribute.Prefix, arrayAttribute.OmitIfEmpty, arrayItemAttribute), arrayAttribute.OmitIfNull); } protected virtual Serializer<TContext> CreateArraySerializer (PropertyInfo property, string name, string @namespace, string prefix, bool omitIfEmpty, XmlArrayItemAttribute arrayItemAttribute) { if (!property.CanRead) { // TODO throw } var item_type = GetIEnumerable (property.PropertyType).GetGenericArguments ()[0]; var next = CreateArrayItemSerializer (item_type, arrayItemAttribute); if (omitIfEmpty) { return (obj, context) => { if (obj != null) { var first = true; foreach (var item in (IEnumerable)obj) { if (first) { context.Writer.WriteStartElement (prefix, name, @namespace); first = false; } next (item, context); } if (!first) { context.Writer.WriteEndElement (); } } }; } else { return (obj, context) => { context.Writer.WriteStartElement (prefix, name, @namespace); if (obj != null) { foreach (var item in (IEnumerable)obj) { next (item, context); } } context.Writer.WriteEndElement (); }; } } protected virtual Serializer<TContext> CreateArrayItemSerializer (Type type, XmlArrayItemAttribute arrayItemAttribute) { if (arrayItemAttribute == null || string.IsNullOrEmpty (arrayItemAttribute.Name)) { return GetCompilerForType (type).TypeSerializer; } else { var name = arrayItemAttribute.Name; var @namespace = arrayItemAttribute.Namespace; var prefix = arrayItemAttribute.Prefix; var next = GetCompilerForType (type).MemberSerializer; return (obj, context) => { context.Writer.WriteStartElement (prefix, name, @namespace); next (obj, context); context.Writer.WriteEndElement (); }; } } protected virtual Serializer<TContext> CreateArrayItemSerializer (PropertyInfo property, XmlArrayItemAttribute arrayItemAttribute) { if (!property.CanRead) { // TODO throw } if (string.IsNullOrEmpty (arrayItemAttribute.Name)) { return CreateArrayItemSerializer (property); } else { return CreateArrayItemSerializer ( property, arrayItemAttribute.Name, arrayItemAttribute.Namespace, arrayItemAttribute.Prefix); } } protected virtual Serializer<TContext> CreateArrayItemSerializer (PropertyInfo property) { var item_type = GetIEnumerable (property.PropertyType).GetGenericArguments ()[0]; var serializer = GetCompilerForType (item_type).TypeSerializer; return (obj, context) => { if (obj != null) { foreach (var item in (IEnumerable)obj) { serializer (item, context); } } }; } protected virtual Serializer<TContext> CreateArrayItemSerializer (PropertyInfo property, string name, string @namespace, string prefix) { var item_type = GetIEnumerable (property.PropertyType).GetGenericArguments ()[0]; var serializer = GetCompilerForType (item_type).MemberSerializer; return (obj, context) => { if (obj != null) { foreach (var item in (IEnumerable)obj) { context.Writer.WriteStartElement (prefix, name, @namespace); serializer (item, context); context.Writer.WriteEndElement (); } } }; } protected virtual Serializer<TContext> CreateFlagSerializer (PropertyInfo property, XmlFlagAttribute flagAttribute) { return CreateFlagSerializer ( property, string.IsNullOrEmpty (flagAttribute.Name) ? property.Name : flagAttribute.Name, flagAttribute.Namespace, flagAttribute.Prefix); } protected virtual Serializer<TContext> CreateFlagSerializer (PropertyInfo property, string name, string @namespace, string prefix) { if (property.PropertyType != typeof (bool)) { // TODO throw } return (obj, context) => { if ((bool)obj) { context.Writer.WriteStartElement (prefix, name, @namespace); context.Writer.WriteEndElement (); } }; } protected static Type GetIEnumerable (Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IEnumerable<>)) { return type; } else { var ienumerable = type.GetInterface ("IEnumerable`1"); if (ienumerable != null) { return ienumerable; } else { // TODO throw return null; } } } static Serializer<TContext> CreateValueSerializer (PropertyInfo property) { return (obj, context) => { if (obj != null) { context.Writer.WriteString (obj.ToString ()); } }; } } }
using System; using System.Collections.Generic; using System.Text; using MO.Common.Content; using MO.Common.Lang; namespace MObj.Windows.Schedule { public class FScheduleTask : IScheduleTask { public const string NAME = "Task"; public const string RES_NAME = "name"; public const string FMT_DATE = "YYYYMMDD"; public const string FMT_TIME = "HH24MISS"; public const string PTY_TYPE = "type"; public const string PTY_VALID = "valid"; public const string PTY_DAY_INTERVAL = "day_interval"; public const string PTY_WEEK_INTERVAL = "week_interval"; public const string PTY_WEEKDAYS = "week_days"; public const string PTY_MONTH_TYPE = "month_type"; public const string PTY_MONTH_INTERVAL = "month_interval"; public const string PTY_MONTH_DAY = "month_day"; public const string PTY_MONTH_WEEK = "month_week"; public const string PTY_MONTH_WEEK_DAY = "month_week_day"; public const string PTY_MONTHS = "months"; public const string PTY_ONCE_DATE = "once_date"; public const string PTY_BEGIN_DATE = "begin_date"; public const string PTY_END_VALID = "end_valid"; public const string PTY_END_DATE = "end_date"; public const string PTY_TIME = "time"; private static IResource _resource = RResource.Find(typeof(FScheduleTask)); internal FScheduleTasks _tasks; protected EScheduleTaskType _type = EScheduleTaskType.Daily; protected bool _valid = true; protected int _dayInterval = 0; protected int _weekInterval = 0; protected EScheduleWeekDay _weekDays = EScheduleWeekDay.None; protected EScheduleMonthType _monthType = EScheduleMonthType.Date; protected int _monthInterval = 0; protected int _monthDay = 1; protected EScheduleMonthWeek _monthWeek = EScheduleMonthWeek.Week1; protected int _monthWeekDay = 1; protected EScheduleMonth _months = EScheduleMonth.None; protected DateTime _onceDate = DateTime.Today; protected DateTime _beginDate = DateTime.Today; protected bool _endValid = false; protected DateTime _endDate = DateTime.Today; protected DateTime _time = DateTime.Now; private object _tag; public FScheduleTask() { } public EScheduleTaskType Type { get { return _type; } set { _type = value; } } public string TypeName { get { return REnum.ToString<EScheduleTaskType>(_type); } } public bool Valid { get { return _valid; } set { _valid = value; } } public int DayInterval { get { return _dayInterval; } set { _dayInterval = value; } } public int WeekInterval { get { return _weekInterval; } set { _weekInterval = value; } } public EScheduleWeekDay WeekDays { get { return _weekDays; } set { _weekDays = value; } } public EScheduleMonthType MonthType { get { return _monthType; } set { _monthType = value; } } public int MonthInterval { get { return _monthInterval; } set { _monthInterval = value; } } public int MonthDay { get { return _monthDay; } set { _monthDay = value; } } public EScheduleMonthWeek MonthWeek { get { return _monthWeek; } set { _monthWeek = value; } } public int MonthWeekDay { get { return _monthWeekDay; } set { _monthWeekDay = value; } } public EScheduleMonth Months { get { return _months; } set { _months = value; } } public DateTime OnceDate { get { return _onceDate; } set { _onceDate = value; } } public DateTime BeginDate { get { return _beginDate; } set { _beginDate = value; } } public bool EndValid { get { return _endValid; } set { _endValid = value; } } public DateTime EndDate { get { return _endDate; } set { _endDate = value; } } public DateTime Time { get { return _time; } set { _time = value; } } public object Tag { get { return _tag; } set { _tag = value; } } public virtual string GetNameInfo() { return "Not support for GetNameInfo"; } public virtual string GetDetailInfo() { return "Not support for GetDetailInfo"; } public void Assign(FScheduleTask task) { _tasks = task._tasks; _type = task._type; _valid = task._valid; _dayInterval = task._dayInterval; _weekInterval = task._weekInterval; _weekDays = task._weekDays; _monthType = task._monthType; _monthInterval = task._monthInterval; _monthDay = task._monthDay; _monthWeek = task._monthWeek; _monthWeekDay = task._monthWeekDay; _months = task._months; _onceDate = task._onceDate; _beginDate = task._beginDate; _endValid = task._endValid; _endDate = task._endDate; _time = task._time; _tag = task._tag; } public virtual void LoadConfig(FXmlNode config) { // Type if(config.Contains(PTY_TYPE)) { _type = REnum.ToValue<EScheduleTaskType>(config[PTY_TYPE]); } // Valid if(config.Contains(PTY_VALID)) { _valid = config.GetBoolean(PTY_VALID); } // Day Interval if(config.Contains(PTY_DAY_INTERVAL)) { _dayInterval = RInt.Parse(config[PTY_DAY_INTERVAL]); } // Week Interval if(config.Contains(PTY_WEEK_INTERVAL)) { _weekInterval = RInt.Parse(config[PTY_WEEK_INTERVAL]); } // Month Interval if(config.Contains(PTY_MONTH_INTERVAL)) { _monthInterval = RInt.Parse(config[PTY_MONTH_INTERVAL]); } // WeekDays if(config.Contains(PTY_WEEKDAYS)) { string weekDays = config[PTY_WEEKDAYS]; if(!RString.IsEmpty(weekDays)) { _weekDays = (EScheduleWeekDay)RInt.Parse(weekDays); } } // Month type if(config.Contains(PTY_MONTH_TYPE)) { string monthType = config[PTY_MONTH_TYPE]; if(!RString.IsEmpty(monthType)) { _monthType = (EScheduleMonthType)RInt.Parse(monthType); } } // Month day if(config.Contains(PTY_MONTH_DAY)) { _monthDay = RInt.Parse(config[PTY_MONTH_DAY]); } // Month week if(config.Contains(PTY_MONTH_WEEK)) { string monthWeek = config[PTY_MONTH_WEEK]; if(!RString.IsEmpty(monthWeek)) { _monthWeek = (EScheduleMonthWeek)RInt.Parse(monthWeek); } } // Month week day if(config.Contains(PTY_MONTH_WEEK_DAY)) { _monthWeekDay = RInt.Parse(config[PTY_MONTH_WEEK_DAY]); } // Months if(config.Contains(PTY_MONTHS)) { string months = config[PTY_MONTHS]; if(!RString.IsEmpty(months)) { _months = (EScheduleMonth)RInt.Parse(months); } } // Once date if(config.Contains(PTY_ONCE_DATE)) { _onceDate = RDate.Parse(config[PTY_ONCE_DATE]); } // Begin date if(config.Contains(PTY_BEGIN_DATE)) { _beginDate = RDate.Parse(config[PTY_BEGIN_DATE]); } // End valid if(config.Contains(PTY_END_VALID)) { _endValid = config.GetBoolean(PTY_END_VALID); } // End date if(config.Contains(PTY_END_DATE)) { _endDate = RDate.Parse(config[PTY_END_DATE]); } // Time if(config.Contains(PTY_TIME)) { _time = RDate.Parse(config[PTY_TIME]); } } public virtual void SaveConfig(FXmlNode config) { // Type config[PTY_TYPE] = _type.ToString(); config.Set(PTY_VALID, _valid); // Day config config.Set(PTY_DAY_INTERVAL, _dayInterval); // Week config config.Set(PTY_WEEK_INTERVAL, _weekInterval); config[PTY_WEEKDAYS] = ((int)_weekDays).ToString(); // Month config config[PTY_MONTH_TYPE] = ((int)_monthType).ToString(); config.Set(PTY_MONTH_INTERVAL, _monthInterval); config.Set(PTY_MONTH_DAY, _monthDay); config[PTY_MONTH_WEEK] = ((int)_monthWeek).ToString(); config.Set(PTY_MONTH_WEEK_DAY, _monthWeekDay); config[PTY_MONTHS] = ((int)_months).ToString(); // Once config config[PTY_ONCE_DATE] = RDate.Format(_onceDate, FMT_DATE); // Public config config[PTY_BEGIN_DATE] = RDate.Format(_beginDate, FMT_DATE); config.Set(PTY_END_VALID, _endValid); config[PTY_END_DATE] = RDate.Format(_endDate, FMT_DATE); config[PTY_TIME] = RDate.Format(_time, FMT_TIME); } public virtual DateTime QueryNextRunTime(DateTime time) { throw new FFatalException("Not support for QueryNextRunTime"); } public FScheduleTask ConvertToType() { return _tasks.ConvertToType(this, _type); } public FScheduleTask ConvertToType(EScheduleTaskType type) { return _tasks.ConvertToType(this, type); } } }
// // - FrameworkServiceContainer.Impl.cs - // // Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Linq; using System.Reflection; using Carbonfrost.Commons.ComponentModel; using Carbonfrost.Commons.Shared.Runtime; namespace Carbonfrost.Commons.Shared.Runtime { public partial class FrameworkServiceContainer : IServiceContainer, IServiceContainerExtension, IActivationFactory { private readonly Dictionary<Type, object> services = CreateTypeDictionary(); private readonly Dictionary<string, object> servicesByName = new Dictionary<string, object>(); private readonly IServiceProvider parentProvider; private readonly IActivationFactory activationFactory; protected object OnServiceResolve(ServiceResolveEventArgs args) { if (ServiceResolve == null) return null; else return ServiceResolve(this, args); } // IActivationFactory implementation public virtual object CreateInstance( Type type, IEnumerable<KeyValuePair<string, object>> values = null, IPopulateComponentCallback callback = null, IServiceProvider serviceProvider = null, params Attribute[] attributes) { return this.activationFactory.CreateInstance(type, values, callback, ServiceProvider.Compose(serviceProvider, this), attributes); } // IServiceContainerExtension implementation public event ServiceResolveEventHandler ServiceResolve; public void AddService(string serviceName, object serviceInstance) { AddService(serviceName, serviceInstance, false); } public void AddService(string serviceName, object serviceInstance, bool promote) { Require.NotNullOrEmptyString("serviceName", serviceName); // $NON-NLS-1 if (this.servicesByName.ContainsKey(serviceName)) throw RuntimeFailure.ServiceAlreadyExists("serviceName", serviceName); this.servicesByName.Add(serviceName, serviceInstance); if (promote) { IServiceContainerExtension ice = this.ParentContainer as IServiceContainerExtension; if (ice != null) ice.AddService(serviceName, serviceInstance, true); } } public void AddService(string serviceName, ServiceCreatorCallback creatorCallback) { AddService(serviceName, creatorCallback, false); } public void AddService(string serviceName, ServiceCreatorCallback creatorCallback, bool promote) { Require.NotNullOrEmptyString("serviceName", serviceName); // $NON-NLS-1 if (this.servicesByName.ContainsKey(serviceName)) throw RuntimeFailure.ServiceAlreadyExists("serviceName", serviceName); this.servicesByName.Add(serviceName, creatorCallback); if (promote) { IServiceContainerExtension ice = this.ParentContainer as IServiceContainerExtension; if (ice != null) ice.AddService(serviceName, creatorCallback, true); } } public void RemoveService(string serviceName, bool promote) { Require.NotNullOrEmptyString("serviceName", serviceName); // $NON-NLS-1 this.servicesByName.Remove(serviceName); if (promote) { IServiceContainerExtension ice = this.ParentContainer as IServiceContainerExtension; if (ice != null) ice.RemoveService(serviceName, true); } } public void RemoveService(string serviceName) { RemoveService(serviceName, false); } public object GetService(string serviceName) { Require.NotNullOrEmptyString("serviceName", serviceName); // $NON-NLS-1 object result; if (this.servicesByName.TryGetValue(serviceName, out result)) return result; else return null; } public IEnumerable<object> GetServices(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); var items = this.services.Values.Concat(this.servicesByName.Values); return items.Where(serviceType.IsInstanceOfType).Distinct(); } // IServiceContainer implementation public void AddService(Type serviceType, object serviceInstance) { if (serviceType == null) throw new ArgumentNullException("serviceType"); // $NON-NLS-1 AddService(serviceType, serviceInstance, false); } public void AddService(Type serviceType, object serviceInstance, bool promote) { if (serviceType == null) throw new ArgumentNullException("serviceType"); // $NON-NLS-1 IService s = (serviceInstance as IService); if (s != null) s.StartService(); if (promote) { IServiceContainer container = this.ParentContainer; if (container != null) { container.AddService(serviceType, serviceInstance, promote); return; } } if (this.services.ContainsKey(serviceType)) throw RuntimeFailure.ServiceAlreadyExists("serviceType", serviceType); this.services[serviceType] = serviceInstance; } public void AddService(Type serviceType, ServiceCreatorCallback callback) { AddService(serviceType, callback, false); } public void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote) { if (serviceType == null) throw new ArgumentNullException("serviceType"); // $NON-NLS-1 if (callback == null) throw new ArgumentNullException("callback"); // $NON-NLS-1 if (promote) { IServiceContainer container = this.ParentContainer; if (container != null) { container.AddService(serviceType, callback, promote); return; } } if (this.services.ContainsKey(serviceType)) throw RuntimeFailure.ServiceAlreadyExists("serviceType", serviceType); this.services[serviceType] = callback; } public void RemoveService(Type serviceType) { RemoveService(serviceType, false); } public void RemoveService(Type serviceType, bool promote) { if (serviceType == null) throw new ArgumentNullException("serviceType"); // $NON-NLS-1 if (promote) { IServiceContainer container = this.ParentContainer; if (container != null) { container.RemoveService(serviceType, promote); return; } } this.services.Remove(serviceType); } public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); // $NON-NLS-1 // Process self if (serviceType.IsInstanceOfType(this)) return this; object service = null; if (service == null) this.services.TryGetValue(serviceType, out service); ServiceCreatorCallback callback = service as ServiceCreatorCallback; if (callback != null) { service = callback(this, serviceType); if (service != null && !serviceType.IsAssignableFrom(service.GetType())) { service = null; } this.services[serviceType] = service; } return service ?? this.ParentProvider.GetService(serviceType) ?? ResolveUsingEvent(null, serviceType); } private object ResolveUsingEvent(string serviceName, Type serviceType) { // prevent reentrancy return OnServiceResolve(new ServiceResolveEventArgs(serviceName, serviceType)); } private static Dictionary<Type, object> CreateTypeDictionary() { return new Dictionary<Type, object>(Utility.EquivalentComparer); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; namespace SimShift.MapTool { public class Ets2Sector { private Dictionary<int, int> FileMap = new Dictionary<int, int>(); public Ets2Sector(Ets2Mapper mapper, string file) { Mapper = mapper; FilePath = file; Nodes = new List<Ets2Node>(); Items = new List<Ets2Item>(); FooterStart = -1; Stream = File.ReadAllBytes(file); Empty = Stream.Length < 60; } // Status flags: public bool Empty { get; private set; } public string FilePath { get; private set; } public List<Ets2Item> Items { get; private set; } public Ets2Mapper Mapper { get; private set; } public List<Ets2Node> Nodes { get; private set; } public bool NoFooterError { get; private set; } public byte[] Stream { get; private set; } private int FooterStart { get; set; } public Ets2Item FindItem(ulong uid) { Tuple<string, int> inp; if (uid == 0) return null; /*if (Mapper.ItemCache.TryGetValue(uid, out inp)) { var item = new Ets2Item(uid, Mapper.Sectors.FirstOrDefault(x => Path.GetFileNameWithoutExtension(x.FilePath) == inp.Item1), inp.Item2); if (!item.Valid) { lock (Mapper.ItemCache) { Mapper.ItemCache.Remove(uid); } } else { return item; } }*/ var pos = SearchUID(BitConverter.GetBytes(uid)); foreach (var off in pos) { var offs = off - 4; var type = BitConverter.ToUInt32(Stream, offs); if (type < 0x40 && type != 0) { var item = new Ets2Item(uid, this, offs); if (item.Valid) { /*lock (Mapper.ItemCache) { Mapper.ItemCache.Add(uid, new Tuple<string, int>(Path.GetFileNameWithoutExtension(FilePath), offs)); }*/ return item; } } } return null; } public void FindItems(Ets2Node node, bool postpone) { if (node.ForwardItemUID > 0) { Ets2Item itemForward; if (Mapper.Items.TryGetValue(node.ForwardItemUID, out itemForward)) { if (itemForward.Apply(node)) node.ForwardItem = itemForward; } else { itemForward = FindItem(node.ForwardItemUID); if (itemForward == null) { if (postpone) Mapper.Find(node, node.ForwardItemUID, false); } else { Items.Add(itemForward); Mapper.Items.TryAdd(node.ForwardItemUID, itemForward); node.ForwardItem = itemForward; if (itemForward.Apply(node)) node.ForwardItem = itemForward; } } } if (node.BackwardItemUID > 0) { Ets2Item itemBackward; if (Mapper.Items.TryGetValue(node.BackwardItemUID, out itemBackward)) { if (itemBackward.Apply(node)) node.BackwardItem = itemBackward; } else { itemBackward = FindItem(node.BackwardItemUID); if (itemBackward == null) { if (postpone) Mapper.Find(node, node.BackwardItemUID, true); } else { Items.Add(itemBackward); Mapper.Items.TryAdd(node.BackwardItemUID, itemBackward); node.BackwardItem = itemBackward; if (itemBackward.Apply(node)) node.BackwardItem = itemBackward; } } } } public void ParseItems() { if (Empty) return; if (NoFooterError) return; foreach (var node in Nodes) { FindItems(node, true); } } public void ParseNodes() { if (Empty) return; Stopwatch sw = new Stopwatch(); sw.Start(); // First determine the number of positions in this file var nodesPieces = BitConverter.ToInt32(Stream, 0x10); int i = Stream.Length; do { i -= 56; // each block is 56 bytes long var node = new Ets2Node(Stream, i); if (node.NodeUID == 0) { FooterStart = i + 56 - 4; break; } Nodes.Add(node); if (Mapper.Nodes.ContainsKey(node.NodeUID) == false) Mapper.Nodes.TryAdd(node.NodeUID, node); var count = BitConverter.ToInt32(Stream, i - 4); if (count >= nodesPieces && count == Nodes.Count) { FooterStart = i - 4; break; } } while (i > 60); //Console.WriteLine("Thereby footer starts at " + FooterStart.ToString("X16")); if (FooterStart < 0) { NoFooterError = true; return; } sw.Stop(); //Console.WriteLine(Path.GetFileNameWithoutExtension(FilePath) + " contains " + Nodes.Count + // " nodes; parsed in " + sw.ElapsedMilliseconds + "ms"); } public override string ToString() { return "Sector " + Path.GetFileNameWithoutExtension(FilePath); } private IEnumerable<int> SearchUID(byte[] uid) { return Stream.IndexesOfUlong(uid); byte firstMatchByte = uid[0]; for (int i = 0; i < FooterStart - 8; i++) { if (firstMatchByte == Stream[i]) { byte[] match = new byte[8]; Array.Copy(Stream, i, match, 0, 8); if (match.SequenceEqual<byte>(uid)) { //yield return i; i += 8; } } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; namespace Microsoft.Azure.Management.Resources { public partial class ResourceManagementClient : ServiceClient<ResourceManagementClient>, IResourceManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IDeploymentOperationOperations _deploymentOperations; /// <summary> /// Operations for managing deployment operations. /// </summary> public virtual IDeploymentOperationOperations DeploymentOperations { get { return this._deploymentOperations; } } private IDeploymentOperations _deployments; /// <summary> /// Operations for managing deployments. /// </summary> public virtual IDeploymentOperations Deployments { get { return this._deployments; } } private IProviderOperations _providers; /// <summary> /// Operations for managing providers. /// </summary> public virtual IProviderOperations Providers { get { return this._providers; } } private IProviderOperationsMetadataOperations _providerOperationsMetadata; /// <summary> /// Operations for getting provider operations metadata. /// </summary> public virtual IProviderOperationsMetadataOperations ProviderOperationsMetadata { get { return this._providerOperationsMetadata; } } private IResourceGroupOperations _resourceGroups; /// <summary> /// Operations for managing resource groups. /// </summary> public virtual IResourceGroupOperations ResourceGroups { get { return this._resourceGroups; } } private IResourceOperations _resources; /// <summary> /// Operations for managing resources. /// </summary> public virtual IResourceOperations Resources { get { return this._resources; } } private IResourceProviderOperationDetailsOperations _resourceProviderOperationDetails; /// <summary> /// Operations for managing Resource provider operations. /// </summary> public virtual IResourceProviderOperationDetailsOperations ResourceProviderOperationDetails { get { return this._resourceProviderOperationDetails; } } private ITagOperations _tags; /// <summary> /// Operations for managing tags. /// </summary> public virtual ITagOperations Tags { get { return this._tags; } } /// <summary> /// Initializes a new instance of the ResourceManagementClient class. /// </summary> public ResourceManagementClient() : base() { this._deploymentOperations = new DeploymentOperationOperations(this); this._deployments = new DeploymentOperations(this); this._providers = new ProviderOperations(this); this._providerOperationsMetadata = new ProviderOperationsMetadataOperations(this); this._resourceGroups = new ResourceGroupOperations(this); this._resources = new ResourceOperations(this); this._resourceProviderOperationDetails = new ResourceProviderOperationDetailsOperations(this); this._tags = new TagOperations(this); this._apiVersion = "2015-11-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ResourceManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ResourceManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ResourceManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ResourceManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public ResourceManagementClient(HttpClient httpClient) : base(httpClient) { this._deploymentOperations = new DeploymentOperationOperations(this); this._deployments = new DeploymentOperations(this); this._providers = new ProviderOperations(this); this._providerOperationsMetadata = new ProviderOperationsMetadataOperations(this); this._resourceGroups = new ResourceGroupOperations(this); this._resources = new ResourceOperations(this); this._resourceProviderOperationDetails = new ResourceProviderOperationDetailsOperations(this); this._tags = new TagOperations(this); this._apiVersion = "2015-11-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ResourceManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ResourceManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ResourceManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ResourceManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com/"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ResourceManagementClient instance /// </summary> /// <param name='client'> /// Instance of ResourceManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ResourceManagementClient> client) { base.Clone(client); if (client is ResourceManagementClient) { ResourceManagementClient clonedClient = ((ResourceManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.BadRequest) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.Accepted) { result.Status = OperationStatus.InProgress; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.Cache { /// <summary> /// This is the default XPath/XQuery data model cache implementation. It will be used whenever /// the user does not supply his own XPathNavigator implementation. /// </summary> internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo { private XPathNode[] _pageCurrent; private XPathNode[] _pageParent; private int _idxCurrent; private int _idxParent; private string _atomizedLocalName; //----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed /// text node, then the parent is a virtualized parent (may be different than .Parent on the current node). /// </summary> public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent) { Debug.Assert(pageCurrent != null && idxCurrent != 0); Debug.Assert((pageParent == null) == (idxParent == 0)); _pageCurrent = pageCurrent; _pageParent = pageParent; _idxCurrent = idxCurrent; _idxParent = idxParent; } /// <summary> /// Copy constructor. /// </summary> public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav._pageCurrent, nav._idxCurrent, nav._pageParent, nav._idxParent) { _atomizedLocalName = nav._atomizedLocalName; } //----------------------------------------------- // XPathItem //----------------------------------------------- /// <summary> /// Get the string value of the current node, computed using data model dm:string-value rules. /// If the node has a typed value, return the string representation of the value. If the node /// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise, /// concatenate all text node descendants of the current node. /// </summary> public override string Value { get { string value; XPathNode[] page, pageEnd; int idx, idxEnd; // Try to get the pre-computed string value of the node value = _pageCurrent[_idxCurrent].Value; if (value != null) return value; #if DEBUG switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: case XPathNodeType.Attribute: case XPathNodeType.Comment: case XPathNodeType.ProcessingInstruction: Debug.Fail("ReadStringValue() should have taken care of these node types."); break; case XPathNodeType.Text: Debug.Assert(_idxParent != 0 && _pageParent[_idxParent].HasCollapsedText, "ReadStringValue() should have taken care of anything but collapsed text."); break; } #endif // If current node is collapsed text, then parent element has a simple text value if (_idxParent != 0) { Debug.Assert(_pageCurrent[_idxCurrent].NodeType == XPathNodeType.Text); return _pageParent[_idxParent].Value; } // Must be node with complex content, so concatenate the string values of all text descendants string s = string.Empty; StringBuilder bldr = null; // Get all text nodes which follow the current node in document order, but which are still descendants page = pageEnd = _pageCurrent; idx = idxEnd = _idxCurrent; if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd)) { pageEnd = null; idxEnd = 0; } while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) { Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText); if (s.Length == 0) { s = page[idx].Value; } else { if (bldr == null) { bldr = new StringBuilder(); bldr.Append(s); } bldr.Append(page[idx].Value); } } return (bldr != null) ? bldr.ToString() : s; } } //----------------------------------------------- // XPathNavigator //----------------------------------------------- /// <summary> /// Create a copy of this navigator, positioned to the same node in the tree. /// </summary> public override XPathNavigator Clone() { return new XPathDocumentNavigator(_pageCurrent, _idxCurrent, _pageParent, _idxParent); } /// <summary> /// Get the XPath node type of the current node. /// </summary> public override XPathNodeType NodeType { get { return _pageCurrent[_idxCurrent].NodeType; } } /// <summary> /// Get the local name portion of the current node's name. /// </summary> public override string LocalName { get { return _pageCurrent[_idxCurrent].LocalName; } } /// <summary> /// Get the namespace portion of the current node's name. /// </summary> public override string NamespaceURI { get { return _pageCurrent[_idxCurrent].NamespaceUri; } } /// <summary> /// Get the name of the current node. /// </summary> public override string Name { get { return _pageCurrent[_idxCurrent].Name; } } /// <summary> /// Get the prefix portion of the current node's name. /// </summary> public override string Prefix { get { return _pageCurrent[_idxCurrent].Prefix; } } /// <summary> /// Get the base URI of the current node. /// </summary> public override string BaseURI { get { XPathNode[] page; int idx; if (_idxParent != 0) { // Get BaseUri of parent for attribute, namespace, and collapsed text nodes page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } do { switch (page[idx].NodeType) { case XPathNodeType.Element: case XPathNodeType.Root: case XPathNodeType.ProcessingInstruction: // BaseUri is always stored with Elements, Roots, and PIs return page[idx].BaseUri; } // Get BaseUri of parent idx = page[idx].GetParent(out page); } while (idx != 0); return string.Empty; } } /// <summary> /// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form. /// </summary> public override bool IsEmptyElement { get { return _pageCurrent[_idxCurrent].AllowShortcutTag; } } /// <summary> /// Return the xml name table which was used to atomize all prefixes, local-names, and /// namespace uris in the document. /// </summary> public override XmlNameTable NameTable { get { return _pageCurrent[_idxCurrent].Document.NameTable; } } /// <summary> /// Position the navigator on the first attribute of the current node and return true. If no attributes /// can be found, return false. /// </summary> public override bool MoveToFirstAttribute() { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if (XPathNodeHelper.GetFirstAttribute(ref _pageCurrent, ref _idxCurrent)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found, /// return false. /// </summary> public override bool MoveToNextAttribute() { return XPathNodeHelper.GetNextAttribute(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// True if the current node has one or more attributes. /// </summary> public override bool HasAttributes { get { return _pageCurrent[_idxCurrent].HasAttribute; } } /// <summary> /// Position the navigator on the attribute with the specified name and return true. If no matching /// attribute can be found, return false. Don't assume the name parts are atomized with respect /// to this document. /// </summary> public override bool MoveToAttribute(string localName, string namespaceURI) { XPathNode[] page = _pageCurrent; int idx = _idxCurrent; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; if (XPathNodeHelper.GetAttribute(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI)) { // Save element parent in order to make node-order comparison simpler _pageParent = page; _idxParent = idx; return true; } return false; } /// <summary> /// Position the navigator on the namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { XPathNode[] page; int idx; if (namespaceScope == XPathNamespaceScope.Local) { // Get local namespaces only idx = XPathNodeHelper.GetLocalNamespaces(_pageCurrent, _idxCurrent, out page); } else { // Get all in-scope namespaces idx = XPathNodeHelper.GetInScopeNamespaces(_pageCurrent, _idxCurrent, out page); } while (idx != 0) { // Don't include the xmlns:xml namespace node if scope is ExcludeXml if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode) { _pageParent = _pageCurrent; _idxParent = _idxCurrent; _pageCurrent = page; _idxCurrent = idx; return true; } // Skip past xmlns:xml idx = page[idx].GetSibling(out page); } return false; } /// <summary> /// Position the navigator on the next namespace within the specified scope. If no matching namespace /// can be found, return false. /// </summary> public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XPathNode[] page = _pageCurrent, pageParent; int idx = _idxCurrent, idxParent; // If current node is not a namespace node, return false if (page[idx].NodeType != XPathNodeType.Namespace) return false; while (true) { // Get next namespace sibling idx = page[idx].GetSibling(out page); // If there are no more nodes, return false if (idx == 0) return false; switch (scope) { case XPathNamespaceScope.Local: // Once parent changes, there are no longer any local namespaces idxParent = page[idx].GetParent(out pageParent); if (idxParent != _idxParent || (object)pageParent != (object)_pageParent) return false; break; case XPathNamespaceScope.ExcludeXml: // If node is xmlns:xml, then skip it if (page[idx].IsXmlNamespaceNode) continue; break; } // Found a matching next namespace node, so return it break; } _pageCurrent = page; _idxCurrent = idx; return true; } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the next content node. Return false if there are no more content nodes. /// </summary> public override bool MoveToNext() { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// If the current node is an attribute or namespace (not content), return false. Otherwise, /// move to the previous (sibling) content node. Return false if there are no previous content nodes. /// </summary> public override bool MoveToPrevious() { // If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do // not have previous siblings. if (_idxParent != 0) return false; return XPathNodeHelper.GetPreviousContentSibling(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Move to the first content-typed child of the current node. Return false if the current /// node has no content children. /// </summary> public override bool MoveToFirstChild() { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position the navigator on the parent of the current node. If the current node has no parent, /// return false. /// </summary> public override bool MoveToParent() { if (_idxParent != 0) { // 1. For attribute nodes, element parent is always stored in order to make node-order // comparison simpler. // 2. For namespace nodes, parent is always stored in navigator in order to virtualize // XPath 1.0 namespaces. // 3. For collapsed text nodes, element parent is always stored in navigator. Debug.Assert(_pageParent != null); _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetParent(ref _pageCurrent, ref _idxCurrent); } /// <summary> /// Position this navigator to the same position as the "other" navigator. If the "other" navigator /// is not of the same type as this navigator, then return false. /// </summary> public override bool MoveTo(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { _pageCurrent = that._pageCurrent; _idxCurrent = that._idxCurrent; _pageParent = that._pageParent; _idxParent = that._idxParent; return true; } return false; } /// <summary> /// Position to the navigator to the element whose id is equal to the specified "id" string. /// </summary> public override bool MoveToId(string id) { XPathNode[] page; int idx; idx = _pageCurrent[_idxCurrent].Document.LookupIdElement(id, out page); if (idx != 0) { // Move to ID element and clear parent state Debug.Assert(page[idx].NodeType == XPathNodeType.Element); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; return true; } return false; } /// <summary> /// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false /// if not, or if the "other" navigator is not the same type as this navigator. /// </summary> public override bool IsSamePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { return _idxCurrent == that._idxCurrent && _pageCurrent == that._pageCurrent && _idxParent == that._idxParent && _pageParent == that._pageParent; } return false; } /// <summary> /// Returns true if the current node has children. /// </summary> public override bool HasChildren { get { return _pageCurrent[_idxCurrent].HasContentChild; } } /// <summary> /// Position the navigator on the root node of the current document. /// </summary> public override void MoveToRoot() { if (_idxParent != 0) { // Clear parent state _pageParent = null; _idxParent = 0; } _idxCurrent = _pageCurrent[_idxCurrent].GetRoot(out _pageCurrent); } /// <summary> /// Move to the first element child of the current node with the specified name. Return false /// if the current node has no matching element children. /// </summary> public override bool MoveToChild(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementChild(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first element sibling of the current node with the specified name. Return false /// if the current node has no matching element siblings. /// </summary> public override bool MoveToNext(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; return XPathNodeHelper.GetElementSibling(ref _pageCurrent, ref _idxCurrent, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the first content child of the current node with the specified type. Return false /// if the current node has no matching children. /// </summary> public override bool MoveToChild(XPathNodeType type) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node if (type != XPathNodeType.Text && type != XPathNodeType.All) return false; // Virtualize collapsed text nodes _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } return XPathNodeHelper.GetContentChild(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the first content sibling of the current node with the specified type. Return false /// if the current node has no matching siblings. /// </summary> public override bool MoveToNext(XPathNodeType type) { return XPathNodeHelper.GetContentSibling(ref _pageCurrent, ref _idxCurrent, type); } /// <summary> /// Move to the next element that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified QName /// Return false if the current node has no matching following elements. /// </summary> public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) { XPathNode[] pageEnd; int idxEnd; if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Get node on which scan ends (null if rest of document should be scanned) idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetElementFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetElementFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, _atomizedLocalName, namespaceURI); } /// <summary> /// Move to the next node that: /// 1. Follows the current node in document order (includes descendants, unlike XPath following axis) /// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered) /// 3. Has the specified XPathNodeType /// Return false if the current node has no matching following nodes. /// </summary> public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end) { XPathDocumentNavigator endTiny = end as XPathDocumentNavigator; XPathNode[] page, pageEnd; int idx, idxEnd; // If searching for text, make sure to handle collapsed text nodes correctly if (type == XPathNodeType.Text || type == XPathNodeType.All) { if (_pageCurrent[_idxCurrent].HasCollapsedText) { // Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end" if (endTiny != null && _idxCurrent == endTiny._idxParent && _pageCurrent == endTiny._pageParent) { // "end" is positioned to a virtual attribute, namespace, or text node return false; } _pageParent = _pageCurrent; _idxParent = _idxCurrent; _idxCurrent = _pageCurrent[_idxCurrent].Document.GetCollapsedTextNode(out _pageCurrent); return true; } if (type == XPathNodeType.Text) { // Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, true, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { page = _pageParent; idx = _idxParent; } else { page = _pageCurrent; idx = _idxCurrent; } // If ending node is a virtual node, and current node is its parent, then we're done if (endTiny != null && endTiny._idxParent != 0 && idx == idxEnd && page == pageEnd) return false; // Get all virtual (collapsed) and physical text nodes which follow the current node if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) return false; if (page[idx].NodeType == XPathNodeType.Element) { // Virtualize collapsed text nodes Debug.Assert(page[idx].HasCollapsedText); _idxCurrent = page[idx].Document.GetCollapsedTextNode(out _pageCurrent); _pageParent = page; _idxParent = idx; } else { // Physical text node Debug.Assert(page[idx].IsText); _pageCurrent = page; _idxCurrent = idx; _pageParent = null; _idxParent = 0; } return true; } } // Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node) idxEnd = GetFollowingEnd(endTiny, false, out pageEnd); // If this navigator is positioned on a virtual node, then compute following of parent if (_idxParent != 0) { if (!XPathNodeHelper.GetContentFollowing(ref _pageParent, ref _idxParent, pageEnd, idxEnd, type)) return false; _pageCurrent = _pageParent; _idxCurrent = _idxParent; _pageParent = null; _idxParent = 0; return true; } return XPathNodeHelper.GetContentFollowing(ref _pageCurrent, ref _idxCurrent, pageEnd, idxEnd, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType. /// </summary> public override XPathNodeIterator SelectChildren(XPathNodeType type) { return new XPathDocumentKindChildIterator(this, type); } /// <summary> /// Return an iterator that ranges over all children of the current node that match the specified QName. /// </summary> public override XPathNodeIterator SelectChildren(string name, string namespaceURI) { // If local name is wildcard, then call XPathNavigator.SelectChildren if (name == null || name.Length == 0) return base.SelectChildren(name, namespaceURI); return new XPathDocumentElementChildIterator(this, name, namespaceURI); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// XPathNodeType. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) { return new XPathDocumentKindDescendantIterator(this, type, matchSelf); } /// <summary> /// Return an iterator that ranges over all descendants of the current node that match the specified /// QName. If matchSelf is true, then also perform the match on the current node. /// </summary> public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) { // If local name is wildcard, then call XPathNavigator.SelectDescendants if (name == null || name.Length == 0) return base.SelectDescendants(name, namespaceURI, matchSelf); return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf); } /// <summary> /// Returns: /// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the /// navigator's are not positioned on nodes in the same document. /// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node /// in document order. /// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node /// in document order. /// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator. /// </summary> public override XmlNodeOrder ComparePosition(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathDocument thisDoc = _pageCurrent[_idxCurrent].Document; XPathDocument thatDoc = that._pageCurrent[that._idxCurrent].Document; if ((object)thisDoc == (object)thatDoc) { int locThis = GetPrimaryLocation(); int locThat = that.GetPrimaryLocation(); if (locThis == locThat) { locThis = GetSecondaryLocation(); locThat = that.GetSecondaryLocation(); if (locThis == locThat) return XmlNodeOrder.Same; } return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After; } } return XmlNodeOrder.Unknown; } /// <summary> /// Return true if the "other" navigator's current node is a descendant of this navigator's current node. /// </summary> public override bool IsDescendant(XPathNavigator other) { XPathDocumentNavigator that = other as XPathDocumentNavigator; if (that != null) { XPathNode[] pageThat; int idxThat; // If that current node's parent is virtualized, then start with the virtual parent if (that._idxParent != 0) { pageThat = that._pageParent; idxThat = that._idxParent; } else { idxThat = that._pageCurrent[that._idxCurrent].GetParent(out pageThat); } while (idxThat != 0) { if (idxThat == _idxCurrent && pageThat == _pageCurrent) return true; idxThat = pageThat[idxThat].GetParent(out pageThat); } } return false; } /// <summary> /// Construct a primary location for this navigator. The location is an integer that can be /// easily compared with other locations in the same document in order to determine the relative /// document order of two nodes. If two locations compare equal, then secondary locations should /// be compared. /// </summary> private int GetPrimaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so primary location should be derived from current node return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); } // Yes, so primary location should be derived from parent node return XPathNodeHelper.GetLocation(_pageParent, _idxParent); } /// <summary> /// Construct a secondary location for this navigator. This location should only be used if /// primary locations previously compared equal. /// </summary> private int GetSecondaryLocation() { // Is the current node virtualized? if (_idxParent == 0) { // No, so secondary location is int.MinValue (always first) return int.MinValue; } // Yes, so secondary location should be derived from current node // This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values switch (_pageCurrent[_idxCurrent].NodeType) { case XPathNodeType.Namespace: // Namespace nodes come first (make location negative, but greater than int.MinValue) return int.MinValue + 1 + XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); case XPathNodeType.Attribute: // Attribute nodes come next (location is always positive) return XPathNodeHelper.GetLocation(_pageCurrent, _idxCurrent); default: // Collapsed text nodes are always last return int.MaxValue; } } /// <summary> /// Create a unique id for the current node. This is used by the generate-id() function. /// </summary> internal override string UniqueId { get { // 32-bit integer is split into 5-bit groups, the maximum number of groups is 7 char[] buf = new char[1 + 7 + 1 + 7]; int idx = 0; int loc; // Ensure distinguishing attributes, namespaces and child nodes buf[idx++] = NodeTypeLetter[(int)_pageCurrent[_idxCurrent].NodeType]; // If the current node is virtualized, code its parent if (_idxParent != 0) { loc = (_pageParent[0].PageInfo.PageNumber - 1) << 16 | (_idxParent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); buf[idx++] = '0'; } // Code the node itself loc = (_pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (_idxCurrent - 1); do { buf[idx++] = UniqueIdTbl[loc & 0x1f]; loc >>= 5; } while (loc != 0); return new string(buf, 0, idx); } } public override object UnderlyingObject { get { // Since we don't have any underlying PUBLIC object // the best one we can return is a clone of the navigator. // Note that it should be a clone as the user might Move the returned navigator // around and thus cause unexpected behavior of the caller of this class (For example the validator) return this.Clone(); } } //----------------------------------------------- // IXmlLineInfo //----------------------------------------------- /// <summary> /// Return true if line number information is recorded in the cache. /// </summary> public bool HasLineInfo() { return _pageCurrent[_idxCurrent].Document.HasLineInfo; } /// <summary> /// Return the source line number of the current node. /// </summary> public int LineNumber { get { // If the current node is a collapsed text node, then return parent element's line number if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].LineNumber; return _pageCurrent[_idxCurrent].LineNumber; } } /// <summary> /// Return the source line position of the current node. /// </summary> public int LinePosition { get { // If the current node is a collapsed text node, then get position from parent element if (_idxParent != 0 && NodeType == XPathNodeType.Text) return _pageParent[_idxParent].CollapsedLinePosition; return _pageCurrent[_idxCurrent].LinePosition; } } //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// Get hashcode based on current position of the navigator. /// </summary> public int GetPositionHashCode() { return _idxCurrent ^ _idxParent; } /// <summary> /// Return true if navigator is positioned to an element having the specified name. /// </summary> public bool IsElementMatch(string localName, string namespaceURI) { if ((object)localName != (object)_atomizedLocalName) _atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null; // Cannot be an element if parent is stored if (_idxParent != 0) return false; return _pageCurrent[_idxCurrent].ElementMatch(_atomizedLocalName, namespaceURI); } /// <summary> /// Return true if navigator is positioned to a content node of the specified kind. Whitespace/SignficantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsContentKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & GetContentKindMask(typ)) != 0); } /// <summary> /// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignficantWhitespace/Text are /// all treated the same (i.e. they all match each other). /// </summary> public bool IsKindMatch(XPathNodeType typ) { return (((1 << (int)_pageCurrent[_idxCurrent].NodeType) & GetKindMask(typ)) != 0); } /// <summary> /// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it /// is positioned to a non-virtual node. If "end" is positioned to a virtual node: /// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent /// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1. /// </summary> private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd) { // If ending navigator is positioned to a node in another document, then return null if (end != null && _pageCurrent[_idxCurrent].Document == end._pageCurrent[end._idxCurrent].Document) { // If the ending navigator is not positioned on a virtual node, then return its current node if (end._idxParent == 0) { pageEnd = end._pageCurrent; return end._idxCurrent; } // If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the // next physical node instead, as the results will be the same. pageEnd = end._pageParent; return (useParentOfVirtual) ? end._idxParent : end._idxParent + 1; } // No following, so set pageEnd to null and return an index of 0 pageEnd = null; return 0; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Input; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Runtime.InteropServices; using Avalonia.Controls; using Avalonia.Input.Raw; using Avalonia.Platform; using Avalonia.Win32.Input; using Avalonia.Win32.Interop; namespace Avalonia.Win32 { public class WindowImpl : IWindowImpl { private static readonly List<WindowImpl> s_instances = new List<WindowImpl>(); private static readonly IntPtr DefaultCursor = UnmanagedMethods.LoadCursor( IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW)); private UnmanagedMethods.WndProc _wndProcDelegate; private string _className; private IntPtr _hwnd; private IInputRoot _owner; private bool _trackingMouse; private bool _isActive; private bool _decorated = true; private double _scaling = 1; private WindowState _showWindowState; public WindowImpl() { CreateWindow(); s_instances.Add(this); } public Action Activated { get; set; } public Action Closed { get; set; } public Action Deactivated { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public Thickness BorderThickness { get { var style = UnmanagedMethods.GetWindowLong(_hwnd, -16); var exStyle = UnmanagedMethods.GetWindowLong(_hwnd, -20); var padding = new UnmanagedMethods.RECT(); if (UnmanagedMethods.AdjustWindowRectEx(ref padding, style, false, exStyle)) { return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom); } else { throw new Win32Exception(); } } } public Size ClientSize { get { UnmanagedMethods.RECT rect; UnmanagedMethods.GetClientRect(_hwnd, out rect); return new Size(rect.right, rect.bottom) / Scaling; } set { if (value != ClientSize) { value *= Scaling; value += BorderThickness; UnmanagedMethods.SetWindowPos( _hwnd, IntPtr.Zero, 0, 0, (int)value.Width, (int)value.Height, UnmanagedMethods.SetWindowPosFlags.SWP_RESIZE); } } } public double Scaling => _scaling; public IPlatformHandle Handle { get; private set; } public bool IsEnabled { get { return UnmanagedMethods.IsWindowEnabled(_hwnd); } set { UnmanagedMethods.EnableWindow(_hwnd, value); } } public Size MaxClientSize { get { return (new Size( UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CXMAXTRACK), UnmanagedMethods.GetSystemMetrics(UnmanagedMethods.SystemMetric.SM_CYMAXTRACK)) - BorderThickness) / Scaling; } } public WindowState WindowState { get { var placement = default(UnmanagedMethods.WINDOWPLACEMENT); UnmanagedMethods.GetWindowPlacement(_hwnd, ref placement); switch (placement.ShowCmd) { case UnmanagedMethods.ShowWindowCommand.Maximize: return WindowState.Maximized; case UnmanagedMethods.ShowWindowCommand.Minimize: return WindowState.Minimized; default: return WindowState.Normal; } } set { if (UnmanagedMethods.IsWindowVisible(_hwnd)) { ShowWindow(value); } else { _showWindowState = value; } } } public void Activate() { UnmanagedMethods.SetActiveWindow(_hwnd); } public IPopupImpl CreatePopup() { return new PopupImpl(); } public void Dispose() { s_instances.Remove(this); UnmanagedMethods.DestroyWindow(_hwnd); } public void Hide() { UnmanagedMethods.ShowWindow(_hwnd, UnmanagedMethods.ShowWindowCommand.Hide); } public void SetSystemDecorations(bool value) { if (value == _decorated) return; var style = (UnmanagedMethods.WindowStyles) UnmanagedMethods.GetWindowLong(_hwnd, -16); style |= UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW; if (!value) style ^= UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW; UnmanagedMethods.RECT windowRect; UnmanagedMethods.GetWindowRect(_hwnd, out windowRect); Rect newRect; var oldThickness = BorderThickness; UnmanagedMethods.SetWindowLong(_hwnd, -16, (uint) style); if (value) { var thickness = BorderThickness; newRect = new Rect( windowRect.left - thickness.Left, windowRect.top - thickness.Top, (windowRect.right - windowRect.left) + (thickness.Left + thickness.Right), (windowRect.bottom - windowRect.top) + (thickness.Top + thickness.Bottom)); } else newRect = new Rect( windowRect.left + oldThickness.Left, windowRect.top + oldThickness.Top, (windowRect.right - windowRect.left) - (oldThickness.Left + oldThickness.Right), (windowRect.bottom - windowRect.top) - (oldThickness.Top + oldThickness.Bottom)); UnmanagedMethods.SetWindowPos(_hwnd, IntPtr.Zero, (int) newRect.X, (int) newRect.Y, (int) newRect.Width, (int) newRect.Height, UnmanagedMethods.SetWindowPosFlags.SWP_NOZORDER | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); _decorated = value; } public void Invalidate(Rect rect) { var f = Scaling; var r = new UnmanagedMethods.RECT { left = (int)(rect.X * f), top = (int)(rect.Y * f), right = (int)(rect.Right * f), bottom = (int)(rect.Bottom * f), }; UnmanagedMethods.InvalidateRect(_hwnd, ref r, false); } public Point PointToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y) / Scaling; } public Point PointToScreen(Point point) { point *= Scaling; var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ClientToScreen(_hwnd, ref p); return new Point(p.X, p.Y); } public void SetInputRoot(IInputRoot inputRoot) { _owner = inputRoot; } public void SetTitle(string title) { UnmanagedMethods.SetWindowText(_hwnd, title); } public virtual void Show() { ShowWindow(_showWindowState); } public void BeginMoveDrag() { UnmanagedMethods.DefWindowProc(_hwnd, (int) UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int)UnmanagedMethods.HitTestValues.HTCAPTION), IntPtr.Zero); } static readonly Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> EdgeDic = new Dictionary<WindowEdge, UnmanagedMethods.HitTestValues> { {WindowEdge.East, UnmanagedMethods.HitTestValues.HTRIGHT}, {WindowEdge.North, UnmanagedMethods.HitTestValues.HTTOP }, {WindowEdge.NorthEast, UnmanagedMethods.HitTestValues.HTTOPRIGHT }, {WindowEdge.NorthWest, UnmanagedMethods.HitTestValues.HTTOPLEFT }, {WindowEdge.South, UnmanagedMethods.HitTestValues.HTBOTTOM }, {WindowEdge.SouthEast, UnmanagedMethods.HitTestValues.HTBOTTOMRIGHT }, {WindowEdge.SouthWest, UnmanagedMethods.HitTestValues.HTBOTTOMLEFT }, {WindowEdge.West, UnmanagedMethods.HitTestValues.HTLEFT} }; public void BeginResizeDrag(WindowEdge edge) { UnmanagedMethods.DefWindowProc(_hwnd, (int) UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN, new IntPtr((int) EdgeDic[edge]), IntPtr.Zero); } public Point Position { get { UnmanagedMethods.RECT rc; UnmanagedMethods.GetWindowRect(_hwnd, out rc); return new Point(rc.left, rc.top); } set { UnmanagedMethods.SetWindowPos( Handle.Handle, IntPtr.Zero, (int) value.X, (int) value.Y, 0, 0, UnmanagedMethods.SetWindowPosFlags.SWP_NOSIZE | UnmanagedMethods.SetWindowPosFlags.SWP_NOACTIVATE); } } public virtual IDisposable ShowDialog() { var disabled = s_instances.Where(x => x != this && x.IsEnabled).ToList(); WindowImpl activated = null; foreach (var window in disabled) { if (window._isActive) { activated = window; } window.IsEnabled = false; } Show(); return Disposable.Create(() => { foreach (var window in disabled) { window.IsEnabled = true; } activated?.Activate(); }); } public void SetCursor(IPlatformHandle cursor) { UnmanagedMethods.SetClassLong(_hwnd, UnmanagedMethods.ClassLongIndex.GCL_HCURSOR, cursor?.Handle ?? DefaultCursor); } protected virtual IntPtr CreateWindowOverride(ushort atom) { return UnmanagedMethods.CreateWindowEx( 0, atom, null, (int)UnmanagedMethods.WindowStyles.WS_OVERLAPPEDWINDOW, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, UnmanagedMethods.CW_USEDEFAULT, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); } [SuppressMessage("Microsoft.StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Using Win32 naming for consistency.")] protected virtual IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { bool unicode = UnmanagedMethods.IsWindowUnicode(hWnd); const double wheelDelta = 120.0; uint timestamp = unchecked((uint)UnmanagedMethods.GetMessageTime()); RawInputEventArgs e = null; WindowsMouseDevice.Instance.CurrentWindow = this; switch ((UnmanagedMethods.WindowsMessage)msg) { case UnmanagedMethods.WindowsMessage.WM_ACTIVATE: var wa = (UnmanagedMethods.WindowActivate)((int)wParam & 0xffff); switch (wa) { case UnmanagedMethods.WindowActivate.WA_ACTIVE: case UnmanagedMethods.WindowActivate.WA_CLICKACTIVE: _isActive = true; Activated?.Invoke(); break; case UnmanagedMethods.WindowActivate.WA_INACTIVE: _isActive = false; Deactivated?.Invoke(); break; } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DESTROY: if (Closed != null) { UnmanagedMethods.UnregisterClass(_className, Marshal.GetHINSTANCE(GetType().Module)); Closed(); } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_DPICHANGED: var dpi = (int)wParam & 0xffff; var newDisplayRect = (UnmanagedMethods.RECT)Marshal.PtrToStructure(lParam, typeof(UnmanagedMethods.RECT)); Position = new Point(newDisplayRect.left, newDisplayRect.top); _scaling = dpi / 96.0; ScalingChanged?.Invoke(_scaling); return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_KEYDOWN: case UnmanagedMethods.WindowsMessage.WM_SYSKEYDOWN: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyDown, KeyInterop.KeyFromVirtualKey((int)wParam), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_KEYUP: case UnmanagedMethods.WindowsMessage.WM_SYSKEYUP: e = new RawKeyEventArgs( WindowsKeyboardDevice.Instance, timestamp, RawKeyEventType.KeyUp, KeyInterop.KeyFromVirtualKey((int)wParam), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_CHAR: // Ignore control chars if (wParam.ToInt32() >= 32) { e = new RawTextInputEventArgs(WindowsKeyboardDevice.Instance, timestamp, new string((char)wParam.ToInt32(), 1)); } break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_MBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_LBUTTONDOWN ? RawMouseEventType.LeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_RBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_LBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_RBUTTONUP: case UnmanagedMethods.WindowsMessage.WM_MBUTTONUP: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int) UnmanagedMethods.WindowsMessage.WM_LBUTTONUP ? RawMouseEventType.LeftButtonUp : msg == (int) UnmanagedMethods.WindowsMessage.WM_RBUTTONUP ? RawMouseEventType.RightButtonUp : RawMouseEventType.MiddleButtonUp, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEMOVE: if (!_trackingMouse) { var tm = new UnmanagedMethods.TRACKMOUSEEVENT { cbSize = Marshal.SizeOf(typeof(UnmanagedMethods.TRACKMOUSEEVENT)), dwFlags = 2, hwndTrack = _hwnd, dwHoverTime = 0, }; UnmanagedMethods.TrackMouseEvent(ref tm); } e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.Move, DipFromLParam(lParam), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSEWHEEL: e = new RawMouseWheelEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, ScreenToClient(DipFromLParam(lParam)), new Vector(0, ((int)wParam >> 16) / wheelDelta), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_MOUSELEAVE: _trackingMouse = false; e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, RawMouseEventType.LeaveWindow, new Point(), WindowsKeyboardDevice.Instance.Modifiers); break; case UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN: case UnmanagedMethods.WindowsMessage.WM_NCMBUTTONDOWN: e = new RawMouseEventArgs( WindowsMouseDevice.Instance, timestamp, _owner, msg == (int)UnmanagedMethods.WindowsMessage.WM_NCLBUTTONDOWN ? RawMouseEventType.NonClientLeftButtonDown : msg == (int)UnmanagedMethods.WindowsMessage.WM_NCRBUTTONDOWN ? RawMouseEventType.RightButtonDown : RawMouseEventType.MiddleButtonDown, new Point(0, 0), GetMouseModifiers(wParam)); break; case UnmanagedMethods.WindowsMessage.WM_PAINT: if (Paint != null) { UnmanagedMethods.PAINTSTRUCT ps; if (UnmanagedMethods.BeginPaint(_hwnd, out ps) != IntPtr.Zero) { UnmanagedMethods.RECT r; UnmanagedMethods.GetUpdateRect(_hwnd, out r, false); var f = Scaling; Paint(new Rect(r.left / f, r.top / f, (r.right - r.left) / f, (r.bottom - r.top) / f)); UnmanagedMethods.EndPaint(_hwnd, ref ps); } } return IntPtr.Zero; case UnmanagedMethods.WindowsMessage.WM_SIZE: if (Resized != null) { var clientSize = new Size((int)lParam & 0xffff, (int)lParam >> 16); Resized(clientSize / Scaling); } return IntPtr.Zero; } if (e != null && Input != null) { Input(e); if (e.Handled) { return IntPtr.Zero; } } return UnmanagedMethods.DefWindowProc(hWnd, msg, wParam, lParam); } static InputModifiers GetMouseModifiers(IntPtr wParam) { var keys = (UnmanagedMethods.ModifierKeys)wParam.ToInt32(); var modifiers = WindowsKeyboardDevice.Instance.Modifiers; if (keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_LBUTTON)) modifiers |= InputModifiers.LeftMouseButton; if(keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_RBUTTON)) modifiers |= InputModifiers.RightMouseButton; if(keys.HasFlag(UnmanagedMethods.ModifierKeys.MK_MBUTTON)) modifiers |= InputModifiers.MiddleMouseButton; return modifiers; } private void CreateWindow() { // Ensure that the delegate doesn't get garbage collected by storing it as a field. _wndProcDelegate = new UnmanagedMethods.WndProc(WndProc); _className = Guid.NewGuid().ToString(); UnmanagedMethods.WNDCLASSEX wndClassEx = new UnmanagedMethods.WNDCLASSEX { cbSize = Marshal.SizeOf(typeof(UnmanagedMethods.WNDCLASSEX)), style = 0, lpfnWndProc = _wndProcDelegate, hInstance = Marshal.GetHINSTANCE(GetType().Module), hCursor = DefaultCursor, hbrBackground = IntPtr.Zero, lpszClassName = _className, }; ushort atom = UnmanagedMethods.RegisterClassEx(ref wndClassEx); if (atom == 0) { throw new Win32Exception(); } _hwnd = CreateWindowOverride(atom); if (_hwnd == IntPtr.Zero) { throw new Win32Exception(); } Handle = new PlatformHandle(_hwnd, PlatformConstants.WindowHandleType); if (UnmanagedMethods.ShCoreAvailable) { uint dpix, dpiy; var monitor = UnmanagedMethods.MonitorFromWindow( _hwnd, UnmanagedMethods.MONITOR.MONITOR_DEFAULTTONEAREST); if (UnmanagedMethods.GetDpiForMonitor( monitor, UnmanagedMethods.MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI, out dpix, out dpiy) == 0) { _scaling = dpix / 96.0; } } } private Point DipFromLParam(IntPtr lParam) { return new Point((short)((int)lParam & 0xffff), (short)((int)lParam >> 16)) / Scaling; } private Point PointFromLParam(IntPtr lParam) { return new Point((short)((int)lParam & 0xffff), (short)((int)lParam >> 16)); } private Point ScreenToClient(Point point) { var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y }; UnmanagedMethods.ScreenToClient(_hwnd, ref p); return new Point(p.X, p.Y); } private void ShowWindow(WindowState state) { UnmanagedMethods.ShowWindowCommand command; switch (state) { case WindowState.Minimized: command = UnmanagedMethods.ShowWindowCommand.Minimize; break; case WindowState.Maximized: command = UnmanagedMethods.ShowWindowCommand.Maximize; break; case WindowState.Normal: command = UnmanagedMethods.ShowWindowCommand.Restore; break; default: throw new ArgumentException("Invalid WindowState."); } UnmanagedMethods.ShowWindow(_hwnd, command); } } }
// 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.Contracts; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.Security.Cryptography { public class CryptoStream : Stream, IDisposable { // Member variables private readonly Stream _stream; private readonly ICryptoTransform _transform; private readonly CryptoStreamMode _transformMode; private byte[] _inputBuffer; // read from _stream before _Transform private int _inputBufferIndex; private int _inputBlockSize; private byte[] _outputBuffer; // buffered output of _Transform private int _outputBufferIndex; private int _outputBlockSize; private bool _canRead; private bool _canWrite; private bool _finalBlockTransformed; private SemaphoreSlim _lazyAsyncActiveSemaphore; private readonly bool _leaveOpen; // Constructors public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : this(stream, transform, mode, false) { } public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, bool leaveOpen) { _stream = stream; _transformMode = mode; _transform = transform; _leaveOpen = leaveOpen; switch (_transformMode) { case CryptoStreamMode.Read: if (!(_stream.CanRead)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotReadable, nameof(stream))); _canRead = true; break; case CryptoStreamMode.Write: if (!(_stream.CanWrite)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotWritable, nameof(stream))); _canWrite = true; break; default: throw new ArgumentException(SR.Argument_InvalidValue); } InitializeBuffer(); } public override bool CanRead { [Pure] get { return _canRead; } } // For now, assume we can never seek into the middle of a cryptostream // and get the state right. This is too strict. public override bool CanSeek { [Pure] get { return false; } } public override bool CanWrite { [Pure] get { return _canWrite; } } public override long Length { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } set { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public bool HasFlushedFinalBlock { get { return _finalBlockTransformed; } } // The flush final block functionality used to be part of close, but that meant you couldn't do something like this: // MemoryStream ms = new MemoryStream(); // CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); // cs.Write(foo, 0, foo.Length); // cs.Close(); // and get the encrypted data out of ms, because the cs.Close also closed ms and the data went away. // so now do this: // cs.Write(foo, 0, foo.Length); // cs.FlushFinalBlock() // which can only be called once // byte[] ciphertext = ms.ToArray(); // cs.Close(); public void FlushFinalBlock() { if (_finalBlockTransformed) throw new NotSupportedException(SR.Cryptography_CryptoStream_FlushFinalBlockTwice); // We have to process the last block here. First, we have the final block in _InputBuffer, so transform it byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex); _finalBlockTransformed = true; // Now, write out anything sitting in the _OutputBuffer... if (_canWrite && _outputBufferIndex > 0) { _stream.Write(_outputBuffer, 0, _outputBufferIndex); _outputBufferIndex = 0; } // Write out finalBytes if (_canWrite) _stream.Write(finalBytes, 0, finalBytes.Length); // If the inner stream is a CryptoStream, then we want to call FlushFinalBlock on it too, otherwise just Flush. CryptoStream innerCryptoStream = _stream as CryptoStream; if (innerCryptoStream != null) { if (!innerCryptoStream.HasFlushedFinalBlock) { innerCryptoStream.FlushFinalBlock(); } } else { _stream.Flush(); } // zeroize plain text material before returning if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); if (_outputBuffer != null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); return; } public override void Flush() { return; } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(CryptoStream)) return base.FlushAsync(cancellationToken); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckReadArguments(buffer, offset, count); return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = AsyncActiveSemaphore; await semaphore.WaitAsync().ForceAsync(); try { return await ReadAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); } finally { semaphore.Release(); } } public override int ReadByte() { // If we have enough bytes in the buffer such that reading 1 will still leave bytes // in the buffer, then take the faster path of simply returning the first byte. // (This unfortunately still involves shifting down the bytes in the buffer, as it // does in Read. If/when that's fixed for Read, it should be fixed here, too.) if (_outputBufferIndex > 1) { byte b = _outputBuffer[0]; Buffer.BlockCopy(_outputBuffer, 1, _outputBuffer, 0, _outputBufferIndex - 1); _outputBufferIndex -= 1; return b; } // Otherwise, fall back to the more robust but expensive path of using the base // Stream.ReadByte to call Read. return base.ReadByte(); } public override void WriteByte(byte value) { // If there's room in the input buffer such that even with this byte we wouldn't // complete a block, simply add the byte to the input buffer. if (_inputBufferIndex + 1 < _inputBlockSize) { _inputBuffer[_inputBufferIndex++] = value; return; } // Otherwise, the logic is complicated, so we simply fall back to the base // implementation that'll use Write. base.WriteByte(value); } public override int Read(byte[] buffer, int offset, int count) { CheckReadArguments(buffer, offset, count); return ReadAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).ConfigureAwait(false).GetAwaiter().GetResult(); } private void CheckReadArguments(byte[] buffer, int offset, int count) { if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync) { // read <= count bytes from the input stream, transforming as we go. // Basic idea: first we deliver any bytes we already have in the // _OutputBuffer, because we know they're good. Then, if asked to deliver // more bytes, we read & transform a block at a time until either there are // no bytes ready or we've delivered enough. int bytesToDeliver = count; int currentOutputIndex = offset; if (_outputBufferIndex != 0) { // we have some already-transformed bytes in the output buffer if (_outputBufferIndex <= count) { Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, _outputBufferIndex); bytesToDeliver -= _outputBufferIndex; currentOutputIndex += _outputBufferIndex; _outputBufferIndex = 0; } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, count); Buffer.BlockCopy(_outputBuffer, count, _outputBuffer, 0, _outputBufferIndex - count); _outputBufferIndex -= count; return (count); } } // _finalBlockTransformed == true implies we're at the end of the input stream // if we got through the previous if block then _OutputBufferIndex = 0, meaning // we have no more transformed bytes to give // so return count-bytesToDeliver, the amount we were able to hand back // eventually, we'll just always return 0 here because there's no more to read if (_finalBlockTransformed) { return (count - bytesToDeliver); } // ok, now loop until we've delivered enough or there's nothing available int amountRead = 0; int numOutputBytes; // OK, see first if it's a multi-block transform and we can speed up things if (bytesToDeliver > _outputBlockSize) { if (_transform.CanTransformMultipleBlocks) { int BlocksToProcess = bytesToDeliver / _outputBlockSize; int numWholeBlocksInBytes = BlocksToProcess * _inputBlockSize; byte[] tempInputBuffer = new byte[numWholeBlocksInBytes]; // get first the block already read Buffer.BlockCopy(_inputBuffer, 0, tempInputBuffer, 0, _inputBufferIndex); amountRead = _inputBufferIndex; amountRead += useAsync ? await _stream.ReadAsync(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex, cancellationToken) : _stream.Read(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex); _inputBufferIndex = 0; if (amountRead <= _inputBlockSize) { _inputBuffer = tempInputBuffer; _inputBufferIndex = amountRead; goto slow; } // Make amountRead an integral multiple of _InputBlockSize int numWholeReadBlocksInBytes = (amountRead / _inputBlockSize) * _inputBlockSize; int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes; if (numIgnoredBytes != 0) { _inputBufferIndex = numIgnoredBytes; Buffer.BlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _inputBuffer, 0, numIgnoredBytes); } byte[] tempOutputBuffer = new byte[(numWholeReadBlocksInBytes / _inputBlockSize) * _outputBlockSize]; numOutputBytes = _transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0); Buffer.BlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); // Now, tempInputBuffer and tempOutputBuffer are no more needed, so zeroize them to protect plain text Array.Clear(tempInputBuffer, 0, tempInputBuffer.Length); Array.Clear(tempOutputBuffer, 0, tempOutputBuffer.Length); bytesToDeliver -= numOutputBytes; currentOutputIndex += numOutputBytes; } } slow: // try to fill _InputBuffer so we have something to transform while (bytesToDeliver > 0) { while (_inputBufferIndex < _inputBlockSize) { amountRead = useAsync ? await _stream.ReadAsync(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex, cancellationToken) : _stream.Read(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex); // first, check to see if we're at the end of the input stream if (amountRead == 0) goto ProcessFinalBlock; _inputBufferIndex += amountRead; } numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); _inputBufferIndex = 0; if (bytesToDeliver >= numOutputBytes) { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); currentOutputIndex += numOutputBytes; bytesToDeliver -= numOutputBytes; } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _outputBufferIndex = numOutputBytes - bytesToDeliver; Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex); return count; } } return count; ProcessFinalBlock: // if so, then call TransformFinalBlock to get whatever is left byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex); // now, since _OutputBufferIndex must be 0 if we're in the while loop at this point, // reset it to be what we just got back _outputBuffer = finalBytes; _outputBufferIndex = finalBytes.Length; // set the fact that we've transformed the final block _finalBlockTransformed = true; // now, return either everything we just got or just what's asked for, whichever is smaller if (bytesToDeliver < _outputBufferIndex) { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _outputBufferIndex -= bytesToDeliver; Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex); return (count); } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, _outputBufferIndex); bytesToDeliver -= _outputBufferIndex; _outputBufferIndex = 0; return (count - bytesToDeliver); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckWriteArguments(buffer, offset, count); return WriteAsyncInternal(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); private async Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = AsyncActiveSemaphore; await semaphore.WaitAsync().ForceAsync(); try { await WriteAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); } finally { semaphore.Release(); } } public override void Write(byte[] buffer, int offset, int count) { CheckWriteArguments(buffer, offset, count); WriteAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).GetAwaiter().GetResult(); } private void CheckWriteArguments(byte[] buffer, int offset, int count) { if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync) { // write <= count bytes to the output stream, transforming as we go. // Basic idea: using bytes in the _InputBuffer first, make whole blocks, // transform them, and write them out. Cache any remaining bytes in the _InputBuffer. int bytesToWrite = count; int currentInputIndex = offset; // if we have some bytes in the _InputBuffer, we have to deal with those first, // so let's try to make an entire block out of it if (_inputBufferIndex > 0) { if (count >= _inputBlockSize - _inputBufferIndex) { // we have enough to transform at least a block, so fill the input block Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex); currentInputIndex += (_inputBlockSize - _inputBufferIndex); bytesToWrite -= (_inputBlockSize - _inputBufferIndex); _inputBufferIndex = _inputBlockSize; // Transform the block and write it out } else { // not enough to transform a block, so just copy the bytes into the _InputBuffer // and return Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, count); _inputBufferIndex += count; return; } } // If the OutputBuffer has anything in it, write it out if (_outputBufferIndex > 0) { if (useAsync) await _stream.WriteAsync(_outputBuffer, 0, _outputBufferIndex, cancellationToken); else _stream.Write(_outputBuffer, 0, _outputBufferIndex); _outputBufferIndex = 0; } // At this point, either the _InputBuffer is full, empty, or we've already returned. // If full, let's process it -- we now know the _OutputBuffer is empty int numOutputBytes; if (_inputBufferIndex == _inputBlockSize) { numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); // write out the bytes we just got if (useAsync) await _stream.WriteAsync(_outputBuffer, 0, numOutputBytes, cancellationToken); else _stream.Write(_outputBuffer, 0, numOutputBytes); // reset the _InputBuffer _inputBufferIndex = 0; } while (bytesToWrite > 0) { if (bytesToWrite >= _inputBlockSize) { // We have at least an entire block's worth to transform // If the transform will handle multiple blocks at once, do that if (_transform.CanTransformMultipleBlocks) { int numWholeBlocks = bytesToWrite / _inputBlockSize; int numWholeBlocksInBytes = numWholeBlocks * _inputBlockSize; byte[] _tempOutputBuffer = new byte[numWholeBlocks * _outputBlockSize]; numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, _tempOutputBuffer, 0); if (useAsync) await _stream.WriteAsync(_tempOutputBuffer, 0, numOutputBytes, cancellationToken); else _stream.Write(_tempOutputBuffer, 0, numOutputBytes); currentInputIndex += numWholeBlocksInBytes; bytesToWrite -= numWholeBlocksInBytes; } else { // do it the slow way numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, _inputBlockSize, _outputBuffer, 0); if (useAsync) await _stream.WriteAsync(_outputBuffer, 0, numOutputBytes, cancellationToken); else _stream.Write(_outputBuffer, 0, numOutputBytes); currentInputIndex += _inputBlockSize; bytesToWrite -= _inputBlockSize; } } else { // In this case, we don't have an entire block's worth left, so store it up in the // input buffer, which by now must be empty. Buffer.BlockCopy(buffer, currentInputIndex, _inputBuffer, 0, bytesToWrite); _inputBufferIndex += bytesToWrite; return; } } return; } public void Clear() { Close(); } protected override void Dispose(bool disposing) { try { if (disposing) { if (!_finalBlockTransformed) { FlushFinalBlock(); } if (!_leaveOpen) { _stream.Dispose(); } } } finally { try { // Ensure we don't try to transform the final block again if we get disposed twice // since it's null after this _finalBlockTransformed = true; // we need to clear all the internal buffers if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); if (_outputBuffer != null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); _inputBuffer = null; _outputBuffer = null; _canRead = false; _canWrite = false; } finally { base.Dispose(disposing); } } } // Private methods private void InitializeBuffer() { if (_transform != null) { _inputBlockSize = _transform.InputBlockSize; _inputBuffer = new byte[_inputBlockSize]; _outputBlockSize = _transform.OutputBlockSize; _outputBuffer = new byte[_outputBlockSize]; } } private SemaphoreSlim AsyncActiveSemaphore { get { // Lazily-initialize _lazyAsyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _lazyAsyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } } } }
using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; using GodLesZ.Library.Win7.Resources; using MS.WindowsAPICodePack.Internal; namespace GodLesZ.Library.Win7.Dialogs { /// <summary> /// Encapsulates the native logic required to create, /// configure, and show a TaskDialog, /// via the TaskDialogIndirect() Win32 function. /// </summary> /// <remarks>A new instance of this class should /// be created for each messagebox show, as /// the HWNDs for TaskDialogs do not remain constant /// across calls to TaskDialogIndirect. /// </remarks> internal class NativeTaskDialog : IDisposable { private TaskDialogNativeMethods.TaskDialogConfiguration nativeDialogConfig; private NativeTaskDialogSettings settings; private IntPtr hWndDialog; private TaskDialog outerDialog; private IntPtr[] updatedStrings = new IntPtr[Enum.GetNames(typeof(TaskDialogNativeMethods.TaskDialogElements)).Length]; private IntPtr buttonArray, radioButtonArray; // Flag tracks whether our first radio // button click event has come through. private bool firstRadioButtonClicked = true; #region Constructors // Configuration is applied at dialog creation time. internal NativeTaskDialog(NativeTaskDialogSettings settings, TaskDialog outerDialog) { nativeDialogConfig = settings.NativeConfiguration; this.settings = settings; // Wireup dialog proc message loop for this instance. nativeDialogConfig.callback = new TaskDialogNativeMethods.TaskDialogCallback(DialogProc); ShowState = DialogShowState.PreShow; // Keep a reference to the outer shell, so we can notify. this.outerDialog = outerDialog; } #endregion #region Public Properties public DialogShowState ShowState { get; private set; } public int SelectedButtonId { get; private set; } public int SelectedRadioButtonId { get; private set; } public bool CheckBoxChecked { get; private set; } #endregion internal void NativeShow() { // Applies config struct and other settings, then // calls main Win32 function. if (settings == null) { throw new InvalidOperationException(LocalizedMessages.NativeTaskDialogConfigurationError); } // Do a last-minute parse of the various dialog control lists, // and only allocate the memory at the last minute. MarshalDialogControlStructs(); // Make the call and show the dialog. // NOTE: this call is BLOCKING, though the thread // WILL re-enter via the DialogProc. try { ShowState = DialogShowState.Showing; int selectedButtonId; int selectedRadioButtonId; bool checkBoxChecked; // Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect(). HResult hresult = TaskDialogNativeMethods.TaskDialogIndirect( nativeDialogConfig, out selectedButtonId, out selectedRadioButtonId, out checkBoxChecked); if (CoreErrorHelper.Failed(hresult)) { string msg; switch (hresult) { case HResult.InvalidArguments: msg = LocalizedMessages.NativeTaskDialogInternalErrorArgs; break; case HResult.OutOfMemory: msg = LocalizedMessages.NativeTaskDialogInternalErrorComplex; break; default: msg = string.Format(System.Globalization.CultureInfo.InvariantCulture, LocalizedMessages.NativeTaskDialogInternalErrorUnexpected, hresult); break; } Exception e = Marshal.GetExceptionForHR((int)hresult); throw new Win32Exception(msg, e); } SelectedButtonId = selectedButtonId; SelectedRadioButtonId = selectedRadioButtonId; CheckBoxChecked = checkBoxChecked; } catch (EntryPointNotFoundException exc) { throw new NotSupportedException(LocalizedMessages.NativeTaskDialogVersionError, exc); } finally { ShowState = DialogShowState.Closed; } } // The new task dialog does not support the existing // Win32 functions for closing (e.g. EndDialog()); instead, // a "click button" message is sent. In this case, we're // abstracting out to say that the TaskDialog consumer can // simply call "Close" and we'll "click" the cancel button. // Note that the cancel button doesn't actually // have to exist for this to work. internal void NativeClose(TaskDialogResult result) { ShowState = DialogShowState.Closing; int id; switch (result) { case TaskDialogResult.Close: id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close; break; case TaskDialogResult.CustomButtonClicked: id = DialogsDefaults.MinimumDialogControlId; // custom buttons break; case TaskDialogResult.No: id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.No; break; case TaskDialogResult.Ok: id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Ok; break; case TaskDialogResult.Retry: id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Retry; break; case TaskDialogResult.Yes: id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Yes; break; default: id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Cancel; break; } SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.ClickButton, id, 0); } #region Main Dialog Proc private int DialogProc( IntPtr windowHandle, uint message, IntPtr wparam, IntPtr lparam, IntPtr referenceData) { // Fetch the HWND - it may be the first time we're getting it. hWndDialog = windowHandle; // Big switch on the various notifications the // dialog proc can get. switch ((TaskDialogNativeMethods.TaskDialogNotifications)message) { case TaskDialogNativeMethods.TaskDialogNotifications.Created: int result = PerformDialogInitialization(); outerDialog.RaiseOpenedEvent(); return result; case TaskDialogNativeMethods.TaskDialogNotifications.ButtonClicked: return HandleButtonClick((int)wparam); case TaskDialogNativeMethods.TaskDialogNotifications.RadioButtonClicked: return HandleRadioButtonClick((int)wparam); case TaskDialogNativeMethods.TaskDialogNotifications.HyperlinkClicked: return HandleHyperlinkClick(lparam); case TaskDialogNativeMethods.TaskDialogNotifications.Help: return HandleHelpInvocation(); case TaskDialogNativeMethods.TaskDialogNotifications.Timer: return HandleTick((int)wparam); case TaskDialogNativeMethods.TaskDialogNotifications.Destroyed: return PerformDialogCleanup(); default: break; } return (int)HResult.Ok; } // Once the task dialog HWND is open, we need to send // additional messages to configure it. private int PerformDialogInitialization() { // Initialize Progress or Marquee Bar. if (IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.ShowProgressBar)) { UpdateProgressBarRange(); // The order of the following is important - // state is more important than value, // and non-normal states turn off the bar value change // animation, which is likely the intended // and preferable behavior. UpdateProgressBarState(settings.ProgressBarState); UpdateProgressBarValue(settings.ProgressBarValue); // Due to a bug that wasn't fixed in time for RTM of Vista, // second SendMessage is required if the state is non-Normal. UpdateProgressBarValue(settings.ProgressBarValue); } else if (IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.ShowMarqueeProgressBar)) { // TDM_SET_PROGRESS_BAR_MARQUEE is necessary // to cause the marquee to start animating. // Note that this internal task dialog setting is // round-tripped when the marquee is // is set to different states, so it never has to // be touched/sent again. SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarMarquee, 1, 0); UpdateProgressBarState(settings.ProgressBarState); } if (settings.ElevatedButtons != null && settings.ElevatedButtons.Count > 0) { foreach (int id in settings.ElevatedButtons) { UpdateElevationIcon(id, true); } } return CoreErrorHelper.Ignored; } private int HandleButtonClick(int id) { // First we raise a Click event, if there is a custom button // However, we implement Close() by sending a cancel button, so // we don't want to raise a click event in response to that. if (ShowState != DialogShowState.Closing) { outerDialog.RaiseButtonClickEvent(id); } // Once that returns, we raise a Closing event for the dialog // The Win32 API handles button clicking-and-closing // as an atomic action, // but it is more .NET friendly to split them up. // Unfortunately, we do NOT have the return values at this stage. if (id < DialogsDefaults.MinimumDialogControlId) { return outerDialog.RaiseClosingEvent(id); } return (int)HResult.False; } private int HandleRadioButtonClick(int id) { // When the dialog sets the radio button to default, // it (somewhat confusingly)issues a radio button clicked event // - we mask that out - though ONLY if // we do have a default radio button if (firstRadioButtonClicked && !IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.NoDefaultRadioButton)) { firstRadioButtonClicked = false; } else { outerDialog.RaiseButtonClickEvent(id); } // Note: we don't raise Closing, as radio // buttons are non-committing buttons return CoreErrorHelper.Ignored; } private int HandleHyperlinkClick(IntPtr href) { string link = Marshal.PtrToStringUni(href); outerDialog.RaiseHyperlinkClickEvent(link); return CoreErrorHelper.Ignored; } private int HandleTick(int ticks) { outerDialog.RaiseTickEvent(ticks); return CoreErrorHelper.Ignored; } private int HandleHelpInvocation() { outerDialog.RaiseHelpInvokedEvent(); return CoreErrorHelper.Ignored; } // There should be little we need to do here, // as the use of the NativeTaskDialog is // that it is instantiated for a single show, then disposed of. private int PerformDialogCleanup() { firstRadioButtonClicked = true; return CoreErrorHelper.Ignored; } #endregion #region Update members internal void UpdateProgressBarValue(int i) { AssertCurrentlyShowing(); SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarPosition, i, 0); } internal void UpdateProgressBarRange() { AssertCurrentlyShowing(); // Build range LPARAM - note it is in REVERSE intuitive order. long range = NativeTaskDialog.MakeLongLParam( settings.ProgressBarMaximum, settings.ProgressBarMinimum); SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarRange, 0, range); } internal void UpdateProgressBarState(TaskDialogProgressBarState state) { AssertCurrentlyShowing(); SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarState, (int)state, 0); } internal void UpdateText(string text) { UpdateTextCore(text, TaskDialogNativeMethods.TaskDialogElements.Content); } internal void UpdateInstruction(string instruction) { UpdateTextCore(instruction, TaskDialogNativeMethods.TaskDialogElements.MainInstruction); } internal void UpdateFooterText(string footerText) { UpdateTextCore(footerText, TaskDialogNativeMethods.TaskDialogElements.Footer); } internal void UpdateExpandedText(string expandedText) { UpdateTextCore(expandedText, TaskDialogNativeMethods.TaskDialogElements.ExpandedInformation); } private void UpdateTextCore(string s, TaskDialogNativeMethods.TaskDialogElements element) { AssertCurrentlyShowing(); FreeOldString(element); SendMessageHelper( TaskDialogNativeMethods.TaskDialogMessages.SetElementText, (int)element, (long)MakeNewString(s, element)); } internal void UpdateMainIcon(TaskDialogStandardIcon mainIcon) { UpdateIconCore(mainIcon, TaskDialogNativeMethods.TaskDialogIconElement.Main); } internal void UpdateFooterIcon(TaskDialogStandardIcon footerIcon) { UpdateIconCore(footerIcon, TaskDialogNativeMethods.TaskDialogIconElement.Footer); } private void UpdateIconCore(TaskDialogStandardIcon icon, TaskDialogNativeMethods.TaskDialogIconElement element) { AssertCurrentlyShowing(); SendMessageHelper( TaskDialogNativeMethods.TaskDialogMessages.UpdateIcon, (int)element, (long)icon); } internal void UpdateCheckBoxChecked(bool cbc) { AssertCurrentlyShowing(); SendMessageHelper( TaskDialogNativeMethods.TaskDialogMessages.ClickVerification, (cbc ? 1 : 0), 1); } internal void UpdateElevationIcon(int buttonId, bool showIcon) { AssertCurrentlyShowing(); SendMessageHelper( TaskDialogNativeMethods.TaskDialogMessages.SetButtonElevationRequiredState, buttonId, Convert.ToInt32(showIcon)); } internal void UpdateButtonEnabled(int buttonID, bool enabled) { AssertCurrentlyShowing(); SendMessageHelper( TaskDialogNativeMethods.TaskDialogMessages.EnableButton, buttonID, enabled == true ? 1 : 0); } internal void UpdateRadioButtonEnabled(int buttonID, bool enabled) { AssertCurrentlyShowing(); SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.EnableRadioButton, buttonID, enabled == true ? 1 : 0); } internal void AssertCurrentlyShowing() { Debug.Assert(ShowState == DialogShowState.Showing, "Update*() methods should only be called while native dialog is showing"); } #endregion #region Helpers private int SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages message, int wparam, long lparam) { // Be sure to at least assert here - // messages to invalid handles often just disappear silently Debug.Assert(hWndDialog != null, "HWND for dialog is null during SendMessage"); return (int)CoreNativeMethods.SendMessage( hWndDialog, (uint)message, (IntPtr)wparam, new IntPtr(lparam)); } private bool IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions flag) { return ((nativeDialogConfig.taskDialogFlags & flag) == flag); } // Allocates a new string on the unmanaged heap, // and stores the pointer so we can free it later. private IntPtr MakeNewString(string text, TaskDialogNativeMethods.TaskDialogElements element) { IntPtr newStringPtr = Marshal.StringToHGlobalUni(text); updatedStrings[(int)element] = newStringPtr; return newStringPtr; } // Checks to see if the given element already has an // updated string, and if so, // frees it. This is done in preparation for a call to // MakeNewString(), to prevent // leaks from multiple updates calls on the same element // within a single native dialog lifetime. private void FreeOldString(TaskDialogNativeMethods.TaskDialogElements element) { int elementIndex = (int)element; if (updatedStrings[elementIndex] != IntPtr.Zero) { Marshal.FreeHGlobal(updatedStrings[elementIndex]); updatedStrings[elementIndex] = IntPtr.Zero; } } // Based on the following defines in WinDef.h and WinUser.h: // #define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h)) // #define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16)) private static long MakeLongLParam(int a, int b) { return (a << 16) + b; } // Builds the actual configuration that the // NativeTaskDialog (and underlying Win32 API) // expects, by parsing the various control lists, // marshaling to the unmanaged heap, etc. private void MarshalDialogControlStructs() { if (settings.Buttons != null && settings.Buttons.Length > 0) { buttonArray = AllocateAndMarshalButtons(settings.Buttons); settings.NativeConfiguration.buttons = buttonArray; settings.NativeConfiguration.buttonCount = (uint)settings.Buttons.Length; } if (settings.RadioButtons != null && settings.RadioButtons.Length > 0) { radioButtonArray = AllocateAndMarshalButtons(settings.RadioButtons); settings.NativeConfiguration.radioButtons = radioButtonArray; settings.NativeConfiguration.radioButtonCount = (uint)settings.RadioButtons.Length; } } private static IntPtr AllocateAndMarshalButtons(TaskDialogNativeMethods.TaskDialogButton[] structs) { IntPtr initialPtr = Marshal.AllocHGlobal( Marshal.SizeOf(typeof(TaskDialogNativeMethods.TaskDialogButton)) * structs.Length); IntPtr currentPtr = initialPtr; foreach (TaskDialogNativeMethods.TaskDialogButton button in structs) { Marshal.StructureToPtr(button, currentPtr, false); currentPtr = (IntPtr)((int)currentPtr + Marshal.SizeOf(button)); } return initialPtr; } #endregion #region IDispose Pattern private bool disposed; // Finalizer and IDisposable implementation. public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~NativeTaskDialog() { Dispose(false); } // Core disposing logic. protected void Dispose(bool disposing) { if (!disposed) { disposed = true; // Single biggest resource - make sure the dialog // itself has been instructed to close. if (ShowState == DialogShowState.Showing) { NativeClose(TaskDialogResult.Cancel); } // Clean up custom allocated strings that were updated // while the dialog was showing. Note that the strings // passed in the initial TaskDialogIndirect call will // be cleaned up automagically by the default // marshalling logic. if (updatedStrings != null) { for (int i = 0; i < updatedStrings.Length; i++) { if (updatedStrings[i] != IntPtr.Zero) { Marshal.FreeHGlobal(updatedStrings[i]); updatedStrings[i] = IntPtr.Zero; } } } // Clean up the button and radio button arrays, if any. if (buttonArray != IntPtr.Zero) { Marshal.FreeHGlobal(buttonArray); buttonArray = IntPtr.Zero; } if (radioButtonArray != IntPtr.Zero) { Marshal.FreeHGlobal(radioButtonArray); radioButtonArray = IntPtr.Zero; } if (disposing) { // Clean up managed resources - currently there are none // that are interesting. } } } #endregion } }
// // System.Data.SqlTypes.SqlDateTime // // Author: // Tim Coleman <tim@timcoleman.com> // Ville Palo <vi64pa@koti.soon.fi> // // (C) Copyright 2002 Tim Coleman // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; namespace System.Data.SqlTypes { public struct SqlDateTime : INullable, IComparable { #region Fields private DateTime value; private bool notNull; public static readonly SqlDateTime MaxValue = new SqlDateTime (9999,12,31,23,59,59); public static readonly SqlDateTime MinValue = new SqlDateTime (1753,1,1); public static readonly SqlDateTime Null; public static readonly int SQLTicksPerHour = 1080000; public static readonly int SQLTicksPerMinute = 18000; public static readonly int SQLTicksPerSecond = 300; #endregion #region Constructors public SqlDateTime (DateTime value) { this.value = value; notNull = true; CheckRange (this); } public SqlDateTime (int dayTicks, int timeTicks) { try { DateTime temp = new DateTime (1900, 1, 1); this.value = new DateTime (temp.Ticks + (long)(dayTicks + timeTicks)); } catch (ArgumentOutOfRangeException ex) { throw new SqlTypeException (ex.Message); } notNull = true; CheckRange (this); } public SqlDateTime (int year, int month, int day) { try { this.value = new DateTime (year, month, day); } catch (ArgumentOutOfRangeException ex) { throw new SqlTypeException (ex.Message); } notNull = true; CheckRange (this); } public SqlDateTime (int year, int month, int day, int hour, int minute, int second) { try { this.value = new DateTime (year, month, day, hour, minute, second); } catch (ArgumentOutOfRangeException ex) { throw new SqlTypeException (ex.Message); } notNull = true; CheckRange (this); } [MonoTODO ("Round milisecond")] public SqlDateTime (int year, int month, int day, int hour, int minute, int second, double millisecond) { try { DateTime t = new DateTime(year, month, day, hour, minute, second); long ticks = (long) (t.Ticks + millisecond * 10000); this.value = new DateTime (ticks); } catch (ArgumentOutOfRangeException ex) { throw new SqlTypeException (ex.Message); } notNull = true; CheckRange (this); } [MonoTODO ("Round bilisecond")] public SqlDateTime (int year, int month, int day, int hour, int minute, int second, int bilisecond) // bilisecond?? { try { DateTime t = new DateTime(year, month, day, hour, minute, second); long dateTick = (long) (t.Ticks + bilisecond * 10); this.value = new DateTime (dateTick); } catch (ArgumentOutOfRangeException ex) { throw new SqlTypeException (ex.Message); } notNull = true; CheckRange (this); } #endregion #region Properties public int DayTicks { get { float DateTimeTicksPerHour = 3.6E+10f; DateTime temp = new DateTime (1900, 1, 1); int result = (int)((this.Value.Ticks - temp.Ticks) / (24 * DateTimeTicksPerHour)); return result; } } public bool IsNull { get { return !notNull; } } public int TimeTicks { get { if (this.IsNull) throw new SqlNullValueException (); return (int)(value.Hour * SQLTicksPerHour + value.Minute * SQLTicksPerMinute + value.Second * SQLTicksPerSecond + value.Millisecond); } } public DateTime Value { get { if (this.IsNull) throw new SqlNullValueException ("The property contains Null."); else return value; } } #endregion #region Methods private static void CheckRange (SqlDateTime target) { if (target.IsNull) return; if (target.value > MaxValue.value || target.value < MinValue.value) throw new SqlTypeException (String.Format ("SqlDateTime overflow. Must be between {0} and {1}. Value was {2}", MinValue.Value, MaxValue.Value, target.value)); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SqlDateTime)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SqlTypes.SqlDateTime")); else if (((SqlDateTime)value).IsNull) return 1; else return this.value.CompareTo (((SqlDateTime)value).Value); } public override bool Equals (object value) { if (!(value is SqlDateTime)) return false; else if (this.IsNull && ((SqlDateTime)value).IsNull) return true; else if (((SqlDateTime)value).IsNull) return false; else return (bool) (this == (SqlDateTime)value); } public static SqlBoolean Equals (SqlDateTime x, SqlDateTime y) { return (x == y); } public override int GetHashCode () { return value.GetHashCode (); } public static SqlBoolean GreaterThan (SqlDateTime x, SqlDateTime y) { return (x > y); } public static SqlBoolean GreaterThanOrEqual (SqlDateTime x, SqlDateTime y) { return (x >= y); } public static SqlBoolean LessThan (SqlDateTime x, SqlDateTime y) { return (x < y); } public static SqlBoolean LessThanOrEqual (SqlDateTime x, SqlDateTime y) { return (x <= y); } public static SqlBoolean NotEquals (SqlDateTime x, SqlDateTime y) { return (x != y); } public static SqlDateTime Parse (string s) { if (s == null) throw new ArgumentNullException ("Argument cannot be null"); // try parsing in local culture DateTimeFormatInfo fmtInfo = DateTimeFormatInfo.CurrentInfo; try { return new SqlDateTime (DateTime.Parse (s, fmtInfo)); } catch (Exception) { } // try parsing in invariant culture try { return new SqlDateTime (DateTime.Parse (s, CultureInfo.InvariantCulture)); } catch (Exception) { } // Not a recognizable format. throw new FormatException (String.Format ("String {0} is not recognized as "+ " valid DateTime.", s)); } public SqlString ToSqlString () { return ((SqlString)this); } public override string ToString () { if (this.IsNull) return "Null"; else return value.ToString (CultureInfo.InvariantCulture); } public static SqlDateTime operator + (SqlDateTime x, TimeSpan t) { if (x.IsNull) return SqlDateTime.Null; return new SqlDateTime (x.Value + t); } public static SqlBoolean operator == (SqlDateTime x, SqlDateTime y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value == y.Value); } public static SqlBoolean operator > (SqlDateTime x, SqlDateTime y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value > y.Value); } public static SqlBoolean operator >= (SqlDateTime x, SqlDateTime y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value >= y.Value); } public static SqlBoolean operator != (SqlDateTime x, SqlDateTime y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (!(x.Value == y.Value)); } public static SqlBoolean operator < (SqlDateTime x, SqlDateTime y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value < y.Value); } public static SqlBoolean operator <= (SqlDateTime x, SqlDateTime y) { if (x.IsNull || y.IsNull) return SqlBoolean.Null; else return new SqlBoolean (x.Value <= y.Value); } public static SqlDateTime operator - (SqlDateTime x, TimeSpan t) { if (x.IsNull) return x; return new SqlDateTime (x.Value - t); } public static explicit operator DateTime (SqlDateTime x) { return x.Value; } public static explicit operator SqlDateTime (SqlString x) { return SqlDateTime.Parse (x.Value); } public static implicit operator SqlDateTime (DateTime x) { return new SqlDateTime (x); } #endregion } }
/* ************************************************************************* ** Custom classes used by C# ************************************************************************* */ using System; using System.Diagnostics; using System.IO; #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE || SQLITE_WINRT) using System.Management; #endif using System.Text; using System.Text.RegularExpressions; using System.Threading; #if SQLITE_WINRT using System.Reflection; #endif using i64 = System.Int64; using u32 = System.UInt32; using time_t = System.Int64; namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { private static int atoi(byte[] inStr) { return atoi(Encoding.UTF8.GetString(inStr, 0, inStr.Length)); } private static int atoi(string inStr) { int i; for (i = 0; i < inStr.Length; i++) { if (!sqlite3Isdigit(inStr[i]) && inStr[i] != '-') break; } int result = 0; #if WINDOWS_MOBILE try { result = Int32.Parse(inStr.Substring(0, i)); } catch { } return result; #else return (Int32.TryParse(inStr.Substring(0, i), out result) ? result : 0); #endif } private static void fprintf(TextWriter tw, string zFormat, params object[] ap) { tw.Write(sqlite3_mprintf(zFormat, ap)); } private static void printf(string zFormat, params object[] ap) { #if !SQLITE_WINRT Console.Out.Write(sqlite3_mprintf(zFormat, ap)); #endif } //Byte Buffer Testing private static int memcmp(byte[] bA, byte[] bB, int Limit) { if (bA.Length < Limit) return (bA.Length < bB.Length) ? -1 : +1; if (bB.Length < Limit) return +1; for (int i = 0; i < Limit; i++) { if (bA[i] != bB[i]) return (bA[i] < bB[i]) ? -1 : 1; } return 0; } //Byte Buffer & String Testing private static int memcmp(string A, byte[] bB, int Limit) { if (A.Length < Limit) return (A.Length < bB.Length) ? -1 : +1; if (bB.Length < Limit) return +1; char[] cA = A.ToCharArray(); for (int i = 0; i < Limit; i++) { if (cA[i] != bB[i]) return (cA[i] < bB[i]) ? -1 : 1; } return 0; } //byte with Offset & String Testing private static int memcmp(byte[] a, int Offset, byte[] b, int Limit) { if (a.Length < Offset + Limit) return (a.Length - Offset < b.Length) ? -1 : +1; if (b.Length < Limit) return +1; for (int i = 0; i < Limit; i++) { if (a[i + Offset] != b[i]) return (a[i + Offset] < b[i]) ? -1 : 1; } return 0; } //byte with Offset & String Testing private static int memcmp(byte[] a, int Aoffset, byte[] b, int Boffset, int Limit) { if (a.Length < Aoffset + Limit) return (a.Length - Aoffset < b.Length - Boffset) ? -1 : +1; if (b.Length < Boffset + Limit) return +1; for (int i = 0; i < Limit; i++) { if (a[i + Aoffset] != b[i + Boffset]) return (a[i + Aoffset] < b[i + Boffset]) ? -1 : 1; } return 0; } private static int memcmp(byte[] a, int Offset, string b, int Limit) { if (a.Length < Offset + Limit) return (a.Length - Offset < b.Length) ? -1 : +1; if (b.Length < Limit) return +1; for (int i = 0; i < Limit; i++) { if (a[i + Offset] != b[i]) return (a[i + Offset] < b[i]) ? -1 : 1; } return 0; } //String Testing private static int memcmp(string A, string B, int Limit) { if (A.Length < Limit) return (A.Length < B.Length) ? -1 : +1; if (B.Length < Limit) return +1; int rc; if ((rc = String.Compare(A, 0, B, 0, Limit, StringComparison.Ordinal)) == 0) return 0; return rc < 0 ? -1 : +1; } // ---------------------------- // ** Builtin Functions // ---------------------------- private static Regex oRegex = null; /* ** The regexp() function. two arguments are both strings ** Collating sequences are not used. */ private static void regexpFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zTest; /* The input string A */ string zRegex; /* The regex string B */ Debug.Assert(argc == 2); UNUSED_PARAMETER(argc); zRegex = sqlite3_value_text(argv[0]); zTest = sqlite3_value_text(argv[1]); if (zTest == null || String.IsNullOrEmpty(zRegex)) { sqlite3_result_int(context, 0); return; } if (oRegex == null || oRegex.ToString() == zRegex) { oRegex = new Regex(zRegex, RegexOptions.IgnoreCase); } sqlite3_result_int(context, oRegex.IsMatch(zTest) ? 1 : 0); } // ---------------------------- // ** Convertion routines // ---------------------------- private static Object lock_va_list = new Object(); private static string vaFORMAT; private static int vaNEXT; private static void va_start(object[] ap, string zFormat) { vaFORMAT = zFormat; vaNEXT = 0; } private static Boolean va_arg(object[] ap, Boolean sysType) { return Convert.ToBoolean(ap[vaNEXT++]); } private static Byte[] va_arg(object[] ap, Byte[] sysType) { return (Byte[])ap[vaNEXT++]; } private static Byte[][] va_arg(object[] ap, Byte[][] sysType) { if (ap[vaNEXT] == null) { { vaNEXT++; return null; } } else { return (Byte[][])ap[vaNEXT++]; } } private static Char va_arg(object[] ap, Char sysType) { if (ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0) { vaNEXT++; return (char)'0'; } else { if (ap[vaNEXT] is Int64) if ((i64)ap[vaNEXT] == 0) { vaNEXT++; return (char)'0'; } else return (char)((i64)ap[vaNEXT++]); else return (char)ap[vaNEXT++]; } } private static Double va_arg(object[] ap, Double sysType) { return Convert.ToDouble(ap[vaNEXT++]); } private static dxLog va_arg(object[] ap, dxLog sysType) { return (dxLog)ap[vaNEXT++]; } private static Int64 va_arg(object[] ap, Int64 sysType) { if (ap[vaNEXT] is System.Int64) return Convert.ToInt64(ap[vaNEXT++]); else return (Int64)(ap[vaNEXT++].GetHashCode()); } private static Int32 va_arg(object[] ap, Int32 sysType) { if (Convert.ToInt64(ap[vaNEXT]) > 0 && (Convert.ToUInt32(ap[vaNEXT]) > Int32.MaxValue)) return (Int32)(Convert.ToUInt32(ap[vaNEXT++]) - System.UInt32.MaxValue - 1); else return (Int32)Convert.ToInt32(ap[vaNEXT++]); } private static Int32[] va_arg(object[] ap, Int32[] sysType) { if (ap[vaNEXT] == null) { { vaNEXT++; return null; } } else { return (Int32[])ap[vaNEXT++]; } } private static MemPage va_arg(object[] ap, MemPage sysType) { return (MemPage)ap[vaNEXT++]; } private static Object va_arg(object[] ap, Object sysType) { return (Object)ap[vaNEXT++]; } private static sqlite3 va_arg(object[] ap, sqlite3 sysType) { return (sqlite3)ap[vaNEXT++]; } private static sqlite3_mem_methods va_arg(object[] ap, sqlite3_mem_methods sysType) { return (sqlite3_mem_methods)ap[vaNEXT++]; } private static sqlite3_mutex_methods va_arg(object[] ap, sqlite3_mutex_methods sysType) { return (sqlite3_mutex_methods)ap[vaNEXT++]; } private static SrcList va_arg(object[] ap, SrcList sysType) { return (SrcList)ap[vaNEXT++]; } private static String va_arg(object[] ap, String sysType) { if (ap.Length < vaNEXT - 1 || ap[vaNEXT] == null) { vaNEXT++; return "NULL"; } else { if (ap[vaNEXT] is Byte[]) if (Encoding.UTF8.GetString((byte[])ap[vaNEXT], 0, ((byte[])ap[vaNEXT]).Length) == "\0") { vaNEXT++; return ""; } else return Encoding.UTF8.GetString((byte[])ap[vaNEXT], 0, ((byte[])ap[vaNEXT++]).Length); else if (ap[vaNEXT] is Int32) { vaNEXT++; return null; } else if (ap[vaNEXT] is StringBuilder) return (String)ap[vaNEXT++].ToString(); else if (ap[vaNEXT] is Char) return ((Char)ap[vaNEXT++]).ToString(); else return (String)ap[vaNEXT++]; } } private static Token va_arg(object[] ap, Token sysType) { return (Token)ap[vaNEXT++]; } private static UInt32 va_arg(object[] ap, UInt32 sysType) { #if SQLITE_WINRT Type t = ap[vaNEXT].GetType(); if ( t.GetTypeInfo().IsClass ) #else if (ap[vaNEXT].GetType().IsClass) #endif { return (UInt32)ap[vaNEXT++].GetHashCode(); } else { return (UInt32)Convert.ToUInt32(ap[vaNEXT++]); } } private static UInt64 va_arg(object[] ap, UInt64 sysType) { #if SQLITE_WINRT Type t = ap[vaNEXT].GetType(); if (t.GetTypeInfo().IsClass) #else if (ap[vaNEXT].GetType().IsClass) #endif { return (UInt64)ap[vaNEXT++].GetHashCode(); } else { return (UInt64)Convert.ToUInt64(ap[vaNEXT++]); } } private static void_function va_arg(object[] ap, void_function sysType) { return (void_function)ap[vaNEXT++]; } private static void va_end(ref string[] ap) { ap = null; vaNEXT = -1; vaFORMAT = ""; } private static void va_end(ref object[] ap) { ap = null; vaNEXT = -1; vaFORMAT = ""; } public static tm localtime(time_t baseTime) { System.DateTime RefTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); RefTime = RefTime.AddSeconds(Convert.ToDouble(baseTime)).ToLocalTime(); tm tm = new tm(); tm.tm_sec = RefTime.Second; tm.tm_min = RefTime.Minute; tm.tm_hour = RefTime.Hour; tm.tm_mday = RefTime.Day; tm.tm_mon = RefTime.Month; tm.tm_year = RefTime.Year; tm.tm_wday = (int)RefTime.DayOfWeek; tm.tm_yday = RefTime.DayOfYear; tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; return tm; } public static long ToUnixtime(System.DateTime date) { System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); System.TimeSpan timeSpan = date - unixStartTime; return Convert.ToInt64(timeSpan.TotalSeconds); } public static System.DateTime ToCSharpTime(long unixTime) { System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); return unixStartTime.AddSeconds(Convert.ToDouble(unixTime)); } public class tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; public struct FILETIME { public u32 dwLowDateTime; public u32 dwHighDateTime; } // Example (C#) public static int GetbytesPerSector(StringBuilder diskPath) { #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE || SQLITE_WINRT) ManagementObjectSearcher mosLogicalDisks = new ManagementObjectSearcher("select * from Win32_LogicalDisk where DeviceID = '" + diskPath.ToString().Remove(diskPath.Length - 1, 1) + "'"); try { foreach (ManagementObject moLogDisk in mosLogicalDisks.Get()) { ManagementObjectSearcher mosDiskDrives = new ManagementObjectSearcher("select * from Win32_DiskDrive where SystemName = '" + moLogDisk["SystemName"] + "'"); foreach (ManagementObject moPDisk in mosDiskDrives.Get()) { return int.Parse(moPDisk["BytesPerSector"].ToString()); } } } catch { } return 4096; #else return 4096; #endif } private static void SWAP<T>(ref T A, ref T B) { T t = A; A = B; B = t; } private static void x_CountStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert(argc <= 1); Mem pMem = sqlite3_aggregate_context(context, 1);//sizeof(*p)); if (pMem._SumCtx == null) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if (p.Context == null) p.Context = pMem; if (argc == 0 || SQLITE_NULL == sqlite3_value_type(argv[0])) { p.cnt++; p.iSum += 1; } else { type = sqlite3_value_numeric_type(argv[0]); if (p != null && type != SQLITE_NULL) { p.cnt++; if (type == SQLITE_INTEGER) { i64 v = sqlite3_value_int64(argv[0]); if (v == 40 || v == 41) { sqlite3_result_error(context, "value of " + v + " handed to x_count", -1); return; } else { p.iSum += v; if (!(p.approx | p.overflow != 0)) { i64 iNewSum = p.iSum + v; int s1 = (int)(p.iSum >> (sizeof(i64) * 8 - 1)); int s2 = (int)(v >> (sizeof(i64) * 8 - 1)); int s3 = (int)(iNewSum >> (sizeof(i64) * 8 - 1)); p.overflow = ((s1 & s2 & ~s3) | (~s1 & ~s2 & s3)) != 0 ? 1 : 0; p.iSum = iNewSum; } } } else { p.rSum += sqlite3_value_double(argv[0]); p.approx = true; } } } } private static void x_CountFinalize(sqlite3_context context) { SumCtx p; Mem pMem = sqlite3_aggregate_context(context, 0); p = pMem._SumCtx; if (p != null && p.cnt > 0) { if (p.overflow != 0) { sqlite3_result_error(context, "integer overflow", -1); } else if (p.approx) { sqlite3_result_double(context, p.rSum); } else if (p.iSum == 42) { sqlite3_result_error(context, "x_count totals to 42", -1); } else { sqlite3_result_int64(context, p.iSum); } } } #if SQLITE_MUTEX_W32 //---------------------WIN32 Definitions private static int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } private static long InterlockedIncrement(long location) { Interlocked.Increment(ref location); return location; } private static void EnterCriticalSection(Object mtx) { //long mid = mtx.GetHashCode(); //int tid = Thread.CurrentThread.ManagedThreadId; //long ticks = cnt++; //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) ); Monitor.Enter(mtx); } private static void InitializeCriticalSection(Object mtx) { //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); } private static void DeleteCriticalSection(Object mtx) { //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) ); } private static void LeaveCriticalSection(Object mtx) { //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Exit(mtx); } #endif // Miscellaneous Windows Constants //#define ERROR_FILE_NOT_FOUND 2L //#define ERROR_HANDLE_DISK_FULL 39L //#define ERROR_NOT_SUPPORTED 50L //#define ERROR_DISK_FULL 112L private const long ERROR_FILE_NOT_FOUND = 2L; private const long ERROR_HANDLE_DISK_FULL = 39L; private const long ERROR_NOT_SUPPORTED = 50L; private const long ERROR_DISK_FULL = 112L; private class SQLite3UpperToLower { private static int[] sqlite3UpperToLower = new int[] { #if SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif }; public int this[int index] { get { if (index < sqlite3UpperToLower.Length) return sqlite3UpperToLower[index]; else return index; } } public int this[u32 index] { get { if (index < sqlite3UpperToLower.Length) return sqlite3UpperToLower[index]; else return (int)index; } } } private static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower(); private static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower; } }
// 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. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A pool in the Azure Batch service. /// </summary> public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty; public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty; public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty; public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty; public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty; public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty; public readonly PropertyAccessor<string> AutoScaleFormulaProperty; public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty; public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty; public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<int?> CurrentDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> CurrentLowPriorityComputeNodesProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty; public readonly PropertyAccessor<IReadOnlyList<ResizeError>> ResizeErrorsProperty; public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty; public readonly PropertyAccessor<StartTask> StartTaskProperty; public readonly PropertyAccessor<Common.PoolState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<PoolStatistics> StatisticsProperty; public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty; public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty; public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty; public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty; public readonly PropertyAccessor<string> VirtualMachineSizeProperty; public PropertyContainer() : base(BindingState.Unbound) { this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>(nameof(AllocationState), BindingAccess.None); this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(AllocationStateTransitionTime), BindingAccess.None); this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write); this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>(nameof(AutoScaleRun), BindingAccess.None); this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None); this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentDedicatedComputeNodes), BindingAccess.None); this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>(nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write); this.ResizeErrorsProperty = this.CreatePropertyAccessor<IReadOnlyList<ResizeError>>(nameof(ResizeErrors), BindingAccess.None); this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write); this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>(nameof(State), BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>(nameof(Statistics), BindingAccess.None); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write); this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None); this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound) { this.AllocationStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState), nameof(AllocationState), BindingAccess.Read); this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.AllocationStateTransitionTime, nameof(AllocationStateTransitionTime), BindingAccess.Read); this.ApplicationLicensesProperty = this.CreatePropertyAccessor( UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o), nameof(ApplicationLicenses), BindingAccess.Read); this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor( ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences), nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write); this.AutoScaleEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableAutoScale, nameof(AutoScaleEnabled), BindingAccess.Read); this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleEvaluationInterval, nameof(AutoScaleEvaluationInterval), BindingAccess.Read); this.AutoScaleFormulaProperty = this.CreatePropertyAccessor( protocolObject.AutoScaleFormula, nameof(AutoScaleFormula), BindingAccess.Read); this.AutoScaleRunProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()), nameof(AutoScaleRun), BindingAccess.Read); this.CertificateReferencesProperty = this.CreatePropertyAccessor( CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences), nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write); this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()), nameof(CloudServiceConfiguration), BindingAccess.Read); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, nameof(CreationTime), BindingAccess.Read); this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.CurrentDedicatedNodes, nameof(CurrentDedicatedComputeNodes), BindingAccess.Read); this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.CurrentLowPriorityNodes, nameof(CurrentLowPriorityComputeNodes), BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, nameof(DisplayName), BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, nameof(ETag), BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, nameof(Id), BindingAccess.Read); this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor( protocolObject.EnableInterNodeCommunication, nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, nameof(LastModified), BindingAccess.Read); this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor( protocolObject.MaxTasksPerNode, nameof(MaxTasksPerComputeNode), BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), nameof(Metadata), BindingAccess.Read | BindingAccess.Write); this.NetworkConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()), nameof(NetworkConfiguration), BindingAccess.Read); this.ResizeErrorsProperty = this.CreatePropertyAccessor( ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors), nameof(ResizeErrors), BindingAccess.Read); this.ResizeTimeoutProperty = this.CreatePropertyAccessor( protocolObject.ResizeTimeout, nameof(ResizeTimeout), BindingAccess.Read); this.StartTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)), nameof(StartTask), BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State), nameof(State), BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, nameof(StateTransitionTime), BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()), nameof(Statistics), BindingAccess.Read); this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetDedicatedNodes, nameof(TargetDedicatedComputeNodes), BindingAccess.Read); this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor( protocolObject.TargetLowPriorityNodes, nameof(TargetLowPriorityComputeNodes), BindingAccess.Read); this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()), nameof(TaskSchedulingPolicy), BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, nameof(Url), BindingAccess.Read); this.UserAccountsProperty = this.CreatePropertyAccessor( UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts), nameof(UserAccounts), BindingAccess.Read); this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()), nameof(VirtualMachineConfiguration), BindingAccess.Read); this.VirtualMachineSizeProperty = this.CreatePropertyAccessor( protocolObject.VmSize, nameof(VirtualMachineSize), BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudPool"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudPool( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudPool( BatchClient parentBatchClient, Models.CloudPool protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudPool"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudPool /// <summary> /// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the /// pool. /// </summary> public Common.AllocationState? AllocationState { get { return this.propertyContainer.AllocationStateProperty.Value; } } /// <summary> /// Gets the time at which the pool entered its current <see cref="AllocationState"/>. /// </summary> public DateTime? AllocationStateTransitionTime { get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the list of application licenses the Batch service will make available on each compute node in the /// pool. /// </summary> /// <remarks> /// The list of application licenses must be a subset of available Batch service application licenses. /// </remarks> public IList<string> ApplicationLicenses { get { return this.propertyContainer.ApplicationLicensesProperty.Value; } set { this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value); } } /// <summary> /// Gets or sets a list of application packages to be installed on each compute node in the pool. /// </summary> public IList<ApplicationPackageReference> ApplicationPackageReferences { get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; } set { this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// <para>If true, the <see cref="AutoScaleFormula"/> property is required, the pool automatically resizes according /// to the formula, and <see cref="TargetDedicatedComputeNodes"/> and <see cref="TargetLowPriorityComputeNodes"/> /// must be null.</para> <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/> /// properties is required.</para><para>The default value is false.</para> /// </remarks> public bool? AutoScaleEnabled { get { return this.propertyContainer.AutoScaleEnabledProperty.Value; } set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; } } /// <summary> /// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>. /// </summary> /// <remarks> /// The default value is 15 minutes. The minimum allowed value is 5 minutes. /// </remarks> public TimeSpan? AutoScaleEvaluationInterval { get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; } set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; } } /// <summary> /// Gets or sets a formula for the desired number of compute nodes in the pool. /// </summary> /// <remarks> /// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/. /// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled /// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid, /// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para> /// </remarks> public string AutoScaleFormula { get { return this.propertyContainer.AutoScaleFormulaProperty.Value; } set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; } } /// <summary> /// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>. /// </summary> public AutoScaleRun AutoScaleRun { get { return this.propertyContainer.AutoScaleRunProperty.Value; } } /// <summary> /// Gets or sets a list of certificates to be installed on each compute node in the pool. /// </summary> public IList<CertificateReference> CertificateReferences { get { return this.propertyContainer.CertificateReferencesProperty.Value; } set { this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool. /// </summary> public CloudServiceConfiguration CloudServiceConfiguration { get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; } set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; } } /// <summary> /// Gets the creation time for the pool. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets the number of dedicated compute nodes currently in the pool. /// </summary> public int? CurrentDedicatedComputeNodes { get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; } } /// <summary> /// Gets the number of low-priority compute nodes currently in the pool. /// </summary> /// <remarks> /// Low-priority compute nodes which have been preempted are included in this count. /// </remarks> public int? CurrentLowPriorityComputeNodes { get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; } } /// <summary> /// Gets or sets the display name of the pool. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the pool. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets or sets the id of the pool. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets whether the pool permits direct communication between its compute nodes. /// </summary> /// <remarks> /// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes /// of the pool. This may result in the pool not reaching its desired size. /// </remarks> public bool? InterComputeNodeCommunicationEnabled { get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; } set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; } } /// <summary> /// Gets the last modified time of the pool. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool. /// </summary> /// <remarks> /// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool /// (the <see cref="VirtualMachineSize"/> property). /// </remarks> public int? MaxTasksPerComputeNode { get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; } set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the pool as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the network configuration of the pool. /// </summary> public NetworkConfiguration NetworkConfiguration { get { return this.propertyContainer.NetworkConfigurationProperty.Value; } set { this.propertyContainer.NetworkConfigurationProperty.Value = value; } } /// <summary> /// Gets a list of errors encountered while performing the last resize on the <see cref="CloudPool"/>. Errors are /// returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see cref="CloudPool.AllocationState"/> /// is <see cref="AllocationState">Steady</see>. /// </summary> public IReadOnlyList<ResizeError> ResizeErrors { get { return this.propertyContainer.ResizeErrorsProperty.Value; } } /// <summary> /// Gets or sets the timeout for allocation of compute nodes to the pool. /// </summary> public TimeSpan? ResizeTimeout { get { return this.propertyContainer.ResizeTimeoutProperty.Value; } set { this.propertyContainer.ResizeTimeoutProperty.Value = value; } } /// <summary> /// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to /// the pool or when the node is restarted. /// </summary> public StartTask StartTask { get { return this.propertyContainer.StartTaskProperty.Value; } set { this.propertyContainer.StartTaskProperty.Value = value; } } /// <summary> /// Gets the current state of the pool. /// </summary> public Common.PoolState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the pool entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets the resource usage statistics for the pool. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. /// </remarks> public PoolStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets or sets the desired number of dedicated compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property /// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false. /// If not specified, the default is 0. /// </remarks> public int? TargetDedicatedComputeNodes { get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; } set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets the desired number of low-priority compute nodes in the pool. /// </summary> /// <remarks> /// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/> /// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default /// is 0. /// </remarks> public int? TargetLowPriorityComputeNodes { get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; } set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; } } /// <summary> /// Gets or sets how tasks are distributed among compute nodes in the pool. /// </summary> public TaskSchedulingPolicy TaskSchedulingPolicy { get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; } set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; } } /// <summary> /// Gets the URL of the pool. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets the list of user accounts to be created on each node in the pool. /// </summary> public IList<UserAccount> UserAccounts { get { return this.propertyContainer.UserAccountsProperty.Value; } set { this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool. /// </summary> public VirtualMachineConfiguration VirtualMachineConfiguration { get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; } set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; } } /// <summary> /// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size. /// </summary> /// <remarks> /// <para>For information about available sizes of virtual machines for Cloud Services pools (pools created with /// a <see cref="CloudServiceConfiguration"/>), see https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/. /// Batch supports all Cloud Services VM sizes except ExtraSmall.</para><para>For information about available VM /// sizes for pools using images from the Virtual Machines Marketplace (pools created with a <see cref="VirtualMachineConfiguration"/>) /// see https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/ or https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/. /// Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (for example STANDARD_GS, /// STANDARD_DS, and STANDARD_DSV2 series).</para> /// </remarks> public string VirtualMachineSize { get { return this.propertyContainer.VirtualMachineSizeProperty.Value; } set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; } } #endregion // CloudPool #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject() { Models.PoolAddParameter result = new Models.PoolAddParameter() { ApplicationLicenses = this.ApplicationLicenses, ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences), EnableAutoScale = this.AutoScaleEnabled, AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval, AutoScaleFormula = this.AutoScaleFormula, CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences), CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled, MaxTasksPerNode = this.MaxTasksPerComputeNode, Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()), ResizeTimeout = this.ResizeTimeout, StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()), TargetDedicatedNodes = this.TargetDedicatedComputeNodes, TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes, TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()), UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts), VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()), VmSize = this.VirtualMachineSize, }; return result; } #endregion // Internal/private methods } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.Common; using System.Dynamic; using System.Linq; using System.Text; namespace Massive.PostgreSQL { public static class ObjectExtensions { /// <summary> /// Extension method for adding in a bunch of parameters /// </summary> public static void AddParams(this DbCommand cmd, params object[] args) { foreach (var item in args) { AddParam(cmd, item); } } /// <summary> /// Extension for adding single parameter /// </summary> public static void AddParam(this DbCommand cmd, object item) { var p = cmd.CreateParameter(); p.ParameterName = string.Format("@{0}", cmd.Parameters.Count); if (item == null) { p.Value = DBNull.Value; } else { if (item.GetType() == typeof(Guid)) { p.Value = item.ToString(); p.DbType = DbType.String; p.Size = 4000; } else if (item.GetType() == typeof(ExpandoObject)) { var d = (IDictionary<string, object>)item; p.Value = d.Values.FirstOrDefault(); } else { p.Value = item; } if (item.GetType() == typeof(string)) p.Size = ((string)item).Length > 4000 ? -1 : 4000; } cmd.Parameters.Add(p); } /// <summary> /// Turns an IDataReader to a Dynamic list of things /// </summary> public static List<dynamic> ToExpandoList(this IDataReader rdr) { var result = new List<dynamic>(); while (rdr.Read()) { result.Add(rdr.RecordToExpando()); } return result; } public static dynamic RecordToExpando(this IDataReader rdr) { dynamic e = new ExpandoObject(); var d = e as IDictionary<string, object>; object[] values = new object[rdr.FieldCount]; rdr.GetValues(values); for(int i = 0; i < values.Length; i++) { var v = values[i]; d.Add(rdr.GetName(i), DBNull.Value.Equals(v) ? null : v); } return e; } /// <summary> /// Turns the object into an ExpandoObject /// </summary> public static dynamic ToExpando(this object o) { if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case var result = new ExpandoObject(); var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i)); } else { var props = o.GetType().GetProperties(); foreach (var item in props) { d.Add(item.Name, item.GetValue(o, null)); } } return result; } /// <summary> /// Turns the object into a Dictionary /// </summary> public static IDictionary<string, object> ToDictionary(this object thingy) { return (IDictionary<string, object>)thingy.ToExpando(); } } /// <summary> /// Convenience class for opening/executing data /// </summary> public static class DB { public static DynamicModel Current { get { if (ConfigurationManager.ConnectionStrings.Count > 1) { return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name); } throw new InvalidOperationException("Need a connection string name - can't determine what it is"); } } } /// <summary> /// A class that wraps your database table in Dynamic Funtime /// </summary> public class DynamicModel : DynamicObject { DbProviderFactory _factory; string ConnectionString; public static DynamicModel Open(string connectionStringName) { dynamic dm = new DynamicModel(connectionStringName); return dm; } public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "", string descriptorField = "") { TableName = tableName == "" ? this.GetType().Name : tableName; PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField; DescriptorField = descriptorField; var _providerName = "Npgsql"; _factory = DbProviderFactories.GetFactory(_providerName); ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; } /// <summary> /// Creates a new Expando from a Form POST - white listed against the columns in the DB /// </summary> public dynamic CreateFrom(NameValueCollection coll) { dynamic result = new ExpandoObject(); var dc = (IDictionary<string, object>)result; var schema = Schema; //loop the collection, setting only what's in the Schema foreach (var item in coll.Keys) { var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower()); if (exists) { var key = item.ToString(); var val = coll[key]; dc.Add(key, val); } } return result; } /// <summary> /// Gets a default value for the column /// </summary> public dynamic DefaultValue(dynamic column) { dynamic result = null; string def = column.COLUMN_DEFAULT; if (String.IsNullOrEmpty(def)) { result = null; } else if (def == "getdate()" || def == "(getdate())") { result = DateTime.Now.ToShortDateString(); } else if (def == "newid()") { result = Guid.NewGuid().ToString(); } else { result = def.Replace("(", "").Replace(")", ""); } return result; } /// <summary> /// Creates an empty Expando set with defaults from the DB /// </summary> public dynamic Prototype { get { dynamic result = new ExpandoObject(); var schema = Schema; foreach (dynamic column in schema) { var dc = (IDictionary<string, object>)result; dc.Add(column.COLUMN_NAME, DefaultValue(column)); } result._Table = this; return result; } } public string DescriptorField { get; protected set; } /// <summary> /// List out all the schema bits for use with ... whatever /// </summary> IEnumerable<dynamic> _schema; public IEnumerable<dynamic> Schema { get { if (_schema == null) _schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName); return _schema; } } /// <summary> /// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert /// </summary> public virtual IEnumerable<dynamic> Query(string sql, params object[] args) { using (var conn = OpenConnection()) { var rdr = CreateCommand(sql, conn, args).ExecuteReader(); while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } } } public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) { using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) { while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } } } /// <summary> /// Returns a single result /// </summary> public virtual object Scalar(string sql, params object[] args) { object result = null; using (var conn = OpenConnection()) { result = CreateCommand(sql, conn, args).ExecuteScalar(); } return result; } /// <summary> /// Creates a DBCommand that you can use for loving your database. /// </summary> DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) { var result = _factory.CreateCommand(); result.Connection = conn; result.CommandText = sql; if (args.Length > 0) result.AddParams(args); return result; } /// <summary> /// Returns and OpenConnection /// </summary> public virtual DbConnection OpenConnection() { var result = _factory.CreateConnection(); result.ConnectionString = ConnectionString; result.Open(); return result; } /// <summary> /// Builds a set of Insert and Update commands based on the passed-on objects. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual List<DbCommand> BuildCommands(params object[] things) { var commands = new List<DbCommand>(); foreach (var item in things) { var ex = item.ToExpando(); if (HasPrimaryKey(item)) { commands.Add(CreateUpdateCommand(ex, GetPrimaryKey(ex))); } else { commands.Add(CreateInsertCommand(ex)); } } return commands; } public virtual int Execute(DbCommand command) { return Execute(new DbCommand[] { command }); } public virtual int Execute(string sql, params object[] args) { return Execute(CreateCommand(sql, null, args)); } /// <summary> /// Executes a series of DBCommands in a transaction /// </summary> public virtual int Execute(IEnumerable<DbCommand> commands) { var result = 0; using (var conn = OpenConnection()) { using (var tx = conn.BeginTransaction()) { foreach (var cmd in commands) { cmd.Connection = conn; cmd.Transaction = tx; result += cmd.ExecuteNonQuery(); } tx.Commit(); } } return result; } public virtual string PrimaryKeyField { get; set; } /// <summary> /// Conventionally introspects the object passed in for a field that /// looks like a PK. If you've named your PrimaryKeyField, this becomes easy /// </summary> public virtual bool HasPrimaryKey(object o) { return o.ToDictionary().ContainsKey(PrimaryKeyField); } /// <summary> /// If the object passed in has a property with the same name as your PrimaryKeyField /// it is returned here. /// </summary> public virtual object GetPrimaryKey(object o) { object result = null; o.ToDictionary().TryGetValue(PrimaryKeyField, out result); return result; } public virtual string TableName { get; set; } /// <summary> /// Returns all records complying with the passed-in WHERE clause and arguments, /// ordered as specified, limited (TOP) by limit. /// </summary> public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) { string sql = BuildSelect(where, orderBy, limit); return Query(string.Format(sql, columns, TableName), args); } private static string BuildSelect(string where, string orderBy, int limit) { string sql = "SELECT {0} FROM {1} "; if (!string.IsNullOrEmpty(where)) sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : " WHERE " + where; if (!String.IsNullOrEmpty(orderBy)) sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy; if (limit > 0) sql += " LIMIT " + limit; return sql; } /// <summary> /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords. /// </summary> public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { return BuildPagedResult(where: where, orderBy: orderBy, columns: columns, pageSize: pageSize, currentPage: currentPage, args: args); } public virtual dynamic Paged(string sql, string primaryKey, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { return BuildPagedResult(sql, primaryKey, where, orderBy, columns, pageSize, currentPage, args); } private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { dynamic result = new ExpandoObject(); var countSQL = ""; if (!string.IsNullOrEmpty(sql)) countSQL = string.Format("SELECT COUNT({0}) FROM ({1}) AS PagedTable", primaryKeyField, sql); else countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName); if (String.IsNullOrEmpty(orderBy)) { orderBy = string.IsNullOrEmpty(primaryKeyField) ? " ORDER BY " + PrimaryKeyField : " ORDER BY " + primaryKeyField; } if (!string.IsNullOrEmpty(where)) { if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase)) { where = " WHERE " + where; } } var query = ""; if (!string.IsNullOrEmpty(sql)) query = string.Format("{0} {1} {2} ", sql, where, orderBy); else query = string.Format("SELECT {0} FROM {1} {2} {3} ", columns, TableName, where, orderBy); var pageStart = (currentPage - 1) * pageSize; query += string.Format(" limit {0} offset {1}", pageSize, pageStart); countSQL += where; result.TotalRecords = Scalar(countSQL, args); result.TotalPages = result.TotalRecords / pageSize; if (result.TotalRecords % pageSize > 0) result.TotalPages += 1; result.Items = Query(string.Format(query, columns, TableName), args); return result; } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(string where, params object[] args) { var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where); return Query(sql, args).FirstOrDefault(); } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(object key, string columns = "*") { var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField); return Query(sql, key).FirstOrDefault(); } /// <summary> /// This will return a string/object dictionary for dropdowns etc /// </summary> public virtual IDictionary<string, object> KeyValues(string orderBy = "") { if (String.IsNullOrEmpty(DescriptorField)) throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see"); var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName); if (!String.IsNullOrEmpty(orderBy)) sql += "ORDER BY " + orderBy; var results = Query(sql).ToList().Cast<IDictionary<string, object>>(); return results.ToDictionary(key => key[PrimaryKeyField].ToString(), value => value[DescriptorField]); } /// <summary> /// This will return an Expando as a Dictionary /// </summary> public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) { return (IDictionary<string, object>)item; } //Checks to see if a key is present based on the passed-in value public virtual bool ItemContainsKey(string key, ExpandoObject item) { var dc = ItemAsDictionary(item); return dc.ContainsKey(key); } /// <summary> /// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual int Save(params object[] things) { foreach (var item in things) { if (!IsValid(item)) { throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray())); } } var commands = BuildCommands(things); return Execute(commands); } public virtual DbCommand CreateInsertCommand(dynamic expando) { DbCommand result = null; var settings = (IDictionary<string, object>)expando; var sbKeys = new StringBuilder(); var sbVals = new StringBuilder(); var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})"; result = CreateCommand(stub, null); int counter = 0; foreach (var item in settings) { sbKeys.AppendFormat("{0},", item.Key); sbVals.AppendFormat("@{0},", counter.ToString()); result.AddParam(item.Value); counter++; } if (counter > 0) { var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1); var vals = sbVals.ToString().Substring(0, sbVals.Length - 1); var sql = string.Format(stub, TableName, keys, vals); result.CommandText = sql; } else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set"); return result; } /// <summary> /// Creates a command for use with transactions - internal stuff mostly, but here for you to play with /// </summary> public virtual DbCommand CreateUpdateCommand(dynamic expando, object key) { var settings = (IDictionary<string, object>)expando; var sbKeys = new StringBuilder(); var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}"; var args = new List<object>(); var result = CreateCommand(stub, null); int counter = 0; foreach (var item in settings) { var val = item.Value; if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null) { result.AddParam(val); sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString()); counter++; } } if (counter > 0) { //add the key result.AddParam(key); //strip the last commas var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4); result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter); } else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs"); return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) { var sql = string.Format("DELETE FROM {0} ", TableName); if (key != null) { sql += string.Format("WHERE {0}=@0", PrimaryKeyField); args = new object[] { key }; } else if (!string.IsNullOrEmpty(where)) { sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where; } return CreateCommand(sql, null, args); } public bool IsValid(dynamic item) { Errors.Clear(); Validate(item); return Errors.Count == 0; } //Temporary holder for error messages public IList<string> Errors = new List<string>(); /// <summary> /// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString /// </summary> public virtual dynamic Insert(object o) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray())); } if (BeforeSave(ex)) { using (dynamic conn = OpenConnection()) { var cmd = CreateInsertCommand(ex); cmd.Connection = conn; cmd.CommandText += String.Format(" returning {0} as newid ", PrimaryKeyField); ex.ID = cmd.ExecuteScalar(); Inserted(ex); } return ex; } else { return null; } } /// <summary> /// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString /// </summary> public virtual int Update(object o, object key) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray())); } var result = 0; if (BeforeSave(ex)) { result = Execute(CreateUpdateCommand(ex, key)); Updated(ex); } return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public int Delete(object key = null, string where = "", params object[] args) { var deleted = this.Single(key); var result = 0; if (BeforeDelete(deleted)) { result = Execute(CreateDeleteCommand(where: where, key: key, args: args)); Deleted(deleted); } return result; } public void DefaultTo(string key, object value, dynamic item) { if (!ItemContainsKey(key, item)) { var dc = (IDictionary<string, object>)item; dc[key] = value; } } //Hooks public virtual void Validate(dynamic item) { } public virtual void Inserted(dynamic item) { } public virtual void Updated(dynamic item) { } public virtual void Deleted(dynamic item) { } public virtual bool BeforeDelete(dynamic item) { return true; } public virtual bool BeforeSave(dynamic item) { return true; } //validation methods public virtual void ValidatesPresenceOf(object value, string message = "Required") { if (value == null) Errors.Add(message); if (String.IsNullOrEmpty(value.ToString())) Errors.Add(message); } //fun methods public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number") { var type = value.GetType().Name; var numerics = new string[] { "Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float" }; if (!numerics.Contains(type)) { Errors.Add(message); } } public virtual void ValidateIsCurrency(object value, string message = "Should be money") { if (value == null) Errors.Add(message); decimal val = decimal.MinValue; decimal.TryParse(value.ToString(), out val); if (val == decimal.MinValue) Errors.Add(message); } public int Count() { return Count(TableName); } public int Count(string tableName, string where = "") { // Scalar returns a long that has been casted to an object. Casting a boxed // long directly to int throws InvalidCastException. This will successfully // cast without changing the API. // HACK: Change API so count returns long return (int)(long)Scalar("SELECT COUNT(*) FROM " + tableName + " " + where); } /// <summary> /// A helpful query tool /// </summary> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { //parse the method var constraints = new List<string>(); var counter = 0; var info = binder.CallInfo; // accepting named args only... SKEET! if (info.ArgumentNames.Count != args.Length) { throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc"); } //first should be "FindBy, Last, Single, First" var op = binder.Name; var columns = " * "; string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField); string sql = ""; string where = ""; var whereArgs = new List<object>(); //loop the named args - see if we have order, columns and constraints if (info.ArgumentNames.Count > 0) { for (int i = 0; i < args.Length; i++) { var name = info.ArgumentNames[i].ToLower(); switch (name) { case "orderby": orderBy = " ORDER BY " + args[i]; break; case "columns": columns = args[i].ToString(); break; default: constraints.Add(string.Format(" {0} = @{1}", name, counter)); whereArgs.Add(args[i]); counter++; break; } } } //Build the WHERE bits if (constraints.Count > 0) { where = " WHERE " + string.Join(" AND ", constraints.ToArray()); //This doesn't work so hot. turns into Where =@0 instead of actual arg } //probably a bit much here but... yeah this whole thing needs to be refactored... if (op.ToLower() == "count") { result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "sum") { result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "max") { result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "min") { result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "avg") { result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else { //build the SQL sql = "SELECT " + columns + " FROM " + TableName + where + " limit 1;"; var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single"); //Be sure to sort by DESC on the PK (PK Sort is the default) if (op.StartsWith("Last")) { orderBy = orderBy + " DESC "; } else { //default to multiple sql = "SELECT " + columns + " FROM " + TableName + where; } if (justOne) { //return a single record result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault(); } else { //return lots result = Query(sql + orderBy, whereArgs.ToArray()); } } return true; } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.IO; using System.Text; using Encog.App.Analyst.CSV.Basic; using Encog.App.Analyst.Script.Normalize; using Encog.App.Quant; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Util.CSV; namespace Encog.App.Analyst.CSV { /// <summary> /// Used by the analyst to evaluate a CSV file. /// </summary> public class AnalystEvaluateRawCSV : BasicFile { /// <summary> /// The analyst file to use. /// </summary> private EncogAnalyst _analyst; /// <summary> /// The ideal count. /// </summary> private int _idealCount; /// <summary> /// The input count. /// </summary> private int _inputCount; /// <summary> /// The output count. /// </summary> private int _outputCount; /// <summary> /// Analyze the data. This counts the records and prepares the data to be /// processed. /// </summary> /// <param name="theAnalyst">The analyst to use.</param> /// <param name="inputFile">The input file.</param> /// <param name="headers">True if headers are present.</param> /// <param name="format">The format the file is in.</param> public void Analyze(EncogAnalyst theAnalyst, FileInfo inputFile, bool headers, CSVFormat format) { InputFilename = inputFile; ExpectInputHeaders = headers; Format = format; _analyst = theAnalyst; Analyzed = true; PerformBasicCounts(); _inputCount = _analyst.DetermineInputCount(); _outputCount = _analyst.DetermineOutputCount(); _idealCount = InputHeadings.Length - _inputCount; if ((InputHeadings.Length != _inputCount) && (InputHeadings.Length != (_inputCount + _outputCount))) { throw new AnalystError("Invalid number of columns(" + InputHeadings.Length + "), must match input(" + _inputCount + ") count or input+output(" + (_inputCount + _outputCount) + ") count."); } } /// <summary> /// Prepare the output file, write headers if needed. /// </summary> /// <param name="outputFile">The name of the output file.</param> /// <returns>The output stream for the text file.</returns> private StreamWriter AnalystPrepareOutputFile(FileInfo outputFile) { try { var tw = new StreamWriter(outputFile.OpenWrite()); // write headers, if needed if (ProduceOutputHeaders) { var line = new StringBuilder(); // first handle the input fields foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields) { if (field.Input) { field.AddRawHeadings(line, null, Format); } } // now, handle any ideal fields if (_idealCount > 0) { foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields) { if (field.Output) { field.AddRawHeadings(line, "ideal:", Format); } } } // now, handle the output fields foreach (AnalystField field in _analyst.Script.Normalize.NormalizedFields) { if (field.Output) { field.AddRawHeadings(line, "output:", Format); } } tw.WriteLine(line.ToString()); } return tw; } catch (IOException e) { throw new QuantError(e); } } /// <summary> /// Process the file. /// </summary> /// <param name="outputFile">The output file.</param> /// <param name="method">The method to use.</param> public void Process(FileInfo outputFile, IMLRegression method) { var csv = new ReadCSV(InputFilename.ToString(), ExpectInputHeaders, Format); if (method.InputCount != _inputCount) { throw new AnalystError("This machine learning method has " + method.InputCount + " inputs, however, the data has " + _inputCount + " inputs."); } var input = new BasicMLData(method.InputCount); StreamWriter tw = AnalystPrepareOutputFile(outputFile); ResetStatus(); while (csv.Next()) { UpdateStatus(false); var row = new LoadedRow(csv, _idealCount); int dataIndex = 0; // load the input data for (int i = 0; i < _inputCount; i++) { String str = row.Data[i]; double d = Format.Parse(str); input[i] = d; dataIndex++; } // do we need to skip the ideal values? dataIndex += _idealCount; // compute the result IMLData output = method.Compute(input); // display the computed result for (int i = 0; i < _outputCount; i++) { double d = output[i]; row.Data[dataIndex++] = Format.Format(d, Precision); } WriteRow(tw, row); } ReportDone(false); tw.Close(); csv.Close(); } } }
//------------------------------------------------------------------------------ // <copyright file="BlobAsyncCopyController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Azure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Storage; using Microsoft.Azure.Storage.Blob; using Microsoft.Azure.Storage.DataMovement; using Microsoft.Azure.Storage.DataMovement.Extensions; /// <summary> /// Blob asynchronous copy. /// </summary> internal class BlobAsyncCopyController : AsyncCopyController { private AzureBlobLocation destLocation; private CloudBlob destBlob; public BlobAsyncCopyController( TransferScheduler transferScheduler, TransferJob transferJob, CancellationToken cancellationToken) : base(transferScheduler, transferJob, cancellationToken) { this.destLocation = transferJob.Destination as AzureBlobLocation; CloudBlob transferDestBlob = this.destLocation.Blob; if (null == transferDestBlob) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ParameterCannotBeNullException, "Dest.Blob"), "transferJob"); } if (transferDestBlob.IsSnapshot) { throw new ArgumentException(Resources.DestinationMustBeBaseBlob, "transferJob"); } AzureBlobLocation sourceBlobLocation = transferJob.Source as AzureBlobLocation; if (sourceBlobLocation != null) { if (sourceBlobLocation.Blob.BlobType != transferDestBlob.BlobType) { throw new ArgumentException(Resources.SourceAndDestinationBlobTypeDifferent, "transferJob"); } if (StorageExtensions.Equals(sourceBlobLocation.Blob, transferDestBlob)) { throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException); } } this.destBlob = transferDestBlob; } protected override Uri DestUri { get { return this.destBlob.Uri; } } protected override Task DoFetchDestAttributesAsync() { AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( this.destLocation.AccessCondition, this.destLocation.CheckedAccessCondition); return this.destBlob.FetchAttributesAsync( accessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } protected override async Task<StorageCopyState> DoStartCopyAsync() { AccessCondition destAccessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition); // To copy from source to blob, DataMovement Library should overwrite destination's properties and meta datas. // Clear destination's meta data here to avoid using destination's meta data. // Please reference to https://docs.microsoft.com/en-us/rest/api/storageservices/Copy-Blob. this.destBlob.Metadata.Clear(); if (null != this.SourceUri) { await this.destBlob.StartCopyAsync( this.SourceUri, null, destAccessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); return new StorageCopyState(this.destBlob.CopyState); } else if (null != this.SourceBlob) { AccessCondition sourceAccessCondition = AccessCondition.GenerateIfMatchCondition(this.SourceBlob.Properties.ETag); await this.destBlob.StartCopyAsync( this.SourceBlob.GenerateCopySourceUri(), sourceAccessCondition, destAccessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); var copyState = new StorageCopyState(this.destBlob.CopyState); if (copyState.Status == StorageCopyStatus.Success) { copyState.TotalBytes = this.SourceBlob.Properties.Length; copyState.BytesCopied = this.SourceBlob.Properties.Length; } return copyState; } else { if (BlobType.BlockBlob == this.destBlob.BlobType) { await (this.destBlob as CloudBlockBlob).StartCopyAsync( this.SourceFile.GenerateCopySourceUri(), null, destAccessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); var copyState = new StorageCopyState(this.destBlob.CopyState); if (copyState.Status == StorageCopyStatus.Success) { copyState.TotalBytes = this.SourceFile.Properties.Length; copyState.BytesCopied = this.SourceFile.Properties.Length; } return copyState; } else if (BlobType.PageBlob == this.destBlob.BlobType) { throw new InvalidOperationException(Resources.AsyncCopyFromFileToPageBlobNotSupportException); } else if (BlobType.AppendBlob == this.destBlob.BlobType) { throw new InvalidOperationException(Resources.AsyncCopyFromFileToAppendBlobNotSupportException); } else { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, Resources.NotSupportedBlobType, this.destBlob.BlobType)); } } } protected override void DoHandleGetDestinationException(StorageException se) { if (null != se) { if (0 == string.Compare(se.Message, Constants.BlobTypeMismatch, StringComparison.OrdinalIgnoreCase)) { // Current use error message to decide whether it caused by blob type mismatch, // We should ask xscl to expose an error code for this.. // Opened workitem 1487579 to track this. throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch, se); } } else { if (null != this.SourceBlob && this.SourceBlob.Properties.BlobType != this.destBlob.Properties.BlobType) { throw new InvalidOperationException(Resources.SourceAndDestinationBlobTypeDifferent); } } } protected override async Task<StorageCopyState> FetchCopyStateAsync() { await this.destBlob.FetchAttributesAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); return new StorageCopyState(this.destBlob.CopyState); } protected override async Task SetAttributesAsync(SetAttributesCallbackAsync setCustomAttributes) { var originalAttributes = Utils.GenerateAttributes(this.destBlob); var originalMetadata = new Dictionary<string, string>(this.destBlob.Metadata); await setCustomAttributes(this.TransferJob.Source.Instance, this.destBlob); if (!Utils.CompareProperties(originalAttributes, Utils.GenerateAttributes(this.destBlob))) { await this.destBlob.SetPropertiesAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } if (!originalMetadata.DictionaryEquals(this.destBlob.Metadata)) { await this.destBlob.SetMetadataAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlServerCe; using System.Collections; using System.Windows.Forms; using DowUtils; namespace Factotum{ public class EOutage : IEntity { public static event EventHandler<EntityChangedEventArgs> Changed; public static event EventHandler<EntityChangedEventArgs> Added; public static event EventHandler<EntityChangedEventArgs> Updated; public static event EventHandler<EntityChangedEventArgs> Deleted; protected virtual void OnChanged(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Changed; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } protected virtual void OnAdded(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Added; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } protected virtual void OnUpdated(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Updated; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } protected virtual void OnDeleted(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Deleted; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } // Mapped database columns // Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not). // Use int?, decimal?, etc for nullable numbers // Strings, images, etc, are reference types already private Guid? OtgDBid; private string OtgName; private Guid? OtgUntID; private Guid? OtgClpID; private Guid? OtgCptID; private string OtgCouplantBatch; private string OtgFacPhone; private DateTime? OtgStartedOn; private DateTime? OtgEndedOn; private DateTime? OtgConfigExportedOn; private DateTime? OtgDataImportedOn; private bool OtgGridColDefaultCCW; // Textbox limits public static int OtgNameCharLimit = 50; public static int OtgCouplantBatchCharLimit = 50; public static int OtgFacPhoneCharLimit = 50; // Field-specific error message strings (normally just needed for textbox data) private string OtgNameErrMsg; private string OtgCouplantBatchErrMsg; private string OtgFacPhoneErrMsg; // Form level validation message private string OtgErrMsg; //-------------------------------------------------------- // Field Properties //-------------------------------------------------------- // Primary key accessor public Guid? ID { get { return OtgDBid; } } public string OutageName { get { return OtgName; } set { OtgName = Util.NullifyEmpty(value); } } public Guid? OutageUntID { get { return OtgUntID; } set { OtgUntID = value; } } public Guid? OutageClpID { get { return OtgClpID; } set { OtgClpID = value; } } public Guid? OutageCptID { get { return OtgCptID; } set { OtgCptID = value; } } public string OutageCouplantBatch { get { return OtgCouplantBatch; } set { OtgCouplantBatch = Util.NullifyEmpty(value); } } public string OutageFacPhone { get { return OtgFacPhone; } set { OtgFacPhone = Util.NullifyEmpty(value); } } public DateTime? OutageStartedOn { get { return OtgStartedOn; } set { OtgStartedOn = value; } } public DateTime? OutageEndedOn { get { return OtgEndedOn; } set { OtgEndedOn = value; } } public DateTime? OutageConfigExportedOn { get { return OtgConfigExportedOn; } set { OtgConfigExportedOn = value; } } public DateTime? OutageDataImportedOn { get { return OtgDataImportedOn; } set { OtgDataImportedOn = value; } } public bool OutageGridColDefaultCCW { get { return OtgGridColDefaultCCW; } set { OtgGridColDefaultCCW = value; } } public string OutageCalibrationProcedureName { get { if (OtgClpID == null) return null; ECalibrationProcedure clp = new ECalibrationProcedure(OtgClpID); return clp.CalibrationProcedureName; } } public string OutageCouplantTypeName { get { if (OtgCptID == null) return null; ECouplantType cpt = new ECouplantType(OtgCptID); return cpt.CouplantTypeName; } } public string OutageNameWithSiteInParens { get { EUnit unt = new EUnit(OtgUntID); if (Util.IsNullOrEmpty(unt.UnitNameWithSite)) return OtgName; return OtgName + " (" + unt.UnitNameWithSite + ")"; } } //----------------------------------------------------------------- // Field Level Error Messages. // Include one for every text column // In cases where we need to ensure data consistency, we may need // them for other types. //----------------------------------------------------------------- public string OutageNameErrMsg { get { return OtgNameErrMsg; } } public string OutageCouplantBatchErrMsg { get { return OtgCouplantBatchErrMsg; } } public string OutageFacPhoneErrMsg { get { return OtgFacPhoneErrMsg; } } //-------------------------------------- // Form level Error Message //-------------------------------------- public string OutageErrMsg { get { return OtgErrMsg; } set { OtgErrMsg = Util.NullifyEmpty(value); } } //-------------------------------------- // Textbox Name Length Validation //-------------------------------------- public bool OutageNameLengthOk(string s) { if (s == null) return true; if (s.Length > OtgNameCharLimit) { OtgNameErrMsg = string.Format("Outage Names cannot exceed {0} characters", OtgNameCharLimit); return false; } else { OtgNameErrMsg = null; return true; } } public bool OutageCouplantBatchLengthOk(string s) { if (s == null) return true; if (s.Length > OtgCouplantBatchCharLimit) { OtgCouplantBatchErrMsg = string.Format("Outage Couplant Batches cannot exceed {0} characters", OtgCouplantBatchCharLimit); return false; } else { OtgCouplantBatchErrMsg = null; return true; } } public bool OutageFacPhoneLengthOk(string s) { if (s == null) return true; if (s.Length > OtgFacPhoneCharLimit) { OtgFacPhoneErrMsg = string.Format("Outage FAC Phones cannot exceed {0} characters", OtgFacPhoneCharLimit); return false; } else { OtgFacPhoneErrMsg = null; return true; } } //-------------------------------------- // Field-Specific Validation // sets and clears error messages //-------------------------------------- public bool OutageNameValid(string name) { if (!OutageNameLengthOk(name)) return false; // KEEP, MODIFY OR REMOVE THIS AS REQUIRED // YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC.. if (NameExistsForUnit(name, OtgDBid, (Guid)OtgUntID)) { OtgNameErrMsg = "That Outage Name is already in use."; return false; } OtgNameErrMsg = null; return true; } public bool OutageCouplantBatchValid(string value) { if (!OutageCouplantBatchLengthOk(value)) return false; OtgCouplantBatchErrMsg = null; return true; } public bool OutageFacPhoneValid(string value) { if (!OutageFacPhoneLengthOk(value)) return false; OtgFacPhoneErrMsg = null; return true; } //-------------------------------------- // Constructors //-------------------------------------- // Default constructor. Field defaults must be set here. // Any defaults set by the database will be overridden. public EOutage() { this.OtgGridColDefaultCCW = false; } // Constructor which loads itself from the supplied id. // If the id is null, this gives the same result as using the default constructor. public EOutage(Guid? id) : this() { Load(id); } //-------------------------------------- // Public Methods //-------------------------------------- //---------------------------------------------------- // Load the object from the database given a Guid? //---------------------------------------------------- public void Load(Guid? id) { if (id == null) return; SqlCeCommand cmd = Globals.cnn.CreateCommand(); SqlCeDataReader dr; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select OtgDBid, OtgName, OtgUntID, OtgClpID, OtgCptID, OtgCouplantBatch, OtgFacPhone, OtgStartedOn, OtgEndedOn, OtgConfigExportedOn, OtgDataImportedOn, OtgGridColDefaultCCW from Outages where OtgDBid = @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // The query should return one record. // If it doesn't return anything (no match) the object is not affected if (dr.Read()) { // For nullable foreign keys, set field to null for dbNull case // For other nullable values, replace dbNull with null OtgDBid = (Guid?)dr[0]; OtgName = (string)dr[1]; OtgUntID = (Guid?)dr[2]; OtgClpID = (Guid?)Util.NullForDbNull(dr[3]); OtgCptID = (Guid?)Util.NullForDbNull(dr[4]); OtgCouplantBatch = (string)Util.NullForDbNull(dr[5]); OtgFacPhone = (string)Util.NullForDbNull(dr[6]); OtgStartedOn = (DateTime?)Util.NullForDbNull(dr[7]); OtgEndedOn = (DateTime?)Util.NullForDbNull(dr[8]); OtgConfigExportedOn = (DateTime?)Util.NullForDbNull(dr[9]); OtgDataImportedOn = (DateTime?)Util.NullForDbNull(dr[10]); OtgGridColDefaultCCW = (bool)dr[11]; } dr.Close(); } //-------------------------------------- // Save the current record if it's valid //-------------------------------------- public Guid? Save() { if (!Valid()) { // Note: We're returning null if we fail, // so don't just assume you're going to get your id back // and set your id to the result of this function call. return null; } SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; if (ID == null) { // we are inserting a new record // first ask the database for a new Guid cmd.CommandText = "Select Newid()"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); OtgDBid = (Guid?)(cmd.ExecuteScalar()); // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", OtgDBid), new SqlCeParameter("@p1", OtgName), new SqlCeParameter("@p2", OtgUntID), new SqlCeParameter("@p3", Util.DbNullForNull(OtgClpID)), new SqlCeParameter("@p4", Util.DbNullForNull(OtgCptID)), new SqlCeParameter("@p5", Util.DbNullForNull(OtgCouplantBatch)), new SqlCeParameter("@p6", Util.DbNullForNull(OtgFacPhone)), new SqlCeParameter("@p7", Util.DbNullForNull(OtgStartedOn)), new SqlCeParameter("@p8", Util.DbNullForNull(OtgEndedOn)), new SqlCeParameter("@p9", Util.DbNullForNull(OtgConfigExportedOn)), new SqlCeParameter("@p10", Util.DbNullForNull(OtgDataImportedOn)), new SqlCeParameter("@p11", OtgGridColDefaultCCW) }); cmd.CommandText = @"Insert Into Outages ( OtgDBid, OtgName, OtgUntID, OtgClpID, OtgCptID, OtgCouplantBatch, OtgFacPhone, OtgStartedOn, OtgEndedOn, OtgConfigExportedOn, OtgDataImportedOn, OtgGridColDefaultCCW ) values (@p0,@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8,@p9,@p10,@p11)"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to insert Outages row"); } OnAdded(ID); } else { // we are updating an existing record // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", OtgDBid), new SqlCeParameter("@p1", OtgName), new SqlCeParameter("@p2", OtgUntID), new SqlCeParameter("@p3", Util.DbNullForNull(OtgClpID)), new SqlCeParameter("@p4", Util.DbNullForNull(OtgCptID)), new SqlCeParameter("@p5", Util.DbNullForNull(OtgCouplantBatch)), new SqlCeParameter("@p6", Util.DbNullForNull(OtgFacPhone)), new SqlCeParameter("@p7", Util.DbNullForNull(OtgStartedOn)), new SqlCeParameter("@p8", Util.DbNullForNull(OtgEndedOn)), new SqlCeParameter("@p9", Util.DbNullForNull(OtgConfigExportedOn)), new SqlCeParameter("@p10", Util.DbNullForNull(OtgDataImportedOn)), new SqlCeParameter("@p11", OtgGridColDefaultCCW)}); cmd.CommandText = @"Update Outages set OtgName = @p1, OtgUntID = @p2, OtgClpID = @p3, OtgCptID = @p4, OtgCouplantBatch = @p5, OtgFacPhone = @p6, OtgStartedOn = @p7, OtgEndedOn = @p8, OtgConfigExportedOn = @p9, OtgDataImportedOn = @p10, OtgGridColDefaultCCW = @p11 Where OtgDBid = @p0"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to update outages row"); } OnUpdated(ID); } OnChanged(ID); return ID; } //-------------------------------------- // Validate the current record //-------------------------------------- // Make this public so that the UI can check validation itself // if it chooses to do so. This is also called by the Save function. public bool Valid() { // First check each field to see if it's valid from the UI perspective if (!OutageNameValid(OutageName)) return false; if (!OutageCouplantBatchValid(OutageCouplantBatch)) return false; if (!OutageFacPhoneValid(OutageFacPhone)) return false; // Check form to make sure all required fields have been filled in if (!RequiredFieldsFilled()) return false; // Check for incorrect field interactions... return true; } //-------------------------------------- // Delete the current record //-------------------------------------- public bool Delete(bool promptUser) { // If the current object doesn't reference a database record, there's nothing to do. if (OtgDBid == null) { OutageErrMsg = "Unable to delete. Record not found."; return false; } if (HasChildren()) { OutageErrMsg = "Unable to delete because this Outage is referenced by Component Reports."; return false; } if (HasDataImported()) { OutageErrMsg = "Unable to delete because data has been imported for this Outage."; return false; } DialogResult rslt = DialogResult.None; if (promptUser) { rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); } if (!promptUser || rslt == DialogResult.OK) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"Delete from Outages where OtgDBid = @p0"; cmd.Parameters.Add("@p0", OtgDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); // Todo: figure out how I really want to do this. // Is there a problem with letting the database try to do cascading deletes? // How should the user be notified of the problem?? if (rowsAffected < 1) { OutageErrMsg = "Unable to delete. Please try again later."; return false; } else { OutageErrMsg = null; OnChanged(ID); OnDeleted(ID); return true; } } else { return false; } } private bool HasDataImported() { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandText = @"Select OtgDataImportedOn from Outages where OtgDBid = @p0"; cmd.Parameters.Add("@p0", OtgDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object result = Util.NullForDbNull(cmd.ExecuteScalar()); return result != null; } private bool HasChildren() { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandText = @"Select IscDBid from InspectedComponents where IscOtgID = @p0"; cmd.Parameters.Add("@p0", OtgDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object result = Util.NullForDbNull(cmd.ExecuteScalar()); return result != null; } //-------------------------------------------------------------------- // Static listing methods which return collections of outages //-------------------------------------------------------------------- // This helper function builds the collection for you based on the flags you send it public static EOutageCollection ListByName(bool addNoSelection) { EOutage outage; EOutageCollection outages = new EOutageCollection(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select OtgDBid, OtgName, OtgUntID, OtgClpID, OtgCptID, OtgCouplantBatch, OtgFacPhone, OtgStartedOn, OtgEndedOn, OtgConfigExportedOn, OtgDataImportedOn, OtgGridColDefaultCCW from Outages"; qry += " order by OtgName"; cmd.CommandText = qry; if (addNoSelection) { // Insert a default item with name "<No Selection>" outage = new EOutage(); outage.OtgName = "<No Selection>"; outages.Add(outage); } SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { outage = new EOutage((Guid?)dr[0]); outage.OtgName = (string)(dr[1]); outage.OtgUntID = (Guid?)(dr[2]); outage.OtgClpID = (Guid?)Util.NullForDbNull(dr[3]); outage.OtgCptID = (Guid?)Util.NullForDbNull(dr[4]); outage.OtgCouplantBatch = (string)Util.NullForDbNull(dr[5]); outage.OtgFacPhone = (string)Util.NullForDbNull(dr[6]); outage.OtgStartedOn = (DateTime?)Util.NullForDbNull(dr[7]); outage.OtgEndedOn = (DateTime?)Util.NullForDbNull(dr[8]); outage.OtgConfigExportedOn = (DateTime?)Util.NullForDbNull(dr[9]); outage.OtgDataImportedOn = (DateTime?)Util.NullForDbNull(dr[10]); outage.OtgGridColDefaultCCW = (bool)(dr[11]); outages.Add(outage); } // Finish up dr.Close(); return outages; } // This helper function builds the collection for you based on the flags you send it public static EOutageCollection ListForUnit(Guid UnitID, bool addNoSelection) { EOutage outage; EOutageCollection outages = new EOutageCollection(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select OtgDBid, OtgUntID, OtgName, OtgClpID, OtgCptID, OtgCouplantBatch, OtgFacPhone, OtgStartedOn, OtgEndedOn, OtgConfigExportedOn, OtgDataImportedOn, OtgGridColDefaultCCW from Outages"; qry += " where OtgUntID = @p1"; qry += " order by OtgName"; cmd.CommandText = qry; cmd.Parameters.Add(new SqlCeParameter("@p1", UnitID)); if (addNoSelection) { // Insert a default item with name "<No Selection>" outage = new EOutage(); outage.OtgName = "<No Selection>"; outages.Add(outage); } SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { outage = new EOutage((Guid?)dr[0]); outage.OtgUntID = (Guid?)(dr[1]); outage.OtgName = (string)(dr[2]); outage.OtgClpID = (Guid?)Util.NullForDbNull(dr[3]); outage.OtgCptID = (Guid?)Util.NullForDbNull(dr[4]); outage.OtgCouplantBatch = (string)Util.NullForDbNull(dr[5]); outage.OtgFacPhone = (string)Util.NullForDbNull(dr[6]); outage.OtgStartedOn = (DateTime?)Util.NullForDbNull(dr[7]); outage.OtgEndedOn = (DateTime?)Util.NullForDbNull(dr[8]); outage.OtgConfigExportedOn = (DateTime?)Util.NullForDbNull(dr[9]); outage.OtgDataImportedOn = (DateTime?)Util.NullForDbNull(dr[10]); outage.OtgGridColDefaultCCW = (bool)(dr[11]); outages.Add(outage); } // Finish up dr.Close(); return outages; } // Get a Default data view with all columns that a user would likely want to see. // You can bind this view to a DataGridView, hide the columns you don't need, filter, etc. // I decided not to indicate inactive in the names of inactive items. The 'user' // can always show the inactive column if they wish. public static DataView GetDefaultDataView() { DataSet ds = new DataSet(); DataView dv; SqlCeDataAdapter da = new SqlCeDataAdapter(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; // Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and // makes the column sortable. // You'll likely want to modify this query further, joining in other tables, etc. string qry = @"Select OtgDBid as ID, OtgName as OutageName, OtgUntID as OutageUntID, OtgClpID as OutageClpID, OtgCptID as OutageCptID, OtgCouplantBatch as OutageCouplantBatch, OtgFacPhone as OutageFacPhone, OtgStartedOn as OutageStartedOn, OtgEndedOn as OutageEndedOn, OtgConfigExportedOn as OutageConfigExportedOn, OtgDataImportedOn as OutageDataImportedOn, CASE WHEN OtgGridColDefaultCCW = 0 THEN 'No' ELSE 'Yes' END as OutageGridColDefaultCCW from Outages"; cmd.CommandText = qry; da.SelectCommand = cmd; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); da.Fill(ds); dv = new DataView(ds.Tables[0]); return dv; } //-------------------------------------- // Private utilities //-------------------------------------- // Check if the name exists for any records besides the current one // This is used to show an error when the user tabs away from the field. // We don't want to show an error if the user has left the field blank. // If it's a required field, we'll catch it when the user hits save. private bool NameExists(string name, Guid? id) { if (Util.IsNullOrEmpty(name)) return false; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SqlCeParameter("@p1", name)); if (id == null) { cmd.CommandText = "Select OtgDBid from Outages where OtgName = @p1"; } else { cmd.CommandText = "Select OtgDBid from Outages where OtgName = @p1 and OtgDBid != @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); } if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); bool test = (cmd.ExecuteScalar() != null); return test; } // Check if the name exists for any records besides the current one // This is used to show an error when the user tabs away from the field. // We don't want to show an error if the user has left the field blank. // If it's a required field, we'll catch it when the user hits save. private bool NameExistsForUnit(string name, Guid? id, Guid unitId) { if (Util.IsNullOrEmpty(name)) return false; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SqlCeParameter("@p1", name)); cmd.Parameters.Add(new SqlCeParameter("@p2", unitId)); if (id == null) { cmd.CommandText = @"Select OtgDBid from Outages where OtgName = @p1 and OtgUntID = @p2"; } else { cmd.CommandText = @"Select OtgDBid from Outages where OtgName = @p1 and OtgUntID = @p2 and OtgDBid != @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); } if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); bool test = (cmd.ExecuteScalar() != null); return test; } // Check for required fields, setting the individual error messages private bool RequiredFieldsFilled() { bool allFilled = true; if (OutageName == null) { OtgNameErrMsg = "An Outage Name is required"; allFilled = false; } else { OtgNameErrMsg = null; } return allFilled; } } //-------------------------------------- // Outage Collection class //-------------------------------------- public class EOutageCollection : CollectionBase { //this event is fired when the collection's items have changed public event EventHandler Changed; //this is the constructor of the collection. public EOutageCollection() { } //the indexer of the collection public EOutage this[int index] { get { return (EOutage)this.List[index]; } } //this method fires the Changed event. protected virtual void OnChanged(EventArgs e) { if (Changed != null) { Changed(this, e); } } public bool ContainsID(Guid? ID) { if (ID == null) return false; foreach (EOutage outage in InnerList) { if (outage.ID == ID) return true; } return false; } //returns the index of an item in the collection public int IndexOf(EOutage item) { return InnerList.IndexOf(item); } //adds an item to the collection public void Add(EOutage item) { this.List.Add(item); OnChanged(EventArgs.Empty); } //inserts an item in the collection at a specified index public void Insert(int index, EOutage item) { this.List.Insert(index, item); OnChanged(EventArgs.Empty); } //removes an item from the collection. public void Remove(EOutage item) { this.List.Remove(item); OnChanged(EventArgs.Empty); } } }
// 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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// DeploymentOperations operations. /// </summary> internal partial class DeploymentOperations : Microsoft.Rest.IServiceOperations<ResourceManagementClient>, IDeploymentOperations { /// <summary> /// Initializes a new instance of the DeploymentOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal DeploymentOperations(ResourceManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the ResourceManagementClient /// </summary> public ResourceManagementClient Client { get; private set; } /// <summary> /// Get a list of deployments operations. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='operationId'> /// Operation Id. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<DeploymentOperation>> GetWithHttpMessagesAsync(string resourceGroupName, string deploymentName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "deploymentName"); } if (deploymentName != null) { if (deploymentName.Length > 64) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "deploymentName", 64); } if (deploymentName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "deploymentName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(deploymentName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "deploymentName", "^[-\\w\\._\\(\\)]+$"); } } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", System.Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<DeploymentOperation>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<DeploymentOperation>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of deployments operations. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='deploymentName'> /// The name of the deployment. /// </param> /// <param name='top'> /// Query parameters. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>> ListWithHttpMessagesAsync(string resourceGroupName, string deploymentName, int? top = default(int?), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (deploymentName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "deploymentName"); } if (deploymentName != null) { if (deploymentName.Length > 64) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MaxLength, "deploymentName", 64); } if (deploymentName.Length < 1) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.MinLength, "deploymentName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(deploymentName, "^[-\\w\\._\\(\\)]+$")) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.Pattern, "deploymentName", "^[-\\w\\._\\(\\)]+$"); } } if (this.Client.ApiVersion == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("top", top); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{deploymentName}", System.Uri.EscapeDataString(deploymentName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, this.Client.SerializationSettings).Trim('"')))); } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DeploymentOperation>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of deployments operations. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (nextPageLink == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<DeploymentOperation>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<DeploymentOperation>>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//--------------------------------------------------------------------- // <copyright file="SqlProviderManifest.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Generic; using System.Data.Common; using System.Data.Entity; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Linq; using System.Text; using System.Xml; namespace System.Data.SqlClient { /// <summary> /// The Provider Manifest for SQL Server /// </summary> internal class SqlProviderManifest : DbXmlEnabledProviderManifest { internal const string TokenSql8 = "2000"; internal const string TokenSql9 = "2005"; internal const string TokenSql10 = "2008"; // '~' is the same escape character that L2S uses internal const char LikeEscapeChar = '~'; internal const string LikeEscapeCharToString = "~"; #region Private Fields // Default to SQL Server 2005 (9.0) private SqlVersion _version = SqlVersion.Sql9; /// <summary> /// maximum size of sql server unicode /// </summary> private const int varcharMaxSize = 8000; private const int nvarcharMaxSize = 4000; private const int binaryMaxSize = 8000; private System.Collections.ObjectModel.ReadOnlyCollection<PrimitiveType> _primitiveTypes = null; private System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> _functions = null; #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="manifestToken">A token used to infer the capabilities of the store</param> public SqlProviderManifest(string manifestToken) : base(SqlProviderManifest.GetProviderManifest()) { // GetSqlVersion will throw ArgumentException if manifestToken is null, empty, or not recognized. _version = SqlVersionUtils.GetSqlVersion(manifestToken); } #endregion #region Properties internal SqlVersion SqlVersion { get { return this._version; } } #endregion #region Private Methods private static XmlReader GetProviderManifest() { return DbProviderServices.GetXmlResource("System.Data.Resources.SqlClient.SqlProviderServices.ProviderManifest.xml"); } private XmlReader GetStoreSchemaMapping(string mslName) { return DbProviderServices.GetXmlResource("System.Data.Resources.SqlClient.SqlProviderServices." + mslName + ".msl"); } private XmlReader GetStoreSchemaDescription(string ssdlName) { if (this._version == SqlVersion.Sql8) { return DbProviderServices.GetXmlResource("System.Data.Resources.SqlClient.SqlProviderServices." + ssdlName + "_Sql8.ssdl"); } return DbProviderServices.GetXmlResource("System.Data.Resources.SqlClient.SqlProviderServices." + ssdlName + ".ssdl"); } #endregion #region Internal Methods /// <summary> /// Function to detect wildcard characters %, _, [ and ^ and escape them with a preceding ~ /// This escaping is used when StartsWith, EndsWith and Contains canonical and CLR functions /// are translated to their equivalent LIKE expression /// NOTE: This code has been copied from LinqToSql /// </summary> /// <param name="text">Original input as specified by the user</param> /// <param name="alwaysEscapeEscapeChar">escape the escape character ~ regardless whether wildcard /// characters were encountered </param> /// <param name="usedEscapeChar">true if the escaping was performed, false if no escaping was required</param> /// <returns>The escaped string that can be used as pattern in a LIKE expression</returns> internal static string EscapeLikeText(string text, bool alwaysEscapeEscapeChar, out bool usedEscapeChar) { usedEscapeChar = false; if (!(text.Contains("%") || text.Contains("_") || text.Contains("[") || text.Contains("^") || alwaysEscapeEscapeChar && text.Contains(LikeEscapeCharToString))) { return text; } StringBuilder sb = new StringBuilder(text.Length); foreach (char c in text) { if (c == '%' || c == '_' || c == '[' || c == '^' || c == LikeEscapeChar) { sb.Append(LikeEscapeChar); usedEscapeChar = true; } sb.Append(c); } return sb.ToString(); } #endregion #region Overrides /// <summary> /// Providers should override this to return information specific to their provider. /// /// This method should never return null. /// </summary> /// <param name="informationType">The name of the information to be retrieved.</param> /// <returns>An XmlReader at the begining of the information requested.</returns> protected override XmlReader GetDbInformation(string informationType) { if (informationType == DbProviderManifest.StoreSchemaDefinitionVersion3 || informationType == DbProviderManifest.StoreSchemaDefinition) { return GetStoreSchemaDescription(informationType); } if (informationType == DbProviderManifest.StoreSchemaMappingVersion3 || informationType == DbProviderManifest.StoreSchemaMapping) { return GetStoreSchemaMapping(informationType); } // Use default Conceptual Schema Definition if (informationType == DbProviderManifest.ConceptualSchemaDefinitionVersion3 || informationType == DbProviderManifest.ConceptualSchemaDefinition) { return null; } throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.ProviderReturnedNullForGetDbInformation(informationType)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] public override System.Collections.ObjectModel.ReadOnlyCollection<PrimitiveType> GetStoreTypes() { if (this._primitiveTypes == null) { if (this._version == SqlVersion.Sql10) { this._primitiveTypes = base.GetStoreTypes(); } else { List<PrimitiveType> primitiveTypes = new List<PrimitiveType>(base.GetStoreTypes()); Debug.Assert((this._version == SqlVersion.Sql8) || (this._version == SqlVersion.Sql9), "Found verion other than Sql 8, 9 or 10"); //Remove the Katmai types for both Sql8 and Sql9 primitiveTypes.RemoveAll(new Predicate<PrimitiveType>( delegate(PrimitiveType primitiveType) { string name = primitiveType.Name.ToLowerInvariant(); return name.Equals("time", StringComparison.Ordinal) || name.Equals("date", StringComparison.Ordinal) || name.Equals("datetime2", StringComparison.Ordinal) || name.Equals("datetimeoffset", StringComparison.Ordinal) || name.Equals("geography", StringComparison.Ordinal) || name.Equals("geometry", StringComparison.Ordinal); } ) ); //Remove the types that won't work in Sql8 if (this._version == SqlVersion.Sql8) { // SQLBUDT 550667 and 551271: Remove xml and 'max' types for SQL Server 2000 primitiveTypes.RemoveAll(new Predicate<PrimitiveType>( delegate(PrimitiveType primitiveType) { string name = primitiveType.Name.ToLowerInvariant(); return name.Equals("xml", StringComparison.Ordinal) || name.EndsWith("(max)", StringComparison.Ordinal); } ) ); } this._primitiveTypes = primitiveTypes.AsReadOnly(); } } return this._primitiveTypes; } public override System.Collections.ObjectModel.ReadOnlyCollection<EdmFunction> GetStoreFunctions() { if (this._functions == null) { if (this._version == SqlVersion.Sql10) { this._functions = base.GetStoreFunctions(); } else { //Remove the functions over katmai types from both Sql 9 and Sql 8. IEnumerable<EdmFunction> functions = base.GetStoreFunctions().Where(f => !IsKatmaiOrNewer(f)); if(this._version == SqlVersion.Sql8) { // SQLBUDT 550998: Remove unsupported overloads from Provider Manifest on SQL 8.0 functions = functions.Where(f => !IsYukonOrNewer(f)); } this._functions = functions.ToList().AsReadOnly(); } } return this._functions; } private static bool IsKatmaiOrNewer(EdmFunction edmFunction) { // Spatial types are only supported from Katmai onward; any functions using them must therefore also be Katmai or newer. if ((edmFunction.ReturnParameter != null && Helper.IsSpatialType(edmFunction.ReturnParameter.TypeUsage)) || edmFunction.Parameters.Any(p => Helper.IsSpatialType(p.TypeUsage))) { return true; } ReadOnlyMetadataCollection<FunctionParameter> funParams = edmFunction.Parameters; switch (edmFunction.Name.ToUpperInvariant()) { case "COUNT": case "COUNT_BIG": case "MAX": case "MIN": { string name = ((CollectionType)funParams[0].TypeUsage.EdmType).TypeUsage.EdmType.Name; return ((name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) || (name.Equals("Time", StringComparison.OrdinalIgnoreCase))); } case "DAY": case "MONTH": case "YEAR": case "DATALENGTH": case "CHECKSUM": { string name = funParams[0].TypeUsage.EdmType.Name; return ((name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) || (name.Equals("Time", StringComparison.OrdinalIgnoreCase))); } case "DATEADD": case "DATEDIFF": { string param1Name = funParams[1].TypeUsage.EdmType.Name; string param2Name = funParams[2].TypeUsage.EdmType.Name; return ((param1Name.Equals("Time", StringComparison.OrdinalIgnoreCase)) || (param2Name.Equals("Time", StringComparison.OrdinalIgnoreCase)) || (param1Name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) || (param2Name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase))); } case "DATENAME": case "DATEPART": { string name = funParams[1].TypeUsage.EdmType.Name; return ((name.Equals("DateTimeOffset", StringComparison.OrdinalIgnoreCase)) || (name.Equals("Time", StringComparison.OrdinalIgnoreCase))); } case "SYSUTCDATETIME": case "SYSDATETIME": case "SYSDATETIMEOFFSET": return true; default: break; } return false; } private static bool IsYukonOrNewer(EdmFunction edmFunction) { ReadOnlyMetadataCollection<FunctionParameter> funParams = edmFunction.Parameters; if (funParams == null || funParams.Count == 0) { return false; } switch (edmFunction.Name.ToUpperInvariant()) { case "COUNT": case "COUNT_BIG": { string name = ((CollectionType)funParams[0].TypeUsage.EdmType).TypeUsage.EdmType.Name; return name.Equals("Guid", StringComparison.OrdinalIgnoreCase); } case "CHARINDEX": { foreach (FunctionParameter funParam in funParams) { if (funParam.TypeUsage.EdmType.Name.Equals("Int64", StringComparison.OrdinalIgnoreCase)) { return true; } } } break; default: break; } return false; } /// <summary> /// This method takes a type and a set of facets and returns the best mapped equivalent type /// in EDM. /// </summary> /// <param name="storeType">A TypeUsage encapsulating a store type and a set of facets</param> /// <returns>A TypeUsage encapsulating an EDM type and a set of facets</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] public override TypeUsage GetEdmType(TypeUsage storeType) { EntityUtil.CheckArgumentNull<TypeUsage>(storeType, "storeType"); string storeTypeName = storeType.EdmType.Name.ToLowerInvariant(); if (!base.StoreTypeNameToEdmPrimitiveType.ContainsKey(storeTypeName)) { throw EntityUtil.Argument(Strings.ProviderDoesNotSupportType(storeTypeName)); } PrimitiveType edmPrimitiveType = base.StoreTypeNameToEdmPrimitiveType[storeTypeName]; int maxLength = 0; bool isUnicode = true; bool isFixedLen = false; bool isUnbounded = true; PrimitiveTypeKind newPrimitiveTypeKind; switch (storeTypeName) { // for some types we just go with simple type usage with no facets case "tinyint": case "smallint": case "bigint": case "bit": case "uniqueidentifier": case "int": case "geography": case "geometry": return TypeUsage.CreateDefaultTypeUsage(edmPrimitiveType); case "varchar": newPrimitiveTypeKind = PrimitiveTypeKind.String; isUnbounded = !TypeHelpers.TryGetMaxLength(storeType, out maxLength); isUnicode = false; isFixedLen = false; break; case "char": newPrimitiveTypeKind = PrimitiveTypeKind.String; isUnbounded = !TypeHelpers.TryGetMaxLength(storeType, out maxLength); isUnicode = false; isFixedLen = true; break; case "nvarchar": newPrimitiveTypeKind = PrimitiveTypeKind.String; isUnbounded = !TypeHelpers.TryGetMaxLength(storeType, out maxLength); isUnicode = true; isFixedLen = false; break; case "nchar": newPrimitiveTypeKind = PrimitiveTypeKind.String; isUnbounded = !TypeHelpers.TryGetMaxLength(storeType, out maxLength); isUnicode = true; isFixedLen = true; break; case "varchar(max)": case "text": newPrimitiveTypeKind = PrimitiveTypeKind.String; isUnbounded = true; isUnicode = false; isFixedLen = false; break; case "nvarchar(max)": case "ntext": case "xml": newPrimitiveTypeKind = PrimitiveTypeKind.String; isUnbounded = true; isUnicode = true; isFixedLen = false; break; case "binary": newPrimitiveTypeKind = PrimitiveTypeKind.Binary; isUnbounded = !TypeHelpers.TryGetMaxLength(storeType, out maxLength); isFixedLen = true; break; case "varbinary": newPrimitiveTypeKind = PrimitiveTypeKind.Binary; isUnbounded = !TypeHelpers.TryGetMaxLength(storeType, out maxLength); isFixedLen = false; break; case "varbinary(max)": case "image": newPrimitiveTypeKind = PrimitiveTypeKind.Binary; isUnbounded = true; isFixedLen = false; break; case "timestamp": case "rowversion": return TypeUsage.CreateBinaryTypeUsage(edmPrimitiveType, true, 8); case "float": case "real": return TypeUsage.CreateDefaultTypeUsage(edmPrimitiveType); case "decimal": case "numeric": { byte precision; byte scale; if (TypeHelpers.TryGetPrecision(storeType, out precision) && TypeHelpers.TryGetScale(storeType, out scale)) { return TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType, precision, scale); } else { return TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType); } } case "money": return TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType, 19, 4); case "smallmoney": return TypeUsage.CreateDecimalTypeUsage(edmPrimitiveType, 10, 4); case "datetime": case "datetime2": case "smalldatetime": return TypeUsage.CreateDateTimeTypeUsage(edmPrimitiveType, null); case "date": return TypeUsage.CreateDefaultTypeUsage(edmPrimitiveType); case "time": return TypeUsage.CreateTimeTypeUsage(edmPrimitiveType, null); case "datetimeoffset": return TypeUsage.CreateDateTimeOffsetTypeUsage(edmPrimitiveType, null); default: throw EntityUtil.NotSupported(Strings.ProviderDoesNotSupportType(storeTypeName)); } Debug.Assert(newPrimitiveTypeKind == PrimitiveTypeKind.String || newPrimitiveTypeKind == PrimitiveTypeKind.Binary, "at this point only string and binary types should be present"); switch(newPrimitiveTypeKind) { case PrimitiveTypeKind.String: if (!isUnbounded) { return TypeUsage.CreateStringTypeUsage(edmPrimitiveType, isUnicode, isFixedLen, maxLength); } else { return TypeUsage.CreateStringTypeUsage(edmPrimitiveType, isUnicode, isFixedLen); } case PrimitiveTypeKind.Binary: if (!isUnbounded) { return TypeUsage.CreateBinaryTypeUsage(edmPrimitiveType, isFixedLen, maxLength); } else { return TypeUsage.CreateBinaryTypeUsage(edmPrimitiveType, isFixedLen); } default: throw EntityUtil.NotSupported(Strings.ProviderDoesNotSupportType(storeTypeName)); } } /// <summary> /// This method takes a type and a set of facets and returns the best mapped equivalent type /// in SQL Server, taking the store version into consideration. /// </summary> /// <param name="storeType">A TypeUsage encapsulating an EDM type and a set of facets</param> /// <returns>A TypeUsage encapsulating a store type and a set of facets</returns> public override TypeUsage GetStoreType(TypeUsage edmType) { EntityUtil.CheckArgumentNull<TypeUsage>(edmType, "edmType"); System.Diagnostics.Debug.Assert(edmType.EdmType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType); PrimitiveType primitiveType = edmType.EdmType as PrimitiveType; if (primitiveType == null) { throw EntityUtil.Argument(Strings.ProviderDoesNotSupportType(edmType.Identity)); } ReadOnlyMetadataCollection<Facet> facets = edmType.Facets; switch (primitiveType.PrimitiveTypeKind) { case PrimitiveTypeKind.Boolean: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bit"]); case PrimitiveTypeKind.Byte: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["tinyint"]); case PrimitiveTypeKind.Int16: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["smallint"]); case PrimitiveTypeKind.Int32: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["int"]); case PrimitiveTypeKind.Int64: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["bigint"]); case PrimitiveTypeKind.Geography: case PrimitiveTypeKind.GeographyPoint: case PrimitiveTypeKind.GeographyLineString: case PrimitiveTypeKind.GeographyPolygon: case PrimitiveTypeKind.GeographyMultiPoint: case PrimitiveTypeKind.GeographyMultiLineString: case PrimitiveTypeKind.GeographyMultiPolygon: case PrimitiveTypeKind.GeographyCollection: return GetStorePrimitiveTypeIfPostSql9("geography", edmType.Identity, primitiveType.PrimitiveTypeKind); case PrimitiveTypeKind.Geometry: case PrimitiveTypeKind.GeometryPoint: case PrimitiveTypeKind.GeometryLineString: case PrimitiveTypeKind.GeometryPolygon: case PrimitiveTypeKind.GeometryMultiPoint: case PrimitiveTypeKind.GeometryMultiLineString: case PrimitiveTypeKind.GeometryMultiPolygon: case PrimitiveTypeKind.GeometryCollection: return GetStorePrimitiveTypeIfPostSql9("geometry", edmType.Identity, primitiveType.PrimitiveTypeKind); case PrimitiveTypeKind.Guid: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["uniqueidentifier"]); case PrimitiveTypeKind.Double: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["float"]); case PrimitiveTypeKind.Single: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["real"]); case PrimitiveTypeKind.Decimal: // decimal, numeric, smallmoney, money { byte precision; if (!TypeHelpers.TryGetPrecision(edmType, out precision)) { precision = 18; } byte scale; if (!TypeHelpers.TryGetScale(edmType, out scale)) { scale = 0; } TypeUsage tu = TypeUsage.CreateDecimalTypeUsage(StoreTypeNameToStorePrimitiveType["decimal"], precision, scale); return tu; } case PrimitiveTypeKind.Binary: // binary, varbinary, varbinary(max), image, timestamp, rowversion { bool isFixedLength = null != facets[DbProviderManifest.FixedLengthFacetName].Value && (bool)facets[DbProviderManifest.FixedLengthFacetName].Value; Facet f = facets[DbProviderManifest.MaxLengthFacetName]; bool isMaxLength = Helper.IsUnboundedFacetValue(f) || null == f.Value || (int)f.Value > binaryMaxSize; int maxLength = !isMaxLength ? (int)f.Value : Int32.MinValue; TypeUsage tu; if (isFixedLength) { tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["binary"], true, (isMaxLength ? binaryMaxSize : maxLength)); } else { if (isMaxLength) { if (_version != SqlVersion.Sql8) { tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary(max)"], false); Debug.Assert(tu.Facets[DbProviderManifest.MaxLengthFacetName].Description.IsConstant, "varbinary(max) is not constant!"); } else { tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, binaryMaxSize); } } else { tu = TypeUsage.CreateBinaryTypeUsage(StoreTypeNameToStorePrimitiveType["varbinary"], false, maxLength); } } return tu; } case PrimitiveTypeKind.String: // char, nchar, varchar, nvarchar, varchar(max), nvarchar(max), ntext, text, xml { bool isUnicode = null == facets[DbProviderManifest.UnicodeFacetName].Value || (bool)facets[DbProviderManifest.UnicodeFacetName].Value; bool isFixedLength = null != facets[DbProviderManifest.FixedLengthFacetName].Value && (bool)facets[DbProviderManifest.FixedLengthFacetName].Value; Facet f = facets[DbProviderManifest.MaxLengthFacetName]; // maxlen is true if facet value is unbounded, the value is bigger than the limited string sizes *or* the facet // value is null. this is needed since functions still have maxlength facet value as null bool isMaxLength = Helper.IsUnboundedFacetValue(f) || null == f.Value || (int)f.Value > (isUnicode ? nvarcharMaxSize : varcharMaxSize); int maxLength = !isMaxLength ? (int)f.Value : Int32.MinValue; TypeUsage tu; if (isUnicode) { if (isFixedLength) { tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nchar"], true, true, (isMaxLength ? nvarcharMaxSize : maxLength)); } else { if (isMaxLength) { // nvarchar(max) (SQL 9) or ntext (SQL 8) if (_version != SqlVersion.Sql8) { tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar(max)"], true, false); Debug.Assert(tu.Facets[DbProviderManifest.MaxLengthFacetName].Description.IsConstant, "NVarchar(max) is not constant!"); } else { // if it is unknown, fallback to nvarchar[4000] instead of ntext since it has limited store semantics tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, nvarcharMaxSize); } } else { tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["nvarchar"], true, false, maxLength); } } } else // !isUnicode { if (isFixedLength) { tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["char"], false, true, (isMaxLength ? varcharMaxSize : maxLength)); } else { if (isMaxLength) { // nvarchar(max) (SQL 9) or ntext (SQL 8) if (_version != SqlVersion.Sql8) { tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar(max)"], false, false); Debug.Assert(tu.Facets[DbProviderManifest.MaxLengthFacetName].Description.IsConstant, "varchar(max) is not constant!"); } else { // if it is unknown, fallback to varchar[8000] instead of text since it has limited store semantics tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, varcharMaxSize); } } else { tu = TypeUsage.CreateStringTypeUsage(StoreTypeNameToStorePrimitiveType["varchar"], false, false, maxLength); } } } return tu; } case PrimitiveTypeKind.DateTime: return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType["datetime"]); case PrimitiveTypeKind.DateTimeOffset: return GetStorePrimitiveTypeIfPostSql9("datetimeoffset", edmType.Identity, primitiveType.PrimitiveTypeKind); case PrimitiveTypeKind.Time: return GetStorePrimitiveTypeIfPostSql9("time", edmType.Identity, primitiveType.PrimitiveTypeKind); default: throw EntityUtil.NotSupported(Strings.NoStoreTypeForEdmType(edmType.Identity, primitiveType.PrimitiveTypeKind)); } } private TypeUsage GetStorePrimitiveTypeIfPostSql9(string storeTypeName, string edmTypeIdentity, PrimitiveTypeKind primitiveTypeKind) { if ((this.SqlVersion != SqlVersion.Sql8) && (this.SqlVersion != SqlVersion.Sql9)) { return TypeUsage.CreateDefaultTypeUsage(StoreTypeNameToStorePrimitiveType[storeTypeName]); } else { throw EntityUtil.NotSupported(Strings.NoStoreTypeForEdmType(edmTypeIdentity, primitiveTypeKind)); } } /// <summary> /// Returns true, SqlClient supports escaping strings to be used as arguments to like /// The escape character is '~' /// </summary> /// <param name="escapeCharacter">The character '~'</param> /// <returns>True</returns> public override bool SupportsEscapingLikeArgument(out char escapeCharacter) { escapeCharacter = SqlProviderManifest.LikeEscapeChar; return true; } /// <summary> /// Escapes the wildcard characters and the escape character in the given argument. /// </summary> /// <param name="argument"></param> /// <returns>Equivalent to the argument, with the wildcard characters and the escape character escaped</returns> public override string EscapeLikeArgument(string argument) { EntityUtil.CheckArgumentNull(argument, "argument"); bool usedEscapeCharacter; return SqlProviderManifest.EscapeLikeText(argument, true, out usedEscapeCharacter); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using Tweetsharp; using Newtonsoft.Json; namespace TweetSharp { #if !Smartphone && !NET20 [DataContract] [DebuggerDisplay("{Type}:{Coordinates.Latitude},{Coordinates.Longitude}")] #endif [JsonObject(MemberSerialization.OptIn)] public class TwitterGeoLocation : PropertyChangedBase, IEquatable<TwitterGeoLocation>, ITwitterModel { /// <summary> /// The inner spatial coordinates for this location. /// </summary> public class GeoCoordinates { /// <summary> /// Gets or sets the latitude. /// </summary> /// <value>The latitude.</value> public virtual double Latitude { get; set; } /// <summary> /// Gets or sets the longitude. /// </summary> /// <value>The longitude.</value> public virtual double Longitude { get; set; } /// <summary> /// Performs an explicit conversion from <see cref="TwitterGeoLocation.GeoCoordinates"/> to array of <see cref="System.Double"/>. /// </summary> /// <param name="location">The location.</param> /// <returns>The result of the conversion.</returns> public static explicit operator double[](GeoCoordinates location) { return new[] { location.Latitude, location.Longitude }; } /// <summary> /// Performs an implicit conversion from <see cref="double"/> to <see cref="TwitterGeoLocation.GeoCoordinates"/>. /// </summary> /// <param name="values">The values.</param> /// <returns>The result of the conversion.</returns> public static implicit operator GeoCoordinates(List<double> values) { return FromEnumerable(values); } /// <summary> /// Performs an implicit conversion from array of <see cref="System.Double"/> to <see cref="TwitterGeoLocation.GeoCoordinates"/>. /// </summary> /// <param name="values">The values.</param> /// <returns>The result of the conversion.</returns> public static implicit operator GeoCoordinates(double[] values) { return FromEnumerable(values); } /// <summary> /// Froms the enumerable. /// </summary> /// <param name="values">The values.</param> /// <returns></returns> private static GeoCoordinates FromEnumerable(IEnumerable<double> values) { if (values == null) { throw new ArgumentNullException("values"); } var latitude = values.First(); var longitude = values.Skip(1).Take(1).Single(); return new GeoCoordinates { Latitude = latitude, Longitude = longitude }; } } private static readonly TwitterGeoLocation _none = new TwitterGeoLocation(); private GeoCoordinates _coordinates; private string _type; /// <summary> /// Initializes a new instance of the <see cref="TwitterGeoLocation"/> struct. /// </summary> /// <param name="latitude">The latitude.</param> /// <param name="longitude">The longitude.</param> public TwitterGeoLocation(double latitude, double longitude) { _coordinates = new GeoCoordinates { Latitude = latitude, Longitude = longitude }; } /// <summary> /// Initializes a new instance of the <see cref="TwitterGeoLocation"/> struct. /// </summary> public TwitterGeoLocation() { } /// <summary> /// Gets or sets the inner spatial coordinates. /// </summary> /// <value>The coordinates.</value> [JsonProperty("coordinates")] public virtual GeoCoordinates Coordinates { get { return _coordinates; } set { _coordinates = value; OnPropertyChanged("Coordinates"); } } /// <summary> /// Gets or sets the type of location. /// </summary> /// <value>The type.</value> [JsonProperty("type")] public virtual string Type { get { return _type; } set { _type = value; OnPropertyChanged("Type"); } } /// <summary> /// Gets an instance of <see cref="TwitterGeoLocation" /> /// that represents nowhere. /// </summary> /// <value>The none.</value> public static TwitterGeoLocation None { get { return _none; } } #region IEquatable<TwitterGeoLocation> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public virtual bool Equals(TwitterGeoLocation other) { if (ReferenceEquals(null, other)) { return false; } return other.Coordinates.Latitude == Coordinates.Latitude && other.Coordinates.Longitude == Coordinates.Longitude; } #endregion /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="instance">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object instance) { if (ReferenceEquals(null, instance)) { return false; } return instance.GetType() == typeof(TwitterGeoLocation) && Equals((TwitterGeoLocation)instance); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(TwitterGeoLocation left, TwitterGeoLocation right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(null, left)) { return false; } return left.Equals(right); } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left.</param> /// <param name="right">The right.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(TwitterGeoLocation left, TwitterGeoLocation right) { if (ReferenceEquals(left, right)) { return false; } if (ReferenceEquals(null, left)) { return true; } return !left.Equals(right); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { unchecked { return (Coordinates.Latitude.GetHashCode() * 397) ^ Coordinates.Longitude.GetHashCode(); } } public override string ToString() { return string.Format("{0},{1}", Coordinates.Latitude, Coordinates.Longitude); } #if !Smartphone && !NET20 [DataMember] #endif public virtual string RawSource { get; set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; namespace System.Globalization.CalendarsTests { // System.Globalization.TaiwanCalendar.ToDateTime(Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32) public class TaiwanCalendarToDateTime { #region Positive Tests // PosTest1: Verify the year is a random year [Fact] public void PosTest1() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era = 0; for (int i = 0; i < tc.Eras.Length; i++) { era = tc.Eras[i]; DateTime dt = tc.ToDateTime(year, month, day, hour, minute, second, milliSecond); DateTime desiredDT = new DateTime(year + 1911, month, day, hour, minute, second, milliSecond); Assert.Equal(desiredDT, dt); } } // PosTest2: Verify the DateTime is 8088-12-31 23:59:29:999 [Fact] public void PosTest2() { System.Globalization.Calendar tc = new TaiwanCalendar(); int year = 8088; int month = 12; int day = 31; int hour = 23; int minute = 59; int second = 59; int milliSecond = 999; int era; for (int i = 0; i < tc.Eras.Length; i++) { era = tc.Eras[i]; DateTime dt = tc.ToDateTime(year, month, day, hour, minute, second, milliSecond); DateTime desireDT = new DateTime(year + 1911, month, day, hour, minute, second, milliSecond); Assert.Equal(desireDT, dt); } } // PosTest3: Verify the DateTime is TaiwanCalendar MinSupportedDateTime [Fact] public void PosTest3() { System.Globalization.Calendar tc = new TaiwanCalendar(); DateTime minDT = tc.MinSupportedDateTime; int year = 1; int month = 1; int day = 1; int hour = 0; int minute = 0; int second = 0; int milliSecond = 0; int era; for (int i = 0; i < tc.Eras.Length; i++) { era = tc.Eras[i]; DateTime dt = tc.ToDateTime(year, month, day, hour, minute, second, milliSecond); Assert.Equal(minDT, dt); } } #endregion #region Negative Tests // NegTest1: The year outside the range supported by the TaiwanCalendar [Fact] public void NegTest1() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MaxSupportedDateTime.Year - 1910, Int32.MaxValue); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); year = rand.Next(Int32.MinValue, tc.MinSupportedDateTime.Year); era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest2: The month outside the range supported by the TaiwanCalendar [Fact] public void NegTest2() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(Int32.MinValue, 1); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); month = rand.Next(13, Int32.MaxValue); era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest3: The day outside the range supported by the TaiwanCalendar [Fact] public void NegTest3() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(Int32.MinValue, 1); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); day = rand.Next(tc.GetDaysInMonth(year, month, era) + 1, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest4: The hour is less than zero or greater than 23 [Fact] public void NegTest4() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(Int32.MinValue, 0); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); hour = rand.Next(24, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest5: The minute is less than zero or greater than 59 [Fact] public void NegTest5() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(Int32.MinValue, 0); int second = rand.Next(0, 60); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); //minute greater than 59; minute = rand.Next(60, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest6: The second is less than zero or greater than 59 [Fact] public void NegTest6() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(Int32.MinValue, 0); int milliSecond = rand.Next(0, 1000); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); //second greater than 59; second = rand.Next(60, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } // NegTest7: The milliSecond is less than zero or greater than 999 [Fact] public void NegTest7() { System.Globalization.Calendar tc = new TaiwanCalendar(); Random rand = new Random(-55); int year = rand.Next(tc.MinSupportedDateTime.Year, tc.MaxSupportedDateTime.Year - 1911); int month = rand.Next(1, 13); int day = rand.Next(1, 29); int hour = rand.Next(0, 24); int minute = rand.Next(0, 60); int second = rand.Next(0, 60); int milliSecond = rand.Next(Int32.MinValue, 0); int era; era = tc.Eras[0]; Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); //milliSecond greater than 999; second = rand.Next(1000, Int32.MaxValue); Assert.Throws<ArgumentOutOfRangeException>(() => { tc.ToDateTime(year, month, day, hour, minute, second, milliSecond, era); }); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Microsoft.Extensions.CommandLineUtils; using NuGet.Common; using NuGet.Configuration; using NuGet.Packaging; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using NuGet.Versioning; namespace PackageBaselineGenerator { /// <summary> /// This generates Baseline.props with information about the last RTM release. /// </summary> class Program : CommandLineApplication { static void Main(string[] args) { new Program().Execute(args); } private readonly CommandOption _sources; private readonly CommandOption _output; private readonly CommandOption _update; private static readonly string[] _defaultSources = new string[] { "https://api.nuget.org/v3/index.json" }; public Program() { _sources = Option( "-s|--package-sources <Sources>", "The NuGet source(s) of packages to fetch", CommandOptionType.MultipleValue); _output = Option("-o|--output <OUT>", "The generated file output path", CommandOptionType.SingleValue); _update = Option("-u|--update", "Regenerate the input (Baseline.xml) file.", CommandOptionType.NoValue); Invoke = () => Run().GetAwaiter().GetResult(); } private async Task<int> Run() { if (_output.HasValue() && _update.HasValue()) { await Error.WriteLineAsync("'--output' and '--update' options must not be used together."); return 1; } var inputPath = Path.Combine(Directory.GetCurrentDirectory(), "Baseline.xml"); var input = XDocument.Load(inputPath); var sources = _sources.HasValue() ? _sources.Values.Select(s => s.TrimEnd('/')) : _defaultSources; var packageSources = sources.Select(s => new PackageSource(s)); var providers = Repository.Provider.GetCoreV3(); // Get v2 and v3 API support var sourceRepositories = packageSources.Select(ps => new SourceRepository(ps, providers)); if (_update.HasValue()) { var updateResult = await RunUpdateAsync(inputPath, input, sourceRepositories); if (updateResult != 0) { return updateResult; } } List<(string packageBase, bool feedV3)> packageBases = new List<(string, bool)>(); foreach (var sourceRepository in sourceRepositories) { var feedType = await sourceRepository.GetFeedType(CancellationToken.None); var feedV3 = feedType == FeedType.HttpV3; var packageBase = sourceRepository.PackageSource + "/package"; if (feedV3) { var resources = await sourceRepository.GetResourceAsync<ServiceIndexResourceV3>(); packageBase = resources.GetServiceEntryUri(ServiceTypes.PackageBaseAddress).ToString().TrimEnd('/'); } packageBases.Add((packageBase, feedV3)); } var output = _output.HasValue() ? _output.Value() : Path.Combine(Directory.GetCurrentDirectory(), "Baseline.Designer.props"); var packageCache = Environment.GetEnvironmentVariable("NUGET_PACKAGES") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".nuget", "packages"); var tempDir = Path.Combine(Directory.GetCurrentDirectory(), "obj", "tmp"); Directory.CreateDirectory(tempDir); var baselineVersion = input.Root.Attribute("Version").Value; // Baseline and .NET Core versions always align in non-preview releases. var parsedVersion = Version.Parse(baselineVersion); var defaultTarget = ((parsedVersion.Major < 5) ? "netcoreapp" : "net") + $"{parsedVersion.Major}.{parsedVersion.Minor}"; var doc = new XDocument( new XComment(" Auto generated. Do not edit manually, use eng/tools/BaselineGenerator/ to recreate. "), new XElement("Project", new XElement("PropertyGroup", new XElement("MSBuildAllProjects", "$(MSBuildAllProjects);$(MSBuildThisFileFullPath)"), new XElement("AspNetCoreBaselineVersion", baselineVersion)))); var client = new HttpClient(); foreach (var pkg in input.Root.Descendants("Package")) { var id = pkg.Attribute("Id").Value; var version = pkg.Attribute("Version").Value; var packageFileName = $"{id}.{version}.nupkg"; var nupkgPath = Path.Combine(packageCache, id.ToLowerInvariant(), version, packageFileName); if (!File.Exists(nupkgPath)) { nupkgPath = Path.Combine(tempDir, packageFileName); } if (!File.Exists(nupkgPath)) { foreach ((string packageBase, bool feedV3) in packageBases) { var url = feedV3 ? $"{packageBase}/{id.ToLowerInvariant()}/{version}/{id.ToLowerInvariant()}.{version}.nupkg" : $"{packageBase}/{id}/{version}"; Console.WriteLine($"Downloading {url}"); try { using (var response = await client.GetStreamAsync(url)) { using (var file = File.Create(nupkgPath)) { await response.CopyToAsync(file); } } } catch (HttpRequestException e) when (e.StatusCode == System.Net.HttpStatusCode.NotFound) { // If it's not found, continue onto the next one. continue; } } if (!File.Exists(nupkgPath)) { throw new Exception($"Could not download package {id} @ {version} using any input feed"); } } using (var reader = new PackageArchiveReader(nupkgPath)) { doc.Root.Add(new XComment($" Package: {id}")); var propertyGroup = new XElement( "PropertyGroup", new XAttribute("Condition", $" '$(PackageId)' == '{id}' "), new XElement("BaselinePackageVersion", version)); doc.Root.Add(propertyGroup); foreach (var group in reader.NuspecReader.GetDependencyGroups()) { // Don't bother generating empty ItemGroup elements. if (!group.Packages.Any()) { continue; } // Handle changes to $(DefaultNetCoreTargetFramework) even if some projects are held back. var targetCondition = $"'$(TargetFramework)' == '{group.TargetFramework.GetShortFolderName()}'"; if (string.Equals( group.TargetFramework.GetShortFolderName(), defaultTarget, StringComparison.OrdinalIgnoreCase)) { targetCondition = $"('$(TargetFramework)' == '$(DefaultNetCoreTargetFramework)' OR '$(TargetFramework)' == '{defaultTarget}')"; } var itemGroup = new XElement( "ItemGroup", new XAttribute("Condition", $" '$(PackageId)' == '{id}' AND {targetCondition} ")); doc.Root.Add(itemGroup); foreach (var dependency in group.Packages) { itemGroup.Add( new XElement("BaselinePackageReference", new XAttribute("Include", dependency.Id), new XAttribute("Version", dependency.VersionRange.ToString()))); } } } } var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Encoding = Encoding.UTF8, Indent = true, }; using (var writer = XmlWriter.Create(output, settings)) { doc.Save(writer); } Console.WriteLine($"Generated file in {output}"); return 0; } private async Task<int> RunUpdateAsync( string documentPath, XDocument document, IEnumerable<SourceRepository> sourceRepositories) { var packageMetadataResources = await Task.WhenAll(sourceRepositories.Select(async sr => await sr.GetResourceAsync<PackageMetadataResource>())); var logger = new Logger(Error, Out); var hasChanged = false; using (var cacheContext = new SourceCacheContext { NoCache = true }) { var versionAttribute = document.Root.Attribute("Version"); hasChanged = await TryUpdateVersionAsync( versionAttribute, "Microsoft.AspNetCore.App.Runtime.win-x64", packageMetadataResources, logger, cacheContext); foreach (var package in document.Root.Descendants("Package")) { var id = package.Attribute("Id").Value; versionAttribute = package.Attribute("Version"); var attributeChanged = await TryUpdateVersionAsync( versionAttribute, id, packageMetadataResources, logger, cacheContext); hasChanged |= attributeChanged; } } if (hasChanged) { await Out.WriteLineAsync($"Updating {documentPath}."); var settings = new XmlWriterSettings { Async = true, CheckCharacters = true, CloseOutput = false, Encoding = Encoding.UTF8, Indent = true, IndentChars = " ", NewLineOnAttributes = false, OmitXmlDeclaration = true, WriteEndDocumentOnClose = true, }; using (var stream = File.OpenWrite(documentPath)) { using (var writer = XmlWriter.Create(stream, settings)) { await document.SaveAsync(writer, CancellationToken.None); } } } else { await Out.WriteLineAsync("No new versions found"); } return 0; } private static async Task<bool> TryUpdateVersionAsync( XAttribute versionAttribute, string packageId, IEnumerable<PackageMetadataResource> packageMetadataResources, ILogger logger, SourceCacheContext cacheContext) { var currentVersion = NuGetVersion.Parse(versionAttribute.Value); var versionRange = new VersionRange( currentVersion, new FloatRange(NuGetVersionFloatBehavior.Patch, currentVersion)); var searchMetadatas = await Task.WhenAll( packageMetadataResources.Select(async pmr => await pmr.GetMetadataAsync( packageId, includePrerelease: false, includeUnlisted: true, // Microsoft.AspNetCore.DataOrotection.Redis package is not listed. sourceCacheContext: cacheContext, log: logger, token: CancellationToken.None))); // Find the latest version among each search metadata NuGetVersion latestVersion = null; foreach (var searchMetadata in searchMetadatas) { var potentialLatestVersion = versionRange.FindBestMatch( searchMetadata.Select(metadata => metadata.Identity.Version)); if (latestVersion == null || (potentialLatestVersion != null && potentialLatestVersion.CompareTo(latestVersion) > 0)) { latestVersion = potentialLatestVersion; } } if (latestVersion == null) { logger.LogWarning($"Unable to find latest version of '{packageId}'."); return false; } var hasChanged = false; if (latestVersion != currentVersion) { hasChanged = true; versionAttribute.Value = latestVersion.ToNormalizedString(); } return hasChanged; } private class Logger : ILogger { private readonly TextWriter _error; private readonly TextWriter _out; public Logger(TextWriter error, TextWriter @out) { _error = error; _out = @out; } public void Log(LogLevel level, string data) { switch (level) { case LogLevel.Debug: LogDebug(data); break; case LogLevel.Error: LogError(data); break; case LogLevel.Information: LogInformation(data); break; case LogLevel.Minimal: LogMinimal(data); break; case LogLevel.Verbose: LogVerbose(data); break; case LogLevel.Warning: LogWarning(data); break; } } public void Log(ILogMessage message) => Log(message.Level, message.Message); public Task LogAsync(LogLevel level, string data) { Log(level, data); return Task.CompletedTask; } public Task LogAsync(ILogMessage message) => LogAsync(message.Level, message.Message); public void LogDebug(string data) => _out.WriteLine($"Debug: {data}"); public void LogError(string data) => _error.WriteLine($"Error: {data}"); public void LogInformation(string data) => _out.WriteLine($"Information: {data}"); public void LogInformationSummary(string data) => _out.WriteLine($"Summary: {data}"); public void LogMinimal(string data) => _out.WriteLine($"Minimal: {data}"); public void LogVerbose(string data) => _out.WriteLine($"Verbose: {data}"); public void LogWarning(string data) => _out.WriteLine($"Warning: {data}"); } } }
using NetApp.Tests.Helpers; using Microsoft.Azure.Management.NetApp; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Xunit; using System; using System.Collections.Generic; using Microsoft.Azure.Management.NetApp.Models; using Microsoft.Rest.Azure; using Newtonsoft.Json; using System.Threading; namespace NetApp.Tests.ResourceTests { public class ANFBackupPolicyTests : TestBase { private const int delay = 5000; [Fact] public void CreateDeleteBackupPolicy() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); //create account ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // create the backupPolicy var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1); var backupPoliciesBefore = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy); // check backupPolicy exists var backupPolciesBefore = netAppMgmtClient.BackupPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1); Assert.Single(backupPolciesBefore); var resultBackupPolicy = netAppMgmtClient.BackupPolicies.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName1}", resultBackupPolicy.Name); // delete the backupPolicy and check again netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } var backupPoliciesAfter = netAppMgmtClient.BackupPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1); Assert.Empty(backupPoliciesAfter); // cleanup - remove the resources netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); } } [Fact] public void ListBackupPolices() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1); // create two backupPolicies under same account var backupPolicy1 = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1); var backupPolicy2 = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName2); var resultbackupPolicy1 = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy1); var resultbackupPolicy2 = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName2, backupPolicy2); // get the backupPolicy list and check var backupPolicies = netAppMgmtClient.BackupPolicies.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1); Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName1}", backupPolicies.ElementAt(0).Name ); Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName2}", backupPolicies.ElementAt(1).Name); Assert.Equal(2, backupPolicies.Count()); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // clean up netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName2); ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); } } [Fact] public void GetBackupPolicyByName() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); //Create account ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1); var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1); // create the backupPolicy var createBackupPolicy = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy); var resultBackupPolicy = netAppMgmtClient.BackupPolicies.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); Assert.Equal($"{ResourceUtils.volumeBackupAccountName1}/{ResourceUtils.backupPolicyName1}", resultBackupPolicy.Name); Assert.Equal(createBackupPolicy.Name, resultBackupPolicy.Name); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // cleanup - remove the resources netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); ResourceUtils.DeletePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); } } [Fact(Skip ="BackupPolicy service side bug causes this to fail, re-enable when fixed")] //[Fact] public void CreateVolumeWithBackupPolicy() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the Pool and account ResourceUtils.CreatePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1, location: ResourceUtils.backupLocation); // create the backupPolicy var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1); var createBackupPolicy = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy); //Get vault var vaultsList = netAppMgmtClient.Vaults.List(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1); Assert.NotEmpty(vaultsList); string vaultID = vaultsList.ElementAt(0).Id; if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // Create volume //var createVolume = ResourceUtils.CreateBackedupVolume(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName:ResourceUtils.volumeBackupAccountName1, vnet: ResourceUtils.backupVnet, backupPolicyId: null, backupVaultId: vaultID); var createVolume = ResourceUtils.CreateVolume(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1, volumeName: ResourceUtils.backupVolumeName1, vnet: ResourceUtils.backupVnet, volumeOnly: true); Assert.Equal("Succeeded", createVolume.ProvisioningState); //Get volume and check if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } var createGetVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1); Assert.Equal("Succeeded", createGetVolume.ProvisioningState); // Now try and modify the backuppolicy var patchBackupPolicy = new BackupPolicyPatch() { DailyBackupsToKeep = 1 }; var resultbackupPolicy = netAppMgmtClient.BackupPolicies.Update(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, patchBackupPolicy); //check volume again createGetVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1); Assert.Equal("Succeeded", createGetVolume.ProvisioningState); // Now try and set dataprotection on the volume var dataProtection = new VolumePatchPropertiesDataProtection { Backup = new VolumeBackupProperties {PolicyEnforced = true, BackupEnabled = true, BackupPolicyId = createBackupPolicy.Id, VaultId = vaultID } }; var volumePatch = new VolumePatch() { DataProtection = dataProtection }; // patch and enable backups var updatedVolume = netAppMgmtClient.Volumes.Update(volumePatch, ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1); //Get volume and check if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } var getVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1); Assert.NotNull(getVolume.DataProtection); Assert.NotNull(getVolume.DataProtection.Backup); Assert.NotNull(getVolume.DataProtection.Backup.BackupPolicyId); Assert.Equal(createBackupPolicy.Id, getVolume.DataProtection.Backup.BackupPolicyId); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // Try and disable backups var disableDataProtection = new VolumePatchPropertiesDataProtection { Backup = new VolumeBackupProperties { BackupEnabled = false, VaultId = vaultID } }; var disableVolumePatch = new VolumePatch() { DataProtection = disableDataProtection }; // patch var disabledBackupVolume = netAppMgmtClient.Volumes.Update(disableVolumePatch, ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } var getDisabledVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.poolName1, ResourceUtils.backupVolumeName1); //check Assert.NotNull(getDisabledVolume.DataProtection); Assert.NotNull(getDisabledVolume.DataProtection.Backup); Assert.False(getDisabledVolume.DataProtection.Backup.BackupEnabled); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // clean up ResourceUtils.DeleteVolume(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1, volumeName: ResourceUtils.backupVolumeName1); netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); ResourceUtils.DeletePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); } } [Fact] public void PatchBackupPolicy() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); //Create acccount ResourceUtils.CreateAccount(netAppMgmtClient, location: ResourceUtils.backupLocation, accountName: ResourceUtils.volumeBackupAccountName1); //create the backupPolicy var backupPolicy = CreateBackupPolicy(ResourceUtils.backupLocation, ResourceUtils.backupPolicyName1); var createBackupPolicy = netAppMgmtClient.BackupPolicies.Create(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, backupPolicy); // Now try and modify it var patchBackupPolicy = new BackupPolicyPatch() { DailyBackupsToKeep = 1 }; var resultbackupPolicy = netAppMgmtClient.BackupPolicies.Update(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1, patchBackupPolicy); Assert.NotNull(resultbackupPolicy); Assert.NotNull(resultbackupPolicy.DailyBackupsToKeep); Assert.Equal(patchBackupPolicy.DailyBackupsToKeep, resultbackupPolicy.DailyBackupsToKeep); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); } // cleanup netAppMgmtClient.BackupPolicies.Delete(ResourceUtils.resourceGroup, ResourceUtils.volumeBackupAccountName1, ResourceUtils.backupPolicyName1); ResourceUtils.DeletePool(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.volumeBackupAccountName1); } } private static BackupPolicy CreateBackupPolicy(string location , string name = "") { // Create basic policy records with a selection of data BackupPolicy testBackupPolicy = new BackupPolicy(location: location, name: name) { Enabled = true, DailyBackupsToKeep = 4, WeeklyBackupsToKeep = 3, MonthlyBackupsToKeep = 2, YearlyBackupsToKeep = 1 }; return testBackupPolicy; } private static string GetSessionsDirectoryPath() { string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.ANFBackupPolicyTests).GetTypeInfo().Assembly.Location; return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords"); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.VisualStudio.Editors.PropertyPages { using EnvDTE; using Microsoft.Win32; using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters; using System.Windows.Forms.ComponentModel.Com2Interop; using System.Windows.Forms.Design; public sealed class AutomationExtenderManager { private static string extenderPropName = "ExtenderCATID"; private ObjectExtenders extensionMgr = null; internal AutomationExtenderManager(ObjectExtenders oe) { this.extensionMgr = oe; } public static AutomationExtenderManager GetAutomationExtenderManager(IServiceProvider sp) { return new AutomationExtenderManager((ObjectExtenders)sp.GetService(typeof(ObjectExtenders))); } public bool GetAllExtenders(object[] selectedObjects, ArrayList allExtenders) { Hashtable[] extenderList = null; bool nullListFound = false; return GetAllExtenders(selectedObjects, allExtenders, ref extenderList, ref nullListFound); } public bool GetAllExtenders(object[] selectedObjects, ArrayList allExtenders, ref Hashtable[] extenderList, ref bool nullListFound) { // 1 : handle intrinsic extensions string catID = null; // do the intersection of intrinsic extensions for (int i = 0; i < selectedObjects.Length; i++) { string id = GetCatID(selectedObjects[i]); // make sure this value is equal to // all the others. // if (catID == null && i == 0) { catID = id; } else if (catID == null || !catID.Equals(id)) { catID = null; break; } } // okay, now we've got a common catID, get the names of each extender for each object for it // here is also where we'll pickup the contextual extenders // // ask the extension manager for any contextual IDs string[] contextualCATIDs = GetContextualCatIDs(extensionMgr); // if we didn't get an intersection and we didn't get any contextual // extenders, quit! // if ((contextualCATIDs == null || contextualCATIDs.Length == 0) && catID == null) { return false; } extenderList = new Hashtable[selectedObjects.Length]; int firstWithItems = -1; // right, here we go; build up the mappings from extender names to extensions // for (int i = 0; i < selectedObjects.Length;i++) { // NOTE: this doesn't actually replace extenderList[i], it // just adds items to it and returns a new one if one didn't // get passed in. So it is possible to get extenders from both // the catID and the contextualCATID. // if (catID != null) { extenderList[i] = GetExtenders(extensionMgr, catID, selectedObjects[i], extenderList[i]); } if (contextualCATIDs != null) { for (int c = 0; c < contextualCATIDs.Length; c++) { extenderList[i] = GetExtenders(extensionMgr, contextualCATIDs[c], selectedObjects[i], extenderList[i]); } } // did we create items for the first time? // if (firstWithItems == -1 && extenderList[i] != null && extenderList[i].Count > 0) { firstWithItems = i; } // make sure the first one has items, otherwise // we can't do an intersection, so quit // if (i == 0 && firstWithItems == -1) { break; } } // the very first item must have extenders or we can skip the merge too // if (firstWithItems == 0) { // now we've gotta merge the extender names to get the common ones... // so we just walk through the list of the first one and see if all // the others have the values... string[] hashKeys = new string[extenderList[0].Keys.Count]; extenderList[0].Keys.CopyTo(hashKeys, 0); nullListFound = false; // walk through all the others looking for the common items. for (int n = 0; !nullListFound && n < hashKeys.Length; n++) { bool found = true; string name = (string)hashKeys[n]; // add it to the total list allExtenders.Add(extenderList[0][name]); // walk through all the extender lists looking for // and item of this name. If one doesn't have it, // we remove it from all the lists, but continue // to walk through because we need to // add all of the extenders to the global list // for the IFilterProperties walk below // for (int i = 1; i < extenderList.Length; i++) { // if we find a null list, quit if (extenderList[i] == null || extenderList[i].Count == 0) { nullListFound = true; break; } object extender = extenderList[i][name]; // do we have this item? if (found) { found &= (extender != null); } // add it to the total list allExtenders.Add(extender); // if we don't find it, remove it from this list // if (!found) { // If this item is in the // middle of the list, do we need to go back // through and remove it from the prior lists? // extenderList[i].Remove(name); } } // if we don't find it, remove it from the list // if (!found) { object extenderItem = extenderList[0][name]; extenderList[0].Remove(name); } } } return true; } public object[] GetExtendedObjects(object[] selectedObjects) { // INTENTIONAL CHANGE from VSIP version of AutomationExtenderManager.cs: internal to public if (extensionMgr == null || selectedObjects == null || selectedObjects.Length == 0) { return selectedObjects; } Hashtable[] extenderList = null; ArrayList allExtenders = new ArrayList(); bool fail = false; if (!GetAllExtenders(selectedObjects, allExtenders, ref extenderList, ref fail)) return selectedObjects; // do the IFilterProperties stuff // here we walk through all the items and apply I filter properites... // 1: do the used items // 2: do the discarded items. // // this makes me queasy just thinking about it. // IEnumerator extEnum = allExtenders.GetEnumerator(); Hashtable modifiedObjects = new Hashtable(); while (extEnum.MoveNext()) { object extender = extEnum.Current; IFilterProperties dteFilter = extender as IFilterProperties; AutomationExtMgr_IFilterProperties privateFilter = extender as AutomationExtMgr_IFilterProperties; Debug.Assert(privateFilter == null || dteFilter != null, "How did we get a private filter but no public DTE filter?"); if (dteFilter != null) { vsFilterProperties filter; // ugh, walk through all the properties of all the objects // and see if this guy would like to filter them // icky and n^2, but that's the spec... // for (int x = 0; x < selectedObjects.Length; x++) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(selectedObjects[x], new Attribute[0]); // INTENTIONAL CHANGE from VSIP version of AutomationExtenderManager.cs: passing in empty Attribute array instead of {BrowsableAttribute.Yes} - see comments at beginning props.Sort(); for (int p = 0; p < props.Count; p++) { filter = vsFilterProperties.vsFilterPropertiesNone; if (privateFilter != null) { if (VSConstants.S_OK != privateFilter.IsPropertyHidden(props[p].Name, out filter)) { filter = vsFilterProperties.vsFilterPropertiesNone; } } else { filter = dteFilter.IsPropertyHidden(props[p].Name); } FilteredObjectWrapper filteredObject = (FilteredObjectWrapper)modifiedObjects[selectedObjects[x]]; if (filteredObject == null) { filteredObject = new FilteredObjectWrapper(selectedObjects[x]); modifiedObjects[selectedObjects[x]] = filteredObject; } switch (filter) { case vsFilterProperties.vsFilterPropertiesAll: filteredObject.FilterProperty(props[p], BrowsableAttribute.No); break; case vsFilterProperties.vsFilterPropertiesSet: filteredObject.FilterProperty(props[p], ReadOnlyAttribute.Yes); break; } } } } } // finally, wrap any extended objects in extender proxies for browsing... // bool applyExtenders = extenderList[0].Count > 0 && !fail; if (modifiedObjects.Count > 0 || applyExtenders) { // create the return array selectedObjects = (object[])selectedObjects.Clone(); Dictionary<object, ExtendedObjectWrapper> objectsWrapperCollection = new Dictionary<object, ExtendedObjectWrapper>(); for (int i = 0; i < selectedObjects.Length; i++) { object originalObj = selectedObjects[i]; object obj = modifiedObjects[originalObj]; if (obj == null) { if (applyExtenders) { obj = originalObj; } else { continue; } } selectedObjects[i] = new ExtendedObjectWrapper(obj, extenderList[i], objectsWrapperCollection, originalObj); } } // phewwwy, done! return selectedObjects; } private static string GetCatID(object component) { // 1 : handle intrinsic extensions string catID = null; if (Marshal.IsComObject(component)) { bool success = false; Type descriptorType = Type.GetType("System.Windows.Forms.ComponentModel.Com2Interop.ComNativeDescriptor, " + typeof(System.Windows.Forms.Form).Assembly.FullName); Debug.Assert(descriptorType != null, "No comnative descriptor; we can't get native property values"); if (descriptorType != null) { MethodInfo getPropertyValue = descriptorType.GetMethod("GetNativePropertyValue", BindingFlags.Static | BindingFlags.Public); Debug.Assert(getPropertyValue != null, "Unable to find GetNativePropertyValue on ComNativeDescriptor"); if (getPropertyValue != null) { object[] args = new object[] {component, extenderPropName, success}; catID = (string)getPropertyValue.Invoke(null, args); success = (bool)args[2]; } } } else { PropertyInfo propCatID = TypeDescriptor.GetReflectionType(component).GetProperty(extenderPropName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty); if (propCatID != null) { object[] tempIndex = null; catID = (string)propCatID.GetValue(component, tempIndex); } } if (catID != null && catID.Length > 0) { try { // is this a vaild catID string? Guid g = new Guid(catID); } catch (FormatException) { Debug.Fail("'" + catID + "' is not a valid CatID (GUID) string"); catID = null; } } else { catID = null; } return catID; } private static string[] GetContextualCatIDs(ObjectExtenders extensionMgr) { string[] catIds = null; try { Object obj = extensionMgr.GetContextualExtenderCATIDs(); #if DEBUG string vType = obj.GetType().FullName; #endif if (obj.GetType().IsArray) { Array catIDArray = (Array)obj; if (typeof(string).IsAssignableFrom(catIDArray.GetType().GetElementType())) { catIds = (string[])catIDArray; } } } catch { } return catIds; } private static string[] GetExtenderNames(ObjectExtenders extensionMgr, string catID, object extendee) { if (extensionMgr == null) { return new string[0]; } try { Object obj = extensionMgr.GetExtenderNames(catID, extendee); if (obj == null || Convert.IsDBNull(obj)) { return new string[0]; } if (obj is Array && typeof(string).IsAssignableFrom(obj.GetType().GetElementType())) { return(string[])((Array)obj); } } catch { return new string[0]; } return new string[0]; } private static Hashtable GetExtenders(ObjectExtenders extensionMgr, string catID, object extendee, Hashtable ht) { if (extensionMgr == null) { return null; } if (ht == null) { ht = new Hashtable(); } object pDisp = extendee; // generate the extender name list. string[] extenderNames = GetExtenderNames(extensionMgr, catID, pDisp); for (int i = 0; i < extenderNames.Length; i++) { try { object pDispExtender = extensionMgr.GetExtender(catID, extenderNames[i], pDisp); if (pDispExtender != null) { // we've got one, so add it to our list ht.Add(extenderNames[i], pDispExtender); } } catch { } } return ht; } } [ComImport, Guid("aade1f59-6ace-43d1-8fca-42af3a5c4f3c"),InterfaceTypeAttribute(ComInterfaceType.InterfaceIsDual)] internal interface AutomationExtMgr_IFilterProperties { [return: System.Runtime.InteropServices.MarshalAs(UnmanagedType.I4)] [PreserveSig] int IsPropertyHidden(string name, [Out]out vsFilterProperties propertyHidden); } internal class ExtendedObjectWrapper : ICustomTypeDescriptor { #if DEBUG private static int count = 0; private int identity; #endif private object baseObject; // a hash table hashed on property names, with a ExtenderItem of the property and the // object it belongs to. private Hashtable extenderList; private Dictionary<string, object> extenderDictionaryCorrected = new Dictionary<string, object>(); private Dictionary<object, ExtendedObjectWrapper> collection = null; internal ExtendedObjectWrapper(object baseObject, Hashtable extenderList, Dictionary<object, ExtendedObjectWrapper> collection, object originalBaseObject) { #if DEBUG this.identity = ++count; #endif this.baseObject = baseObject; this.collection = collection != null ? collection : new Dictionary<object, ExtendedObjectWrapper>(); this.extenderList = CreateExtendedProperties(extenderList); this.collection[originalBaseObject] = this; } /// <devdoc> /// Creates the extended descriptors for an object given a list of extenders /// and property names. /// </devdoc> private Hashtable CreateExtendedProperties(Hashtable extenderList) { string[] keys = new string[extenderList.Keys.Count]; extenderList.Keys.CopyTo(keys, 0); Hashtable extenders = new Hashtable(); for (int i = 0; i < keys.Length; i++) { string name = keys[i]; object extender = extenderList[name]; this.extenderDictionaryCorrected[name] = extender; PropertyDescriptorCollection props = TypeDescriptor.GetProperties(extender, new Attribute[0]); // INTENTIONAL CHANGE from VSIP version of AutomationExtenderManager.cs: passing in empty Attribute array instead of {BrowsableAttribute.Yes} - see comments at beginning props.Sort(); if (props != null) { for (int p = 0; p < props.Count; p++) { #if DEBUG string pname = props[p].Name; Debug.Assert(extenders[pname] == null, "multiple extenders of name '" + pname + "' detected"); #endif extenders[props[p].Name] = new ExtenderItem(props[p], extender, this, name); } } } return extenders; } /// <devdoc> /// Retrieves an array of member attributes for the given object. /// </devdoc> AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(baseObject); } /// <devdoc> /// Retrieves the class name for this object. If null is returned, /// the type name is used. /// </devdoc> string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(baseObject); } /// <devdoc> /// Retrieves the name for this object. If null is returned, /// the default is used. /// </devdoc> string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(baseObject); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(baseObject); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(baseObject); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(baseObject, editorBaseType); } /// <devdoc> /// Retrieves an array of events that the given component instance /// provides. This may differ from the set of events the class /// provides. If the component is sited, the site may add or remove /// additional events. /// </devdoc> EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(baseObject); } /// <devdoc> /// Retrieves an array of events that the given component instance /// provides. This may differ from the set of events the class /// provides. If the component is sited, the site may add or remove /// additional events. The returned array of events will be /// filtered by the given set of attributes. /// </devdoc> EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(baseObject, attributes); } /// <devdoc> /// Retrieves an array of properties that the given component instance /// provides. This may differ from the set of properties the class /// provides. If the component is sited, the site may add or remove /// additional properties. /// </devdoc> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]); } /// <devdoc> /// Retrieves an array of properties that the given component instance /// provides. This may differ from the set of properties the class /// provides. If the component is sited, the site may add or remove /// additional properties. The returned array of properties will be /// filtered by the given set of attributes. /// </devdoc> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection baseProps = TypeDescriptor.GetProperties(baseObject, attributes); PropertyDescriptor[] extProps = new PropertyDescriptor[extenderList.Count]; IEnumerator propEnum = extenderList.Values.GetEnumerator(); int count = 0; while (propEnum.MoveNext()) { PropertyDescriptor pd = (PropertyDescriptor)propEnum.Current; if (pd.Attributes.Contains(attributes)) { extProps[count++] = pd; } } PropertyDescriptor[] allProps = new PropertyDescriptor[baseProps.Count + count]; baseProps.CopyTo(allProps, 0); Array.Copy(extProps, 0, allProps, baseProps.Count, count); return new PropertyDescriptorCollection(allProps); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { if (pd != null) { ExtenderItem item = (ExtenderItem)extenderList[pd.Name]; if (item != null && (pd == item.property || pd == item)) { return item.extender; } } object unwrappedObject = baseObject; while (unwrappedObject is ICustomTypeDescriptor) { object lastObj = unwrappedObject; unwrappedObject = ((ICustomTypeDescriptor)unwrappedObject).GetPropertyOwner(pd); if (lastObj == unwrappedObject) { break; } } return unwrappedObject; } internal object GetCorrectExtender(object extender, string propertyKey, object component) { ExtendedObjectWrapper correctWrapper = this; if (component != null) { if (component is ExtendedObjectWrapper) { correctWrapper = component as ExtendedObjectWrapper; if (correctWrapper == null) { correctWrapper = this; } } else { if (!collection.TryGetValue(component, out correctWrapper) || correctWrapper == null) { correctWrapper = this; } } } object correctExtender = extender; if (correctWrapper != null && (!correctWrapper.extenderDictionaryCorrected.TryGetValue(propertyKey, out correctExtender) || correctExtender == null)) { correctExtender = extender; } return correctExtender; } private class ExtenderItem : PropertyDescriptor { internal readonly PropertyDescriptor property; internal readonly object extender; internal ExtendedObjectWrapper owner; internal string propertyKey; internal ExtenderItem(PropertyDescriptor prop, object extenderObject, ExtendedObjectWrapper owner, string propertyKey) : base(prop) { Debug.Assert(prop != null, "Null property passed to ExtenderItem"); Debug.Assert(extenderObject != null, "Null extenderObject passed to ExtenderItem"); this.property = prop; this.extender = extenderObject; this.owner = owner; this.propertyKey = propertyKey; } internal object CorrectExtender(object component) { return owner.GetCorrectExtender(extender, propertyKey, component); } public override Type ComponentType { get { return property.ComponentType; } } public override TypeConverter Converter { get { return property.Converter; } } public override bool IsLocalizable { get { return property.IsLocalizable; } } public override bool IsReadOnly { get{ return property.IsReadOnly; } } public override Type PropertyType { get{ return property.PropertyType; } } public override bool CanResetValue(object component) { return property.CanResetValue(CorrectExtender(component)); } public override string DisplayName { get { return property.DisplayName; } } public override object GetEditor(Type editorBaseType) { return property.GetEditor(editorBaseType); } public override object GetValue(object component) { return property.GetValue(CorrectExtender(component)); } public override void ResetValue(object component) { property.ResetValue(CorrectExtender(component)); } public override void SetValue(object component, object value) { property.SetValue(CorrectExtender(component), value); } public override bool ShouldSerializeValue(object component) { return property.ShouldSerializeValue(CorrectExtender(component)); } // BEGIN INTENTIONAL CHANGES from VSIP version of AutomationExtenderManager.cs // Clients interested in receiving the ValueChanged // event through the ExtenderItem property descriptor subclass // need to have their request forwarded to the wrapped property, // which is where the change will actually take place and from // wheret the ValueChanged event will actually be fired. So we override // AddValueChanged and RemoveValueChanged. Note that // like SetValue, we pass in the extender as the component, ignoring // the component passed in. Otherwise the event would not fire properly. public override void AddValueChanged(object component, EventHandler handler) { property.AddValueChanged(CorrectExtender(component), handler); } public override void RemoveValueChanged(object component, EventHandler handler) { property.RemoveValueChanged(CorrectExtender(component), handler); } // END INTENTIONAL CHANGES } } internal class FilteredObjectWrapper : ICustomTypeDescriptor { private object baseObject; private Hashtable filteredProps; internal FilteredObjectWrapper(object baseObject) { this.baseObject = baseObject; this.filteredProps = new Hashtable(); } /// <devdoc> /// Filters the given property with the given member attribute. We only /// support filtering by adding a single attribute here. /// </devdoc> internal void FilterProperty(PropertyDescriptor prop, Attribute attr) { filteredProps[prop] = attr; } /// <devdoc> /// Retrieves an array of member attributes for the given object. /// </devdoc> AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(baseObject); } /// <devdoc> /// Retrieves the class name for this object. If null is returned, /// the type name is used. /// </devdoc> string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(baseObject); } /// <devdoc> /// Retrieves the name for this object. If null is returned, /// the default is used. /// </devdoc> string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(baseObject); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(baseObject); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty(baseObject); } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(baseObject, editorBaseType); } /// <devdoc> /// Retrieves an array of events that the given component instance /// provides. This may differ from the set of events the class /// provides. If the component is sited, the site may add or remove /// additional events. /// </devdoc> EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(baseObject); } /// <devdoc> /// Retrieves an array of events that the given component instance /// provides. This may differ from the set of events the class /// provides. If the component is sited, the site may add or remove /// additional events. The returned array of events will be /// filtered by the given set of attributes. /// </devdoc> EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(baseObject, attributes); } /// <devdoc> /// Retrieves an array of properties that the given component instance /// provides. This may differ from the set of properties the class /// provides. If the component is sited, the site may add or remove /// additional properties. /// </devdoc> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(new Attribute[0]); } /// <devdoc> /// Retrieves an array of properties that the given component instance /// provides. This may differ from the set of properties the class /// provides. If the component is sited, the site may add or remove /// additional properties. The returned array of properties will be /// filtered by the given set of attributes. /// </devdoc> PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection baseProps = TypeDescriptor.GetProperties(baseObject, attributes); if (filteredProps.Keys.Count > 0) { ArrayList propList = new ArrayList(); foreach (PropertyDescriptor prop in baseProps) { Attribute attr = (Attribute)filteredProps[prop]; if (attr != null) { //BEGIN INTENTIONAL CHANGES from VSIP version of AutomationExtenderManager.cs PropertyDescriptor filteredProp; if (attr is System.ComponentModel.ReadOnlyAttribute) { // If we're filtering this property to be read-only, we want to simply wrap it // with a class that makes the property appear read-only. We don't use // TypeDescriptor.CreateProperty() because it doesn't work well with // Com2PropertyDescriptor (gives an exception trying to get the value). // We can't change this behavior for properties we're "hiding" // without changing current behavior in the project designer. filteredProp = new ReadOnlyPropertyDescriptorWrapper(prop); } else { filteredProp = TypeDescriptor.CreateProperty(baseObject.GetType(), prop, attr); } //END INTENTIONAL CHANGES if (filteredProp.Attributes.Contains(attributes)) { propList.Add(filteredProp); } } else { propList.Add(prop); } } PropertyDescriptor[] propArray = new PropertyDescriptor[propList.Count]; propList.CopyTo(propArray, 0); baseProps = new PropertyDescriptorCollection(propArray); } return baseProps; } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return baseObject; } //////////////////////////////////////// /// <summary> /// Wraps a PropertyDescriptor but changes it to read-only. All other /// functionality is delegated to the original property descriptor. /// </summary> internal class ReadOnlyPropertyDescriptorWrapper : PropertyDescriptor { PropertyDescriptor prop; public ReadOnlyPropertyDescriptorWrapper(PropertyDescriptor prop) : base(prop.Name, AttributeCollectionToArray(prop.Attributes)) { this.prop = prop; } /// <summary> /// Creates an Attribute array from an AttributeCollection instance /// </summary> /// <param name="collection"></param> /// <returns></returns> private static Attribute[] AttributeCollectionToArray(AttributeCollection collection) { Attribute[] array = new Attribute[collection.Count]; collection.CopyTo(array, 0); return array; } public override bool CanResetValue(object component) { return false; //override original property descriptor } public override Type ComponentType { get { return prop.ComponentType; } } public override object GetValue(object component) { return prop.GetValue(component); } public override bool IsReadOnly { get { return true; //override original property descriptor } } public override Type PropertyType { get { return prop.PropertyType; } } public override void ResetValue(object component) { throw new NotSupportedException(); //override original property descriptor } public override void SetValue(object component, object value) { throw new NotSupportedException(); //override original property descriptor } public override bool ShouldSerializeValue(object component) { return prop.ShouldSerializeValue(component); } public override TypeConverter Converter { get { return prop.Converter; } } } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion --- License --- using Newtonsoft.Json; using System; using System.Runtime.InteropServices; namespace MatterHackers.VectorMath { /// <summary> /// Represents a 3D vector using three double-precision floating-point numbers. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3 : IEquatable<Vector3> { #region Fields /// <summary> /// The X component of the Vector3. /// </summary> public double x; /// <summary> /// The Y component of the Vector3. /// </summary> public double y; /// <summary> /// The Z component of the Vector3. /// </summary> public double z; #endregion Fields #region Constructors /// <summary> /// Constructs a new Vector3. /// </summary> /// <param name="x">The x component of the Vector3.</param> /// <param name="y">The y component of the Vector3.</param> /// <param name="z">The z component of the Vector3.</param> public Vector3(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } /// <summary> /// Constructs a new instance from the given Vector2d. /// </summary> /// <param name="v">The Vector2d to copy components from.</param> public Vector3(Vector2 v, double z = 0) { x = v.x; y = v.y; this.z = z; } /// <summary> /// Constructs a new instance from the given Vector3d. /// </summary> /// <param name="v">The Vector3d to copy components from.</param> public Vector3(Vector3 v) { x = v.x; y = v.y; z = v.z; } public Vector3(Vector3Float v) { x = v.x; y = v.y; z = v.z; } public Vector3(double[] doubleArray) { x = doubleArray[0]; y = doubleArray[1]; z = doubleArray[2]; } /// <summary> /// Constructs a new instance from the given Vector4d. /// </summary> /// <param name="v">The Vector4d to copy components from.</param> public Vector3(Vector4 v) { x = v.x; y = v.y; z = v.z; } #endregion Constructors #region Properties public double this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; default: return 0; } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; default: throw new Exception(); } } } #endregion Properties #region Public Members #region Instance #region public double Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <see cref="LengthFast"/> /// <seealso cref="LengthSquared"/> [JsonIgnoreAttribute] public double Length { get { return System.Math.Sqrt(x * x + y * y + z * z); } } #endregion public double Length #region public double LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> /// <seealso cref="LengthFast"/> [JsonIgnoreAttribute] public double LengthSquared { get { return x * x + y * y + z * z; } } #endregion public double LengthSquared #region public void Normalize() /// <summary> /// Returns a normalized Vector of this. /// </summary> /// <returns></returns> public Vector3 GetNormal() { Vector3 temp = this; temp.Normalize(); return temp; } /// <summary> /// Scales the Vector3d to unit length. /// </summary> public void Normalize() { double scale = 1.0 / this.Length; x *= scale; y *= scale; z *= scale; } #endregion public void Normalize() #region public double[] ToArray() public double[] ToArray() { return new double[] { x, y, z }; } #endregion public double[] ToArray() #endregion Instance #region Static #region Fields /// <summary> /// Defines a unit-length Vector3d that points towards the X-axis. /// </summary> public static readonly Vector3 UnitX = new Vector3(1, 0, 0); /// <summary> /// Defines a unit-length Vector3d that points towards the Y-axis. /// </summary> public static readonly Vector3 UnitY = new Vector3(0, 1, 0); /// <summary> /// /// Defines a unit-length Vector3d that points towards the Z-axis. /// </summary> public static readonly Vector3 UnitZ = new Vector3(0, 0, 1); /// <summary> /// Defines a zero-length Vector3. /// </summary> public static readonly Vector3 Zero = new Vector3(0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector3 One = new Vector3(1, 1, 1); /// <summary> /// Defines an instance with all components set to positive infinity. /// </summary> public static readonly Vector3 PositiveInfinity = new Vector3(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity); /// <summary> /// Defines an instance with all components set to negative infinity. /// </summary> public static readonly Vector3 NegativeInfinity = new Vector3(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity); /// <summary> /// Defines the size of the Vector3d struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector3()); #endregion Fields #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector3 Add(Vector3 a, Vector3 b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector3 a, ref Vector3 b, out Vector3 result) { result = new Vector3(a.x + b.x, a.y + b.y, a.z + b.z); } #endregion Add #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector3 Subtract(Vector3 a, Vector3 b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector3 a, ref Vector3 b, out Vector3 result) { result = new Vector3(a.x - b.x, a.y - b.y, a.z - b.z); } #endregion Subtract #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3 Multiply(Vector3 vector, double scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3 vector, double scale, out Vector3 result) { result = new Vector3(vector.x * scale, vector.y * scale, vector.z * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3 Multiply(Vector3 vector, Vector3 scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector3 vector, ref Vector3 scale, out Vector3 result) { result = new Vector3(vector.x * scale.x, vector.y * scale.y, vector.z * scale.z); } #endregion Multiply #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3 Divide(Vector3 vector, double scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3 vector, double scale, out Vector3 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector3 Divide(Vector3 vector, Vector3 scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector3 vector, ref Vector3 scale, out Vector3 result) { result = new Vector3(vector.x / scale.x, vector.y / scale.y, vector.z / scale.z); } #endregion Divide #region ComponentMin /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector3 ComponentMin(Vector3 a, Vector3 b) { a.x = a.x < b.x ? a.x : b.x; a.y = a.y < b.y ? a.y : b.y; a.z = a.z < b.z ? a.z : b.z; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void ComponentMin(ref Vector3 a, ref Vector3 b, out Vector3 result) { result.x = a.x < b.x ? a.x : b.x; result.y = a.y < b.y ? a.y : b.y; result.z = a.z < b.z ? a.z : b.z; } #endregion ComponentMin #region ComponentMax /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector3 ComponentMax(Vector3 a, Vector3 b) { a.x = a.x > b.x ? a.x : b.x; a.y = a.y > b.y ? a.y : b.y; a.z = a.z > b.z ? a.z : b.z; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void ComponentMax(ref Vector3 a, ref Vector3 b, out Vector3 result) { result.x = a.x > b.x ? a.x : b.x; result.y = a.y > b.y ? a.y : b.y; result.z = a.z > b.z ? a.z : b.z; } #endregion ComponentMax #region Min /// <summary> /// Returns the Vector3d with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3</returns> public static Vector3 Min(Vector3 left, Vector3 right) { return left.LengthSquared < right.LengthSquared ? left : right; } #endregion Min #region Max /// <summary> /// Returns the Vector3d with the minimum magnitude /// </summary> /// <param name="left">Left operand</param> /// <param name="right">Right operand</param> /// <returns>The minimum Vector3</returns> public static Vector3 Max(Vector3 left, Vector3 right) { return left.LengthSquared >= right.LengthSquared ? left : right; } #endregion Max #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector3 Clamp(Vector3 vec, Vector3 min, Vector3 max) { vec.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x; vec.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y; vec.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector3 vec, ref Vector3 min, ref Vector3 max, out Vector3 result) { result.x = vec.x < min.x ? min.x : vec.x > max.x ? max.x : vec.x; result.y = vec.y < min.y ? min.y : vec.y > max.y ? max.y : vec.y; result.z = vec.z < min.z ? min.z : vec.z > max.z ? max.z : vec.z; } #endregion Clamp #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector3 Normalize(Vector3 vec) { double scale = 1.0 / vec.Length; vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector3 vec, out Vector3 result) { double scale = 1.0 / vec.Length; result.x = vec.x * scale; result.y = vec.y * scale; result.z = vec.z * scale; } #endregion Normalize #region Dot /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static double Dot(Vector3 left, Vector3 right) { return left.x * right.x + left.y * right.y + left.z * right.z; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector3 left, ref Vector3 right, out double result) { result = left.x * right.x + left.y * right.y + left.z * right.z; } #endregion Dot #region Cross /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> public static Vector3 Cross(Vector3 left, Vector3 right) { Vector3 result; Cross(ref left, ref right, out result); return result; } /// <summary> /// Caclulate the cross (vector) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The cross product of the two inputs</returns> /// <param name="result">The cross product of the two inputs</param> public static void Cross(ref Vector3 left, ref Vector3 right, out Vector3 result) { result = new Vector3(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, left.x * right.y - left.y * right.x); } #endregion Cross #region Utility /// <summary> /// Checks if 3 points are collinear (all lie on the same line). /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <param name="c"></param> /// <param name="epsilon"></param> /// <returns></returns> public static bool Collinear(Vector3 a, Vector3 b, Vector3 c, double epsilon = .000001) { // Return true if a, b, and c all lie on the same line. return Math.Abs(Cross(b - a, c - a).Length) < epsilon; } public static Vector3 GetPerpendicular(Vector3 a, Vector3 b) { if (!Collinear(a, b, Zero)) { return Vector3.Cross(a, b); } else { Vector3 zOne = new Vector3(0, 0, 100000); if (!Collinear(a, b, zOne)) { return Vector3.Cross(a - zOne, b - zOne); } else { Vector3 xOne = new Vector3(1000000, 0, 0); return Vector3.Cross(a - xOne, b - xOne); } } } #endregion Utility #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector3 Lerp(Vector3 a, Vector3 b, double blend) { a.x = blend * (b.x - a.x) + a.x; a.y = blend * (b.y - a.y) + a.y; a.z = blend * (b.z - a.z) + a.z; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector3 a, ref Vector3 b, double blend, out Vector3 result) { result.x = blend * (b.x - a.x) + a.x; result.y = blend * (b.y - a.y) + a.y; result.z = blend * (b.z - a.z) + a.z; } #endregion Lerp #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector3 BaryCentric(Vector3 a, Vector3 b, Vector3 c, double u, double v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector3 a, ref Vector3 b, ref Vector3 c, double u, double v, out Vector3 result) { result = a; // copy Vector3 temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion Barycentric #region Transform /// <summary>Transform a direction vector by the given Matrix /// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored. /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3 TransformVector(Vector3 vec, Matrix4X4 mat) { return new Vector3( Vector3.Dot(vec, new Vector3(mat.Column0)), Vector3.Dot(vec, new Vector3(mat.Column1)), Vector3.Dot(vec, new Vector3(mat.Column2))); } /// <summary>Transform a direction vector by the given Matrix /// Assumes the matrix has a bottom row of (0,0,0,1), that is the translation part is ignored. /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void TransformVector(ref Vector3 vec, ref Matrix4X4 mat, out Vector3 result) { result.x = vec.x * mat.Row0.x + vec.y * mat.Row1.x + vec.z * mat.Row2.x; result.y = vec.x * mat.Row0.y + vec.y * mat.Row1.y + vec.z * mat.Row2.y; result.z = vec.x * mat.Row0.z + vec.y * mat.Row1.z + vec.z * mat.Row2.z; } /// <summary>Transform a Normal by the given Matrix</summary> /// <remarks> /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed normal</returns> public static Vector3 TransformNormal(Vector3 norm, Matrix4X4 mat) { mat.Invert(); return TransformNormalInverse(norm, mat); } /// <summary>Transform a Normal by the given Matrix</summary> /// <remarks> /// This calculates the inverse of the given matrix, use TransformNormalInverse if you /// already have the inverse to avoid this extra calculation /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed normal</param> public static void TransformNormal(ref Vector3 norm, ref Matrix4X4 mat, out Vector3 result) { Matrix4X4 Inverse = Matrix4X4.Invert(mat); Vector3.TransformNormalInverse(ref norm, ref Inverse, out result); } /// <summary>Transform a Normal by the (transpose of the) given Matrix</summary> /// <remarks> /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="invMat">The inverse of the desired transformation</param> /// <returns>The transformed normal</returns> public static Vector3 TransformNormalInverse(Vector3 norm, Matrix4X4 invMat) { return new Vector3( Vector3.Dot(norm, new Vector3(invMat.Row0)), Vector3.Dot(norm, new Vector3(invMat.Row1)), Vector3.Dot(norm, new Vector3(invMat.Row2))); } /// <summary>Transform a Normal by the (transpose of the) given Matrix</summary> /// <remarks> /// This version doesn't calculate the inverse matrix. /// Use this version if you already have the inverse of the desired transform to hand /// </remarks> /// <param name="norm">The normal to transform</param> /// <param name="invMat">The inverse of the desired transformation</param> /// <param name="result">The transformed normal</param> public static void TransformNormalInverse(ref Vector3 norm, ref Matrix4X4 invMat, out Vector3 result) { result.x = norm.x * invMat.Row0.x + norm.y * invMat.Row0.y + norm.z * invMat.Row0.z; result.y = norm.x * invMat.Row1.x + norm.y * invMat.Row1.y + norm.z * invMat.Row1.z; result.z = norm.x * invMat.Row2.x + norm.y * invMat.Row2.y + norm.z * invMat.Row2.z; } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed position</returns> public static Vector3 TransformPosition(Vector3 pos, Matrix4X4 mat) { return new Vector3( Vector3.Dot(pos, new Vector3(mat.Column0)) + mat.Row3.x, Vector3.Dot(pos, new Vector3(mat.Column1)) + mat.Row3.y, Vector3.Dot(pos, new Vector3(mat.Column2)) + mat.Row3.z); } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed position</param> public static void TransformPosition(ref Vector3 pos, ref Matrix4X4 mat, out Vector3 result) { result.x = pos.x * mat.Row0.x + pos.y * mat.Row1.x + pos.z * mat.Row2.x + mat.Row3.x; result.y = pos.x * mat.Row0.y + pos.y * mat.Row1.y + pos.z * mat.Row2.y + mat.Row3.y; result.z = pos.x * mat.Row0.z + pos.y * mat.Row1.z + pos.z * mat.Row2.z + mat.Row3.z; } /// <summary> /// Transform all the vectors in the array by the given Matrix. /// </summary> /// <param name="boundsVerts"></param> /// <param name="rotationQuaternion"></param> public static void Transform(Vector3[] vecArray, Matrix4X4 mat) { for (int i = 0; i < vecArray.Length; i++) { vecArray[i] = Transform(vecArray[i], mat); } } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3 Transform(Vector3 vec, Matrix4X4 mat) { Vector3 result; Transform(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector3 vec, ref Matrix4X4 mat, out Vector3 result) { Vector4 v4 = new Vector4(vec.x, vec.y, vec.z, 1.0); Vector4.Transform(ref v4, ref mat, out v4); result = v4.Xyz; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector3 Transform(Vector3 vec, Quaternion quat) { Vector3 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector3 vec, ref Quaternion quat, out Vector3 result) { // Since vec.W == 0, we can optimize quat * vec * quat^-1 as follows: // vec + 2.0 * cross(quat.xyz, cross(quat.xyz, vec) + quat.w * vec) Vector3 xyz = quat.Xyz, temp, temp2; Vector3.Cross(ref xyz, ref vec, out temp); Vector3.Multiply(ref vec, quat.W, out temp2); Vector3.Add(ref temp, ref temp2, out temp); Vector3.Cross(ref xyz, ref temp, out temp); Vector3.Multiply(ref temp, 2, out temp); Vector3.Add(ref vec, ref temp, out result); } /// <summary> /// Transform all the vectors in the array by the quaternion rotation. /// </summary> /// <param name="boundsVerts"></param> /// <param name="rotationQuaternion"></param> public static void Transform(Vector3[] vecArray, Quaternion rotationQuaternion) { for (int i = 0; i < vecArray.Length; i++) { vecArray[i] = Transform(vecArray[i], rotationQuaternion); } } /// <summary> /// Transform a Vector3d by the given Matrix, and project the resulting Vector4 back to a Vector3 /// </summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector3 TransformPerspective(Vector3 vec, Matrix4X4 mat) { Vector3 result; TransformPerspective(ref vec, ref mat, out result); return result; } /// <summary>Transform a Vector3d by the given Matrix, and project the resulting Vector4d back to a Vector3d</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void TransformPerspective(ref Vector3 vec, ref Matrix4X4 mat, out Vector3 result) { Vector4 v = new Vector4(vec); Vector4.Transform(ref v, ref mat, out v); result.x = v.x / v.w; result.y = v.y / v.w; result.z = v.z / v.w; } #endregion Transform #region CalculateAngle /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static double CalculateAngle(Vector3 first, Vector3 second) { return System.Math.Acos((Vector3.Dot(first, second)) / (first.Length * second.Length)); } /// <summary>Calculates the angle (in radians) between two vectors.</summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void CalculateAngle(ref Vector3 first, ref Vector3 second, out double result) { double temp; Vector3.Dot(ref first, ref second, out temp); result = System.Math.Acos(temp / (first.Length * second.Length)); } #endregion CalculateAngle #endregion Static #region Swizzle /// <summary> /// Gets or sets an OpenTK.Vector2d with the X and Y components of this instance. /// </summary> [JsonIgnoreAttribute] public Vector2 Xy { get { return new Vector2(x, y); } set { x = value.x; y = value.y; } } #endregion Swizzle #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator +(Vector3 left, Vector3 right) { left.x += right.x; left.y += right.y; left.z += right.z; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator -(Vector3 left, Vector3 right) { left.x -= right.x; left.y -= right.y; left.z -= right.z; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator -(Vector3 vec) { vec.x = -vec.x; vec.y = -vec.y; vec.z = -vec.z; return vec; } /// <summary> /// Component wise multiply two vectors together, x*x, y*y, z*z. /// </summary> /// <param name="vecA"></param> /// <param name="vecB"></param> /// <returns></returns> public static Vector3 operator *(Vector3 vecA, Vector3 vecB) { vecA.x *= vecB.x; vecA.y *= vecB.y; vecA.z *= vecB.z; return vecA; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator *(Vector3 vec, double scale) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator *(double scale, Vector3 vec) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } /// <summary> /// Creates a new vector which is the numerator devided by each component of the vector. /// </summary> /// <param name="numerator"></param> /// <param name="vec"></param> /// <returns>The result of the calculation.</returns> public static Vector3 operator /(double numerator, Vector3 vec) { return new Vector3((numerator / vec.x), (numerator / vec.y), (numerator / vec.z)); } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector3 operator /(Vector3 vec, double scale) { double mult = 1 / scale; vec.x *= mult; vec.y *= mult; vec.z *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector3 left, Vector3 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector3 left, Vector3 right) { return !left.Equals(right); } #endregion Operators #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Vector3. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("[{0}, {1}, {2}]", x, y, z); } #endregion public override string ToString() #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return new { x, y, z }.GetHashCode(); } #endregion public override int GetHashCode() #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector3)) return false; return this.Equals((Vector3)obj); } /// <summary> /// Indicates whether this instance and a specified object are equal within an error range. /// </summary> /// <param name="OtherVector"></param> /// <param name="ErrorValue"></param> /// <returns>True if the instances are equal; false otherwise.</returns> public bool Equals(Vector3 OtherVector, double ErrorValue) { if ((x < OtherVector.x + ErrorValue && x > OtherVector.x - ErrorValue) && (y < OtherVector.y + ErrorValue && y > OtherVector.y - ErrorValue) && (z < OtherVector.z + ErrorValue && z > OtherVector.z - ErrorValue)) { return true; } return false; } #endregion public override bool Equals(object obj) #endregion Overrides #endregion Public Members #region IEquatable<Vector3> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector3 other) { return x == other.x && y == other.y && z == other.z; } #endregion IEquatable<Vector3> Members public static double ComponentMax(Vector3 vector3) { return Math.Max(vector3.x, Math.Max(vector3.y, vector3.z)); } public static double ComponentMin(Vector3 vector3) { return Math.Min(vector3.x, Math.Min(vector3.y, vector3.z)); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/20/2009 2:00:23 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Design; using System.Globalization; using System.Linq; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// FeatureScheme /// </summary> public abstract class FeatureScheme : Scheme, IFeatureScheme { #region IFeatureScheme Members /// <summary> /// Occurs when a category indicates that its filter expression should be used /// to select its members. /// </summary> public event EventHandler<ExpressionEventArgs> SelectFeatures; /// <summary> /// Occurs when the deselect features context menu is clicked. /// </summary> public event EventHandler<ExpressionEventArgs> DeselectFeatures; #endregion /// <summary> /// Occurs when there are more than 1000 unique categories. If the "Cancel" /// is set to true, then only the first 1000 categories are returned. Otherwise /// it may allow the application to lock up, but will return all of them. /// If this event is not handled, cancle is assumed to be true. /// </summary> public event EventHandler<CancelEventArgs> TooManyCategories; /// <summary> /// Occurs /// </summary> public event EventHandler NonNumericField; #region Private Variables private readonly Dictionary<string, ArrayList> _cachedUniqueValues; private bool _appearsInLegend; private UITypeEditor _propertyEditor; #endregion #region Constructors /// <summary> /// Creates a new instance of FeatureScheme /// </summary> protected FeatureScheme() { // This normally is replaced by a shape type specific collection, and is just a precaution. _appearsInLegend = false; _cachedUniqueValues = new Dictionary<string, ArrayList>(); EditorSettings = new FeatureEditorSettings(); Breaks = new List<Break>(); } #endregion #region Methods #endregion #region Properties /// <summary> /// Gets or sets a boolean that indicates whether or not the legend should draw this item as a categorical /// tier in the legend. If so, it will allow the LegendText to be visible as a kind of group for the /// categories. If not, the categories will appear directly below the layer. /// </summary> [Category("Behavior"), Description("Gets or sets a boolean that indicates whether or not the legend should draw this item as a grouping")] [Serialize("AppearsInLegend")] public bool AppearsInLegend { get { return _appearsInLegend; } set { _appearsInLegend = value; } } /// <summary> /// When using this scheme to define the symbology, these individual categories will be referenced in order to /// create genuine categories (that will be cached). /// </summary> public abstract IEnumerable<IFeatureCategory> GetCategories(); /// <summary> /// Gets or sets the dialog settings /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new FeatureEditorSettings EditorSettings { get { return base.EditorSettings as FeatureEditorSettings; } set { base.EditorSettings = value; } } /// <summary> /// Gets or sets the UITypeEditor to use for editing this FeatureScheme /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UITypeEditor PropertyEditor { get { return _propertyEditor; } protected set { _propertyEditor = value; } } /// <summary> /// Gets the number of categories in this scheme /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual int NumCategories { get { return 0; } } #endregion #region Protected Methods /// <summary> /// An enumerable of LegendItems allowing the true members to be cycled through. /// </summary> [ShallowCopy] public override IEnumerable<ILegendItem> LegendItems { get { if (AppearsInLegend) { return GetCategories().Cast<ILegendItem>(); } return base.LegendItems; } } /// <summary> /// Queries this layer and the entire parental tree up to the map frame to determine if /// this layer is within the selected layers. /// </summary> public bool IsWithinLegendSelection() { if (IsSelected) return true; ILayer lyr = GetParentItem() as ILayer; while (lyr != null) { if (lyr.IsSelected) return true; lyr = lyr.GetParentItem() as ILayer; } return false; } /// <summary> /// Special handling of not copying the parent during a copy operation /// </summary> /// <param name="copy"></param> protected override void OnCopy(Descriptor copy) { FeatureScheme scheme = copy as FeatureScheme; if (scheme != null && scheme.SelectFeatures != null) { foreach (var handler in scheme.SelectFeatures.GetInvocationList()) { scheme.SelectFeatures -= (EventHandler<ExpressionEventArgs>)handler; } } // Disconnecting the parent prevents the immediate application of copied scheme categories to the original layer. SuspendEvents(); base.OnCopy(copy); ResumeEvents(); } /// <summary> /// Handles the special case of not copying the parent during an on copy properties operation /// </summary> /// <param name="source"></param> protected override void OnCopyProperties(object source) { base.OnCopyProperties(source); ILegendItem parent = GetParentItem(); IFeatureLayer p = parent as IFeatureLayer; if (p != null) p.ApplyScheme(this); } /// <summary> /// Ensures that the parentage gets set properly in the event that /// this scheme is not appearing in the legend. /// </summary> /// <param name="value"></param> protected override void OnSetParentItem(ILegendItem value) { base.OnSetParentItem(value); if (_appearsInLegend) return; IEnumerable<IFeatureCategory> categories = GetCategories(); foreach (IFeatureCategory category in categories) { category.SetParentItem(value); } } #endregion #region Symbology Methods /// <summary> /// This keeps the existing categories, but uses the current scheme settings to apply /// a new color to each of the symbols. /// </summary> public void RegenerateColors() { List<IFeatureCategory> cats = GetCategories().ToList(); List<Color> colors = GetColorSet(cats.Count); int i = 0; foreach (IFeatureCategory category in cats) { category.SetColor(colors[i]); i++; } } /// <summary> /// Creates categories either based on unique values, or classification method. /// If the method is /// </summary> /// <param name="table">The System.DataTable to that has the data values to use</param> public void CreateCategories(DataTable table) { string fieldName = EditorSettings.FieldName; if (EditorSettings.ClassificationType == ClassificationType.Custom) return; if (EditorSettings.ClassificationType == ClassificationType.UniqueValues) { CreateUniqueCategories(fieldName, table); } else { if (table.Columns[fieldName].DataType == typeof(string)) { //MessageBox.Show(MessageStrings.FieldNotNumeric); if (NonNumericField != null) NonNumericField(this, EventArgs.Empty); return; } if (GetUniqueValues(fieldName, table).Count <= EditorSettings.NumBreaks) { CreateUniqueCategories(fieldName, table); } else { GetValues(table); CreateBreakCategories(); } } AppearsInLegend = true; LegendText = fieldName; } /// <inheritdoc /> public void CreateCategories(IAttributeSource source, ICancelProgressHandler progressHandler) { string fieldName = EditorSettings.FieldName; if (EditorSettings.ClassificationType == ClassificationType.Custom) return; if (EditorSettings.ClassificationType == ClassificationType.UniqueValues) { CreateUniqueCategories(fieldName, source, progressHandler); } else { if (source.GetColumn(fieldName).DataType == typeof(string)) { //MessageBox.Show(MessageStrings.FieldNotNumeric); if (NonNumericField != null) NonNumericField(this, EventArgs.Empty); return; } if (!SufficientValues(fieldName, source, EditorSettings.NumBreaks)) { CreateUniqueCategories(fieldName, source, progressHandler); } else { GetValues(source, progressHandler); CreateBreakCategories(); } } AppearsInLegend = true; LegendText = fieldName; } /// <summary> /// Uses the settings on this scheme to create a random category. /// </summary> /// <returns>A new IFeatureCategory</returns> /// <param name="filterExpression">The filter expression to use</param> public virtual IFeatureCategory CreateRandomCategory(string filterExpression) { return null; } /// <summary> /// This simply ensures that we are creating the appropriate empty filter expression version /// of create random category. /// </summary> /// <returns></returns> public override ICategory CreateRandomCategory() { return CreateRandomCategory(string.Empty); } /// <summary> /// Gets the values from a file based data source rather than an in memory object. /// </summary> /// <param name="source"></param> /// <param name="progressHandler"></param> public void GetValues(IAttributeSource source, ICancelProgressHandler progressHandler) { int pageSize = 100000; Values = new List<double>(); string normField = EditorSettings.NormField; string fieldName = EditorSettings.FieldName; if (source.NumRows() < EditorSettings.MaxSampleCount) { int numPages = (int)Math.Ceiling((double)source.NumRows() / pageSize); for (int ipage = 0; ipage < numPages; ipage++) { int numRows = (ipage == numPages - 1) ? source.NumRows() % pageSize : pageSize; DataTable table = source.GetAttributes(ipage * pageSize, numRows); if (!string.IsNullOrEmpty(EditorSettings.ExcludeExpression)) { DataRow[] rows = table.Select("NOT (" + EditorSettings.ExcludeExpression + ")"); foreach (DataRow row in rows) { double val; if (!double.TryParse(row[fieldName].ToString(), out val)) continue; if (double.IsNaN(val)) continue; if (normField != null) { double norm; if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue; Values.Add(val / norm); continue; } Values.Add(val); } } else { foreach (DataRow row in table.Rows) { double val; if (!double.TryParse(row[fieldName].ToString(), out val)) continue; if (double.IsNaN(val)) continue; if (normField != null) { double norm; if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue; Values.Add(val / norm); continue; } Values.Add(val); } } } } else { Dictionary<int, double> randomValues = new Dictionary<int, double>(); pageSize = 10000; int count = EditorSettings.MaxSampleCount; Random rnd = new Random(); AttributePager ap = new AttributePager(source, pageSize); int countPerPage = count / ap.NumPages(); ProgressMeter pm = new ProgressMeter(progressHandler, "Sampling " + count + " random values", count); for (int iPage = 0; iPage < ap.NumPages(); iPage++) { for (int i = 0; i < countPerPage; i++) { double val; double norm = 1; int index; bool failed = false; do { index = rnd.Next(ap.StartIndex, ap.StartIndex + pageSize); DataRow dr = ap.Row(index); if (!double.TryParse(dr[fieldName].ToString(), out val)) failed = true; if (normField == null) continue; if (!double.TryParse(dr[normField].ToString(), out norm)) failed = true; } while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed); if (normField != null) { Values.Add(val / norm); } else { Values.Add(val); } randomValues.Add(index, val); pm.CurrentValue = i + iPage * countPerPage; } //Application.DoEvents(); if (progressHandler != null && progressHandler.Cancel) { break; } } } Values.Sort(); Statistics.Calculate(Values); } /// <summary> /// Before attempting to create categories using a color ramp, this must be calculated /// to updated the cache of values that govern statistics and break placement. /// </summary> /// <param name="table">The data Table to use.</param> public void GetValues(DataTable table) { Values = new List<double>(); string normField = EditorSettings.NormField; string fieldName = EditorSettings.FieldName; if (!string.IsNullOrEmpty(EditorSettings.ExcludeExpression)) { DataRow[] rows = table.Select("NOT (" + EditorSettings.ExcludeExpression + ")"); foreach (DataRow row in rows) { if (rows.Length < EditorSettings.MaxSampleCount) { double val; if (!double.TryParse(row[fieldName].ToString(), out val)) continue; if (double.IsNaN(val)) continue; if (normField != null) { double norm; if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue; Values.Add(val / norm); continue; } Values.Add(val); } else { Dictionary<int, double> randomValues = new Dictionary<int, double>(); int count = EditorSettings.MaxSampleCount; int max = rows.Length; Random rnd = new Random(); for (int i = 0; i < count; i++) { double val; double norm = 1; int index; bool failed = false; do { index = rnd.Next(max); if (!double.TryParse(rows[index][fieldName].ToString(), out val)) failed = true; if (normField == null) continue; if (!double.TryParse(rows[index][normField].ToString(), out norm)) failed = true; } while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed); if (normField != null) { Values.Add(val / norm); } else { Values.Add(val); } randomValues.Add(index, val); } } } Values.Sort(); Statistics.Calculate(Values); return; } if (table.Rows.Count < EditorSettings.MaxSampleCount) { // Simply grab all the values foreach (DataRow row in table.Rows) { double val; if (!double.TryParse(row[fieldName].ToString(), out val)) continue; if (double.IsNaN(val)) continue; if (normField == null) { Values.Add(val); continue; } double norm; if (!double.TryParse(row[normField].ToString(), out norm) || double.IsNaN(val)) continue; Values.Add(val / norm); } } else { // Grab random samples Dictionary<int, double> randomValues = new Dictionary<int, double>(); int count = EditorSettings.MaxSampleCount; int max = table.Rows.Count; Random rnd = new Random(); for (int i = 0; i < count; i++) { double val; double norm = 1; int index; bool failed = false; do { index = rnd.Next(max); if (!double.TryParse(table.Rows[index][fieldName].ToString(), out val)) failed = true; if (normField == null) continue; if (!double.TryParse(table.Rows[index][normField].ToString(), out norm)) failed = true; } while (randomValues.ContainsKey(index) || double.IsNaN(val) || failed); if (normField != null) { Values.Add(val / norm); } else { Values.Add(val); } randomValues.Add(index, val); } } Values.Sort(); } /// <summary> /// Returns /// </summary> private static bool SufficientValues(string fieldName, IAttributeSource source, int numValues) { ArrayList lst = new ArrayList(); AttributeCache ac = new AttributeCache(source, numValues); foreach (Dictionary<string, object> dr in ac) { object val = dr[fieldName] ?? "[NULL]"; if (val.ToString() == string.Empty) val = "[NULL]"; if (lst.Contains(val)) continue; lst.Add(val); if (lst.Count > numValues) return true; } return false; } /// <summary> /// Gets a list of all unique values of the attribute field. /// </summary> private List<Break> GetUniqueValues(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler) { ArrayList lst; bool hugeCountOk = false; if (_cachedUniqueValues.ContainsKey(fieldName)) { lst = _cachedUniqueValues[fieldName]; } else { lst = new ArrayList(); AttributePager ap = new AttributePager(source, 5000); ProgressMeter pm = new ProgressMeter(progressHandler, "Discovering Unique Values", source.NumRows()); for (int row = 0; row < source.NumRows(); row++) { object val = ap.Row(row)[fieldName] ?? "[NULL]"; if (val.ToString() == string.Empty) val = "[NULL]"; if (lst.Contains(val)) continue; lst.Add(val); if (lst.Count > 1000 && !hugeCountOk) { CancelEventArgs args = new CancelEventArgs(true); if (TooManyCategories != null) TooManyCategories(this, args); if (args.Cancel) break; hugeCountOk = true; } pm.CurrentValue = row; if (progressHandler.Cancel) break; } lst.Sort(); if (lst.Count < EditorSettings.MaxSampleCount) { _cachedUniqueValues[fieldName] = lst; } } List<Break> result = new List<Break>(); if (lst != null) { foreach (object item in lst) { result.Add(new Break(item.ToString())); } } return result; } /// <summary> /// Gets a list of all unique values of the attribute field. /// </summary> private static List<Break> GetUniqueValues(string fieldName, DataTable table) { HashSet<object> lst = new HashSet<object>(); bool containsNull = false; foreach (DataRow dr in table.Rows) { object val = dr[fieldName]; if (val == null || dr[fieldName] is DBNull || val.ToString() == string.Empty) { containsNull = true; } else if (!lst.Contains(val)) { lst.Add(val); } } List<Break> result = new List<Break>(); if (containsNull) result.Add(new Break("[NULL]")); foreach (object item in lst.OrderBy(o => o)) { result.Add(new Break(string.Format(CultureInfo.InvariantCulture, "{0}", item))); // Changed by jany_ (2015-07-27) use InvariantCulture because this is used in Datatable.Select in FeatureCategoryControl and causes error when german localization is used } return result; } /// <summary> /// This checks the type of the specified field whether it's a string field /// </summary> private static bool CheckFieldType(string fieldName, DataTable table) { return table.Columns[fieldName].DataType == typeof(string); } /// <summary> /// This checks the type of the specified field whether it's a string field /// </summary> private static bool CheckFieldType(string fieldName, IAttributeSource source) { return source.GetColumn(fieldName).DataType == typeof(string); } private void CreateUniqueCategories(string fieldName, IAttributeSource source, ICancelProgressHandler progressHandler) { Breaks = GetUniqueValues(fieldName, source, progressHandler); string fieldExpression = "[" + fieldName.ToUpper() + "]"; ClearCategories(); bool isStringField = CheckFieldType(fieldName, source); ProgressMeter pm = new ProgressMeter(progressHandler, "Building Feature Categories", Breaks.Count); List<double> sizeRamp = GetSizeSet(Breaks.Count); List<Color> colorRamp = GetColorSet(Breaks.Count); for (int colorIndex = 0; colorIndex < Breaks.Count; colorIndex++) { Break brk = Breaks[colorIndex]; //get the color for the category Color randomColor = colorRamp[colorIndex]; double size = sizeRamp[colorIndex]; IFeatureCategory cat = CreateNewCategory(randomColor, size) as IFeatureCategory; if (cat != null) { //cat.SelectionSymbolizer = _selectionSymbolizer.Copy(); cat.LegendText = brk.Name; if (isStringField) cat.FilterExpression = fieldExpression + "= '" + brk.Name.Replace("'", "''") + "'"; else cat.FilterExpression = fieldExpression + "=" + brk.Name; AddCategory(cat); } colorIndex++; pm.CurrentValue = colorIndex; } pm.Reset(); } private void CreateUniqueCategories(string fieldName, DataTable table) { Breaks = GetUniqueValues(fieldName, table); List<double> sizeRamp = GetSizeSet(Breaks.Count); List<Color> colorRamp = GetColorSet(Breaks.Count); string fieldExpression = "[" + fieldName.ToUpper() + "]"; ClearCategories(); bool isStringField = CheckFieldType(fieldName, table); int colorIndex = 0; foreach (Break brk in Breaks) { //get the color for the category Color randomColor = colorRamp[colorIndex]; double size = sizeRamp[colorIndex]; IFeatureCategory cat = CreateNewCategory(randomColor, size) as IFeatureCategory; if (cat != null) { //cat.SelectionSymbolizer = _selectionSymbolizer.Copy(); cat.LegendText = brk.Name; if (isStringField) cat.FilterExpression = fieldExpression + "= '" + brk.Name.Replace("'", "''") + "'"; else cat.FilterExpression = fieldExpression + "=" + brk.Name; if (cat.FilterExpression != null) { if (cat.FilterExpression.Contains("=[NULL]")) { cat.FilterExpression = cat.FilterExpression.Replace("=[NULL]", " is NULL"); } else if (cat.FilterExpression.Contains("= '[NULL]'")) { cat.FilterExpression = cat.FilterExpression.Replace("= '[NULL]'", " is NULL"); } } AddCategory(cat); } colorIndex++; } } /// <summary> /// Instructs the parent layer to select features matching the specified expression. /// </summary> /// <param name="sender">The object sender.</param> /// <param name="e">The event args.</param> protected virtual void OnSelectFeatures(object sender, ExpressionEventArgs e) { ExpressionEventArgs myE = e; if (EditorSettings.ExcludeExpression != null) { myE = new ExpressionEventArgs(myE.Expression + " AND NOT (" + EditorSettings.ExcludeExpression + ")"); } if (SelectFeatures != null) SelectFeatures(sender, myE); } /// <summary> /// Instructs the parent layer to select features matching the specified expression. /// </summary> /// <param name="sender">The object sender.</param> /// <param name="e">The event args.</param> protected virtual void OnDeselectFeatures(object sender, ExpressionEventArgs e) { ExpressionEventArgs myE = e; if (EditorSettings.ExcludeExpression != null) { myE = new ExpressionEventArgs(myE.Expression + " AND NOT (" + EditorSettings.ExcludeExpression + ")"); } if (DeselectFeatures != null) DeselectFeatures(sender, myE); } /// <summary> /// Uses the current settings to generate a random color between the start and end color. /// </summary> /// <returns>A Randomly created color that is within the bounds of this scheme.</returns> protected Color CreateRandomColor() { Random rnd = new Random(DateTime.Now.Millisecond); return CreateRandomColor(rnd); } /// <summary> /// This replaces the constant size calculation with a size /// calculation that is appropriate for features. /// </summary> /// <param name="count">The integer count of the number of sizes to create.</param> /// <returns>A list of double valued sizes.</returns> protected override List<double> GetSizeSet(int count) { List<double> result = new List<double>(); if (EditorSettings.UseSizeRange) { double start = EditorSettings.StartSize; double dr = (EditorSettings.EndSize - start); double dx = dr / count; if (!EditorSettings.RampColors) { Random rnd = new Random(DateTime.Now.Millisecond); for (int i = 0; i < count; i++) { result.Add(start + rnd.NextDouble() * dr); } } else { for (int i = 0; i < count; i++) { result.Add(start + i * dx); } } } else { Size2D sizes = new Size2D(2, 2); IPointSymbolizer ps = EditorSettings.TemplateSymbolizer as IPointSymbolizer; if (ps != null) sizes = ps.GetSize(); double size = Math.Max(sizes.Width, sizes.Height); for (int i = 0; i < count; i++) { result.Add(size); } } return result; } /// <summary> /// Calculates the unique colors as a scheme /// </summary> /// <param name="fs">The featureset with the data Table definition</param> /// <param name="uniqueField">The unique field</param> /// <param name="categoryFunc">Func for creating category</param> protected Hashtable GenerateUniqueColors(IFeatureSet fs, string uniqueField, Func<Color, IFeatureCategory> categoryFunc) { if (categoryFunc == null) throw new ArgumentNullException("categoryFunc"); var result = new Hashtable(); // a hashtable of colors var dt = fs.DataTable; var vals = new ArrayList(); var i = 0; var rnd = new Random(); foreach (DataRow row in dt.Rows) { var ind = -1; if (uniqueField != "FID") { if (vals.Contains(row[uniqueField]) == false) { ind = vals.Add(row[uniqueField]); } } else { ind = vals.Add(i); i++; } if (ind == -1) continue; var item = vals[ind]; var c = rnd.NextColor(); while (result.ContainsKey(c)) { c = rnd.NextColor(); } var cat = categoryFunc(c); string flt = "[" + uniqueField + "] = "; if (uniqueField == "FID") { flt += item; } else { if (dt.Columns[uniqueField].DataType == typeof(string)) { flt += "'" + item + "'"; } else { flt += Convert.ToString(item, CultureInfo.InvariantCulture); } } cat.FilterExpression = flt; AddCategory(cat); result.Add(c, item); } return result; } #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.Collections.Generic; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class SocketAsyncEventArgsTest { [Fact] public void Usertoken_Roundtrips() { using (var args = new SocketAsyncEventArgs()) { object o = new object(); Assert.Null(args.UserToken); args.UserToken = o; Assert.Same(o, args.UserToken); } } [Fact] public void SocketFlags_Roundtrips() { using (var args = new SocketAsyncEventArgs()) { Assert.Equal(SocketFlags.None, args.SocketFlags); args.SocketFlags = SocketFlags.Broadcast; Assert.Equal(SocketFlags.Broadcast, args.SocketFlags); } } [Fact] public void SendPacketsSendSize_Roundtrips() { using (var args = new SocketAsyncEventArgs()) { Assert.Equal(0, args.SendPacketsSendSize); args.SendPacketsSendSize = 4; Assert.Equal(4, args.SendPacketsSendSize); } } [Fact] public void SendPacketsFlags_Roundtrips() { using (var args = new SocketAsyncEventArgs()) { Assert.Equal((TransmitFileOptions)0, args.SendPacketsFlags); args.SendPacketsFlags = TransmitFileOptions.UseDefaultWorkerThread; Assert.Equal(TransmitFileOptions.UseDefaultWorkerThread, args.SendPacketsFlags); } } [Fact] public void Dispose_MultipleCalls_Success() { using (var args = new SocketAsyncEventArgs()) { args.Dispose(); } } [Fact] public async Task Dispose_WhileInUse_DisposeDelayed() { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listen.Listen(1); Task<Socket> acceptTask = listen.AcceptAsync(); await Task.WhenAll( acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port))); using (Socket server = await acceptTask) using (var receiveSaea = new SocketAsyncEventArgs()) { var tcs = new TaskCompletionSource<bool>(); receiveSaea.SetBuffer(new byte[1], 0, 1); receiveSaea.Completed += delegate { tcs.SetResult(true); }; Assert.True(client.ReceiveAsync(receiveSaea)); Assert.Throws<InvalidOperationException>(() => client.ReceiveAsync(receiveSaea)); // already in progress receiveSaea.Dispose(); server.Send(new byte[1]); await tcs.Task; // completes successfully even though it was disposed Assert.Throws<ObjectDisposedException>(() => client.ReceiveAsync(receiveSaea)); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task ExecutionContext_FlowsIfNotSuppressed(bool suppressed) { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listen.Listen(1); Task<Socket> acceptTask = listen.AcceptAsync(); await Task.WhenAll( acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port))); using (Socket server = await acceptTask) using (var receiveSaea = new SocketAsyncEventArgs()) { if (suppressed) { ExecutionContext.SuppressFlow(); } var local = new AsyncLocal<int>(); local.Value = 42; int threadId = Environment.CurrentManagedThreadId; var mres = new ManualResetEventSlim(); receiveSaea.SetBuffer(new byte[1], 0, 1); receiveSaea.Completed += delegate { Assert.NotEqual(threadId, Environment.CurrentManagedThreadId); Assert.Equal(suppressed ? 0 : 42, local.Value); mres.Set(); }; Assert.True(client.ReceiveAsync(receiveSaea)); server.Send(new byte[1]); mres.Wait(); } } } [Fact] public void SetBuffer_InvalidArgs_Throws() { using (var saea = new SocketAsyncEventArgs()) { AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(new byte[1], -1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(new byte[1], 2, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, 2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 1, 2)); } } [Fact] public void SetBuffer_NoBuffer_ResetsCountOffset() { using (var saea = new SocketAsyncEventArgs()) { saea.SetBuffer(42, 84); Assert.Equal(0, saea.Offset); Assert.Equal(0, saea.Count); saea.SetBuffer(new byte[3], 1, 2); Assert.Equal(1, saea.Offset); Assert.Equal(2, saea.Count); saea.SetBuffer(null, 1, 2); Assert.Equal(0, saea.Offset); Assert.Equal(0, saea.Count); } } [Fact] public void SetBufferListWhenBufferSet_Throws() { using (var saea = new SocketAsyncEventArgs()) { var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) }; byte[] buffer = new byte[1]; saea.SetBuffer(buffer, 0, 1); AssertExtensions.Throws<ArgumentException>(null, () => saea.BufferList = bufferList); Assert.Same(buffer, saea.Buffer); Assert.Null(saea.BufferList); saea.SetBuffer(null, 0, 0); saea.BufferList = bufferList; // works fine when Buffer has been set back to null } } [Fact] public void SetBufferWhenBufferListSet_Throws() { using (var saea = new SocketAsyncEventArgs()) { var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) }; saea.BufferList = bufferList; AssertExtensions.Throws<ArgumentException>(null, () => saea.SetBuffer(new byte[1], 0, 1)); Assert.Same(bufferList, saea.BufferList); Assert.Null(saea.Buffer); saea.BufferList = null; saea.SetBuffer(new byte[1], 0, 1); // works fine when BufferList has been set back to null } } [Fact] public void SetBufferListWhenBufferListSet_Succeeds() { using (var saea = new SocketAsyncEventArgs()) { Assert.Null(saea.BufferList); saea.BufferList = null; Assert.Null(saea.BufferList); var bufferList1 = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) }; saea.BufferList = bufferList1; Assert.Same(bufferList1, saea.BufferList); saea.BufferList = bufferList1; Assert.Same(bufferList1, saea.BufferList); var bufferList2 = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) }; saea.BufferList = bufferList2; Assert.Same(bufferList2, saea.BufferList); } } [Fact] public void SetBufferWhenBufferSet_Succeeds() { using (var saea = new SocketAsyncEventArgs()) { byte[] buffer1 = new byte[1]; saea.SetBuffer(buffer1, 0, buffer1.Length); Assert.Same(buffer1, saea.Buffer); saea.SetBuffer(buffer1, 0, buffer1.Length); Assert.Same(buffer1, saea.Buffer); byte[] buffer2 = new byte[1]; saea.SetBuffer(buffer2, 0, buffer1.Length); Assert.Same(buffer2, saea.Buffer); } } [Theory] [InlineData(1, -1, 0)] // offset low [InlineData(1, 2, 0)] // offset high [InlineData(1, 0, -1)] // count low [InlineData(1, 1, 2)] // count high public void BufferList_InvalidArguments_Throws(int length, int offset, int count) { using (var e = new SocketAsyncEventArgs()) { ArraySegment<byte> invalidBuffer = new FakeArraySegment { Array = new byte[length], Offset = offset, Count = count }.ToActual(); Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { invalidBuffer }); ArraySegment<byte> validBuffer = new ArraySegment<byte>(new byte[1]); Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { validBuffer, invalidBuffer }); } } [Fact] public async Task Completed_RegisterThenInvoked_UnregisterThenNotInvoked() { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listen.Listen(1); Task<Socket> acceptTask = listen.AcceptAsync(); await Task.WhenAll( acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port))); using (Socket server = await acceptTask) using (var receiveSaea = new SocketAsyncEventArgs()) { receiveSaea.SetBuffer(new byte[1], 0, 1); TaskCompletionSource<bool> tcs1 = null, tcs2 = null; EventHandler<SocketAsyncEventArgs> handler1 = (_, __) => tcs1.SetResult(true); EventHandler<SocketAsyncEventArgs> handler2 = (_, __) => tcs2.SetResult(true); receiveSaea.Completed += handler2; receiveSaea.Completed += handler1; tcs1 = new TaskCompletionSource<bool>(); tcs2 = new TaskCompletionSource<bool>(); Assert.True(client.ReceiveAsync(receiveSaea)); server.Send(new byte[1]); await Task.WhenAll(tcs1.Task, tcs2.Task); receiveSaea.Completed -= handler2; tcs1 = new TaskCompletionSource<bool>(); tcs2 = new TaskCompletionSource<bool>(); Assert.True(client.ReceiveAsync(receiveSaea)); server.Send(new byte[1]); await tcs1.Task; Assert.False(tcs2.Task.IsCompleted); } } } [Fact] public void CancelConnectAsync_InstanceConnect_CancelsInProgressConnect() { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); using (var connectSaea = new SocketAsyncEventArgs()) { var tcs = new TaskCompletionSource<SocketError>(); connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError); connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port); Assert.True(client.ConnectAsync(connectSaea), $"ConnectAsync completed synchronously with SocketError == {connectSaea.SocketError}"); if (tcs.Task.IsCompleted) { Assert.NotEqual(SocketError.Success, tcs.Task.Result); } Socket.CancelConnectAsync(connectSaea); Assert.False(client.Connected, "Expected Connected to be false"); } } } [Fact] public void CancelConnectAsync_StaticConnect_CancelsInProgressConnect() { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); using (var connectSaea = new SocketAsyncEventArgs()) { var tcs = new TaskCompletionSource<SocketError>(); connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError); connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port); bool pending = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, connectSaea); if (!pending) tcs.SetResult(connectSaea.SocketError); if (tcs.Task.IsCompleted) { Assert.NotEqual(SocketError.Success, tcs.Task.Result); } Socket.CancelConnectAsync(connectSaea); } } } [Fact] public async Task ReuseSocketAsyncEventArgs_SameInstance_MultipleSockets() { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listen.Listen(1); Task<Socket> acceptTask = listen.AcceptAsync(); await Task.WhenAll( acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port))); using (Socket server = await acceptTask) { TaskCompletionSource<bool> tcs = null; var args = new SocketAsyncEventArgs(); args.SetBuffer(new byte[1024], 0, 1024); args.Completed += (_,__) => tcs.SetResult(true); for (int i = 1; i <= 10; i++) { tcs = new TaskCompletionSource<bool>(); args.Buffer[0] = (byte)i; args.SetBuffer(0, 1); if (server.SendAsync(args)) { await tcs.Task; } args.Buffer[0] = 0; tcs = new TaskCompletionSource<bool>(); if (client.ReceiveAsync(args)) { await tcs.Task; } Assert.Equal(1, args.BytesTransferred); Assert.Equal(i, args.Buffer[0]); } } } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task ReuseSocketAsyncEventArgs_MutateBufferList() { using (var listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listen.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listen.Listen(1); Task<Socket> acceptTask = listen.AcceptAsync(); await Task.WhenAll( acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port))); using (Socket server = await acceptTask) { TaskCompletionSource<bool> tcs = null; var sendBuffer = new byte[64]; var sendBufferList = new List<ArraySegment<byte>>(); sendBufferList.Add(new ArraySegment<byte>(sendBuffer, 0, 1)); var sendArgs = new SocketAsyncEventArgs(); sendArgs.BufferList = sendBufferList; sendArgs.Completed += (_,__) => tcs.SetResult(true); var recvBuffer = new byte[64]; var recvBufferList = new List<ArraySegment<byte>>(); recvBufferList.Add(new ArraySegment<byte>(recvBuffer, 0, 1)); var recvArgs = new SocketAsyncEventArgs(); recvArgs.BufferList = recvBufferList; recvArgs.Completed += (_,__) => tcs.SetResult(true); for (int i = 1; i <= 10; i++) { tcs = new TaskCompletionSource<bool>(); sendBuffer[0] = (byte)i; if (server.SendAsync(sendArgs)) { await tcs.Task; } recvBuffer[0] = 0; tcs = new TaskCompletionSource<bool>(); if (client.ReceiveAsync(recvArgs)) { await tcs.Task; } Assert.Equal(1, recvArgs.BytesTransferred); Assert.Equal(i, recvBuffer[0]); // Mutate the send/recv BufferLists // This should not affect Send or Receive behavior, since the buffer list is cached // at the time it is set. sendBufferList[0] = new ArraySegment<byte>(sendBuffer, i, 1); sendBufferList.Insert(0, new ArraySegment<byte>(sendBuffer, i * 2, 1)); recvBufferList[0] = new ArraySegment<byte>(recvBuffer, i, 1); recvBufferList.Add(new ArraySegment<byte>(recvBuffer, i * 2, 1)); } } } } public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args) { EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } [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)); 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] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Failure() { 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)); } } } }
using System; using System.Data; using System.Xml; using System.Xml.XPath; using System.Collections; using System.IO; using System.Web.Security; using Umbraco.Core.IO; namespace umbraco.cms.businesslogic.web { /// <summary> /// Summary description for Access. /// </summary> public class Access { public Access() { // // TODO: Add constructor logic here // } static private Hashtable _checkedPages = new Hashtable(); //must be volatile for double check lock to work static private volatile XmlDocument _accessXmlContent; static private string _accessXmlSource; private static void clearCheckPages() { _checkedPages.Clear(); } static object _locko = new object(); public static XmlDocument AccessXml { get { if (_accessXmlContent == null) { lock (_locko) { if (_accessXmlContent == null) { if (_accessXmlSource == null) { //if we pop it here it'll make for better stack traces ;) _accessXmlSource = IOHelper.MapPath(SystemFiles.AccessXml, true); } _accessXmlContent = new XmlDocument(); if (!System.IO.File.Exists(_accessXmlSource)) { var file = new FileInfo(_accessXmlSource); if (!Directory.Exists(file.DirectoryName)) { Directory.CreateDirectory(file.Directory.FullName); //ensure the folder exists! } System.IO.FileStream f = System.IO.File.Open(_accessXmlSource, FileMode.Create); System.IO.StreamWriter sw = new StreamWriter(f); sw.WriteLine("<access/>"); sw.Close(); f.Close(); } _accessXmlContent.Load(_accessXmlSource); } } } return _accessXmlContent; } } public static void AddMembershipRoleToDocument(int documentId, string role) { //event AddMemberShipRoleToDocumentEventArgs e = new AddMemberShipRoleToDocumentEventArgs(); new Access().FireBeforeAddMemberShipRoleToDocument(new Document(documentId), role, e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(documentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.SelectSingleNode("group [@id = '" + role + "']") == null) { XmlElement groupXml = (XmlElement)AccessXml.CreateNode(XmlNodeType.Element, "group", ""); groupXml.SetAttribute("id", role); x.AppendChild(groupXml); save(); } } new Access().FireAfterAddMemberShipRoleToDocument(new Document(documentId), role, e); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void AddMemberGroupToDocument(int DocumentId, int MemberGroupId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.SelectSingleNode("group [@id = '" + MemberGroupId.ToString() + "']") == null) { XmlElement groupXml = (XmlElement) AccessXml.CreateNode(XmlNodeType.Element, "group", ""); groupXml.SetAttribute("id", MemberGroupId.ToString()); x.AppendChild(groupXml); save(); } } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void AddMemberToDocument(int DocumentId, int MemberId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.Attributes.GetNamedItem("memberId") != null) x.Attributes.GetNamedItem("memberId").Value = MemberId.ToString(); else x.SetAttribute("memberId", MemberId.ToString()); save(); } } public static void AddMembershipUserToDocument(int documentId, string membershipUserName) { //event AddMembershipUserToDocumentEventArgs e = new AddMembershipUserToDocumentEventArgs(); new Access().FireBeforeAddMembershipUserToDocument(new Document(documentId), membershipUserName, e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(documentId); if (x == null) throw new Exception("Document is not protected!"); else { if (x.Attributes.GetNamedItem("memberId") != null) x.Attributes.GetNamedItem("memberId").Value = membershipUserName; else x.SetAttribute("memberId", membershipUserName); save(); } new Access().FireAfterAddMembershipUserToDocument(new Document(documentId), membershipUserName, e); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static void RemoveMemberGroupFromDocument(int DocumentId, int MemberGroupId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x == null) throw new Exception("Document is not protected!"); else { XmlNode xGroup = x.SelectSingleNode("group [@id = '" + MemberGroupId.ToString() + "']"); if (xGroup != null) { x.RemoveChild(xGroup); save(); } } } public static void RemoveMembershipRoleFromDocument(int documentId, string role) { RemoveMemberShipRoleFromDocumentEventArgs e = new RemoveMemberShipRoleFromDocumentEventArgs(); new Access().FireBeforeRemoveMemberShipRoleFromDocument(new Document(documentId), role, e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(documentId); if (x == null) throw new Exception("Document is not protected!"); else { XmlNode xGroup = x.SelectSingleNode("group [@id = '" + role + "']"); if (xGroup != null) { x.RemoveChild(xGroup); save(); } } new Access().FireAfterRemoveMemberShipRoleFromDocument(new Document(documentId), role, e); } } public static bool RenameMemberShipRole(string oldRolename, string newRolename) { bool hasChange = false; if (oldRolename != newRolename) { oldRolename = oldRolename.Replace("'", "&apos;"); foreach (XmlNode x in AccessXml.SelectNodes("//group [@id = '" + oldRolename + "']")) { x.Attributes["id"].Value = newRolename; hasChange = true; } if (hasChange) save(); } return hasChange; } public static void ProtectPage(bool Simple, int DocumentId, int LoginDocumentId, int ErrorDocumentId) { AddProtectionEventArgs e = new AddProtectionEventArgs(); new Access().FireBeforeAddProtection(new Document(DocumentId), e); if (!e.Cancel) { XmlElement x = (XmlElement)getPage(DocumentId); if (x == null) { x = (XmlElement)_accessXmlContent.CreateNode(XmlNodeType.Element, "page", ""); AccessXml.DocumentElement.AppendChild(x); } // if using simple mode, make sure that all existing groups are removed else if (Simple) { x.RemoveAll(); } x.SetAttribute("id", DocumentId.ToString()); x.SetAttribute("loginPage", LoginDocumentId.ToString()); x.SetAttribute("noRightsPage", ErrorDocumentId.ToString()); x.SetAttribute("simple", Simple.ToString()); save(); clearCheckPages(); new Access().FireAfterAddProtection(new Document(DocumentId), e); } } public static void RemoveProtection(int DocumentId) { XmlElement x = (XmlElement) getPage(DocumentId); if (x != null) { //event RemoveProtectionEventArgs e = new RemoveProtectionEventArgs(); new Access().FireBeforeRemoveProtection(new Document(DocumentId), e); if (!e.Cancel) { x.ParentNode.RemoveChild(x); save(); clearCheckPages(); new Access().FireAfterRemoveProtection(new Document(DocumentId), e); } } } private static void save() { SaveEventArgs e = new SaveEventArgs(); new Access().FireBeforeSave(e); if (!e.Cancel) { System.IO.FileStream f = System.IO.File.Open(_accessXmlSource, FileMode.Create); AccessXml.Save(f); f.Close(); new Access().FireAfterSave(e); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static bool IsProtectedByGroup(int DocumentId, int GroupId) { bool isProtected = false; cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) isProtected = false; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.SelectSingleNode("./group [@id=" + GroupId.ToString() + "]") != null) { isProtected = true; } } return isProtected; } public static bool IsProtectedByMembershipRole(int documentId, string role) { bool isProtected = false; CMSNode d = new CMSNode(documentId); if (!IsProtected(documentId, d.Path)) isProtected = false; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { isProtected = true; } } return isProtected; } public static string[] GetAccessingMembershipRoles(int documentId, string path) { ArrayList roles = new ArrayList(); if (!IsProtected(documentId, path)) return null; else { XmlNode currentNode = getPage(getProtectedPage(path)); foreach (XmlNode n in currentNode.SelectNodes("./group")) { roles.Add(n.Attributes.GetNamedItem("id").Value); } return (string[])roles.ToArray(typeof(string)); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static cms.businesslogic.member.MemberGroup[] GetAccessingGroups(int DocumentId) { cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) return null; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); cms.businesslogic.member.MemberGroup[] mg = new umbraco.cms.businesslogic.member.MemberGroup[currentNode.SelectNodes("./group").Count]; int count = 0; foreach (XmlNode n in currentNode.SelectNodes("./group")) { mg[count] = new cms.businesslogic.member.MemberGroup(int.Parse(n.Attributes.GetNamedItem("id").Value)); count++; } return mg; } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static cms.businesslogic.member.Member GetAccessingMember(int DocumentId) { cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) return null; else if (GetProtectionType(DocumentId) != ProtectionType.Simple) throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead"); else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.Attributes.GetNamedItem("memberId") != null) return new cms.businesslogic.member.Member(int.Parse( currentNode.Attributes.GetNamedItem("memberId").Value)); else throw new Exception("Document doesn't contain a memberId. This might be caused if document is protected using umbraco RC1 or older."); } } public static MembershipUser GetAccessingMembershipUser(int documentId) { CMSNode d = new CMSNode(documentId); if (!IsProtected(documentId, d.Path)) return null; else if (GetProtectionType(documentId) != ProtectionType.Simple) throw new Exception("Document isn't protected using Simple mechanism. Use GetAccessingMemberGroups instead"); else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (currentNode.Attributes.GetNamedItem("memberId") != null) return Membership.GetUser(currentNode.Attributes.GetNamedItem("memberId").Value); else throw new Exception("Document doesn't contain a memberId. This might be caused if document is protected using umbraco RC1 or older."); } } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] public static bool HasAccess(int DocumentId, cms.businesslogic.member.Member Member) { bool hasAccess = false; cms.businesslogic.web.Document d = new Document(DocumentId); if (!IsProtected(DocumentId, d.Path)) hasAccess = true; else { XmlNode currentNode = getPage(getProtectedPage(d.Path)); if (Member != null) { IDictionaryEnumerator ide = Member.Groups.GetEnumerator(); while(ide.MoveNext()) { cms.businesslogic.member.MemberGroup mg = (cms.businesslogic.member.MemberGroup) ide.Value; if (currentNode.SelectSingleNode("./group [@id=" + mg.Id.ToString() + "]") != null) { hasAccess = true; break; } } } } return hasAccess; } public static bool HasAccces(int documentId, object memberId) { bool hasAccess = false; cms.businesslogic.CMSNode node = new CMSNode(documentId); if (!IsProtected(documentId, node.Path)) return true; else { MembershipUser member = Membership.GetUser(memberId); XmlNode currentNode = getPage(getProtectedPage(node.Path)); if (member != null) { foreach(string role in Roles.GetRolesForUser()) { if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { hasAccess = true; break; } } } } return hasAccess; } [Obsolete("This method is no longer supported. Use the ASP.NET MemberShip methods instead", true)] private static bool HasAccess(int DocumentId, string Path, cms.businesslogic.member.Member Member) { bool hasAccess = false; if (!IsProtected(DocumentId, Path)) hasAccess = true; else { XmlNode currentNode = getPage(getProtectedPage(Path)); if (Member != null) { IDictionaryEnumerator ide = Member.Groups.GetEnumerator(); while(ide.MoveNext()) { cms.businesslogic.member.MemberGroup mg = (cms.businesslogic.member.MemberGroup) ide.Value; if (currentNode.SelectSingleNode("./group [@id=" + mg.Id.ToString() + "]") != null) { hasAccess = true; break; } } } } return hasAccess; } public static bool HasAccess(int documentId, string path, MembershipUser member) { bool hasAccess = false; if (!IsProtected(documentId, path)) hasAccess = true; else { XmlNode currentNode = getPage(getProtectedPage(path)); if (member != null) { string[] roles = Roles.GetRolesForUser(member.UserName); foreach(string role in roles) { if (currentNode.SelectSingleNode("./group [@id='" + role + "']") != null) { hasAccess = true; break; } } } } return hasAccess; } public static ProtectionType GetProtectionType(int DocumentId) { XmlNode x = getPage(DocumentId); try { if (bool.Parse(x.Attributes.GetNamedItem("simple").Value)) return ProtectionType.Simple; else return ProtectionType.Advanced; } catch { return ProtectionType.NotProtected; } } public static bool IsProtected(int DocumentId, string Path) { bool isProtected = false; if (!_checkedPages.ContainsKey(DocumentId)) { foreach(string id in Path.Split(',')) { if (getPage(int.Parse(id)) != null) { isProtected = true; break; } } // Add thread safe updating to the hashtable if (System.Web.HttpContext.Current != null) System.Web.HttpContext.Current.Application.Lock(); if (!_checkedPages.ContainsKey(DocumentId)) _checkedPages.Add(DocumentId, isProtected); if (System.Web.HttpContext.Current != null) System.Web.HttpContext.Current.Application.UnLock(); } else isProtected = (bool) _checkedPages[DocumentId]; return isProtected; } public static int GetErrorPage(string Path) { return int.Parse(getPage(getProtectedPage(Path)).Attributes.GetNamedItem("noRightsPage").Value); } public static int GetLoginPage(string Path) { return int.Parse(getPage(getProtectedPage(Path)).Attributes.GetNamedItem("loginPage").Value); } private static int getProtectedPage(string Path) { int protectedPage = 0; foreach(string id in Path.Split(',')) if (getPage(int.Parse(id)) != null) protectedPage = int.Parse(id); return protectedPage; } private static XmlNode getPage(int documentId) { XmlNode x = AccessXml.SelectSingleNode("/access/page [@id=" + documentId.ToString() + "]"); return x; } //Event delegates public delegate void SaveEventHandler(Access sender, SaveEventArgs e); public delegate void AddProtectionEventHandler(Document sender, AddProtectionEventArgs e); public delegate void RemoveProtectionEventHandler(Document sender, RemoveProtectionEventArgs e); public delegate void AddMemberShipRoleToDocumentEventHandler(Document sender, string role, AddMemberShipRoleToDocumentEventArgs e); public delegate void RemoveMemberShipRoleFromDocumentEventHandler(Document sender, string role, RemoveMemberShipRoleFromDocumentEventArgs e); public delegate void RemoveMemberShipUserFromDocumentEventHandler(Document sender, string MembershipUserName, RemoveMemberShipUserFromDocumentEventArgs e); public delegate void AddMembershipUserToDocumentEventHandler(Document sender, string MembershipUserName, AddMembershipUserToDocumentEventArgs e); //Events public static event SaveEventHandler BeforeSave; protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) BeforeSave(this, e); } public static event SaveEventHandler AfterSave; protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) AfterSave(this, e); } public static event AddProtectionEventHandler BeforeAddProtection; protected virtual void FireBeforeAddProtection(Document doc, AddProtectionEventArgs e) { if (BeforeAddProtection != null) BeforeAddProtection(doc, e); } public static event AddProtectionEventHandler AfterAddProtection; protected virtual void FireAfterAddProtection(Document doc, AddProtectionEventArgs e) { if (AfterAddProtection != null) AfterAddProtection(doc, e); } public static event RemoveProtectionEventHandler BeforeRemoveProtection; protected virtual void FireBeforeRemoveProtection(Document doc, RemoveProtectionEventArgs e) { if (BeforeRemoveProtection != null) BeforeRemoveProtection(doc, e); } public static event RemoveProtectionEventHandler AfterRemoveProtection; protected virtual void FireAfterRemoveProtection(Document doc, RemoveProtectionEventArgs e) { if (AfterRemoveProtection != null) AfterRemoveProtection(doc, e); } public static event AddMemberShipRoleToDocumentEventHandler BeforeAddMemberShipRoleToDocument; protected virtual void FireBeforeAddMemberShipRoleToDocument(Document doc, string role, AddMemberShipRoleToDocumentEventArgs e) { if (BeforeAddMemberShipRoleToDocument != null) BeforeAddMemberShipRoleToDocument(doc, role, e); } public static event AddMemberShipRoleToDocumentEventHandler AfterAddMemberShipRoleToDocument; protected virtual void FireAfterAddMemberShipRoleToDocument(Document doc, string role, AddMemberShipRoleToDocumentEventArgs e) { if (AfterAddMemberShipRoleToDocument != null) AfterAddMemberShipRoleToDocument(doc, role, e); } public static event RemoveMemberShipRoleFromDocumentEventHandler BeforeRemoveMemberShipRoleToDocument; protected virtual void FireBeforeRemoveMemberShipRoleFromDocument(Document doc, string role, RemoveMemberShipRoleFromDocumentEventArgs e) { if (BeforeRemoveMemberShipRoleToDocument != null) BeforeRemoveMemberShipRoleToDocument(doc, role, e); } public static event RemoveMemberShipRoleFromDocumentEventHandler AfterRemoveMemberShipRoleToDocument; protected virtual void FireAfterRemoveMemberShipRoleFromDocument(Document doc, string role, RemoveMemberShipRoleFromDocumentEventArgs e) { if (AfterRemoveMemberShipRoleToDocument != null) AfterRemoveMemberShipRoleToDocument(doc, role, e); } public static event RemoveMemberShipUserFromDocumentEventHandler BeforeRemoveMembershipUserFromDocument; protected virtual void FireBeforeRemoveMembershipUserFromDocument(Document doc, string username, RemoveMemberShipUserFromDocumentEventArgs e) { if (BeforeRemoveMembershipUserFromDocument != null) BeforeRemoveMembershipUserFromDocument(doc, username, e); } public static event RemoveMemberShipUserFromDocumentEventHandler AfterRemoveMembershipUserFromDocument; protected virtual void FireAfterRemoveMembershipUserFromDocument(Document doc, string username, RemoveMemberShipUserFromDocumentEventArgs e) { if (AfterRemoveMembershipUserFromDocument != null) AfterRemoveMembershipUserFromDocument(doc, username, e); } public static event AddMembershipUserToDocumentEventHandler BeforeAddMembershipUserToDocument; protected virtual void FireBeforeAddMembershipUserToDocument(Document doc, string username, AddMembershipUserToDocumentEventArgs e) { if (BeforeAddMembershipUserToDocument != null) BeforeAddMembershipUserToDocument(doc, username, e); } public static event AddMembershipUserToDocumentEventHandler AfterAddMembershipUserToDocument; protected virtual void FireAfterAddMembershipUserToDocument(Document doc, string username, AddMembershipUserToDocumentEventArgs e) { if (AfterAddMembershipUserToDocument != null) AfterAddMembershipUserToDocument(doc, username, e); } } public enum ProtectionType { NotProtected, Simple, Advanced } }
using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * HC-256 is a software-efficient stream cipher created by Hongjun Wu. It * generates keystream from a 256-bit secret key and a 256-bit initialization * vector. * <p> * http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc256_p3.pdf * </p><p> * Its brother, HC-128, is a third phase candidate in the eStream contest. * The algorithm is patent-free. No attacks are known as of today (April 2007). * See * * http://www.ecrypt.eu.org/stream/hcp3.html * </p> */ public class HC256Engine : IStreamCipher { private uint[] p = new uint[1024]; private uint[] q = new uint[1024]; private uint cnt = 0; private uint Step() { uint j = cnt & 0x3FF; uint ret; if (cnt < 1024) { uint x = p[(j - 3 & 0x3FF)]; uint y = p[(j - 1023 & 0x3FF)]; p[j] += p[(j - 10 & 0x3FF)] + (RotateRight(x, 10) ^ RotateRight(y, 23)) + q[((x ^ y) & 0x3FF)]; x = p[(j - 12 & 0x3FF)]; ret = (q[x & 0xFF] + q[((x >> 8) & 0xFF) + 256] + q[((x >> 16) & 0xFF) + 512] + q[((x >> 24) & 0xFF) + 768]) ^ p[j]; } else { uint x = q[(j - 3 & 0x3FF)]; uint y = q[(j - 1023 & 0x3FF)]; q[j] += q[(j - 10 & 0x3FF)] + (RotateRight(x, 10) ^ RotateRight(y, 23)) + p[((x ^ y) & 0x3FF)]; x = q[(j - 12 & 0x3FF)]; ret = (p[x & 0xFF] + p[((x >> 8) & 0xFF) + 256] + p[((x >> 16) & 0xFF) + 512] + p[((x >> 24) & 0xFF) + 768]) ^ q[j]; } cnt = cnt + 1 & 0x7FF; return ret; } private byte[] key, iv; private bool initialised; private void Init() { if (key.Length != 32 && key.Length != 16) throw new ArgumentException("The key must be 128/256 bits long"); if (iv.Length < 16) throw new ArgumentException("The IV must be at least 128 bits long"); if (key.Length != 32) { byte[] k = new byte[32]; Array.Copy(key, 0, k, 0, key.Length); Array.Copy(key, 0, k, 16, key.Length); key = k; } if (iv.Length < 32) { byte[] newIV = new byte[32]; Array.Copy(iv, 0, newIV, 0, iv.Length); Array.Copy(iv, 0, newIV, iv.Length, newIV.Length - iv.Length); iv = newIV; } cnt = 0; uint[] w = new uint[2560]; for (int i = 0; i < 32; i++) { w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3))); } for (int i = 0; i < 32; i++) { w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3))); } for (uint i = 16; i < 2560; i++) { uint x = w[i - 2]; uint y = w[i - 15]; w[i] = (RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10)) + w[i - 7] + (RotateRight(y, 7) ^ RotateRight(y, 18) ^ (y >> 3)) + w[i - 16] + i; } Array.Copy(w, 512, p, 0, 1024); Array.Copy(w, 1536, q, 0, 1024); for (int i = 0; i < 4096; i++) { Step(); } cnt = 0; } public virtual string AlgorithmName { get { return "HC-256"; } } /** * Initialise a HC-256 cipher. * * @param forEncryption whether or not we are for encryption. Irrelevant, as * encryption and decryption are the same. * @param params the parameters required to set up the cipher. * @throws ArgumentException if the params argument is * inappropriate (ie. the key is not 256 bit long). */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { ICipherParameters keyParam = parameters; if (parameters is ParametersWithIV) { iv = ((ParametersWithIV)parameters).GetIV(); keyParam = ((ParametersWithIV)parameters).Parameters; } else { iv = new byte[0]; } if (keyParam is KeyParameter) { key = ((KeyParameter)keyParam).GetKey(); Init(); } else { throw new ArgumentException( "Invalid parameter passed to HC256 init - " + parameters.GetType().Name, "parameters"); } initialised = true; } private byte[] buf = new byte[4]; private int idx = 0; private byte GetByte() { if (idx == 0) { Pack.UInt32_To_LE(Step(), buf); } byte ret = buf[idx]; idx = idx + 1 & 0x3; return ret; } public virtual void ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); Check.DataLength(input, inOff, len, "input buffer too short"); Check.OutputLength(output, outOff, len, "output buffer too short"); for (int i = 0; i < len; i++) { output[outOff + i] = (byte)(input[inOff + i] ^ GetByte()); } } public virtual void Reset() { idx = 0; Init(); } public virtual byte ReturnByte(byte input) { return (byte)(input ^ GetByte()); } private static uint RotateRight(uint x, int bits) { return (x >> bits) | (x << -bits); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Linq; using QuantConnect.Util; using QuantConnect.Logging; using QuantConnect.Interfaces; using QuantConnect.Configuration; using System.Collections.Generic; using QuantConnect.Data.Auxiliary; namespace QuantConnect.Securities { /// <summary> /// Resolves standardized security definitions such as FIGI, CUSIP, ISIN, SEDOL into /// a properly mapped Lean <see cref="Symbol"/>. /// </summary> public class SecurityDefinitionSymbolResolver { private List<SecurityDefinition> _securityDefinitions; private readonly IMapFileProvider _mapFileProvider; private readonly string _securitiesDefinitionKey; private readonly IDataProvider _dataProvider; /// <summary> /// Creates an instance of the symbol resolver /// </summary> /// <param name="dataProvider">Data provider used to obtain symbol mappings data</param> /// <param name="securitiesDefinitionKey">Location to read the securities definition data from</param> public SecurityDefinitionSymbolResolver(IDataProvider dataProvider = null, string securitiesDefinitionKey = null) { _securitiesDefinitionKey = securitiesDefinitionKey ?? Path.Combine(Globals.DataFolder, "symbol-properties", "security-database.csv"); _dataProvider = dataProvider ?? Composer.Instance.GetExportedValueByTypeName<IDataProvider>( Config.Get("data-provider", "QuantConnect.Lean.Engine.DataFeeds.DefaultDataProvider")); _mapFileProvider = Composer.Instance.GetExportedValueByTypeName<IMapFileProvider>(Config.Get("map-file-provider", "LocalDiskMapFileProvider")); _mapFileProvider.Initialize(_dataProvider); } /// <summary> /// Converts CUSIP into a Lean <see cref="Symbol"/> /// </summary> /// <param name="cusip"> /// The Committee on Uniform Securities Identification Procedures (CUSIP) number of a security /// </param> /// <param name="tradingDate"> /// The date that the stock was trading at with the CUSIP provided. This is used /// to get the ticker of the symbol on this date. /// </param> /// <returns>The Lean Symbol corresponding to the CUSIP number on the trading date provided</returns> public Symbol CUSIP(string cusip, DateTime tradingDate) { if (string.IsNullOrWhiteSpace(cusip)) { return null; } return SecurityDefinitionToSymbol( GetSecurityDefinitions().FirstOrDefault(x => x.CUSIP != null && x.CUSIP.Equals(cusip, StringComparison.InvariantCultureIgnoreCase)), tradingDate); } /// <summary> /// Converts an asset's composite FIGI into a Lean <see cref="Symbol"/> /// </summary> /// <param name="compositeFigi"> /// The composite Financial Instrument Global Identifier (FIGI) of a security /// </param> /// <param name="tradingDate"> /// The date that the stock was trading at with the composite FIGI provided. This is used /// to get the ticker of the symbol on this date. /// </param> /// <returns>The Lean Symbol corresponding to the composite FIGI on the trading date provided</returns> public Symbol CompositeFIGI(string compositeFigi, DateTime tradingDate) { if (string.IsNullOrWhiteSpace(compositeFigi)) { return null; } return SecurityDefinitionToSymbol( GetSecurityDefinitions().FirstOrDefault(x => x.CompositeFIGI != null && x.CompositeFIGI.Equals(compositeFigi, StringComparison.InvariantCultureIgnoreCase)), tradingDate); } /// <summary> /// Converts SEDOL into a Lean <see cref="Symbol"/> /// </summary> /// <param name="sedol"> /// The Stock Exchange Daily Official List (SEDOL) security identifier of a security /// </param> /// <param name="tradingDate"> /// The date that the stock was trading at with the SEDOL provided. This is used /// to get the ticker of the symbol on this date. /// </param> /// <returns>The Lean Symbol corresponding to the SEDOL on the trading date provided</returns> public Symbol SEDOL(string sedol, DateTime tradingDate) { if (string.IsNullOrWhiteSpace(sedol)) { return null; } return SecurityDefinitionToSymbol( GetSecurityDefinitions().FirstOrDefault(x => x.SEDOL != null && x.SEDOL.Equals(sedol, StringComparison.InvariantCultureIgnoreCase)), tradingDate); } /// <summary> /// Converts ISIN into a Lean <see cref="Symbol"/> /// </summary> /// <param name="isin"> /// The International Securities Identification Number (ISIN) of a security /// </param> /// <param name="tradingDate"> /// The date that the stock was trading at with the ISIN provided. This is used /// to get the ticker of the symbol on this date. /// </param> /// <returns>The Lean Symbol corresponding to the ISIN on the trading date provided</returns> public Symbol ISIN(string isin, DateTime tradingDate) { if (string.IsNullOrWhiteSpace(isin)) { return null; } return SecurityDefinitionToSymbol( GetSecurityDefinitions().FirstOrDefault(x => x.ISIN != null && x.ISIN.Equals(isin, StringComparison.InvariantCultureIgnoreCase)), tradingDate); } /// <summary> /// Converts a SecurityDefinition to a <see cref="Symbol" /> /// </summary> /// <param name="securityDefinition">Security definition</param> /// <param name="tradingDate"> /// The date that the stock was being traded. This is used to resolve /// the ticker that the stock was trading under on this date. /// </param> /// <returns>Symbol if matching Lean Symbol was found on the trading date, null otherwise</returns> private Symbol SecurityDefinitionToSymbol(SecurityDefinition securityDefinition, DateTime tradingDate) { if (securityDefinition == null) { return null; } var mapFileResolver = _mapFileProvider.Get(AuxiliaryDataKey.Create(securityDefinition.SecurityIdentifier)); // Get the first ticker the symbol traded under, and then lookup the // trading date to get the ticker on the trading date. var mapFile = mapFileResolver .ResolveMapFile(securityDefinition.SecurityIdentifier.Symbol, securityDefinition.SecurityIdentifier.Date); // The mapped ticker will be null if the map file is null or there's // no entry found for the given trading date. var mappedTicker = mapFile?.GetMappedSymbol(tradingDate, null); // If we're null, then try again; get the last entry of the map file and use // it as the Symbol we return to the caller. mappedTicker ??= mapFile? .LastOrDefault()? .MappedSymbol; return string.IsNullOrWhiteSpace(mappedTicker) ? null : new Symbol(securityDefinition.SecurityIdentifier, mappedTicker); } /// <summary> /// Get's the security definitions using a lazy initialization /// </summary> private IEnumerable<SecurityDefinition> GetSecurityDefinitions() { if (_securityDefinitions != null) { return _securityDefinitions; } if (!SecurityDefinition.TryRead(_dataProvider, _securitiesDefinitionKey, out _securityDefinitions)) { _securityDefinitions = new List<SecurityDefinition>(); Log.Error($"SecurityDefinitionSymbolResolver(): No security definitions data loaded from file: {_securitiesDefinitionKey}"); } return _securityDefinitions; } } }
using System; using System.Diagnostics; using System.Text; using u8 = System.Byte; using u32 = System.UInt32; namespace System.Data.SQLite { using sqlite3_value = Sqlite3.Mem; internal partial class Sqlite3 { /* ** 2003 April 6 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_ATTACH /// <summary> /// Resolve an expression that was part of an ATTACH or DETACH statement. This /// is slightly different from resolving a normal SQL expression, because simple /// identifiers are treated as strings, not possible column names or aliases. /// /// i.e. if the parser sees: /// /// ATTACH DATABASE abc AS def /// /// it treats the two expressions as literal strings 'abc' and 'def' instead of /// looking for columns of the same name. /// /// This only applies to the root node of pExpr, so the statement: /// /// ATTACH DATABASE abc||def AS 'db2' /// /// will fail because neither abc or def can be resolved. /// </summary> static int resolveAttachExpr(NameContext pName, Expr pExpr) { int rc = SQLITE_OK; if (pExpr != null) { if (pExpr.op != TK_ID) { rc = sqlite3ResolveExprNames(pName, ref pExpr); if (rc == SQLITE_OK && sqlite3ExprIsConstant(pExpr) == 0) { sqlite3ErrorMsg(pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken); return SQLITE_ERROR; } } else { pExpr.op = TK_STRING; } } return rc; } /// <summary> /// An SQL user-function registered to do the work of an ATTACH statement. The /// three arguments to the function come directly from an attach statement: /// /// ATTACH DATABASE x AS y KEY z /// /// SELECT sqlite_attach(x, y, z) /// /// If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the /// third argument. /// </summary> static void attachFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { int i; int rc = 0; sqlite3 db = sqlite3_context_db_handle(context); string zName; string zFile; string zPath = ""; string zErr = ""; int flags; Db aNew = null; string zErrDyn = ""; sqlite3_vfs pVfs = null; UNUSED_PARAMETER(NotUsed); zFile = argv[0].z != null && (argv[0].z.Length > 0) && argv[0].flags != MEM_Null ? sqlite3_value_text(argv[0]) : ""; zName = argv[1].z != null && (argv[1].z.Length > 0) && argv[1].flags != MEM_Null ? sqlite3_value_text(argv[1]) : ""; //if( zFile==null ) zFile = ""; //if ( zName == null ) zName = ""; /* Check for the following errors: ** ** * Too many attached databases, ** * Transaction currently open ** * Specified database name already being used. */ if (db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2) { zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", db.aLimit[SQLITE_LIMIT_ATTACHED] ); goto attach_error; } if (0 == db.autoCommit) { zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction"); goto attach_error; } for (i = 0; i < db.nDb; i++) { string z = db.aDb[i].zName; Debug.Assert(z != null && zName != null); if (z.Equals(zName, StringComparison.InvariantCultureIgnoreCase)) { zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName); goto attach_error; } } /* Allocate the new entry in the db.aDb[] array and initialise the schema ** hash tables. */ //if( db.aDb==db.aDbStatic ){ // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 ); // if( aNew==0 ) return; // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2); //}else { if (db.aDb.Length <= db.nDb) Array.Resize(ref db.aDb, db.nDb + 1);//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) ); if (db.aDb == null) return; // if( aNew==0 ) return; //} db.aDb[db.nDb] = new Db();//db.aDb = aNew; aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew)); // memset(aNew, 0, sizeof(*aNew)); /* Open the database file. If the btree is successfully opened, use ** it to obtain the database schema. At this point the schema may ** or may not be initialised. */ flags = (int)db.openFlags; rc = sqlite3ParseUri(db.pVfs.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr); if (rc != SQLITE_OK) { //if ( rc == SQLITE_NOMEM ) //db.mallocFailed = 1; sqlite3_result_error(context, zErr, -1); //sqlite3_free( zErr ); return; } Debug.Assert(pVfs != null); flags |= SQLITE_OPEN_MAIN_DB; rc = sqlite3BtreeOpen(pVfs, zPath, db, ref aNew.pBt, 0, (int)flags); //sqlite3_free( zPath ); db.nDb++; if (rc == SQLITE_CONSTRAINT) { rc = SQLITE_ERROR; zErrDyn = sqlite3MPrintf(db, "database is already attached"); } else if (rc == SQLITE_OK) { Pager pPager; aNew.pSchema = sqlite3SchemaGet(db, aNew.pBt); //if ( aNew.pSchema == null ) //{ // rc = SQLITE_NOMEM; //} //else if (aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC(db)) { zErrDyn = sqlite3MPrintf(db, "attached databases must use the same text encoding as main database"); rc = SQLITE_ERROR; } pPager = sqlite3BtreePager(aNew.pBt); sqlite3PagerLockingMode(pPager, db.dfltLockMode); sqlite3BtreeSecureDelete(aNew.pBt, sqlite3BtreeSecureDelete(db.aDb[0].pBt, -1)); } aNew.safety_level = 3; aNew.zName = zName;//sqlite3DbStrDup(db, zName); //if( rc==SQLITE_OK && aNew.zName==0 ){ // rc = SQLITE_NOMEM; //} #if SQLITE_HAS_CODEC if ( rc == SQLITE_OK ) { //extern int sqlite3CodecAttach(sqlite3*, int, const void*, int); //extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); int nKey; string zKey; int t = sqlite3_value_type( argv[2] ); switch ( t ) { case SQLITE_INTEGER: case SQLITE_FLOAT: zErrDyn = "Invalid key value"; //sqlite3DbStrDup( db, "Invalid key value" ); rc = SQLITE_ERROR; break; case SQLITE_TEXT: case SQLITE_BLOB: nKey = sqlite3_value_bytes( argv[2] ); zKey = sqlite3_value_blob( argv[2] ).ToString(); // (char *)sqlite3_value_blob(argv[2]); rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey ); break; case SQLITE_NULL: /* No key specified. Use the key from the main database */ sqlite3CodecGetKey( db, 0, out zKey, out nKey ); //sqlite3CodecGetKey(db, 0, (void**)&zKey, nKey); if ( nKey > 0 || sqlite3BtreeGetReserve( db.aDb[0].pBt ) > 0 ) { rc = sqlite3CodecAttach( db, db.nDb - 1, zKey, nKey ); } break; } } #endif /* If the file was opened successfully, read the schema for the new database. ** If this fails, or if opening the file failed, then close the file and ** remove the entry from the db.aDb[] array. i.e. put everything back the way ** we found it. */ if (rc == SQLITE_OK) { sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, ref zErrDyn); sqlite3BtreeLeaveAll(db); } if (rc != 0) { int iDb = db.nDb - 1; Debug.Assert(iDb >= 2); if (db.aDb[iDb].pBt != null) { sqlite3BtreeClose(ref db.aDb[iDb].pBt); db.aDb[iDb].pBt = null; db.aDb[iDb].pSchema = null; } sqlite3ResetInternalSchema(db, -1); db.nDb = iDb; if (rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM) { //// db.mallocFailed = 1; sqlite3DbFree(db, ref zErrDyn); zErrDyn = sqlite3MPrintf(db, "out of memory"); } else if (zErrDyn == "") { zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile); } goto attach_error; } return; attach_error: /* Return an error if we get here */ if (zErrDyn != "") { sqlite3_result_error(context, zErrDyn, -1); sqlite3DbFree(db, ref zErrDyn); } if (rc != 0) sqlite3_result_error_code(context, rc); } /// <summary> /// An SQL user-function registered to do the work of an DETACH statement. The /// three arguments to the function come directly from a detach statement: /// /// DETACH DATABASE x /// /// SELECT sqlite_detach(x) /// </summary> static void detachFunc( sqlite3_context context, int NotUsed, sqlite3_value[] argv ) { string zName = argv[0].z != null && (argv[0].z.Length > 0) ? sqlite3_value_text(argv[0]) : "";//(sqlite3_value_text(argv[0]); sqlite3 db = sqlite3_context_db_handle(context); int i; Db pDb = null; StringBuilder zErr = new StringBuilder(200); UNUSED_PARAMETER(NotUsed); if (zName == null) zName = ""; for (i = 0; i < db.nDb; i++) { pDb = db.aDb[i]; if (pDb.pBt == null) continue; if (pDb.zName.Equals(zName, StringComparison.InvariantCultureIgnoreCase)) break; } if (i >= db.nDb) { sqlite3_snprintf(200, zErr, "no such database: %s", zName); goto detach_error; } if (i < 2) { sqlite3_snprintf(200, zErr, "cannot detach database %s", zName); goto detach_error; } if (0 == db.autoCommit) { sqlite3_snprintf(200, zErr, "cannot DETACH database within transaction"); goto detach_error; } if (sqlite3BtreeIsInReadTrans(pDb.pBt) || sqlite3BtreeIsInBackup(pDb.pBt)) { sqlite3_snprintf(200, zErr, "database %s is locked", zName); goto detach_error; } sqlite3BtreeClose(ref pDb.pBt); pDb.pBt = null; pDb.pSchema = null; sqlite3ResetInternalSchema(db, -1); return; detach_error: sqlite3_result_error(context, zErr.ToString(), -1); } /// <summary> /// This procedure generates VDBE code for a single invocation of either the /// sqlite_detach() or sqlite_attach() SQL user functions. /// </summary> /// <param name='pParse'> /// The parser context /// </param> /// <param name='type'> /// Either SQLITE_ATTACH or SQLITE_DETACH /// </param> /// <param name='pFunc'> /// FuncDef wrapper for detachFunc() or attachFunc() /// </param> /// <param name='pAuthArg'> /// Expression to pass to authorization callback /// </param> /// <param name='pFilename'> /// Name of database file /// </param> /// <param name='pDbname'> /// Name of the database to use internally /// </param> /// <param name='pKey'> /// Database key for encryption extension /// </param> static void codeAttach( Parse pParse, int type, FuncDef pFunc, Expr pAuthArg, Expr pFilename, Expr pDbname, Expr pKey ) { NameContext sName; Vdbe v; sqlite3 db = pParse.db; int regArgs; sName = new NameContext();// memset( &sName, 0, sizeof(NameContext)); sName.pParse = pParse; if ( SQLITE_OK != (resolveAttachExpr(sName, pFilename)) || SQLITE_OK != (resolveAttachExpr(sName, pDbname)) || SQLITE_OK != (resolveAttachExpr(sName, pKey)) ) { pParse.nErr++; goto attach_end; } #if !SQLITE_OMIT_AUTHORIZATION if( pAuthArg ){ char *zAuthArg; if( pAuthArg->op==TK_STRING ){ zAuthArg = pAuthArg->u.zToken; }else{ zAuthArg = 0; } rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0); if(rc!=SQLITE_OK ){ goto attach_end; } } #endif //* SQLITE_OMIT_AUTHORIZATION */ v = sqlite3GetVdbe(pParse); regArgs = sqlite3GetTempRange(pParse, 4); sqlite3ExprCode(pParse, pFilename, regArgs); sqlite3ExprCode(pParse, pDbname, regArgs + 1); sqlite3ExprCode(pParse, pKey, regArgs + 2); Debug.Assert(v != null /*|| db.mallocFailed != 0 */ ); if (v != null) { sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3); Debug.Assert(pFunc.nArg == -1 || (pFunc.nArg & 0xff) == pFunc.nArg); sqlite3VdbeChangeP5(v, (u8)(pFunc.nArg)); sqlite3VdbeChangeP4(v, -1, pFunc, P4_FUNCDEF); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ sqlite3VdbeAddOp1(v, OP_Expire, (type == SQLITE_ATTACH) ? 1 : 0); } attach_end: sqlite3ExprDelete(db, ref pFilename); sqlite3ExprDelete(db, ref pDbname); sqlite3ExprDelete(db, ref pKey); } /// <summary> /// Called by the parser to compile a DETACH statement. /// /// DETACH pDbname /// </summary> static FuncDef detach_func = new FuncDef( 1, /* nArg */ SQLITE_UTF8, /* iPrefEnc */ 0, /* flags */ null, /* pUserData */ null, /* pNext */ detachFunc, /* xFunc */ null, /* xStep */ null, /* xFinalize */ "sqlite_detach", /* zName */ null, /* pHash */ null /* pDestructor */ ); static void sqlite3Detach(Parse pParse, Expr pDbname) { codeAttach(pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname); } /// <summary> /// Called by the parser to compile an ATTACH statement. /// /// ATTACH p AS pDbname KEY pKey /// </summary> static FuncDef attach_func = new FuncDef( 3, /* nArg */ SQLITE_UTF8, /* iPrefEnc */ 0, /* flags */ null, /* pUserData */ null, /* pNext */ attachFunc, /* xFunc */ null, /* xStep */ null, /* xFinalize */ "sqlite_attach", /* zName */ null, /* pHash */ null /* pDestructor */ ); static void sqlite3Attach(Parse pParse, Expr p, Expr pDbname, Expr pKey) { codeAttach(pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey); } #endif // * SQLITE_OMIT_ATTACH */ /// <summary> /// Initialize a DbFixer structure. This routine must be called prior /// to passing the structure to one of the sqliteFixAAAA() routines below. /// /// The return value indicates whether or not fixation is required. TRUE /// means we do need to fix the database references, FALSE means we do not. /// </summary> static int sqlite3FixInit( DbFixer pFix, /* The fixer to be initialized */ Parse pParse, /* Error messages will be written here */ int iDb, /* This is the database that must be used */ string zType, /* "view", "trigger", or "index" */ Token pName /* Name of the view, trigger, or index */ ) { sqlite3 db; if (NEVER(iDb < 0) || iDb == 1) return 0; db = pParse.db; Debug.Assert(db.nDb > iDb); pFix.pParse = pParse; pFix.zDb = db.aDb[iDb].zName; pFix.zType = zType; pFix.pName = pName; return 1; } /// <summary> /// The following set of routines walk through the parse tree and assign /// a specific database to all table references where the database name /// was left unspecified in the original SQL statement. The pFix structure /// must have been initialized by a prior call to sqlite3FixInit(). /// /// These routines are used to make sure that an index, trigger, or /// view in one database does not refer to objects in a different database. /// (Exception: indices, triggers, and views in the TEMP database are /// allowed to refer to anything.) If a reference is explicitly made /// to an object in a different database, an error message is added to /// pParse.zErrMsg and these routines return non-zero. If everything /// checks out, these routines return 0. /// </summary> static int sqlite3FixSrcList( DbFixer pFix, /* Context of the fixation */ SrcList pList /* The Source list to check and modify */ ) { int i; string zDb; SrcList_item pItem; if (NEVER(pList == null)) return 0; zDb = pFix.zDb; for (i = 0; i < pList.nSrc; i++) {//, pItem++){ pItem = pList.a[i]; if (pItem.zDatabase == null) { pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb ); } else if (!pItem.zDatabase.Equals(zDb, StringComparison.InvariantCultureIgnoreCase)) { sqlite3ErrorMsg(pFix.pParse, "%s %T cannot reference objects in database %s", pFix.zType, pFix.pName, pItem.zDatabase); return 1; } #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER if (sqlite3FixSelect(pFix, pItem.pSelect) != 0) return 1; if (sqlite3FixExpr(pFix, pItem.pOn) != 0) return 1; #endif } return 0; } #if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER static int sqlite3FixSelect( DbFixer pFix, /* Context of the fixation */ Select pSelect /* The SELECT statement to be fixed to one database */ ) { while (pSelect != null) { if (sqlite3FixExprList(pFix, pSelect.pEList) != 0) { return 1; } if (sqlite3FixSrcList(pFix, pSelect.pSrc) != 0) { return 1; } if (sqlite3FixExpr(pFix, pSelect.pWhere) != 0) { return 1; } if (sqlite3FixExpr(pFix, pSelect.pHaving) != 0) { return 1; } pSelect = pSelect.pPrior; } return 0; } static int sqlite3FixExpr( DbFixer pFix, /* Context of the fixation */ Expr pExpr /* The expression to be fixed to one database */ ) { while (pExpr != null) { if (ExprHasAnyProperty(pExpr, EP_TokenOnly)) break; if (ExprHasProperty(pExpr, EP_xIsSelect)) { if (sqlite3FixSelect(pFix, pExpr.x.pSelect) != 0) return 1; } else { if (sqlite3FixExprList(pFix, pExpr.x.pList) != 0) return 1; } if (sqlite3FixExpr(pFix, pExpr.pRight) != 0) { return 1; } pExpr = pExpr.pLeft; } return 0; } static int sqlite3FixExprList( DbFixer pFix, /* Context of the fixation */ ExprList pList /* The expression to be fixed to one database */ ) { int i; ExprList_item pItem; if (pList == null) return 0; for (i = 0; i < pList.nExpr; i++)//, pItem++ ) { pItem = pList.a[i]; if (sqlite3FixExpr(pFix, pItem.pExpr) != 0) { return 1; } } return 0; } #endif #if !SQLITE_OMIT_TRIGGER static int sqlite3FixTriggerStep( DbFixer pFix, /* Context of the fixation */ TriggerStep pStep /* The trigger step be fixed to one database */ ) { while (pStep != null) { if (sqlite3FixSelect(pFix, pStep.pSelect) != 0) { return 1; } if (sqlite3FixExpr(pFix, pStep.pWhere) != 0) { return 1; } if (sqlite3FixExprList(pFix, pStep.pExprList) != 0) { return 1; } pStep = pStep.pNext; } return 0; } #endif } }
// ------------------------------------------------------------------------------ // 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 ContactRequest. /// </summary> public partial class ContactRequest : BaseRequest, IContactRequest { /// <summary> /// Constructs a new ContactRequest. /// </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 ContactRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Contact using POST. /// </summary> /// <param name="contactToCreate">The Contact to create.</param> /// <returns>The created Contact.</returns> public System.Threading.Tasks.Task<Contact> CreateAsync(Contact contactToCreate) { return this.CreateAsync(contactToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Contact using POST. /// </summary> /// <param name="contactToCreate">The Contact to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Contact.</returns> public async System.Threading.Tasks.Task<Contact> CreateAsync(Contact contactToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Contact>(contactToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Contact. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Contact. /// </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<Contact>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Contact. /// </summary> /// <returns>The Contact.</returns> public System.Threading.Tasks.Task<Contact> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Contact. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Contact.</returns> public async System.Threading.Tasks.Task<Contact> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Contact>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Contact using PATCH. /// </summary> /// <param name="contactToUpdate">The Contact to update.</param> /// <returns>The updated Contact.</returns> public System.Threading.Tasks.Task<Contact> UpdateAsync(Contact contactToUpdate) { return this.UpdateAsync(contactToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Contact using PATCH. /// </summary> /// <param name="contactToUpdate">The Contact to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Contact.</returns> public async System.Threading.Tasks.Task<Contact> UpdateAsync(Contact contactToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Contact>(contactToUpdate, 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 IContactRequest 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 IContactRequest Expand(Expression<Func<Contact, 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 IContactRequest 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 IContactRequest Select(Expression<Func<Contact, 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="contactToInitialize">The <see cref="Contact"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Contact contactToInitialize) { if (contactToInitialize != null && contactToInitialize.AdditionalData != null) { if (contactToInitialize.Extensions != null && contactToInitialize.Extensions.CurrentPage != null) { contactToInitialize.Extensions.AdditionalData = contactToInitialize.AdditionalData; object nextPageLink; contactToInitialize.AdditionalData.TryGetValue("extensions@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { contactToInitialize.Extensions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (contactToInitialize.SingleValueExtendedProperties != null && contactToInitialize.SingleValueExtendedProperties.CurrentPage != null) { contactToInitialize.SingleValueExtendedProperties.AdditionalData = contactToInitialize.AdditionalData; object nextPageLink; contactToInitialize.AdditionalData.TryGetValue("singleValueExtendedProperties@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { contactToInitialize.SingleValueExtendedProperties.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (contactToInitialize.MultiValueExtendedProperties != null && contactToInitialize.MultiValueExtendedProperties.CurrentPage != null) { contactToInitialize.MultiValueExtendedProperties.AdditionalData = contactToInitialize.AdditionalData; object nextPageLink; contactToInitialize.AdditionalData.TryGetValue("multiValueExtendedProperties@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { contactToInitialize.MultiValueExtendedProperties.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// 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.ServiceModel.Channels; using System.ServiceModel.Description; using System.Xml; using ISignatureValueSecurityElement = System.IdentityModel.ISignatureValueSecurityElement; namespace System.ServiceModel.Security { public abstract class SecurityVersion { private readonly XmlDictionaryString _headerName; private readonly XmlDictionaryString _headerNamespace; private readonly XmlDictionaryString _headerPrefix; internal SecurityVersion(XmlDictionaryString headerName, XmlDictionaryString headerNamespace, XmlDictionaryString headerPrefix) { _headerName = headerName; _headerNamespace = headerNamespace; _headerPrefix = headerPrefix; } internal XmlDictionaryString HeaderName { get { return _headerName; } } internal XmlDictionaryString HeaderNamespace { get { return _headerNamespace; } } internal XmlDictionaryString HeaderPrefix { get { return _headerPrefix; } } internal abstract XmlDictionaryString FailedAuthenticationFaultCode { get; } internal abstract XmlDictionaryString InvalidSecurityTokenFaultCode { get; } internal abstract XmlDictionaryString InvalidSecurityFaultCode { get; } internal virtual bool SupportsSignatureConfirmation { get { return false; } } public static SecurityVersion WSSecurity10 { get { return SecurityVersion10.Instance; } } public static SecurityVersion WSSecurity11 { get { return SecurityVersion11.Instance; } } internal static SecurityVersion Default { get { return WSSecurity11; } } internal abstract ReceiveSecurityHeader CreateReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction, int headerIndex); internal abstract SendSecurityHeader CreateSendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction); internal bool DoesMessageContainSecurityHeader(Message message) { return message.Headers.FindHeader(this.HeaderName.Value, this.HeaderNamespace.Value) >= 0; } internal int FindIndexOfSecurityHeader(Message message, string[] actors) { return message.Headers.FindHeader(this.HeaderName.Value, this.HeaderNamespace.Value, actors); } internal virtual bool IsReaderAtSignatureConfirmation(XmlDictionaryReader reader) { return false; } internal virtual ISignatureValueSecurityElement ReadSignatureConfirmation(XmlDictionaryReader reader) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.SignatureConfirmationNotSupported)); } // The security always look for Empty soap role. If not found, we will also look for Ultimate actors (next incl). // In the future, till we support intermediary scenario, we should refactor this api to do not take actor parameter. internal ReceiveSecurityHeader TryCreateReceiveSecurityHeader(Message message, string actor, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction) { int headerIndex = message.Headers.FindHeader(this.HeaderName.Value, this.HeaderNamespace.Value, actor); if (headerIndex < 0 && String.IsNullOrEmpty(actor)) { headerIndex = message.Headers.FindHeader(this.HeaderName.Value, this.HeaderNamespace.Value, message.Version.Envelope.UltimateDestinationActorValues); } if (headerIndex < 0) { return null; } MessageHeaderInfo headerInfo = message.Headers[headerIndex]; return CreateReceiveSecurityHeader(message, headerInfo.Actor, headerInfo.MustUnderstand, headerInfo.Relay, standardsManager, algorithmSuite, direction, headerIndex); } internal virtual void WriteSignatureConfirmation(XmlDictionaryWriter writer, string id, byte[] signatureConfirmation) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.SignatureConfirmationNotSupported)); } internal void WriteStartHeader(XmlDictionaryWriter writer) { writer.WriteStartElement(this.HeaderPrefix.Value, this.HeaderName, this.HeaderNamespace); } internal class SecurityVersion10 : SecurityVersion { private static readonly SecurityVersion10 s_instance = new SecurityVersion10(); protected SecurityVersion10() : base(XD.SecurityJan2004Dictionary.Security, XD.SecurityJan2004Dictionary.Namespace, XD.SecurityJan2004Dictionary.Prefix) { } public static SecurityVersion10 Instance { get { return s_instance; } } internal override XmlDictionaryString FailedAuthenticationFaultCode { get { return XD.SecurityJan2004Dictionary.FailedAuthenticationFaultCode; } } internal override XmlDictionaryString InvalidSecurityTokenFaultCode { get { return XD.SecurityJan2004Dictionary.InvalidSecurityTokenFaultCode; } } internal override XmlDictionaryString InvalidSecurityFaultCode { get { return XD.SecurityJan2004Dictionary.InvalidSecurityFaultCode; } } internal override SendSecurityHeader CreateSendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction) { return new WSSecurityOneDotZeroSendSecurityHeader(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction); } internal override ReceiveSecurityHeader CreateReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction, int headerIndex) { return new WSSecurityOneDotZeroReceiveSecurityHeader( message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, headerIndex, direction); } public override string ToString() { return "WSSecurity10"; } } internal sealed class SecurityVersion11 : SecurityVersion10 { private static readonly SecurityVersion11 s_instance = new SecurityVersion11(); private SecurityVersion11() : base() { } public new static SecurityVersion11 Instance { get { return s_instance; } } internal override bool SupportsSignatureConfirmation { get { return true; } } internal override ReceiveSecurityHeader CreateReceiveSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction, int headerIndex) { return new WSSecurityOneDotOneReceiveSecurityHeader( message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, headerIndex, direction); } internal override SendSecurityHeader CreateSendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection direction) { return new WSSecurityOneDotOneSendSecurityHeader(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, direction); } internal override bool IsReaderAtSignatureConfirmation(XmlDictionaryReader reader) { return reader.IsStartElement(XD.SecurityXXX2005Dictionary.SignatureConfirmation, XD.SecurityXXX2005Dictionary.Namespace); } internal override ISignatureValueSecurityElement ReadSignatureConfirmation(XmlDictionaryReader reader) { reader.MoveToStartElement(XD.SecurityXXX2005Dictionary.SignatureConfirmation, XD.SecurityXXX2005Dictionary.Namespace); bool isEmptyElement = reader.IsEmptyElement; string id = XmlHelper.GetRequiredNonEmptyAttribute(reader, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace); byte[] signatureValue = XmlHelper.GetRequiredBase64Attribute(reader, XD.SecurityXXX2005Dictionary.ValueAttribute, null); reader.ReadStartElement(); if (!isEmptyElement) { reader.ReadEndElement(); } return new SignatureConfirmationElement(id, signatureValue, this); } internal override void WriteSignatureConfirmation(XmlDictionaryWriter writer, string id, byte[] signature) { if (id == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("id"); } if (signature == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("signature"); } writer.WriteStartElement(XD.SecurityXXX2005Dictionary.Prefix.Value, XD.SecurityXXX2005Dictionary.SignatureConfirmation, XD.SecurityXXX2005Dictionary.Namespace); writer.WriteAttributeString(XD.UtilityDictionary.Prefix.Value, XD.UtilityDictionary.IdAttribute, XD.UtilityDictionary.Namespace, id); writer.WriteStartAttribute(XD.SecurityXXX2005Dictionary.ValueAttribute, null); writer.WriteBase64(signature, 0, signature.Length); writer.WriteEndAttribute(); writer.WriteEndElement(); } public override string ToString() { return "WSSecurity11"; } } } }
/* * Copyright 2012 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; using ZXing.Core; using ZXing.PDF417.Internal; using ZXing.Writer; namespace ZXing.PDF417 { /// <summary> /// <author>Jacob Haynes</author> /// <author>qwandor@google.com (Andrew Walbran)</author> /// </summary> public sealed class PDF417Writer : ZXingWriter { /// <summary> /// default white space (margin) around the code /// </summary> private const int WHITE_SPACE = 30; /// <summary> /// </summary> /// <param name="contents">The contents to encode in the barcode</param> /// <param name="format">The barcode format to generate</param> /// <param name="width">The preferred width in pixels</param> /// <param name="height">The preferred height in pixels</param> /// <param name="hints">Additional parameters to supply to the encoder</param> /// <returns> /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) /// </returns> public BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary<EncodeHintType, object> hints) { if (format != BarcodeFormat.PDF_417) { throw new ArgumentException("Can only encode PDF_417, but got " + format); } var encoder = new Internal.PDF417(); var margin = WHITE_SPACE; var errorCorrectionLevel = 2; if (hints != null) { if (hints.ContainsKey(EncodeHintType.PDF417_COMPACT)) { encoder.setCompact((Boolean) hints[EncodeHintType.PDF417_COMPACT]); } if (hints.ContainsKey(EncodeHintType.PDF417_COMPACTION)) { encoder.setCompaction((Compaction) hints[EncodeHintType.PDF417_COMPACTION]); } if (hints.ContainsKey(EncodeHintType.PDF417_DIMENSIONS)) { var dimensions = (Dimensions) hints[EncodeHintType.PDF417_DIMENSIONS]; encoder.setDimensions(dimensions.MaxCols, dimensions.MinCols, dimensions.MaxRows, dimensions.MinRows); } if (hints.ContainsKey(EncodeHintType.MARGIN)) { margin = (int)(hints[EncodeHintType.MARGIN]); } if (hints.ContainsKey(EncodeHintType.ERROR_CORRECTION)) { var value = hints[EncodeHintType.ERROR_CORRECTION]; if (value is PDF417ErrorCorrectionLevel || value is int) { errorCorrectionLevel = (int)value; } } if (hints.ContainsKey(EncodeHintType.CHARACTER_SET)) { #if !SILVERLIGHT || WINDOWS_PHONE var encoding = (String)hints[EncodeHintType.CHARACTER_SET]; if (encoding != null) { encoder.setEncoding(encoding); } #else // Silverlight supports only UTF-8 and UTF-16 out-of-the-box encoder.setEncoding("UTF-8"); #endif } if (hints.ContainsKey(EncodeHintType.DISABLE_ECI)) { encoder.setDisableEci((bool)hints[EncodeHintType.DISABLE_ECI]); } } return bitMatrixFromEncoder(encoder, contents, width, height, margin, errorCorrectionLevel); } /// <summary> /// Encode a barcode using the default settings. /// </summary> /// <param name="contents">The contents to encode in the barcode</param> /// <param name="format">The barcode format to generate</param> /// <param name="width">The preferred width in pixels</param> /// <param name="height">The preferred height in pixels</param> /// <returns> /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) /// </returns> public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } /// <summary> /// Takes encoder, accounts for width/height, and retrieves bit matrix /// </summary> private static BitMatrix bitMatrixFromEncoder(Internal.PDF417 encoder, String contents, int width, int height, int margin, int errorCorrectionLevel) { encoder.generateBarcodeLogic(contents, errorCorrectionLevel); const int lineThickness = 2; const int aspectRatio = 4; sbyte[][] originalScale = encoder.BarcodeMatrix.getScaledMatrix(lineThickness, aspectRatio*lineThickness); bool rotated = false; if ((height > width) ^ (originalScale[0].Length < originalScale.Length)) { originalScale = rotateArray(originalScale); rotated = true; } int scaleX = width/originalScale[0].Length; int scaleY = height/originalScale.Length; int scale; if (scaleX < scaleY) { scale = scaleX; } else { scale = scaleY; } if (scale > 1) { sbyte[][] scaledMatrix = encoder.BarcodeMatrix.getScaledMatrix(scale*lineThickness, scale*aspectRatio*lineThickness); if (rotated) { scaledMatrix = rotateArray(scaledMatrix); } return bitMatrixFrombitArray(scaledMatrix, margin); } return bitMatrixFrombitArray(originalScale, margin); } /// <summary> /// This takes an array holding the values of the PDF 417 /// </summary> /// <param name="input">a byte array of information with 0 is black, and 1 is white</param> /// <param name="margin">border around the barcode</param> /// <returns>BitMatrix of the input</returns> private static BitMatrix bitMatrixFrombitArray(sbyte[][] input, int margin) { // Creates the bitmatrix with extra space for whitespace var output = new BitMatrix(input[0].Length + 2 * margin, input.Length + 2 * margin); var yOutput = output.Height - margin - 1; for (int y = 0; y < input.Length; y++) { var currentInput = input[y]; var currentInputLength = currentInput.Length; for (int x = 0; x < currentInputLength; x++) { // Zero is white in the bytematrix if (currentInput[x] == 1) { output[x + margin, yOutput] = true; } } yOutput--; } return output; } /// <summary> /// Takes and rotates the it 90 degrees /// </summary> private static sbyte[][] rotateArray(sbyte[][] bitarray) { sbyte[][] temp = new sbyte[bitarray[0].Length][]; for (int idx = 0; idx < bitarray[0].Length; idx++) temp[idx] = new sbyte[bitarray.Length]; for (int ii = 0; ii < bitarray.Length; ii++) { // This makes the direction consistent on screen when rotating the // screen; int inverseii = bitarray.Length - ii - 1; for (int jj = 0; jj < bitarray[0].Length; jj++) { temp[jj][inverseii] = bitarray[ii][jj]; } } return temp; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using IxMilia.BCad.Collections; using IxMilia.BCad.Commands; using IxMilia.BCad.Core.Services; using IxMilia.BCad.Display; using IxMilia.BCad.Entities; using IxMilia.BCad.EventArguments; using IxMilia.BCad.Services; using IxMilia.BCad.Settings; namespace IxMilia.BCad { public abstract class WorkspaceBase : IWorkspace { private RubberBandGenerator rubberBandGenerator; private readonly Regex settingsPattern = new Regex(@"^/p:([a-zA-Z\.]+)=(.*)$"); private List<CadCommandInfo> _commands = new List<CadCommandInfo>(); private List<IWorkspaceService> _services = new List<IWorkspaceService>(); public WorkspaceBase() { Drawing = new Drawing(); DrawingPlane = new Plane(Point.Origin, Vector.ZAxis); ActiveViewPort = ViewPort.CreateDefaultViewPort(); SelectedEntities = new ObservableHashSet<Entity>(); ViewControl = null; RubberBandGenerator = null; RegisterDefaultCommands(); RegisterDefaultServices(); RegisterDefaultSettings(); } private void RegisterDefaultCommands() { RegisterCommand(new CadCommandInfo("Edit.Copy", "COPY", new CopyCommand(), ModifierKeys.Control, Key.C, "copy", "co")); RegisterCommand(new CadCommandInfo("Debug.Dump", "DUMP", new DebugDumpCommand(), "dump")); RegisterCommand(new CadCommandInfo("Debug.Attach", "ATTACH", new DebuggerAttachCommand(), "attach")); RegisterCommand(new CadCommandInfo("Edit.Delete", "DELETE", new DeleteCommand(), ModifierKeys.None, Key.Delete, "delete", "d", "del")); RegisterCommand(new CadCommandInfo("View.Distance", "DIST", new DistanceCommand(), "distance", "di", "dist")); RegisterCommand(new CadCommandInfo("Draw.Arc", "ARC", new DrawArcCommand(), "arc", "a")); RegisterCommand(new CadCommandInfo("Draw.Circle", "CIRCLE", new DrawCircleCommand(), "circle", "c", "cir")); RegisterCommand(new CadCommandInfo("Draw.Ellipse", "ELLIPSE", new DrawEllipseCommand(), "ellipse", "el")); RegisterCommand(new CadCommandInfo("Draw.Line", "LINE", new DrawLineCommand(), "line", "l")); RegisterCommand(new CadCommandInfo("Draw.Point", "POINT", new DrawPointCommand(), "point", "p")); RegisterCommand(new CadCommandInfo("Draw.Polygon", "POLYGON", new DrawPolygonCommand(), "polygon", "pg")); RegisterCommand(new CadCommandInfo("Draw.PolyLine", "POLYLINE", new DrawPolyLineCommand(), "polyline", "pl")); RegisterCommand(new CadCommandInfo("Draw.Rectangle", "RECTANGLE", new DrawRectangleCommand(), "rectangle", "rect")); RegisterCommand(new CadCommandInfo("Draw.Text", "TEXT", new DrawTextCommand(), "text", "t")); RegisterCommand(new CadCommandInfo("View.Properties", "PROPERTIES", new EntityPropertiesCommand(), "properties", "prop", "p")); RegisterCommand(new CadCommandInfo("Edit.Extend", "EXTEND", new ExtendCommand(), "extend", "ex")); RegisterCommand(new CadCommandInfo("Edit.Intersection", "INTERSECTION", new IntersectionCommand(), "intersection", "int")); RegisterCommand(new CadCommandInfo("Edit.JoinPolyline", "PJOIN", new JoinPolylineCommand(), "pjoin")); RegisterCommand(new CadCommandInfo("Edit.Layers", "LAYERS", new LayersCommand(), ModifierKeys.Control, Key.L, "layers", "layer", "la")); RegisterCommand(new CadCommandInfo("Edit.Move", "MOVE", new MoveCommand(), "move", "mov", "m")); RegisterCommand(new CadCommandInfo("File.New", "NEW", new NewCommand(), ModifierKeys.Control, Key.N, "new", "n")); RegisterCommand(new CadCommandInfo("Edit.Offset", "OFFSET", new OffsetCommand(), "offset", "off", "of")); RegisterCommand(new CadCommandInfo("View.Pan", "PAN", new PanCommand(), "pan", "p")); RegisterCommand(new CadCommandInfo("File.Plot", "PLOT", new PlotCommand(), ModifierKeys.Control, Key.P, "plot")); RegisterCommand(new CadCommandInfo("Edit.Rotate", "ROTATE", new RotateCommand(), "rotate", "rot", "ro")); RegisterCommand(new CadCommandInfo("Edit.Subtract", "SUBTRACT", new SubtractCommand(), "subtract", "sub")); RegisterCommand(new CadCommandInfo("Edit.Trim", "TRIM", new TrimCommand(), "trim", "tr")); RegisterCommand(new CadCommandInfo("Edit.Union", "UNION", new UnionCommand(), "union", "un")); RegisterCommand(new CadCommandInfo("Zoom.Extents", "ZOOMEXTENTS",new ZoomExtentsCommand(), "zoomextents", "ze")); RegisterCommand(new CadCommandInfo("Zoom.Window", "ZOOMWINDOW", new ZoomWindowCommand(), "zoomwindow", "zw")); } private void RegisterDefaultServices() { RegisterService<IDebugService>(new DebugService()); RegisterService<IReaderWriterService>(new ReaderWriterService(this)); RegisterService<IInputService>(new InputService(this)); RegisterService<IOutputService>(new OutputService()); RegisterService<ISettingsService>(new SettingsService(this)); RegisterService<IUndoRedoService>(new UndoRedoService(this)); } private void RegisterDefaultSettings() { SettingsService.RegisterSetting(DefaultSettingsNames.Debug, typeof(bool), false); SettingsService.RegisterSetting(DisplaySettingsNames.AngleSnap, typeof(bool), true); SettingsService.RegisterSetting(DisplaySettingsNames.BackgroundColor, typeof(CadColor), "#FF2F2F2F"); SettingsService.RegisterSetting(DisplaySettingsNames.CursorSize, typeof(int), 60); SettingsService.RegisterSetting(DisplaySettingsNames.EntitySelectionRadius, typeof(double), 3.0); SettingsService.RegisterSetting(DisplaySettingsNames.HotPointColor, typeof(CadColor), "#FF0000FF"); SettingsService.RegisterSetting(DisplaySettingsNames.HotPointSize, typeof(double), 10.0); SettingsService.RegisterSetting(DisplaySettingsNames.Ortho, typeof(bool), false); SettingsService.RegisterSetting(DisplaySettingsNames.PointSnap, typeof(bool), true); SettingsService.RegisterSetting(DisplaySettingsNames.SnapAngleDistance, typeof(double), 30.0); SettingsService.RegisterSetting(DisplaySettingsNames.SnapAngles, typeof(double[]), new[] { 0.0, 90.0, 180.0, 270.0 }); SettingsService.RegisterSetting(DisplaySettingsNames.SnapPointColor, typeof(CadColor), "#FFFFFF00"); SettingsService.RegisterSetting(DisplaySettingsNames.SnapPointDistance, typeof(double), 15.0); SettingsService.RegisterSetting(DisplaySettingsNames.SnapPointSize, typeof(double), 15.0); SettingsService.RegisterSetting(DisplaySettingsNames.TextCursorSize, typeof(int), 18); SettingsService.RegisterSetting(DisplaySettingsNames.PointDisplaySize, typeof(double), 48.0); } #region Events public event CommandExecutingEventHandler CommandExecuting; protected virtual void OnCommandExecuting(CadCommandExecutingEventArgs e) { var executing = CommandExecuting; if (executing != null) executing(this, e); } public event CommandExecutedEventHandler CommandExecuted; protected virtual void OnCommandExecuted(CadCommandExecutedEventArgs e) { var executed = CommandExecuted; if (executed != null) executed(this, e); } public event EventHandler RubberBandGeneratorChanged; protected virtual void OnRubberBandGeneratorChanged(EventArgs e) { var changed = RubberBandGeneratorChanged; if (changed != null) changed(this, e); } #endregion #region Properties public bool IsDirty { get; private set; } public Drawing Drawing { get; private set; } public Plane DrawingPlane { get; private set; } public ViewPort ActiveViewPort { get; private set; } public IViewControl ViewControl { get; private set; } public ObservableHashSet<Entity> SelectedEntities { get; private set; } public RubberBandGenerator RubberBandGenerator { get { return rubberBandGenerator; } set { if (rubberBandGenerator == value) return; rubberBandGenerator = value; OnRubberBandGeneratorChanged(new EventArgs()); } } public bool IsDrawing { get { return RubberBandGenerator != null; } } public bool IsCommandExecuting { get; private set; } #endregion #region IWorkspace implementation public void RegisterService<TService>(TService service) where TService : class, IWorkspaceService { _services.Add(service); } public TService GetService<TService>() where TService : class, IWorkspaceService { return _services.OfType<TService>().SingleOrDefault(); } // well-known services private IDebugService _debugServiceCache; public IDebugService DebugService => CacheService<IDebugService>(ref _debugServiceCache); private IDialogService _dialogServiceCache; public IDialogService DialogService => CacheService<IDialogService>(ref _dialogServiceCache); private IInputService _inputServiceCache; public IInputService InputService => CacheService<IInputService>(ref _inputServiceCache); private IOutputService _outputServiceCache; public IOutputService OutputService => CacheService<IOutputService>(ref _outputServiceCache); private IReaderWriterService _readerWriterServiceCache; public IReaderWriterService ReaderWriterService => CacheService<IReaderWriterService>(ref _readerWriterServiceCache); private ISettingsService _settingsService; public ISettingsService SettingsService => CacheService<ISettingsService>(ref _settingsService); private IUndoRedoService _undoRedoServiceCache; public IUndoRedoService UndoRedoService => CacheService<IUndoRedoService>(ref _undoRedoServiceCache); private TService CacheService<TService>(ref TService backingStore) where TService : class, IWorkspaceService { if (backingStore == null) { backingStore = GetService<TService>(); } return backingStore; } public async Task Initialize(params string[] args) { string fileName = null; foreach (var arg in args) { var match = settingsPattern.Match(arg); if (match.Success) { var settingName = match.Groups[1].Value; var settingValue = match.Groups[2].Value; SettingsService.SetValue(settingName, settingValue); } else { // try to match a file to open if (!string.IsNullOrEmpty(fileName)) { throw new NotSupportedException("More than one file specified on the command line."); } else { fileName = arg; } } } if (!string.IsNullOrEmpty(fileName)) { Update(isDirty: false); // don't let the following command prompt for unsaved changes await ExecuteCommand("File.Open", fileName); } } public virtual void Update( Optional<Drawing> drawing = default(Optional<Drawing>), Optional<Plane> drawingPlane = default(Optional<Plane>), Optional<ViewPort> activeViewPort = default(Optional<ViewPort>), Optional<IViewControl> viewControl = default(Optional<IViewControl>), bool isDirty = true) { var e = new WorkspaceChangeEventArgs( drawing.HasValue, drawingPlane.HasValue, activeViewPort.HasValue, viewControl.HasValue, this.IsDirty != isDirty); OnWorkspaceChanging(e); if (drawing.HasValue) this.Drawing = drawing.Value; if (drawingPlane.HasValue) this.DrawingPlane = drawingPlane.Value; if (activeViewPort.HasValue) this.ActiveViewPort = activeViewPort.Value; if (viewControl.HasValue) this.ViewControl = viewControl.Value; this.IsDirty = isDirty; OnWorkspaceChanged(e); } public event WorkspaceChangingEventHandler WorkspaceChanging; protected void OnWorkspaceChanging(WorkspaceChangeEventArgs e) { var handler = WorkspaceChanging; if (handler != null) handler(this, e); } public event WorkspaceChangedEventHandler WorkspaceChanged; protected void OnWorkspaceChanged(WorkspaceChangeEventArgs e) { var handler = WorkspaceChanged; if (handler != null) handler(this, e); } private async Task<bool> Execute(Tuple<ICadCommand, string> commandPair, object arg) { var command = commandPair.Item1; var display = commandPair.Item2; var outputService = GetService<IOutputService>(); OnCommandExecuting(new CadCommandExecutingEventArgs(command)); outputService.WriteLine(display); bool result; try { result = await command.Execute(this, arg); } catch (Exception ex) { outputService.WriteLine("Error: {0} - {1}", ex.GetType().ToString(), ex.Message); result = false; } RubberBandGenerator = null; OnCommandExecuted(new CadCommandExecutedEventArgs(command)); return result; } public void RegisterCommand(CadCommandInfo commandInfo) { _commands.Add(commandInfo); } public async Task<bool> ExecuteCommand(string commandName, object arg) { if (commandName == null && lastCommand == null) { return false; } lock (executeGate) { if (IsCommandExecuting) return false; IsCommandExecuting = true; } commandName = commandName ?? lastCommand; var debugService = GetService<IDebugService>(); var outputService = GetService<IOutputService>(); debugService.Add(new WorkspaceLogEntry(string.Format("execute {0}", commandName))); var commandPair = GetCommand(commandName); if (commandPair == null) { outputService.WriteLine("Command {0} not found", commandName); IsCommandExecuting = false; return false; } var selectedStart = SelectedEntities; var result = await Execute(commandPair, arg); lastCommand = commandName; lock (executeGate) { IsCommandExecuting = false; SelectedEntities = selectedStart; } return result; } public bool CommandExists(string commandName) { return GetCommand(commandName) != null; } public bool CanExecute() { return !this.IsCommandExecuting; } public abstract Task<UnsavedChangesResult> PromptForUnsavedChanges(); #endregion #region Privates private string lastCommand = null; private object executeGate = new object(); public virtual Tuple<ICadCommand, string> GetCommand(string commandName) { var candidateCommands = from commandInfo in _commands where string.Compare(commandInfo.Name, commandName, StringComparison.OrdinalIgnoreCase) == 0 || commandInfo.Aliases.Any(alias => string.Compare(alias, commandName, StringComparison.OrdinalIgnoreCase) == 0) select commandInfo; var command = candidateCommands.FirstOrDefault(); if (candidateCommands.Count() > 1) { throw new InvalidOperationException($"Ambiguous command name '{commandName}'. Possibilities: {string.Join(", ", candidateCommands.Select(c => c.Name))}"); } return command == null ? null : Tuple.Create(command.Command, command.DisplayName); } #endregion } }
using System; using System.Diagnostics; using System.IO; using System.Text; namespace newtelligence.DasBlog.Runtime.Html.Formatting { internal sealed class FormattedTextWriter : TextWriter { private TextWriter baseWriter; private string indentString; private int currentColumn; private int indentLevel; private bool indentPending; private bool onNewLine; public FormattedTextWriter(TextWriter writer, string indentString) { this.baseWriter = writer; this.indentString = indentString; this.onNewLine = true; currentColumn = 0; } public override Encoding Encoding { get { return baseWriter.Encoding; } } public override string NewLine { get { return baseWriter.NewLine; } set { baseWriter.NewLine = value; } } public int Indent { get { return indentLevel; } set { if (value < 0) { value = 0; } indentLevel = value; Debug.Assert(value >= 0, "Invalid IndentLevel"); } } public override void Close() { baseWriter.Close(); } public override void Flush() { baseWriter.Flush(); } public static bool HasBackWhiteSpace(string s) { if ((s == null) || (s.Length == 0)) { return false; } return (Char.IsWhiteSpace(s[s.Length - 1])); } public static bool HasFrontWhiteSpace(string s) { if ((s == null) || (s.Length == 0)) { return false; } return (Char.IsWhiteSpace(s[0])); } public static bool IsWhiteSpace(string s) { for (int i = 0; i < s.Length; i++) { if (!Char.IsWhiteSpace(s[i])) { return false; } } return true; } /// <summary> /// Converts the string into a single line seperated by single spaces /// </summary> /// <param name="s"></param> /// <returns></returns> /// TODO: Rename to CollapseWhitespace private string MakeSingleLine(string s) { StringBuilder builder = new StringBuilder(); int i = 0; while (i < s.Length) { char c = s[i]; if (Char.IsWhiteSpace(c)) { builder.Append(' '); while ((i < s.Length) && (Char.IsWhiteSpace(s[i]))) { i++; } } else { builder.Append(c); i++; } } return builder.ToString(); } public static string Trim(string text, bool frontWhiteSpace) { if (text.Length == 0) { // If there is no text, return the empty string return String.Empty; } if (IsWhiteSpace(text)) { // If the text is all whitespace if (frontWhiteSpace) { // If the caller wanted to preserve front whitespace, then return just one space return " "; } else { // If the caller isn't trying to preserve anything, return the empty string return String.Empty; } } // Trim off all whitespace string t = text.Trim(); if (frontWhiteSpace && HasFrontWhiteSpace(text)) { // Add front whitespace if there was some and we're trying to preserve it t = ' ' + t; } if (HasBackWhiteSpace(text)) { // Add back whitespace if there was some t = t + ' '; } return t; } private void OutputIndent() { if (indentPending) { for (int i = 0; i < indentLevel; i++) { baseWriter.Write(indentString); } indentPending = false; } } public void WriteLiteral(string s) { if (s.Length != 0) { StringReader reader = new StringReader(s); // We want to output the first line of the string trimming the back whitespace // the middle lines trimming all whitespace // and the last line trimming the leading whitespace (which requires a one string lookahead) string lastString = reader.ReadLine(); string nextString = reader.ReadLine(); while (lastString != null) { Write(lastString); lastString = nextString; nextString = reader.ReadLine(); if (lastString != null) { WriteLine(); } if (nextString != null) { lastString = lastString.Trim(); } else if (lastString != null) { lastString = Trim(lastString, false); } } } } public void WriteLiteralWrapped(string s, int maxLength) { if (s.Length != 0) { // First make the string a single line space-delimited string and split on the strings string[] tokens = MakeSingleLine(s).Split(null); // Preserve the initial whitespace if (HasFrontWhiteSpace(s)) { Write(' '); } // Write out all tokens, wrapping when the length exceeds the specified length for (int i = 0; i < tokens.Length; i++) { if (tokens[i].Length > 0) { Write(tokens[i]); if ((i < (tokens.Length - 1)) && (tokens[i + 1].Length > 0)) { if (currentColumn > maxLength) { WriteLine(); } else { Write(' '); } } } } if (HasBackWhiteSpace(s) && !IsWhiteSpace(s)) { Write(' '); } } } public void WriteLineIfNotOnNewLine() { if (onNewLine == false) { baseWriter.WriteLine(); onNewLine = true; currentColumn = 0; indentPending = true; } } public override void Write(string s) { OutputIndent(); baseWriter.Write(s); onNewLine = false; currentColumn += s.Length; } public override void Write(bool value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(char value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn ++; } public override void Write(char[] buffer) { OutputIndent(); baseWriter.Write(buffer); onNewLine = false; currentColumn += buffer.Length; } public override void Write(char[] buffer, int index, int count) { OutputIndent(); baseWriter.Write(buffer, index, count); onNewLine = false; currentColumn += count; } public override void Write(double value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(float value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(int value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(long value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(object value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(string format, object arg0) { OutputIndent(); string s = String.Format(format, arg0); baseWriter.Write(s); onNewLine = false; currentColumn += s.Length; } public override void Write(string format, object arg0, object arg1) { OutputIndent(); string s = String.Format(format, arg0, arg1); baseWriter.Write(s); onNewLine = false; currentColumn += s.Length; } public override void Write(string format, params object[] arg) { OutputIndent(); string s = String.Format(format, arg); baseWriter.Write(s); onNewLine = false; currentColumn += s.Length; } public override void WriteLine(string s) { OutputIndent(); baseWriter.WriteLine(s); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine() { OutputIndent(); baseWriter.WriteLine(); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(bool value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(char value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(char[] buffer) { OutputIndent(); baseWriter.WriteLine(buffer); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(char[] buffer, int index, int count) { OutputIndent(); baseWriter.WriteLine(buffer, index, count); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(double value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(float value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(int value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(long value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(object value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(string format, object arg0) { OutputIndent(); baseWriter.WriteLine(format, arg0); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(string format, object arg0, object arg1) { OutputIndent(); baseWriter.WriteLine(format, arg0, arg1); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(string format, params object[] arg) { OutputIndent(); baseWriter.WriteLine(format, arg); indentPending = true; currentColumn = 0; onNewLine = true; } } }
/* * 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 System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client; [TestFixture] [Category("group1")] [Category("unicast_only")] [Category("generics")] public class ThinClientRegionInterestFailoverInterest2Tests : ThinClientRegionSteps { #region Private members and methods private UnitProcess m_client1, m_client2, m_client3, m_feeder; private static string[] m_regexes = { "Key-*1", "Key-*2", "Key-*3", "Key-*4" }; private const string m_regex23 = "Key-[23]"; private const string m_regexWildcard = "Key-.*"; private const int m_numUnicodeStrings = 5; private static string[] m_keysNonRegex = { "key-1", "key-2", "key-3" }; private static string[] m_keysForRegex = {"key-regex-1", "key-regex-2", "key-regex-3" }; private static string[] RegionNamesForInterestNotify = { "RegionTrue", "RegionFalse", "RegionOther" }; string GetUnicodeString(int index) { return new string('\x0905', 40) + index.ToString("D10"); } #endregion protected override ClientBase[] GetClients() { m_client1 = new UnitProcess(); m_client2 = new UnitProcess(); m_client3 = new UnitProcess(); m_feeder = new UnitProcess(); return new ClientBase[] { m_client1, m_client2, m_client3, m_feeder }; } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { m_client1.Call(DestroyRegions); m_client2.Call(DestroyRegions); CacheHelper.ClearEndpoints(); } finally { CacheHelper.StopJavaServers(); } base.EndTest(); } #region Steps for Thin Client IRegion<object, object> with Interest public void StepFourIL() { VerifyCreated(m_regionNames[0], m_keys[0]); VerifyCreated(m_regionNames[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); } public void StepFourRegex3() { IRegion<object, object> region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); IRegion<object, object> region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); try { Util.Log("Registering empty regular expression."); region0.GetSubscriptionService().RegisterRegex(string.Empty); Assert.Fail("Did not get expected exception!"); } catch (Exception ex) { Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message); } try { Util.Log("Registering null regular expression."); region1.GetSubscriptionService().RegisterRegex(null); Assert.Fail("Did not get expected exception!"); } catch (Exception ex) { Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message); } try { Util.Log("Registering non-existent regular expression."); region1.GetSubscriptionService().UnregisterRegex("Non*Existent*Regex*"); Assert.Fail("Did not get expected exception!"); } catch (Exception ex) { Util.Log("Got expected exception {0}: {1}", ex.GetType(), ex.Message); } } public void StepFourFailoverRegex() { VerifyCreated(m_regionNames[0], m_keys[0]); VerifyCreated(m_regionNames[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); UpdateEntry(m_regionNames[1], m_keys[1], m_vals[1], true); UnregisterRegexes(null, m_regexes[2]); } public void StepFiveIL() { VerifyCreated(m_regionNames[0], m_keys[1]); VerifyCreated(m_regionNames[1], m_keys[3]); VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false); } public void StepFiveRegex() { CreateEntry(m_regionNames[0], m_keys[2], m_vals[2]); CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]); } public void CreateAllEntries(string regionName) { CreateEntry(regionName, m_keys[0], m_vals[0]); CreateEntry(regionName, m_keys[1], m_vals[1]); CreateEntry(regionName, m_keys[2], m_vals[2]); CreateEntry(regionName, m_keys[3], m_vals[3]); } public void VerifyAllEntries(string regionName, bool newVal, bool checkVal) { string[] vals = newVal ? m_nvals : m_vals; VerifyEntry(regionName, m_keys[0], vals[0], checkVal); VerifyEntry(regionName, m_keys[1], vals[1], checkVal); VerifyEntry(regionName, m_keys[2], vals[2], checkVal); VerifyEntry(regionName, m_keys[3], vals[3], checkVal); } public void VerifyInvalidAll(string regionName, params string[] keys) { if (keys != null) { foreach (string key in keys) { VerifyInvalid(regionName, key); } } } public void UpdateAllEntries(string regionName, bool checkVal) { UpdateEntry(regionName, m_keys[0], m_nvals[0], checkVal); UpdateEntry(regionName, m_keys[1], m_nvals[1], checkVal); UpdateEntry(regionName, m_keys[2], m_nvals[2], checkVal); UpdateEntry(regionName, m_keys[3], m_nvals[3], checkVal); } public void DoNetsearchAllEntries(string regionName, bool newVal, bool checkNoKey) { string[] vals; if (newVal) { vals = m_nvals; } else { vals = m_vals; } DoNetsearch(regionName, m_keys[0], vals[0], checkNoKey); DoNetsearch(regionName, m_keys[1], vals[1], checkNoKey); DoNetsearch(regionName, m_keys[2], vals[2], checkNoKey); DoNetsearch(regionName, m_keys[3], vals[3], checkNoKey); } public void StepFiveFailoverRegex() { UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false); VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1], false); } public void StepSixIL() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); IRegion<object, object> region0 = CacheHelper.GetRegion<object, object>(m_regionNames[0]); IRegion<object, object> region1 = CacheHelper.GetRegion<object, object>(m_regionNames[1]); region0.Remove(m_keys[1]); region1.Remove(m_keys[3]); } public void StepSixRegex() { CreateEntry(m_regionNames[0], m_keys[0], m_vals[0]); CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); UnregisterRegexes(null, m_regexes[3]); } public void StepSixFailoverRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2], false); UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], false); } public void StepSevenIL() { VerifyDestroyed(m_regionNames[0], m_keys[1]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); } public void StepSevenRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]); UpdateEntry(m_regionNames[0], m_keys[2], m_nvals[2], true); UpdateEntry(m_regionNames[1], m_keys[3], m_nvals[3], true); UnregisterRegexes(null, m_regexes[1]); } public void StepSevenRegex2() { VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[0], m_keys[2], m_vals[2]); DoNetsearch(m_regionNames[0], m_keys[0], m_vals[0], true); DoNetsearch(m_regionNames[0], m_keys[3], m_vals[3], true); UpdateAllEntries(m_regionNames[1], true); } public void StepSevenInterestResultPolicyInv() { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region.GetSubscriptionService().RegisterRegex(m_regex23); VerifyInvalidAll(m_regionNames[0], m_keys[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0], true); VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3], true); } public void StepSevenFailoverRegex() { UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], true); UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], true); VerifyEntry(m_regionNames[1], m_keys[1], m_nvals[1]); } public void StepEightIL() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]); } public void StepEightRegex() { VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], true); UpdateEntry(m_regionNames[1], m_keys[1], m_nvals[1], true); } public void StepEightInterestResultPolicyInv() { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); region.GetSubscriptionService().RegisterAllKeys(); VerifyInvalidAll(m_regionNames[1], m_keys[0], m_keys[1], m_keys[2], m_keys[3]); UpdateAllEntries(m_regionNames[0], true); } public void StepEightFailoverRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); } public void StepNineRegex() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[1], m_vals[1]); } public void StepNineRegex2() { VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[0], m_keys[1], m_nvals[1]); VerifyEntry(m_regionNames[0], m_keys[2], m_nvals[2]); VerifyEntry(m_regionNames[0], m_keys[3], m_vals[3]); } public void StepNineInterestResultPolicyInv() { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region.GetSubscriptionService().UnregisterRegex(m_regex23); List<Object> keys = new List<Object>(); keys.Add(m_keys[0]); keys.Add(m_keys[1]); keys.Add(m_keys[2]); region.GetSubscriptionService().RegisterKeys(keys); VerifyInvalidAll(m_regionNames[0], m_keys[0], m_keys[1], m_keys[2]); } public void PutUnicodeKeys(string regionName, bool updates) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); string key; object val; for (int index = 0; index < m_numUnicodeStrings; ++index) { key = GetUnicodeString(index); if (updates) { val = index + 100; } else { val = (float)index + 20.0F; } region[key] = val; } } public void RegisterUnicodeKeys(string regionName) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); string[] keys = new string[m_numUnicodeStrings]; for (int index = 0; index < m_numUnicodeStrings; ++index) { keys[m_numUnicodeStrings - index - 1] = GetUnicodeString(index); } region.GetSubscriptionService().RegisterKeys(keys); } public void VerifyUnicodeKeys(string regionName, bool updates) { IRegion<object, object> region = CacheHelper.GetVerifyRegion<object, object>(regionName); string key; object expectedVal; for (int index = 0; index < m_numUnicodeStrings; ++index) { key = GetUnicodeString(index); if (updates) { expectedVal = index + 100; Assert.AreEqual(expectedVal, region.GetEntry(key).Value, "Got unexpected value"); } else { expectedVal = (float)index + 20.0F; Assert.AreEqual(expectedVal, region[key], "Got unexpected value"); } } } public void CreateRegionsInterestNotify_Pool(string[] regionNames, string locators, string poolName, bool notify, string nbs) { var props = Properties<string, string>.Create(); //props.Insert("notify-by-subscription-override", nbs); CacheHelper.InitConfig(props); CacheHelper.CreateTCRegion_Pool(regionNames[0], true, true, new TallyListener<object, object>(), locators, poolName, notify); CacheHelper.CreateTCRegion_Pool(regionNames[1], true, true, new TallyListener<object, object>(), locators, poolName, notify); CacheHelper.CreateTCRegion_Pool(regionNames[2], true, true, new TallyListener<object, object>(), locators, poolName, notify); } /* public void CreateRegionsInterestNotify(string[] regionNames, string endpoints, bool notify, string nbs) { Properties props = Properties.Create(); //props.Insert("notify-by-subscription-override", nbs); CacheHelper.InitConfig(props); CacheHelper.CreateTCRegion(regionNames[0], true, false, new TallyListener(), endpoints, notify); CacheHelper.CreateTCRegion(regionNames[1], true, false, new TallyListener(), endpoints, notify); CacheHelper.CreateTCRegion(regionNames[2], true, false, new TallyListener(), endpoints, notify); } * */ public void DoFeed() { foreach (string regionName in RegionNamesForInterestNotify) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); foreach (string key in m_keysNonRegex) { region[key] = "00"; } foreach (string key in m_keysForRegex) { region[key] = "00"; } } } public void DoFeederOps() { foreach (string regionName in RegionNamesForInterestNotify) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); foreach (string key in m_keysNonRegex) { region[key] = "11"; region[key] = "22"; region[key] = "33"; region.GetLocalView().Invalidate(key); region.Remove(key); } foreach (string key in m_keysForRegex) { region[key] = "11"; region[key] = "22"; region[key] = "33"; region.GetLocalView().Invalidate(key); region.Remove(key); } } } public void DoRegister() { DoRegisterInterests(RegionNamesForInterestNotify[0], true); DoRegisterInterests(RegionNamesForInterestNotify[1], false); // We intentionally do not register interest in Region3 //DoRegisterInterestsBlah(RegionNamesForInterestNotifyBlah[2]); } public void DoRegisterInterests(string regionName, bool receiveValues) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); List<string> keys = new List<string>(); foreach (string key in m_keysNonRegex) { keys.Add(key); } region.GetSubscriptionService().RegisterKeys(keys.ToArray(), false, false, receiveValues); region.GetSubscriptionService().RegisterRegex("key-regex.*", false, false, receiveValues); } public void DoUnregister() { DoUnregisterInterests(RegionNamesForInterestNotify[0]); DoUnregisterInterests(RegionNamesForInterestNotify[1]); } public void DoUnregisterInterests(string regionName) { List<string> keys = new List<string>(); foreach (string key in m_keysNonRegex) { keys.Add(key); } IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); region.GetSubscriptionService().UnregisterKeys(keys.ToArray()); region.GetSubscriptionService().UnregisterRegex("key-regex.*"); } public void DoValidation(string clientName, string regionName, int creates, int updates, int invalidates, int destroys) { IRegion<object, object> region = CacheHelper.GetRegion<object, object>(regionName); TallyListener<object, object> listener = region.Attributes.CacheListener as TallyListener<object, object>; Util.Log(clientName + ": " + regionName + ": creates expected=" + creates + ", actual=" + listener.Creates); Util.Log(clientName + ": " + regionName + ": updates expected=" + updates + ", actual=" + listener.Updates); Util.Log(clientName + ": " + regionName + ": invalidates expected=" + invalidates + ", actual=" + listener.Invalidates); Util.Log(clientName + ": " + regionName + ": destroys expected=" + destroys + ", actual=" + listener.Destroys); Assert.AreEqual(creates, listener.Creates, clientName + ": " + regionName); Assert.AreEqual(updates, listener.Updates, clientName + ": " + regionName); Assert.AreEqual(invalidates, listener.Invalidates, clientName + ": " + regionName); Assert.AreEqual(destroys, listener.Destroys, clientName + ": " + regionName); } #endregion [Test] public void FailoverInterest2() { CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml", "cacheserver_notify_subscription2.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator started"); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); m_client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", true); Util.Log("StepOne complete."); m_client2.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", true); Util.Log("StepTwo complete."); m_client2.Call(RegisterAllKeys, RegionNames); Util.Log("StepTwo complete."); m_client1.Call(StepThree); Util.Log("StepThree complete."); m_client2.Call(StepFourIL); Util.Log("StepFour complete."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("Cacheserver 2 started."); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); m_client1.Call(StepFiveFailover); Util.Log("StepFive complete."); m_client2.Call(StepSixFailover); Util.Log("StepSix complete."); // Client2, unregister all keys m_client2.Call(UnregisterAllKeys, RegionNames); Util.Log("UnregisterAllKeys complete."); m_client1.Call(StepSevenFailover); Util.Log("StepSeven complete."); m_client2.Call(StepEightIL); Util.Log("StepEight complete."); m_client1.Call(Close); m_client2.Call(Close); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator stopped"); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } } }
using System; using System.Diagnostics; namespace Fairweather.Service { // autogenerated: D:\Scripts\struct_creator2.pl [Serializable] [DebuggerStepThrough] public class Mutable_Pair<T1, T2> : IPair<T1, T2> { public Mutable_Pair(T1 first, T2 second) { this.First = first; this.Second = second; } public T1 First { get; set; } public T2 Second { get; set; } public object[] ToArray() { return new object[] { First, Second }; } /* Boilerplate */ // public override string ToString() { // string ret = ""; // const string _null = "[null]"; //#pragma warning disable 472 // ret += "First = " + this.First == null ? _null : this.First.ToString(); // ret += ", "; // ret += "Second = " + this.Second == null ? _null : this.Second.ToString(); //#pragma warning restore // ret = "{Mutable_Pair<,>: " + ret + "}"; // return ret; // } // public bool Equals(Mutable_Pair<T1, T2> obj2) { //#pragma warning disable 472 // if (this.First == null) { // if (obj2.First != null) // return false; // } // else if (!this.First.Equals(obj2.First)) { // return false; // } // if (this.Second == null) { // if (obj2.Second != null) // return false; // } // else if (!this.Second.Equals(obj2.Second)) { // return false; // } //#pragma warning restore // return true; // } // public override bool Equals(object obj2) { // if (obj2 == null) // return false; // if (!(obj2 is Mutable_Pair<T1, T2>)) // return false; // var ret = this.Equals((Mutable_Pair<T1, T2>)obj2); // return ret; // } // public static bool operator ==(Mutable_Pair<T1, T2> left, Mutable_Pair<T1, T2> right) { // var ret = left.Equals(right); // return ret; // } // public static bool operator !=(Mutable_Pair<T1, T2> left, Mutable_Pair<T1, T2> right) { // var ret = !left.Equals(right); // return ret; // } // public override int GetHashCode() { //#pragma warning disable 472 // unchecked { // int ret = 23; // int temp; // if (this.First != null) { // ret *= 31; // temp = this.First.GetHashCode(); // ret += temp; // } // if (this.Second != null) { // ret *= 31; // temp = this.Second.GetHashCode(); // ret += temp; // } // return ret; // } // unchecked block //#pragma warning restore // } // method } // autogenerated: D:\Scripts\struct_creator2.pl [Serializable] [DebuggerStepThrough] public class Mutable_Triple<T1, T2, T3> : ITriple<T1, T2, T3> { public Mutable_Triple(T1 first, T2 second, T3 third) { this.First = first; this.Second = second; this.Third = third; } public T1 First { get; set; } public T2 Second { get; set; } public T3 Third { get; set; } public object[] ToArray() { return new object[] { First, Second, Third }; } /* Boilerplate */ // public override string ToString() { // string ret = ""; // const string _null = "[null]"; //#pragma warning disable 472 // ret += "First = " + this.First == null ? _null : this.First.ToString(); // ret += ", "; // ret += "Second = " + this.Second == null ? _null : this.Second.ToString(); // ret += ", "; // ret += "Third = " + this.Third == null ? _null : this.Third.ToString(); //#pragma warning restore // ret = "{Mutable_Triple<T1, T2, T3>: " + ret + "}"; // return ret; // } // public bool Equals(Mutable_Triple<T1, T2, T3> obj2) { //#pragma warning disable 472 // if (this.First == null) { // if (obj2.First != null) // return false; // } // else if (!this.First.Equals(obj2.First)) { // return false; // } // if (this.Second == null) { // if (obj2.Second != null) // return false; // } // else if (!this.Second.Equals(obj2.Second)) { // return false; // } // if (this.Third == null) { // if (obj2.Third != null) // return false; // } // else if (!this.Third.Equals(obj2.Third)) { // return false; // } //#pragma warning restore // return true; // } // public override bool Equals(object obj2) { // if (obj2 == null) // return false; // if (!(obj2 is Mutable_Triple<T1, T2, T3>)) // return false; // var ret = this.Equals((Mutable_Triple<T1, T2, T3>)obj2); // return ret; // } // public static bool operator ==(Mutable_Triple<T1, T2, T3> left, Mutable_Triple<T1, T2, T3> right) { // var ret = left.Equals(right); // return ret; // } // public static bool operator !=(Mutable_Triple<T1, T2, T3> left, Mutable_Triple<T1, T2, T3> right) { // var ret = !left.Equals(right); // return ret; // } // public override int GetHashCode() { //#pragma warning disable 472 // unchecked { // int ret = 23; // int temp; // if (this.First != null) { // ret *= 31; // temp = this.First.GetHashCode(); // ret += temp; // } // if (this.Second != null) { // ret *= 31; // temp = this.Second.GetHashCode(); // ret += temp; // } // if (this.Third != null) { // ret *= 31; // temp = this.Third.GetHashCode(); // ret += temp; // } // return ret; // } // unchecked block //#pragma warning restore // } // method } // autogenerated: D:\Scripts\struct_creator2.pl [Serializable] [DebuggerStepThrough] public class Mutable_Quad<T1, T2, T3, T4> : IQuad<T1, T2, T3, T4> { public Mutable_Quad(T1 first, T2 second, T3 third, T4 fourth) { this.First = first; this.Second = second; this.Third = third; this.Fourth = fourth; } public T1 First { get; set; } public T2 Second { get; set; } public T3 Third { get; set; } public T4 Fourth { get; set; } public object[] ToArray() { return new object[] { First, Second, Third, Fourth }; } /* Boilerplate */ // public override string ToString() { // string ret = ""; // const string _null = "[null]"; //#pragma warning disable 472 // ret += "First = " + this.First == null ? _null : this.First.ToString(); // ret += ", "; // ret += "Second = " + this.Second == null ? _null : this.Second.ToString(); // ret += ", "; // ret += "Third = " + this.Third == null ? _null : this.Third.ToString(); // ret += ", "; // ret += "Fourth = " + this.Fourth == null ? _null : this.Fourth.ToString(); //#pragma warning restore // ret = "{Mutable_Quad<T1, T2, T3, T4>: " + ret + "}"; // return ret; // } // public bool Equals(Mutable_Quad<T1, T2, T3, T4> obj2) { //#pragma warning disable 472 // if (this.First == null) { // if (obj2.First != null) // return false; // } // else if (!this.First.Equals(obj2.First)) { // return false; // } // if (this.Second == null) { // if (obj2.Second != null) // return false; // } // else if (!this.Second.Equals(obj2.Second)) { // return false; // } // if (this.Third == null) { // if (obj2.Third != null) // return false; // } // else if (!this.Third.Equals(obj2.Third)) { // return false; // } // if (this.Fourth == null) { // if (obj2.Fourth != null) // return false; // } // else if (!this.Fourth.Equals(obj2.Fourth)) { // return false; // } //#pragma warning restore // return true; // } // public override bool Equals(object obj2) { // if (obj2 == null) // return false; // if (!(obj2 is Mutable_Quad<T1, T2, T3, T4>)) // return false; // var ret = this.Equals((Mutable_Quad<T1, T2, T3, T4>)obj2); // return ret; // } // public static bool operator ==(Mutable_Quad<T1, T2, T3, T4> left, Mutable_Quad<T1, T2, T3, T4> right) { // var ret = left.Equals(right); // return ret; // } // public static bool operator !=(Mutable_Quad<T1, T2, T3, T4> left, Mutable_Quad<T1, T2, T3, T4> right) { // var ret = !left.Equals(right); // return ret; // } // public override int GetHashCode() { //#pragma warning disable 472 // unchecked { // int ret = 23; // int temp; // if (this.First != null) { // ret *= 31; // temp = this.First.GetHashCode(); // ret += temp; // } // if (this.Second != null) { // ret *= 31; // temp = this.Second.GetHashCode(); // ret += temp; // } // if (this.Third != null) { // ret *= 31; // temp = this.Third.GetHashCode(); // ret += temp; // } // if (this.Fourth != null) { // ret *= 31; // temp = this.Fourth.GetHashCode(); // ret += temp; // } // return ret; // } // unchecked block //#pragma warning restore // } // method } }
// Copyright 2009-2012 Matvei Stefarov <me@matvei.org> using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using fCraft.Events; using JetBrains.Annotations; namespace fCraft { /// <summary> Persistent database of player information. </summary> public static class PlayerDB { static readonly Trie<PlayerInfo> Trie = new Trie<PlayerInfo>(); static List<PlayerInfo> list = new List<PlayerInfo>(); /// <summary> Cached list of all players in the database. /// May be quite long. Make sure to copy a reference to /// the list before accessing it in a loop, since this /// array be frequently be replaced by an updated one. </summary> public static PlayerInfo[] PlayerInfoList { get; private set; } static int maxID = 255; const int BufferSize = 64 * 1024; /* * Version 0 - before 0.530 - all dates/times are local * Version 1 - 0.530-0.536 - all dates and times are stored as UTC unix timestamps (milliseconds) * Version 2 - 0.600 dev - all dates and times are stored as UTC unix timestamps (seconds) * Version 3 - 0.600 dev - same as v2, but sorting by ID is enforced * Version 4 - 0.600 dev - added LastModified column, forced banned players to be unfrozen/unmuted/unhidden. * Version 5 - 0.600+ - removed FailedLoginCount column */ //Version 10 - RPG Style public const int FormatVersion = 10; const string Header = "fCraft PlayerDB | Row format: " + "Name,IPAddress,Rank,RankChangeDate,RankChangedBy,Banned,BanDate,BannedBy," + "UnbanDate,UnbannedBy,BanReason,UnbanReason,LastFailedLoginDate," + "LastFailedLoginIP,Points,FirstLoginDate,LastLoginDate,TotalTime," + "BlocksBuilt,BlocksDeleted,TimesVisited,MessagesWritten,PromoCount,MojangAccount," + "PreviousRank,RankChangeReason,TimesKicked,TimesKickedOthers," + "TimesBannedOthers,ID,RankChangeType,LastKickDate,LastSeen,BlocksDrawn," + "LastKickBy,LastKickReason,BannedUntil,IsFrozen,FrozenBy,FrozenOn,MutedUntil,MutedBy," + "Password,IsOnline,BandwidthUseMode,IsHidden,LastModified,DisplayedName,Agility," + "Alignment,Defence,Elemental,Focus,Luck,MagicDefence,Mana,Strength,Vitality,Wisdom,XP,Race"; // used to ensure PlayerDB consistency when adding/removing PlayerDB entries static readonly object AddLocker = new object(); // used to prevent concurrent access to the PlayerDB file static readonly object SaveLoadLocker = new object(); public static bool IsLoaded { get; private set; } static void CheckIfLoaded() { if (!IsLoaded) throw new InvalidOperationException("PlayerDB is not loaded."); } [NotNull] public static PlayerInfo AddFakeEntry([NotNull] string name, RankChangeType rankChangeType) { if (name == null) throw new ArgumentNullException("name"); CheckIfLoaded(); PlayerInfo info; lock (AddLocker) { info = Trie.Get(name); if (info != null) { throw new ArgumentException("A PlayerDB entry already exists for this name.", "name"); } var e = new PlayerInfoCreatingEventArgs(name, IPAddress.None, RankManager.DefaultRank, true); PlayerInfo.RaiseCreatingEvent(e); if (e.Cancel) { throw new OperationCanceledException("Cancelled by a plugin."); } info = new PlayerInfo(name, e.StartingRank, false, rankChangeType); list.Add(info); Trie.Add(info.Name, info); UpdateCache(); } PlayerInfo.RaiseCreatedEvent(info, false); return info; } #region Saving/Loading internal static void Load() { lock (SaveLoadLocker) { if (File.Exists(Paths.PlayerDBFileName)) { Stopwatch sw = Stopwatch.StartNew(); using (FileStream fs = OpenRead(Paths.PlayerDBFileName)) { using (StreamReader reader = new StreamReader(fs, Encoding.UTF8, true, BufferSize)) { string header = reader.ReadLine(); // if PlayerDB is an empty file if (header == null) { Logger.Log(LogType.Warning, "PlayerDB.Load: PlayerDB file is empty."); } else { lock (AddLocker) { LoadInternal(reader, header); } } } } sw.Stop(); Logger.Log(LogType.Debug, "PlayerDB.Load: Done loading player DB ({0} records) in {1}ms. MaxID={2}", Trie.Count, sw.ElapsedMilliseconds, maxID); } else { Logger.Log(LogType.Warning, "PlayerDB.Load: No player DB file found."); } UpdateCache(); IsLoaded = true; } } static void LoadInternal(StreamReader reader, string header) { int version = IdentifyFormatVersion(header); if (version > FormatVersion) { Logger.Log(LogType.Warning, "PlayerDB.Load: Attempting to load unsupported PlayerDB format ({0}). Errors may occur.", version); } else if (version < FormatVersion) { Logger.Log(LogType.Warning, "PlayerDB.Load: Converting PlayerDB to a newer format (version {0} to {1}).", version, FormatVersion); } int emptyRecords = 0; while (true) { string line = reader.ReadLine(); if (line == null) break; string[] fields = line.Split(','); if (fields.Length >= PlayerInfo.MinFieldCount) { #if !DEBUG try { #endif PlayerInfo info; switch (version) { case 0: info = PlayerInfo.LoadFormat0(fields, true); break; case 1: info = PlayerInfo.LoadFormat1(fields); break; default: // Versions 2-5 differ in semantics only, not in actual serialization format. info = PlayerInfo.LoadFormat2(fields); break; } if (info.ID > maxID) { maxID = info.ID; Logger.Log(LogType.Warning, "PlayerDB.Load: Adjusting wrongly saved MaxID ({0} to {1})."); } // A record is considered "empty" if the player has never logged in. // Empty records may be created by /Import, /Ban, and /Rank commands on typos. // Deleting such records should have no negative impact on DB completeness. if ((info.LastIP.Equals(IPAddress.None) || info.LastIP.Equals(IPAddress.Any) || info.TimesVisited == 0) && !info.IsBanned && info.Rank == RankManager.DefaultRank) { Logger.Log(LogType.SystemActivity, "PlayerDB.Load: Skipping an empty record for player \"{0}\"", info.Name); emptyRecords++; continue; } // Check for duplicates. Unless PlayerDB.txt was altered externally, this does not happen. if (Trie.ContainsKey(info.Name)) { Logger.Log(LogType.Error, "PlayerDB.Load: Duplicate record for player \"{0}\" skipped.", info.Name); } else { Trie.Add(info.Name, info); list.Add(info); } #if !DEBUG } catch( Exception ex ) { Logger.LogAndReportCrash( "Error while parsing PlayerInfo record: " + line, "800Craft", ex, false ); } #endif } else { Logger.Log(LogType.Error, "PlayerDB.Load: Unexpected field count ({0}), expecting at least {1} fields for a PlayerDB entry.", fields.Length, PlayerInfo.MinFieldCount); } } if (emptyRecords > 0) { Logger.Log(LogType.Warning, "PlayerDB.Load: Skipped {0} empty records.", emptyRecords); } RunCompatibilityChecks(version); } static Dictionary<int, Rank> rankMapping; internal static Rank GetRankByIndex(int index) { Rank rank; if (rankMapping.TryGetValue(index, out rank)) { return rank; } else { Logger.Log(LogType.Error, "Unknown rank index ({0}). Assigning rank {1} instead.", index, RankManager.DefaultRank); return RankManager.DefaultRank; } } static void RunCompatibilityChecks(int loadedVersion) { // Sorting the list allows finding players by ID using binary search. list.Sort(PlayerIDComparer.Instance); if (loadedVersion < 4) { int unhid = 0, unfroze = 0, unmuted = 0; Logger.Log(LogType.SystemActivity, "PlayerDB: Checking consistency of banned player records..."); for (int i = 0; i < list.Count; i++) { if (list[i].IsBanned) { if (list[i].IsHidden) { unhid++; list[i].IsHidden = false; } if (list[i].IsFrozen) { list[i].Unfreeze(); unfroze++; } if (list[i].IsMuted) { list[i].Unmute(); unmuted++; } } } Logger.Log(LogType.SystemActivity, "PlayerDB: Unhid {0}, unfroze {1}, and unmuted {2} banned accounts.", unhid, unfroze, unmuted); } } static int IdentifyFormatVersion([NotNull] string header) { if (header == null) throw new ArgumentNullException("header"); if (header.StartsWith("playerName")) return 0; string[] headerParts = header.Split(' '); if (headerParts.Length < 2) { throw new FormatException("Invalid PlayerDB header format: " + header); } int maxIDField; if (Int32.TryParse(headerParts[0], out maxIDField)) { if (maxIDField >= 255) {// IDs start at 256 maxID = maxIDField; } } int version; if (Int32.TryParse(headerParts[1], out version)) { return version; } else { return 0; } } public static void Save() { CheckIfLoaded(); const string tempFileName = Paths.PlayerDBFileName + ".temp"; lock (SaveLoadLocker) { PlayerInfo[] listCopy = PlayerInfoList; Stopwatch sw = Stopwatch.StartNew(); using (FileStream fs = OpenWrite(tempFileName)) { using (StreamWriter writer = new StreamWriter(fs, Encoding.UTF8, BufferSize)) { writer.WriteLine("{0} {1} {2}", maxID, FormatVersion, Header); StringBuilder sb = new StringBuilder(); for (int i = 0; i < listCopy.Length; i++) { listCopy[i].Serialize(sb); writer.WriteLine(sb.ToString()); sb.Length = 0; } } } sw.Stop(); Logger.Log(LogType.Debug, "PlayerDB.Save: Saved player database ({0} records) in {1}ms", Trie.Count, sw.ElapsedMilliseconds); try { Paths.MoveOrReplace(tempFileName, Paths.PlayerDBFileName); } catch (Exception ex) { Logger.Log(LogType.Error, "PlayerDB.Save: An error occured while trying to save PlayerDB: {0}", ex); } } } static FileStream OpenRead(string fileName) { return new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan); } static FileStream OpenWrite(string fileName) { return new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize); } #endregion #region Scheduled Saving static SchedulerTask saveTask; static TimeSpan saveInterval = TimeSpan.FromSeconds(90); public static TimeSpan SaveInterval { get { return saveInterval; } set { if (value.Ticks < 0) throw new ArgumentException("Save interval may not be negative"); saveInterval = value; if (saveTask != null) saveTask.Interval = value; } } internal static void StartSaveTask() { saveTask = Scheduler.NewBackgroundTask(SaveTask) .RunForever(SaveInterval, SaveInterval + TimeSpan.FromSeconds(15)); } static void SaveTask(SchedulerTask task) { Save(); } #endregion #region Lookup [NotNull] public static PlayerInfo FindOrCreateInfoForPlayer([NotNull] string name, [NotNull] IPAddress lastIP) { if (name == null) throw new ArgumentNullException("name"); if (lastIP == null) throw new ArgumentNullException("lastIP"); CheckIfLoaded(); PlayerInfo info; // this flag is used to avoid executing PlayerInfoCreated event in the lock bool raiseCreatedEvent = false; lock (AddLocker) { info = Trie.Get(name); if (info == null) { var e = new PlayerInfoCreatingEventArgs(name, lastIP, RankManager.DefaultRank, false); PlayerInfo.RaiseCreatingEvent(e); if (e.Cancel) throw new OperationCanceledException("Cancelled by a plugin."); info = new PlayerInfo(name, lastIP, e.StartingRank); Trie.Add(name, info); list.Add(info); UpdateCache(); raiseCreatedEvent = true; } } if (raiseCreatedEvent) { PlayerInfo.RaiseCreatedEvent(info, false); } return info; } [NotNull] public static PlayerInfo[] FindPlayers([NotNull] IPAddress address) { if (address == null) throw new ArgumentNullException("address"); return FindPlayers(address, Int32.MaxValue); } [NotNull] public static PlayerInfo[] FindPlayers([NotNull] IPAddress address, int limit) { if (address == null) throw new ArgumentNullException("address"); if (limit < 0) throw new ArgumentOutOfRangeException("limit"); CheckIfLoaded(); List<PlayerInfo> result = new List<PlayerInfo>(); int count = 0; PlayerInfo[] cache = PlayerInfoList; for (int i = 0; i < cache.Length; i++) { if (cache[i].LastIP.Equals(address)) { result.Add(cache[i]); count++; if (count >= limit) return result.ToArray(); } } return result.ToArray(); } [NotNull] public static PlayerInfo[] FindPlayersCidr([NotNull] IPAddress address, byte range) { if (address == null) throw new ArgumentNullException("address"); if (range > 32) throw new ArgumentOutOfRangeException("range"); return FindPlayersCidr(address, range, Int32.MaxValue); } [NotNull] public static PlayerInfo[] FindPlayersCidr([NotNull] IPAddress address, byte range, int limit) { if (address == null) throw new ArgumentNullException("address"); if (range > 32) throw new ArgumentOutOfRangeException("range"); if (limit < 0) throw new ArgumentOutOfRangeException("limit"); CheckIfLoaded(); List<PlayerInfo> result = new List<PlayerInfo>(); int count = 0; uint addressInt = address.AsUInt(); uint netMask = IPAddressUtil.NetMask(range); PlayerInfo[] cache = PlayerInfoList; for (int i = 0; i < cache.Length; i++) { if (cache[i].LastIP.Match(addressInt, netMask)) { result.Add(cache[i]); count++; if (count >= limit) return result.ToArray(); } } return result.ToArray(); } [NotNull] public static PlayerInfo[] FindPlayers([NotNull] Regex regex) { if (regex == null) throw new ArgumentNullException("regex"); return FindPlayers(regex, Int32.MaxValue); } [NotNull] public static PlayerInfo[] FindPlayers([NotNull] Regex regex, int limit) { if (regex == null) throw new ArgumentNullException("regex"); CheckIfLoaded(); List<PlayerInfo> result = new List<PlayerInfo>(); int count = 0; PlayerInfo[] cache = PlayerInfoList; for (int i = 0; i < cache.Length; i++) { if (regex.IsMatch(cache[i].Name)) { result.Add(cache[i]); count++; if (count >= limit) break; } } return result.ToArray(); } [NotNull] public static PlayerInfo[] FindPlayers([NotNull] string namePart) { if (namePart == null) throw new ArgumentNullException("namePart"); return FindPlayers(namePart, Int32.MaxValue); } [NotNull] public static PlayerInfo[] FindPlayers([NotNull] string namePart, int limit) { if (namePart == null) throw new ArgumentNullException("namePart"); CheckIfLoaded(); lock (AddLocker) { //return Trie.ValuesStartingWith( namePart ).Take( limit ).ToArray(); // <- works, but is slightly slower return Trie.GetList(namePart, limit).ToArray(); } } /// <summary>Searches for player names starting with namePart, returning just one or none of the matches.</summary> /// <param name="namePart">Partial or full player name</param> /// <param name="info">PlayerInfo to output (will be set to null if no single match was found)</param> /// <returns>true if one or zero matches were found, false if multiple matches were found</returns> internal static bool FindPlayerInfo([NotNull] string namePart, out PlayerInfo info) { if (namePart == null) throw new ArgumentNullException("namePart"); CheckIfLoaded(); lock (AddLocker) { return Trie.GetOneMatch(namePart, out info); } } [CanBeNull] public static PlayerInfo FindPlayerInfoExact([NotNull] string name) { if (name == null) throw new ArgumentNullException("name"); CheckIfLoaded(); lock (AddLocker) { return Trie.Get(name); } } public static PlayerInfo[] FindPlayerInfoByEmail([NotNull] string name) { if (name == null) throw new ArgumentNullException("name"); CheckIfLoaded(); return PlayerInfoList.Where(p => p.MojangAccount == name).ToArray(); } [CanBeNull] public static PlayerInfo FindPlayerInfoOrPrintMatches([NotNull] Player player, [NotNull] string name) { if (player == null) throw new ArgumentNullException("player"); if (name == null) throw new ArgumentNullException("name"); CheckIfLoaded(); if (name == "-") { if (player.LastUsedPlayerName != null) { name = player.LastUsedPlayerName; } else { player.Message("Cannot repeat player name: you haven't used any names yet."); return null; } } if (!Player.ContainsValidCharacters(name)) { player.MessageInvalidPlayerName(name); return null; } PlayerInfo target = FindPlayerInfoExact(name); if (target == null) { PlayerInfo[] targets = FindPlayers(name); if (targets.Length == 0) { player.MessageNoPlayer(name); return null; } else if (targets.Length > 1) { Array.Sort(targets, new PlayerInfoComparer(player)); player.MessageManyMatches("player", targets.Take(25).ToArray()); return null; } target = targets[0]; } player.LastUsedPlayerName = target.Name; return target; } [NotNull] public static string FindExactClassyName([CanBeNull] string name) { if (string.IsNullOrEmpty(name)) return "?"; PlayerInfo info = FindPlayerInfoExact(name); if (info == null) return name; else return info.ClassyName; } #endregion #region Stats public static int BannedCount { get { return PlayerInfoList.Count(t => t.IsBanned); } } public static float BannedPercentage { get { var listCache = PlayerInfoList; if (listCache.Length == 0) { return 0; } else { return listCache.Count(t => t.IsBanned) * 100f / listCache.Length; } } } public static int Size { get { return Trie.Count; } } #endregion public static int GetNextID() { return Interlocked.Increment(ref maxID); } /// <summary> Finds PlayerInfo by ID. Returns null of not found. </summary> [CanBeNull] public static PlayerInfo FindPlayerInfoByID(int id) { CheckIfLoaded(); PlayerInfo dummy = new PlayerInfo(id); lock (AddLocker) { int index = list.BinarySearch(dummy, PlayerIDComparer.Instance); if (index >= 0) { return list[index]; } else { return null; } } } public static int MassRankChange([NotNull] Player player, [NotNull] Rank from, [NotNull] Rank to, [NotNull] string reason) { if (player == null) throw new ArgumentNullException("player"); if (from == null) throw new ArgumentNullException("from"); if (to == null) throw new ArgumentNullException("to"); if (reason == null) throw new ArgumentNullException("reason"); CheckIfLoaded(); int affected = 0; string fullReason = reason + "~MassRank"; lock (AddLocker) { for (int i = 0; i < PlayerInfoList.Length; i++) { if (PlayerInfoList[i].Rank == from) { try { list[i].ChangeRank(player, to, fullReason, true, true, false); } catch (PlayerOpException ex) { player.Message(ex.MessageColored); } affected++; } } return affected; } } static void UpdateCache() { lock (AddLocker) { PlayerInfoList = list.ToArray(); } } #region Experimental & Debug things internal static int CountInactivePlayers() { lock (AddLocker) { Dictionary<IPAddress, List<PlayerInfo>> playersByIP = new Dictionary<IPAddress, List<PlayerInfo>>(); PlayerInfo[] playerInfoListCache = PlayerInfoList; for (int i = 0; i < playerInfoListCache.Length; i++) { if (!playersByIP.ContainsKey(playerInfoListCache[i].LastIP)) { playersByIP[playerInfoListCache[i].LastIP] = new List<PlayerInfo>(); } playersByIP[playerInfoListCache[i].LastIP].Add(PlayerInfoList[i]); } int count = 0; // ReSharper disable LoopCanBeConvertedToQuery for (int i = 0; i < playerInfoListCache.Length; i++) { // ReSharper restore LoopCanBeConvertedToQuery if (PlayerIsInactive(playersByIP, playerInfoListCache[i], true)) count++; } return count; } } internal static int RemoveInactivePlayers() { int count = 0; lock (AddLocker) { Dictionary<IPAddress, List<PlayerInfo>> playersByIP = new Dictionary<IPAddress, List<PlayerInfo>>(); PlayerInfo[] playerInfoListCache = PlayerInfoList; for (int i = 0; i < playerInfoListCache.Length; i++) { if (!playersByIP.ContainsKey(playerInfoListCache[i].LastIP)) { playersByIP[playerInfoListCache[i].LastIP] = new List<PlayerInfo>(); } playersByIP[playerInfoListCache[i].LastIP].Add(PlayerInfoList[i]); } List<PlayerInfo> newList = new List<PlayerInfo>(); for (int i = 0; i < playerInfoListCache.Length; i++) { PlayerInfo p = playerInfoListCache[i]; if (PlayerIsInactive(playersByIP, p, true)) { count++; } else { newList.Add(p); } } list = newList; Trie.Clear(); foreach (PlayerInfo p in list) { Trie.Add(p.Name, p); } list.TrimExcess(); UpdateCache(); } return count; } static bool PlayerIsInactive([NotNull] IDictionary<IPAddress, List<PlayerInfo>> playersByIP, [NotNull] PlayerInfo player, bool checkIP) { if (playersByIP == null) throw new ArgumentNullException("playersByIP"); if (player == null) throw new ArgumentNullException("player"); if (player.BanStatus != BanStatus.NotBanned || player.UnbanDate != DateTime.MinValue || player.IsFrozen || player.IsMuted || player.TimesKicked != 0 || player.Rank != RankManager.DefaultRank || player.PreviousRank != null) { return false; } if (player.TotalTime.TotalMinutes > 30 || player.TimeSinceLastSeen.TotalDays < 30) { return false; } if (IPBanList.Get(player.LastIP) != null) { return false; } if (checkIP) { return playersByIP[player.LastIP].All(other => (other == player) || PlayerIsInactive(playersByIP, other, false)); } return true; } internal static void SwapPlayerInfo([NotNull] PlayerInfo p1, [NotNull] PlayerInfo p2) { if (p1 == null) throw new ArgumentNullException("p1"); if (p2 == null) throw new ArgumentNullException("p2"); lock (AddLocker) { lock (SaveLoadLocker) { if (p1.IsOnline || p2.IsOnline) { throw new Exception("Both players must be offline to swap info."); } Swap(ref p1.BanDate, ref p2.BanDate); Swap(ref p1.BandwidthUseMode, ref p2.BandwidthUseMode); Swap(ref p1.BannedBy, ref p2.BannedBy); Swap(ref p1.BannedUntil, ref p2.BannedUntil); Swap(ref p1.BanStatus, ref p2.BanStatus); Swap(ref p1.BanReason, ref p2.BanReason); Swap(ref p1.BlocksBuilt, ref p2.BlocksBuilt); Swap(ref p1.BlocksDeleted, ref p2.BlocksDeleted); Swap(ref p1.BlocksDrawn, ref p2.BlocksDrawn); Swap(ref p1.DisplayedName, ref p2.DisplayedName); Swap(ref p1.FirstLoginDate, ref p2.FirstLoginDate); Swap(ref p1.FrozenBy, ref p2.FrozenBy); Swap(ref p1.FrozenOn, ref p2.FrozenOn); Swap(ref p1.ID, ref p2.ID); Swap(ref p1.IsFrozen, ref p2.IsFrozen); //Swap( ref p1.IsHidden, ref p2.IsHidden ); Swap(ref p1.LastFailedLoginDate, ref p2.LastFailedLoginDate); Swap(ref p1.LastFailedLoginIP, ref p2.LastFailedLoginIP); //Swap( ref p1.LastIP, ref p2.LastIP ); Swap(ref p1.LastKickBy, ref p2.LastKickBy); Swap(ref p1.LastKickDate, ref p2.LastKickDate); Swap(ref p1.LastKickReason, ref p2.LastKickReason); //Swap( ref p1.LastLoginDate, ref p2.LastLoginDate ); //Swap( ref p1.LastSeen, ref p2.LastSeen ); //Swap( ref p1.LeaveReason, ref p2.LeaveReason ); Swap(ref p1.MessagesWritten, ref p2.MessagesWritten); Swap(ref p1.Points, ref p2.Points); Swap(ref p1.MutedBy, ref p2.MutedBy); Swap(ref p1.MutedUntil, ref p2.MutedUntil); //Swap( ref p1.Name, ref p2.Name ); //Swap( ref p1.Online, ref p2.Online ); Swap(ref p1.Password, ref p2.Password); //Swap( ref p1.PlayerObject, ref p2.PlayerObject ); Swap(ref p1.PreviousRank, ref p2.PreviousRank); Swap(ref p1.PromoCount, ref p2.PromoCount); Rank p1Rank = p1.Rank; p1.Rank = p2.Rank; p2.Rank = p1Rank; Swap(ref p1.RankChangeDate, ref p2.RankChangeDate); Swap(ref p1.RankChangedBy, ref p2.RankChangedBy); Swap(ref p1.RankChangeReason, ref p2.RankChangeReason); Swap(ref p1.RankChangeType, ref p2.RankChangeType); Swap(ref p1.TimesBannedOthers, ref p2.TimesBannedOthers); Swap(ref p1.TimesKicked, ref p2.TimesKicked); Swap(ref p1.TimesKickedOthers, ref p2.TimesKickedOthers); Swap(ref p1.TimesVisited, ref p2.TimesVisited); /* Swap(ref p1.totalDeathsTDM, ref p2.totalDeathsTDM); Swap(ref p1.totalKillsTDM, ref p2.totalKillsTDM); Swap(ref p1.totalDeathsFFA, ref p2.totalDeathsFFA); Swap(ref p1.totalKillsFFA, ref p2.totalKillsFFA); */ Swap(ref p1.TotalTime, ref p2.TotalTime); Swap(ref p1.UnbanDate, ref p2.UnbanDate); Swap(ref p1.UnbannedBy, ref p2.UnbannedBy); Swap(ref p1.UnbanReason, ref p2.UnbanReason); list.Sort(PlayerIDComparer.Instance); } } } static void Swap<T>(ref T t1, ref T t2) { var temp = t2; t2 = t1; t1 = temp; } #endregion sealed class PlayerIDComparer : IComparer<PlayerInfo> { public static readonly PlayerIDComparer Instance = new PlayerIDComparer(); private PlayerIDComparer() { } public int Compare(PlayerInfo x, PlayerInfo y) { return x.ID - y.ID; } } public static StringBuilder AppendEscaped([NotNull] this StringBuilder sb, [CanBeNull] string str) { if (sb == null) throw new ArgumentNullException("sb"); if (!String.IsNullOrEmpty(str)) { if (str.IndexOf(',') > -1) { int startIndex = sb.Length; sb.Append(str); sb.Replace(',', '\xFF', startIndex, str.Length); } else { sb.Append(str); } } return sb; } } }
// // ProductsController.cs // // Author: // Eddy Zavaleta <eddy@mictlanix.com> // Eduardo Nieto <enieto@mictlanix.com> // // Copyright (C) 2011-2016 Eddy Zavaleta, Mictlanix, and contributors. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.IO; using System.Security.Cryptography; using System.Web; using System.Web.Mvc; using Castle.ActiveRecord; using NHibernate; using NHibernate.Exceptions; using Mictlanix.BE.Model; using Mictlanix.BE.Web.Models; using Mictlanix.BE.Web.Mvc; using Mictlanix.BE.Web.Helpers; namespace Mictlanix.BE.Web.Controllers.Mvc { [Authorize] public class ProductsController : CustomController { public ActionResult Index () { var search = SearchProducts (new Search<Product> { Limit = WebConfig.PageSize }); return View (search); } [HttpPost] public ActionResult Index (Search<Product> search) { if (ModelState.IsValid) { search = SearchProducts (search); } if (Request.IsAjaxRequest ()) { return PartialView ("_Index", search); } return View (search); } Search<Product> SearchProducts (Search<Product> search) { IQueryable<Product> query; var pattern = (search.Pattern ?? string.Empty).Trim (); if (string.IsNullOrEmpty (pattern)) { query = from x in Product.Queryable orderby x.Name select x; } else { query = from x in Product.Queryable where x.Name.Contains (pattern) || x.Code.Contains (pattern) || x.Model.Contains (pattern) || x.SKU.Contains (pattern) || x.Brand.Contains (pattern) orderby x.Name select x; } search.Total = query.Count (); search.Results = query.Skip (search.Offset).Take (search.Limit).ToList (); return search; } public ActionResult Create () { return PartialView ("_Create", new Product { UnitOfMeasurementId = "N/A" }); } [HttpPost] public ActionResult Create (Product item) { item.Supplier = Supplier.TryFind (item.SupplierId); item.ProductService = SatProductService.TryFind (item.ProductServiceId); item.UnitOfMeasurement = SatUnitOfMeasurement.TryFind (item.UnitOfMeasurementId); if (!ModelState.IsValid) { return PartialView ("_Create", item); } item.MinimumOrderQuantity = 1; item.TaxRate = WebConfig.DefaultVAT; item.IsTaxIncluded = WebConfig.IsTaxIncluded; item.PriceType = WebConfig.DefaultPriceType; item.Photo = WebConfig.DefaultPhotoFile; using (var scope = new TransactionScope ()) { item.Create (); foreach (var l in PriceList.Queryable.ToList ()) { var price = new ProductPrice { Product = item, List = l }; price.Create (); } scope.Flush (); } return PartialView ("_CreateSuccesful", item); } [HttpPost] public ActionResult SetPhoto (int id, HttpPostedFileBase file) { var entity = Product.Find (id); entity.Photo = SavePhoto (file) ?? WebConfig.DefaultPhotoFile; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return Json (new { id = id, url = Url.Content (entity.Photo) }); } public ActionResult View (int id) { var entity = Product.Find (id); return PartialView ("_View", entity); } public ActionResult Edit (int id) { var entity = Product.Find (id); return PartialView ("_Edit", entity); } [HttpPost] public ActionResult Edit (Product item) { item.Supplier = Supplier.TryFind (item.SupplierId); item.ProductService = SatProductService.TryFind (item.ProductServiceId); item.UnitOfMeasurement = SatUnitOfMeasurement.TryFind (item.UnitOfMeasurementId); if (!ModelState.IsValid) return PartialView ("_Edit", item); var entity = Product.Find (item.Id); entity.Brand = item.Brand; entity.Code = item.Code; entity.Comment = item.Comment; entity.IsStockable = item.IsStockable; entity.IsPerishable = item.IsPerishable; entity.IsSeriable = item.IsSeriable; entity.IsPurchasable = item.IsPurchasable; entity.IsSalable = item.IsSalable; entity.IsInvoiceable = item.IsInvoiceable; entity.Location = item.Location; entity.Model = item.Model; entity.Name = item.Name; entity.SKU = item.SKU; entity.UnitOfMeasurement = item.UnitOfMeasurement; entity.Supplier = item.Supplier; entity.ProductService = item.ProductService; using (var scope = new TransactionScope ()) { entity.UpdateAndFlush (); } return PartialView ("_Refresh"); } public ActionResult Delete (int id) { var item = Product.Find (id); return PartialView ("_Delete", item); } [HttpPost, ActionName ("Delete")] public ActionResult DeleteConfirmed (int id) { var item = Product.Find (id); try { using (var scope = new TransactionScope ()) { foreach (var x in item.Prices) { x.DeleteAndFlush (); } item.DeleteAndFlush (); } return PartialView ("_DeleteSuccesful", item); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine (ex); return PartialView ("DeleteUnsuccessful"); } } public ActionResult Merge () { return View (); } [HttpPost] public ActionResult Merge (int product, int duplicate) { var prod = Product.TryFind (product); var dup = Product.TryFind (duplicate); string sql = @"UPDATE customer_discount SET product = :product WHERE product = :duplicate; UPDATE customer_refund_detail SET product = :product WHERE product = :duplicate; UPDATE delivery_order_detail SET product = :product WHERE product = :duplicate; UPDATE fiscal_document_detail SET product = :product WHERE product = :duplicate; UPDATE inventory_issue_detail SET product = :product WHERE product = :duplicate; UPDATE inventory_receipt_detail SET product = :product WHERE product = :duplicate; UPDATE inventory_transfer_detail SET product = :product WHERE product = :duplicate; UPDATE lot_serial_rqmt SET product = :product WHERE product = :duplicate; UPDATE lot_serial_tracking SET product = :product WHERE product = :duplicate; UPDATE purchase_order_detail SET product = :product WHERE product = :duplicate; UPDATE sales_order_detail SET product = :product WHERE product = :duplicate; UPDATE sales_quote_detail SET product = :product WHERE product = :duplicate; UPDATE supplier_return_detail SET product = :product WHERE product = :duplicate; DELETE FROM product_label WHERE product = :duplicate; DELETE FROM product_price WHERE product = :duplicate; DELETE FROM product WHERE product_id = :duplicate;"; ActiveRecordMediator<Product>.Execute (delegate (ISession session, object instance) { int ret; using (var tx = session.BeginTransaction ()) { var query = session.CreateSQLQuery (sql); query.AddScalar ("product", NHibernateUtil.Int32); query.AddScalar ("duplicate", NHibernateUtil.Int32); query.SetInt32 ("product", product); query.SetInt32 ("duplicate", duplicate); ret = query.ExecuteUpdate (); tx.Commit (); } return ret; }, null); return View (new Pair<Product, Product> { First = prod, Second = dup }); } string SavePhoto (HttpPostedFileBase file) { if (file == null || file.ContentLength == 0) return null; using (var stream = file.InputStream) { using (var img = Image.FromStream (stream)) { var hash = string.Format ("{0}.png", HashFromImage (img)); var path = Path.Combine (Server.MapPath (WebConfig.PhotosPath), hash); img.Save (path, ImageFormat.Png); return Path.Combine (WebConfig.PhotosPath, hash); } } } string HashFromStream (Stream stream) { string hash; byte [] bytes = null; using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider ()) { bytes = sha1.ComputeHash (stream); hash = BitConverter.ToString (bytes).Replace ("-", "").ToLower (); } return hash; } string HashFromImage (Image img) { string hash; byte [] bytes = null; using (MemoryStream ms = new MemoryStream ()) { img.Save (ms, img.RawFormat); bytes = ms.ToArray (); } using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider ()) { bytes = sha1.ComputeHash (bytes); hash = BitConverter.ToString (bytes).Replace ("-", "").ToLower (); } return hash; } public JsonResult GetSuggestions (string pattern) { var query = from x in Product.Queryable where x.Name.Contains (pattern) || x.Code.Contains (pattern) || x.Model.Contains (pattern) || x.SKU.Contains (pattern) || x.Brand.Contains (pattern) orderby x.Name select x; var items = from x in query.Take (15).ToList () select new { id = x.Id, name = x.Name, code = x.Code, model = x.Model, sku = x.SKU, url = Url.Content (x.Photo) }; return Json (items, JsonRequestBehavior.AllowGet); } public ActionResult Labels (int id) { var item = Product.Find (id); return PartialView ("_Labels", item.Labels); } [HttpPost] public ActionResult SetLabels (int id, int [] value) { var entity = Product.Find (id); if (value == null) { var param = Request.Params ["value[]"]; if (!string.IsNullOrWhiteSpace (param)) { value = param.Split (',').Select (x => Convert.ToInt32 (x)).ToArray (); } } if (entity == null) { Response.StatusCode = 400; return Content (Resources.ItemNotFound); } using (var scope = new TransactionScope ()) { entity.Labels.Clear (); if (value != null) { foreach (int v in value) { entity.Labels.Add (Label.Find (v)); } } entity.UpdateAndFlush (); } return Json (new { id = id, value = value }); } public JsonResult Brands (string pattern) { IQueryable<string> query; if (string.IsNullOrWhiteSpace (pattern)) { query = from x in Product.Queryable where x.Brand != null && x.Brand != string.Empty orderby x.Brand select x.Brand; } else { query = from x in Product.Queryable where x.Brand.Contains (pattern) orderby x.Brand select x.Brand; } var items = from x in query.Distinct ().ToList () select new { id = x, name = x }; return Json (items, JsonRequestBehavior.AllowGet); } public JsonResult Models (string pattern) { IQueryable<string> query; if (string.IsNullOrWhiteSpace (pattern)) { query = from x in Product.Queryable where x.Model != null && x.Model != string.Empty orderby x.Model select x.Model; } else { query = from x in Product.Queryable where x.Model.Contains (pattern) orderby x.Model select x.Model; } var items = from x in query.Distinct ().ToList () select new { id = x, name = x }; return Json (items, JsonRequestBehavior.AllowGet); } public JsonResult ProductServiceKeys (string pattern) { var query = from x in SatProductService.Queryable where x.Id.Contains (pattern) || x.Description.Contains (pattern) || x.Keywords.Contains (pattern) select x; var items = from x in query.Take (15).ToList () select new { id = x.Id, name = x.ToString () }; return Json (items, JsonRequestBehavior.AllowGet); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Storage { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// The Storage Management Client. /// </summary> public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IStorageAccountsOperations. /// </summary> public virtual IStorageAccountsOperations StorageAccounts { get; private set; } /// <summary> /// Gets the IUsageOperations. /// </summary> public virtual IUsageOperations Usage { get; private set; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected StorageManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected StorageManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the StorageManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public StorageManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { StorageAccounts = new StorageAccountsOperations(this); Usage = new UsageOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2015-06-15"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.IO; using Avalonia.OpenGL; using Avalonia.OpenGL.Imaging; using Avalonia.Utilities; using SkiaSharp; using static Avalonia.OpenGL.GlConsts; namespace Avalonia.Skia { class GlOpenGlBitmapImpl : IOpenGlBitmapImpl, IDrawableBitmapImpl { private readonly IGlContext _context; private readonly object _lock = new object(); private IGlPresentableOpenGlSurface _surface; public GlOpenGlBitmapImpl(IGlContext context, PixelSize pixelSize, Vector dpi) { _context = context; PixelSize = pixelSize; Dpi = dpi; } public Vector Dpi { get; } public PixelSize PixelSize { get; } public int Version { get; private set; } public void Save(string fileName) => throw new NotSupportedException(); public void Save(Stream stream) => throw new NotSupportedException(); public void Draw(DrawingContextImpl context, SKRect sourceRect, SKRect destRect, SKPaint paint) { lock (_lock) { if (_surface == null) return; using (_surface.Lock()) { using (var backendTexture = new GRBackendTexture(PixelSize.Width, PixelSize.Height, false, new GRGlTextureInfo( GlConsts.GL_TEXTURE_2D, (uint)_surface.GetTextureId(), (uint)_surface.InternalFormat))) using (var surface = SKSurface.Create(context.GrContext, backendTexture, GRSurfaceOrigin.TopLeft, SKColorType.Rgba8888)) { // Again, silently ignore, if something went wrong it's not our fault if (surface == null) return; using (var snapshot = surface.Snapshot()) context.Canvas.DrawImage(snapshot, sourceRect, destRect, paint); } } } } public IOpenGlBitmapAttachment CreateFramebufferAttachment(IGlContext context, Action presentCallback) { if (!SupportsContext(context)) throw new OpenGlException("Context is not supported for texture sharing"); return new SharedOpenGlBitmapAttachment(this, context, presentCallback); } public bool SupportsContext(IGlContext context) { // TODO: negotiated platform surface sharing return _context.IsSharedWith(context); } public void Dispose() { } internal void Present(IGlPresentableOpenGlSurface surface) { lock (_lock) { _surface = surface; } } } interface IGlPresentableOpenGlSurface : IDisposable { int GetTextureId(); int InternalFormat { get; } IDisposable Lock(); } class SharedOpenGlBitmapAttachment : IOpenGlBitmapAttachment, IGlPresentableOpenGlSurface { private readonly GlOpenGlBitmapImpl _bitmap; private readonly IGlContext _context; private readonly Action _presentCallback; private readonly int _fbo; private readonly int _texture; private readonly int _frontBuffer; private bool _disposed; private readonly DisposableLock _lock = new DisposableLock(); public SharedOpenGlBitmapAttachment(GlOpenGlBitmapImpl bitmap, IGlContext context, Action presentCallback) { _bitmap = bitmap; _context = context; _presentCallback = presentCallback; using (_context.EnsureCurrent()) { var glVersion = _context.Version; InternalFormat = glVersion.Type == GlProfileType.OpenGLES ? GL_RGBA : GL_RGBA8; _context.GlInterface.GetIntegerv(GL_FRAMEBUFFER_BINDING, out _fbo); if (_fbo == 0) throw new OpenGlException("Current FBO is 0"); { var gl = _context.GlInterface; var textures = new int[2]; gl.GenTextures(2, textures); _texture = textures[0]; _frontBuffer = textures[1]; gl.GetIntegerv(GL_TEXTURE_BINDING_2D, out var oldTexture); foreach (var t in textures) { gl.BindTexture(GL_TEXTURE_2D, t); gl.TexImage2D(GL_TEXTURE_2D, 0, InternalFormat, _bitmap.PixelSize.Width, _bitmap.PixelSize.Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, IntPtr.Zero); gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } gl.FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texture, 0); gl.BindTexture(GL_TEXTURE_2D, oldTexture); } } } public void Present() { using (_context.MakeCurrent()) { if (_disposed) throw new ObjectDisposedException(nameof(SharedOpenGlBitmapAttachment)); var gl = _context.GlInterface; gl.Finish(); using (Lock()) { gl.GetIntegerv(GL_FRAMEBUFFER_BINDING, out var oldFbo); gl.GetIntegerv(GL_TEXTURE_BINDING_2D, out var oldTexture); gl.GetIntegerv(GL_ACTIVE_TEXTURE, out var oldActive); gl.BindFramebuffer(GL_FRAMEBUFFER, _fbo); gl.BindTexture(GL_TEXTURE_2D, _frontBuffer); gl.ActiveTexture(GL_TEXTURE0); gl.CopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, _bitmap.PixelSize.Width, _bitmap.PixelSize.Height); gl.BindFramebuffer(GL_FRAMEBUFFER, oldFbo); gl.BindTexture(GL_TEXTURE_2D, oldTexture); gl.ActiveTexture(oldActive); gl.Finish(); } } _bitmap.Present(this); _presentCallback(); } public void Dispose() { var gl = _context.GlInterface; _bitmap.Present(null); if(_disposed) return; using (_context.MakeCurrent()) using (Lock()) { if(_disposed) return; _disposed = true; gl.DeleteTextures(2, new[] { _texture, _frontBuffer }); } } int IGlPresentableOpenGlSurface.GetTextureId() { return _frontBuffer; } public int InternalFormat { get; } public IDisposable Lock() => _lock.Lock(); } }
using System.Diagnostics; using Meziantou.Framework.Globbing.Internals; using Meziantou.Framework.Globbing.Internals.Segments; namespace Meziantou.Framework.Globbing; internal static class GlobParser { private static readonly char[] s_separator = { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }; public static bool TryParse(ReadOnlySpan<char> pattern, GlobOptions options, [NotNullWhen(true)] out Glob? result, [NotNullWhen(false)] out string? errorMessage) { result = null; if (pattern.IsEmpty) { errorMessage = "The pattern is empty"; return false; } var ignoreCase = options.HasFlag(GlobOptions.IgnoreCase); var exclude = false; var segments = new List<Segment>(); List<Segment>? subSegments = null; List<string>? setSubsegment = null; List<CharacterRange>? rangeSubsegment = null; char? rangeStart = null; var rangeInverse = false; if (options.HasFlag(GlobOptions.Git)) { // Check if there is a separator at start or middle of the string if (pattern[0..^1].IndexOf('/') < 0) { segments.Add(RecursiveMatchAllSegment.Instance); } } var escape = false; var parserContext = GlobParserContext.Segment; Span<char> sbSpan = stackalloc char[128]; var currentLiteral = new ValueStringBuilder(sbSpan); try { for (var i = 0; i < pattern.Length; i++) { var c = pattern[i]; if (escape) { currentLiteral.Append(c); escape = false; continue; } if (c == '!' && i == 0) { exclude = true; continue; } if (parserContext == GlobParserContext.Segment) { if (c == '/') { FinishSegment(segments, ref subSegments, ref currentLiteral, ignoreCase); continue; } else if (c == '.') { if (subSegments == null && currentLiteral.Length == 0) { if (EndOfSegmentEqual(pattern[i..], "..")) { if (segments.Count == 0) { errorMessage = "the pattern cannot start with '..'"; return false; } if (segments[^1] is RecursiveMatchAllSegment) { errorMessage = "the pattern cannot contain '..' after a '**'"; return false; } segments.RemoveAt(segments.Count - 1); i += 2; continue; } if (EndOfSegmentEqual(pattern[i..], ".")) { i += 1; continue; } } } else if (c == '?') { AddSubsegment(ref subSegments, ref currentLiteral, ignoreCase, MatchAnyCharacterSegment.Instance); continue; } else if (c == '*') { if (subSegments == null && currentLiteral.Length == 0) { if (EndOfSegmentEqual(pattern[i..], "**")) { // Merge two consecutive '**' (**/**) if (segments.Count == 0 || segments[^1] is not RecursiveMatchAllSegment) { segments.Add(RecursiveMatchAllSegment.Instance); } i += 2; continue; } if (EndOfSegmentEqual(pattern[i..], "*")) { segments.Add(MatchAllSegment.Instance); i += 1; continue; } } // Merge 2 consecutive '*' if (currentLiteral.Length == 0 && subSegments != null && subSegments.Count > 0 && subSegments[^1] is MatchAllSubSegment) continue; AddSubsegment(ref subSegments, ref currentLiteral, ignoreCase, MatchAllSubSegment.Instance); continue; } else if (c == '{') // Start LiteralSet { Debug.Assert(setSubsegment == null); AddSubsegment(ref subSegments, ref currentLiteral, ignoreCase, subSegment: null); parserContext = GlobParserContext.LiteralSet; setSubsegment = new List<string>(); continue; } else if (c == '[') // Range { Debug.Assert(rangeSubsegment == null); AddSubsegment(ref subSegments, ref currentLiteral, ignoreCase, subSegment: null); parserContext = GlobParserContext.Range; rangeSubsegment = new List<CharacterRange>(); rangeInverse = i + 1 < pattern.Length && pattern[i + 1] == '!'; if (rangeInverse) { i++; } continue; } } else if (parserContext == GlobParserContext.LiteralSet) { Debug.Assert(setSubsegment != null); if (c == ',') // end of current value { setSubsegment.Add(currentLiteral.AsSpan().ToString()); currentLiteral.Clear(); continue; } else if (c == '}') // end of literal set { setSubsegment.Add(currentLiteral.AsSpan().ToString()); currentLiteral.Clear(); if (setSubsegment.Any(s => s.IndexOfAny(s_separator) >= 0)) { errorMessage = "set contains a path separator"; return false; } AddSubsegment(ref subSegments, ref currentLiteral, ignoreCase, new LiteralSetSegment(setSubsegment.ToArray(), ignoreCase)); setSubsegment = null; parserContext = GlobParserContext.Segment; continue; } } else if (parserContext == GlobParserContext.Range) { Debug.Assert(rangeSubsegment != null); if (c == ']') // end of literal set, except if empty []] or [!]] { // [a-] => '-' is considered as a character if (rangeStart.HasValue) { rangeSubsegment.Add(new CharacterRange(rangeStart.GetValueOrDefault())); rangeSubsegment.Add(new CharacterRange('-')); rangeStart = null; } if (rangeSubsegment.Count > 0) { if (rangeSubsegment.Any(s => s.IsInRange(Path.DirectorySeparatorChar) || s.IsInRange(Path.AltDirectorySeparatorChar))) { errorMessage = "range contains a path separator"; return false; } AddSubsegment(ref subSegments, ref currentLiteral, ignoreCase, CreateRangeSubsegment(rangeSubsegment, rangeInverse, ignoreCase)); rangeSubsegment = null; parserContext = GlobParserContext.Segment; continue; } } if (rangeStart.HasValue) { var rangeStartValue = rangeStart.GetValueOrDefault(); if (rangeStartValue > c) { errorMessage = $"Invalid range '{rangeStartValue}' > '{c}'"; return false; } rangeSubsegment.Add(new CharacterRange(rangeStartValue, c)); rangeStart = null; } else { if (i + 1 < pattern.Length && pattern[i + 1] == '-') { rangeStart = c; i++; } else { rangeSubsegment.Add(new CharacterRange(c)); } } continue; } switch (c) { case '\\': // Escape next character escape = true; break; default: currentLiteral.Append(c); break; } } if (parserContext != GlobParserContext.Segment) { errorMessage = $"The '{parserContext}' is not complete"; return false; } // If the last character is a '\' if (escape) { errorMessage = "Expecting a character after '\\'"; return false; } FinishSegment(segments, ref subSegments, ref currentLiteral, ignoreCase); if (options.HasFlag(GlobOptions.Git)) { if (pattern[^1] == '/') { segments.Add(RecursiveMatchAllSegment.Instance); segments.Add(MatchAllSegment.Instance); } } errorMessage = null; result = CreateGlob(segments, exclude, ignoreCase); return true; } finally { currentLiteral.Dispose(); } static void AddSubsegment(ref List<Segment>? subSegments, ref ValueStringBuilder currentLiteral, bool ignoreCase, Segment? subSegment) { if (subSegments == null) { subSegments = new List<Segment>(); } if (currentLiteral.Length > 0) { subSegments.Add(new LiteralSegment(currentLiteral.AsSpan().ToString(), ignoreCase)); currentLiteral.Clear(); } if (subSegment != null) { subSegments.Add(subSegment); } } static void FinishSegment(List<Segment> segments, ref List<Segment>? subSegments, ref ValueStringBuilder currentLiteral, bool ignoreCase) { if (subSegments != null) { if (currentLiteral.Length > 0) { subSegments.Add(new LiteralSegment(currentLiteral.AsSpan().ToString(), ignoreCase)); currentLiteral.Clear(); } segments.Add(CreateSegment(subSegments, ignoreCase)); subSegments = null; } else if (currentLiteral.Length > 0) { segments.Add(new LiteralSegment(currentLiteral.AsSpan().ToString(), ignoreCase)); currentLiteral.Clear(); } } } private static Glob CreateGlob(List<Segment> segments, bool exclude, bool ignoreCase) { // Optimize segments if (segments.Count >= 2) { if (segments[^2] is RecursiveMatchAllSegment && segments[^1] is MatchAllSegment) // **/* { var lastSegment = MatchNonEmptyTextSegment.Instance; segments.RemoveRange(segments.Count - 2, 2); segments.Add(lastSegment); } else if (segments[^2] is RecursiveMatchAllSegment && segments[^1] is EndsWithSegment endsWith) // **/*.txt { var lastSegment = new MatchAllEndsWithSegment(endsWith.Value, ignoreCase); segments.RemoveRange(segments.Count - 2, 2); segments.Add(lastSegment); } else if (segments[^2] is RecursiveMatchAllSegment) // **/segment { var lastSegment = new LastSegment(segments[^1]); segments.RemoveRange(segments.Count - 2, 2); segments.Add(lastSegment); } } return new Glob(segments.ToArray(), exclude ? GlobMode.Exclude : GlobMode.Include); } private static bool EndOfSegmentEqual(ReadOnlySpan<char> rest, string expected) { // Could be "{rest}/" or "{rest}"$ if (rest.Length == expected.Length) return rest.SequenceEqual(expected.AsSpan()); if (rest.Length > expected.Length) return rest.StartsWith(expected.AsSpan(), StringComparison.Ordinal) && rest[expected.Length] == '/'; return false; } private static Segment CreateRangeSubsegment(List<CharacterRange> ranges, bool inverse, bool ignoreCase) { var singleCharRanges = ranges.Where(r => r.IsSingleCharacterRange).Select(r => r.Min).ToArray(); var rangeCharRanges = ranges.Where(r => !r.IsSingleCharacterRange).ToArray(); if (singleCharRanges.Length > 0) { if (rangeCharRanges.Length == 0) return CreateCharacterSet(singleCharRanges, inverse, ignoreCase); } else if (rangeCharRanges.Length == 1) { return CreateCharacterRange(rangeCharRanges[0], ignoreCase, inverse); } // Inverse flags is set on the combination var segments = rangeCharRanges.Select(r => CreateCharacterRange(r, ignoreCase, inverse: false)); if (singleCharRanges.Length > 0) { segments = segments.Prepend(CreateCharacterSet(singleCharRanges, inverse: false, ignoreCase)); } return new OrSegment(segments.ToArray(), inverse); } private static Segment CreateCharacterSet(char[] set, bool inverse, bool ignoreCase) { return inverse ? new CharacterSetInverseSegment(new string(set), ignoreCase) : new CharacterSetSegment(new string(set), ignoreCase); } private static Segment CreateCharacterRange(CharacterRange range, bool ignoreCase, bool inverse) { return (ignoreCase, inverse) switch { (ignoreCase: false, inverse: false) => new CharacterRangeSegment(range), (ignoreCase: false, inverse: true) => new CharacterRangeInverseSegment(range), (ignoreCase: true, inverse: false) => new CharacterRangeIgnoreCaseSegment(range), (ignoreCase: true, inverse: true) => new CharacterRangeIgnoreCaseInverseSegment(range), }; } private static Segment CreateSegment(List<Segment> parts, bool ignoreCase) { Debug.Assert(parts.Count > 0); // Concat Literal and single character sets (abc[d]) for (var i = parts.Count - 2; i >= 0; i--) { var s1 = GetString(parts[i]); var s2 = GetString(parts[i + 1]); if (s1 is null || s2 is null) continue; // Merge var literal = new LiteralSegment(s1 + s2, ignoreCase); parts[i] = literal; parts.RemoveAt(i + 1); static string? GetString(Segment segment) { return segment switch { LiteralSegment literal => literal.Value, CharacterSetSegment set when set.Set.Length == 1 => set.Set, _ => null, }; } } // Try to optimize common cases if (parts.Count == 2) { // Starts with: test.* if (parts[1] is MatchAllSubSegment && parts[0] is LiteralSegment startsWithLiteral) return new StartsWithSegment(startsWithLiteral.Value, ignoreCase); } if (parts.Count > 2) { if (parts.Count > 2 && parts[^1] is MatchAllSubSegment && parts[^3] is MatchAllSubSegment && parts[^2] is LiteralSegment containsLiteral) // Contains: *test* { parts.RemoveRange(parts.Count - 3, 3); parts.Add(new ContainsSegment(containsLiteral.Value, ignoreCase)); } } if (parts.Count >= 2) { if (parts[^2] is MatchAllSubSegment && parts[^1] is LiteralSegment endsWithLiteral) // Ends with: *.txt { parts.RemoveRange(parts.Count - 2, 2); parts.Add(new EndsWithSegment(endsWithLiteral.Value, ignoreCase)); } // *(pattern) => Check if the first character is known and easily validatable // /, \, Literal[0], CharacterSet [abc], CharacterRange [a-z] if interval is small (<=5), LiteralSet {abc,def} for (var i = 0; i < parts.Count - 1; i++) { if (parts[i] is MatchAllSubSegment) { var next = parts[i + 1]; var nextCharacters = next switch { LiteralSegment literal => new List<char> { literal.Value[0] }, CharacterSetSegment characterSet => characterSet.Set.ToList(), CharacterRangeSegment characterRange when characterRange.Range.Length < 3 => characterRange.Range.EnumerateCharacters().ToList(), LiteralSetSegment literalSet => literalSet.Values.Where(v => v.Length > 0).Select(v => v[0]).ToList(), _ => null, }; if (nextCharacters != null) { nextCharacters.Add(Path.DirectorySeparatorChar); if (Path.DirectorySeparatorChar != Path.AltDirectorySeparatorChar) { nextCharacters.Add(Path.AltDirectorySeparatorChar); } parts.Insert(i, new ConsumeSegmentUntilSegment(nextCharacters.ToArray())); i++; } } } } if (parts[^1] is MatchAllSubSegment) { parts[^1] = MatchAllEndOfSegment.Instance; } if (parts.Count == 1) return parts[0]; return new RaggedSegment(parts.ToArray()); } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using ASC.Common.Web; using ASC.Core; using ASC.Core.Users; using ASC.Mail.Autoreply.AddressParsers; using ASC.Mail.Net; using ASC.Mail.Net.MIME; using ASC.Mail.Net.Mail; using ASC.Mail.Net.SMTP.Server; using ASC.Mail.Net.TCP; using log4net; namespace ASC.Mail.Autoreply { internal class AutoreplyService : IDisposable { private readonly ILog _log = LogManager.GetLogger(typeof(AutoreplyService)); private readonly List<IAddressParser> _addressParsers = new List<IAddressParser>(); private readonly SMTP_Server _smtpServer; private readonly ApiService _apiService; private readonly CooldownInspector _cooldownInspector; private readonly bool _storeIncomingMail; private readonly string _mailFolder; public AutoreplyService(AutoreplyServiceConfiguration configuration = null) { configuration = configuration ?? AutoreplyServiceConfiguration.GetSection(); _storeIncomingMail = configuration.IsDebug; _mailFolder = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), configuration.MailFolder); if (!Directory.Exists(_mailFolder)) Directory.CreateDirectory(_mailFolder); _smtpServer = new SMTP_Server { MaxBadCommands = configuration.SmtpConfiguration.MaxBadCommands, MaxTransactions = configuration.SmtpConfiguration.MaxTransactions, MaxMessageSize = configuration.SmtpConfiguration.MaxMessageSize, MaxRecipients = configuration.SmtpConfiguration.MaxRecipients, MaxConnectionsPerIP = configuration.SmtpConfiguration.MaxConnectionsPerIP, MaxConnections = configuration.SmtpConfiguration.MaxConnections, Bindings = new[] {new IPBindInfo("localhost", IPAddress.Any, configuration.SmtpConfiguration.Port, SslMode.None, null)}, }; _smtpServer.Error += OnSmtpError; _smtpServer.SessionCreated += OnSmtpSessionCreated; _cooldownInspector = new CooldownInspector(configuration.CooldownConfiguration); _apiService = new ApiService(configuration.Https); } public void Start() { _smtpServer.Start(); _apiService.Start(); _cooldownInspector.Start(); } public void Stop() { _smtpServer.Stop(); _apiService.Stop(); _cooldownInspector.Stop(); } public void Dispose() { Stop(); _smtpServer.Dispose(); } public void RegisterAddressParser(IAddressParser addressHandler) { _addressParsers.Add(addressHandler); } private void OnSmtpSessionCreated(object sender, TCP_ServerSessionEventArgs<SMTP_Session> e) { e.Session.Started += (sndr, args) => _log.DebugFormat("session started: {0}", e.Session); e.Session.MailFrom += OnSessionMailFrom; e.Session.RcptTo += OnSessionRcptTo; e.Session.GetMessageStream += OnSessionGetMessageStream; e.Session.MessageStoringCanceled += OnSessionMessageStoringCancelled; e.Session.MessageStoringCompleted += OnSessionMessageStoringCompleted; } private void OnSmtpError(object sender, Error_EventArgs e) { _log.WarnFormat("smtp error: {0}", e.Exception); } private void OnSessionMailFrom(object sender, SMTP_e_MailFrom e) { e.Session.Tag = Regex.Replace(e.MailFrom.Mailbox, "^prvs=[0-9a-zA-Z]+=", "", RegexOptions.Compiled); //Set session mailbox } private void OnSessionRcptTo(object sender, SMTP_e_RcptTo e) { _log.Debug("start processing rcpt to event"); var addressTo = e.RcptTo.Mailbox; var addressFrom = (string)e.Session.Tag; var requestInfo = _addressParsers.Select(routeParser => routeParser.ParseRequestInfo(addressTo)) .FirstOrDefault(rInfo => rInfo != null); if (requestInfo == null) { _log.WarnFormat("could not create request from the address {0}", addressTo); e.Reply = new SMTP_Reply(501, "Could not create request from the address " + addressTo); return; } CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant); UserInfo user = CoreContext.UserManager.GetUserByEmail(addressFrom); if (user.Equals(Constants.LostUser)) { e.Reply = new SMTP_Reply(501, "Could not find user by email address " + addressFrom); return; } if (_cooldownInspector != null) { var cooldownMinutes = Math.Ceiling(_cooldownInspector.GetCooldownRemainigTime(user.ID).TotalMinutes); if (cooldownMinutes > 0) { e.Reply = new SMTP_Reply(554, string.Format("User {0} can not use the autoreply service for another {1} minutes", addressFrom, cooldownMinutes)); return; } _cooldownInspector.RegisterServiceUsage(user.ID); } requestInfo.User = user; _log.DebugFormat("created request info {0}", requestInfo); e.Session.Tags.Add(e.RcptTo.Mailbox, requestInfo); _log.Debug("complete processing rcpt to event"); } private void OnSessionGetMessageStream(object sender, SMTP_e_Message e) { try { var messageFileName = Path.Combine(_mailFolder, DateTime.UtcNow.ToString("yyyy'-'MM'-'dd HH'-'mm'-'ss'Z'") + ".eml"); e.Stream = new FileStream(messageFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 8096, _storeIncomingMail ? FileOptions.None : FileOptions.DeleteOnClose); } catch (Exception error) { _log.Error("error while allocating temporary stream for the message", error); } } private void OnSessionMessageStoringCancelled(object sender, SMTP_e_MessageStored e) { try { e.Stream.Close(); } catch (Exception error) { _log.Error("error while closing message stream", error); } } private void OnSessionMessageStoringCompleted(object sender, SMTP_e_MessageStored e) { _log.Debug("begin processing message storing completed event"); try { e.Stream.Flush(); e.Stream.Seek(0, SeekOrigin.Begin); Mail_Message message = Mail_Message.ParseFromStream(e.Stream); message.Subject = Regex.Replace(message.Subject, @"\t", ""); foreach (var requestInfo in e.Session.To .Where(x => e.Session.Tags.ContainsKey(x.Mailbox)) .Select(x => (ApiRequest)e.Session.Tags[x.Mailbox])) { try { _log.Debug("begin process request (" + requestInfo + ")"); CoreContext.TenantManager.SetCurrentTenant(requestInfo.Tenant); if (requestInfo.Parameters != null) { foreach (var parameter in requestInfo.Parameters.Where(x => x.ValueResolver != null)) { parameter.Value = parameter.ValueResolver.ResolveParameterValue(message); } } if (requestInfo.FilesToPost != null) { requestInfo.FilesToPost = message.AllEntities.Where(IsAttachment).Select(GetAsAttachment).ToList(); } if (requestInfo.FilesToPost == null || requestInfo.FilesToPost.Count > 0) { _apiService.EnqueueRequest(requestInfo); } _log.Debug("end process request (" + requestInfo + ")"); } catch (Exception ex) { _log.Error("error while processing request info", ex); } } } catch (Exception error) { _log.Error("error while processing message storing completed event", error); } finally { e.Stream.Close(); } _log.Debug("complete processing message storing completed event"); } private static bool IsAttachment(MIME_Entity entity) { return entity.Body.ContentType != null && entity.Body.ContentType.TypeWithSubype != null && entity.ContentDisposition != null && entity.ContentDisposition.DispositionType == MIME_DispositionTypes.Attachment && (!string.IsNullOrEmpty(entity.ContentDisposition.Param_FileName) || !string.IsNullOrEmpty(entity.ContentType.Param_Name)) && entity.Body is MIME_b_SinglepartBase; } private static RequestFileInfo GetAsAttachment(MIME_Entity entity) { var attachment = new RequestFileInfo { Body = ((MIME_b_SinglepartBase)entity.Body).Data }; if (!string.IsNullOrEmpty(entity.ContentDisposition.Param_FileName)) { attachment.Name = entity.ContentDisposition.Param_FileName; } else if (!string.IsNullOrEmpty(entity.ContentType.Param_Name)) { attachment.Name = entity.ContentType.Param_Name; } attachment.ContentType = MimeMapping.GetMimeMapping(attachment.Name); return attachment; } } }
// // 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.Management.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Management\Add-Computer command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class AddComputer : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public AddComputer() { this.DisplayName = "Add-Computer"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Management\\Add-Computer"; } } // Arguments /// <summary> /// Provides access to the LocalCredential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> LocalCredential { get; set; } /// <summary> /// Provides access to the UnjoinDomainCredential parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.PSCredential> UnjoinDomainCredential { 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 DomainName parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> DomainName { get; set; } /// <summary> /// Provides access to the OUPath parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> OUPath { get; set; } /// <summary> /// Provides access to the Server parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> Server { get; set; } /// <summary> /// Provides access to the Unsecure parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Unsecure { get; set; } /// <summary> /// Provides access to the Options parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<Microsoft.PowerShell.Commands.JoinOptions> Options { get; set; } /// <summary> /// Provides access to the WorkgroupName parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> WorkgroupName { get; set; } /// <summary> /// Provides access to the Restart parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Restart { get; set; } /// <summary> /// Provides access to the PassThru parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> PassThru { get; set; } /// <summary> /// Provides access to the NewName parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String> NewName { get; set; } /// <summary> /// Provides access to the Force parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> Force { get; set; } /// <summary> /// Declares that this activity supports its own remoting. /// </summary> protected override bool SupportsCustomRemoting { get { return true; } } // 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(LocalCredential.Expression != null) { targetCommand.AddParameter("LocalCredential", LocalCredential.Get(context)); } if(UnjoinDomainCredential.Expression != null) { targetCommand.AddParameter("UnjoinDomainCredential", UnjoinDomainCredential.Get(context)); } if(Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if(DomainName.Expression != null) { targetCommand.AddParameter("DomainName", DomainName.Get(context)); } if(OUPath.Expression != null) { targetCommand.AddParameter("OUPath", OUPath.Get(context)); } if(Server.Expression != null) { targetCommand.AddParameter("Server", Server.Get(context)); } if(Unsecure.Expression != null) { targetCommand.AddParameter("Unsecure", Unsecure.Get(context)); } if(Options.Expression != null) { targetCommand.AddParameter("Options", Options.Get(context)); } if(WorkgroupName.Expression != null) { targetCommand.AddParameter("WorkgroupName", WorkgroupName.Get(context)); } if(Restart.Expression != null) { targetCommand.AddParameter("Restart", Restart.Get(context)); } if(PassThru.Expression != null) { targetCommand.AddParameter("PassThru", PassThru.Get(context)); } if(NewName.Expression != null) { targetCommand.AddParameter("NewName", NewName.Get(context)); } if(Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } if(GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom)) { targetCommand.AddParameter("ComputerName", PSComputerName.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
namespace GitAspx.Lib { using System.Collections.Generic; using System.IO; using NGit; using NGit.Errors; using NGit.Storage.File; using NGit.Util; using Sharpen; public class NGitBasedSimpleRefWriter : NGitRefWriter { private readonly FileRepository _db; public NGitBasedSimpleRefWriter(FileRepository db, ICollection<Ref> refs) : base(refs) { _db = db; } protected internal override void WriteFile(string file, byte[] content) { FilePath p = new FilePath(_db.Directory, file); LockFile lck = new LockFile(p, FS.DETECTED); if (!lck.Lock()) throw new ObjectWritingException("Can't write " + p); try { lck.Write(content); } catch (IOException) { throw new ObjectWritingException("Can't write " + p); } if (!lck.Commit()) throw new ObjectWritingException("Can't write " + p); } } //The following code is copied from NGit, because all protected members in NGit are internally visible only. /* This code is derived from jgit (http://eclipse.org/jgit). Copyright owners are documented in jgit's IP log. This program and the accompanying materials are made available under the terms of the Eclipse Distribution License v1.0 which accompanies this distribution, is reproduced below, and is available at http://www.eclipse.org/org/documents/edl-v10.php All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the Eclipse Foundation, 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. */ /// <summary> /// Writes out refs to the /// <see cref="Constants.INFO_REFS">Constants.INFO_REFS</see> /// and /// <see cref="Constants.PACKED_REFS">Constants.PACKED_REFS</see> /// files. /// This class is abstract as the writing of the files must be handled by the /// caller. This is because it is used by transport classes as well. /// </summary> public abstract class NGitRefWriter { private readonly ICollection<Ref> refs; /// <param name="refs"> /// the complete set of references. This should have been computed /// by applying updates to the advertised refs already discovered. /// </param> public NGitRefWriter(ICollection<Ref> refs) { this.refs = RefComparator.Sort(refs); } /// <param name="refs"> /// the complete set of references. This should have been computed /// by applying updates to the advertised refs already discovered. /// </param> public NGitRefWriter(IDictionary<string, Ref> refs) { if (refs is RefMap) { this.refs = refs.Values; } else { this.refs = RefComparator.Sort(refs.Values); } } /// <param name="refs"> /// the complete set of references. This should have been computed /// by applying updates to the advertised refs already discovered. /// </param> public NGitRefWriter(RefList<Ref> refs) { this.refs = refs.AsList(); } /// <summary> /// Rebuild the /// <see cref="Constants.INFO_REFS">Constants.INFO_REFS</see> /// . /// <p> /// This method rebuilds the contents of the /// <see cref="Constants.INFO_REFS">Constants.INFO_REFS</see> /// file /// to match the passed list of references. /// </summary> /// <exception cref="System.IO.IOException"> /// writing is not supported, or attempting to write the file /// failed, possibly due to permissions or remote disk full, etc. /// </exception> public virtual void WriteInfoRefs() { StringWriter w = new StringWriter(); char[] tmp = new char[Constants.OBJECT_ID_STRING_LENGTH]; foreach (Ref r in refs) { if (Constants.HEAD.Equals(r.GetName())) { // Historically HEAD has never been published through // the INFO_REFS file. This is a mistake, but its the // way things are. // continue; } r.GetObjectId().CopyTo(tmp, w); w.Write('\t'); w.Write(r.GetName()); w.Write('\n'); if (r.GetPeeledObjectId() != null) { r.GetPeeledObjectId().CopyTo(tmp, w); w.Write('\t'); w.Write(r.GetName()); w.Write("^{}\n"); } } WriteFile(Constants.INFO_REFS, Constants.Encode(w.ToString())); } /// <summary> /// Rebuild the /// <see cref="Constants.PACKED_REFS">Constants.PACKED_REFS</see> /// file. /// <p> /// This method rebuilds the contents of the /// <see cref="Constants.PACKED_REFS">Constants.PACKED_REFS</see> /// file to match the passed list of references, including only those refs /// that have a storage type of /// <see cref="RefStorage.PACKED">RefStorage.PACKED</see> /// . /// </summary> /// <exception cref="System.IO.IOException"> /// writing is not supported, or attempting to write the file /// failed, possibly due to permissions or remote disk full, etc. /// </exception> public virtual void WritePackedRefs() { bool peeled = false; foreach (Ref r in refs) { if (r.GetStorage().IsPacked() && r.IsPeeled()) { peeled = true; break; } } StringWriter w = new StringWriter(); if (peeled) { w.Write(RefDirectory.PACKED_REFS_HEADER); if (peeled) { w.Write(RefDirectory.PACKED_REFS_PEELED); } w.Write('\n'); } char[] tmp = new char[Constants.OBJECT_ID_STRING_LENGTH]; foreach (Ref r_1 in refs) { if (r_1.GetStorage() != RefStorage.PACKED) { continue; } r_1.GetObjectId().CopyTo(tmp, w); w.Write(' '); w.Write(r_1.GetName()); w.Write('\n'); if (r_1.GetPeeledObjectId() != null) { w.Write('^'); r_1.GetPeeledObjectId().CopyTo(tmp, w); w.Write('\n'); } } WriteFile(Constants.PACKED_REFS, Constants.Encode(w.ToString())); } /// <summary> /// Handles actual writing of ref files to the git repository, which may /// differ slightly depending on the destination and transport. /// </summary> /// <remarks> /// Handles actual writing of ref files to the git repository, which may /// differ slightly depending on the destination and transport. /// </remarks> /// <param name="file">path to ref file.</param> /// <param name="content">byte content of file to be written.</param> /// <exception cref="System.IO.IOException">System.IO.IOException</exception> protected internal abstract void WriteFile(string file, byte[] content); } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; namespace XenAPI { /// <summary> /// A virtual block device /// First published in XenServer 4.0. /// </summary> public partial class VBD : XenObject<VBD> { public VBD() { } public VBD(string uuid, List<vbd_operations> allowed_operations, Dictionary<string, vbd_operations> current_operations, XenRef<VM> VM, XenRef<VDI> VDI, string device, string userdevice, bool bootable, vbd_mode mode, vbd_type type, bool unpluggable, bool storage_lock, bool empty, Dictionary<string, string> other_config, bool currently_attached, long status_code, string status_detail, Dictionary<string, string> runtime_properties, string qos_algorithm_type, Dictionary<string, string> qos_algorithm_params, string[] qos_supported_algorithms, XenRef<VBD_metrics> metrics) { this.uuid = uuid; this.allowed_operations = allowed_operations; this.current_operations = current_operations; this.VM = VM; this.VDI = VDI; this.device = device; this.userdevice = userdevice; this.bootable = bootable; this.mode = mode; this.type = type; this.unpluggable = unpluggable; this.storage_lock = storage_lock; this.empty = empty; this.other_config = other_config; this.currently_attached = currently_attached; this.status_code = status_code; this.status_detail = status_detail; this.runtime_properties = runtime_properties; this.qos_algorithm_type = qos_algorithm_type; this.qos_algorithm_params = qos_algorithm_params; this.qos_supported_algorithms = qos_supported_algorithms; this.metrics = metrics; } /// <summary> /// Creates a new VBD from a Proxy_VBD. /// </summary> /// <param name="proxy"></param> public VBD(Proxy_VBD proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(VBD update) { uuid = update.uuid; allowed_operations = update.allowed_operations; current_operations = update.current_operations; VM = update.VM; VDI = update.VDI; device = update.device; userdevice = update.userdevice; bootable = update.bootable; mode = update.mode; type = update.type; unpluggable = update.unpluggable; storage_lock = update.storage_lock; empty = update.empty; other_config = update.other_config; currently_attached = update.currently_attached; status_code = update.status_code; status_detail = update.status_detail; runtime_properties = update.runtime_properties; qos_algorithm_type = update.qos_algorithm_type; qos_algorithm_params = update.qos_algorithm_params; qos_supported_algorithms = update.qos_supported_algorithms; metrics = update.metrics; } internal void UpdateFromProxy(Proxy_VBD proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vbd_operations>(proxy.allowed_operations); current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vbd_operations(proxy.current_operations); VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); VDI = proxy.VDI == null ? null : XenRef<VDI>.Create(proxy.VDI); device = proxy.device == null ? null : (string)proxy.device; userdevice = proxy.userdevice == null ? null : (string)proxy.userdevice; bootable = (bool)proxy.bootable; mode = proxy.mode == null ? (vbd_mode) 0 : (vbd_mode)Helper.EnumParseDefault(typeof(vbd_mode), (string)proxy.mode); type = proxy.type == null ? (vbd_type) 0 : (vbd_type)Helper.EnumParseDefault(typeof(vbd_type), (string)proxy.type); unpluggable = (bool)proxy.unpluggable; storage_lock = (bool)proxy.storage_lock; empty = (bool)proxy.empty; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); currently_attached = (bool)proxy.currently_attached; status_code = proxy.status_code == null ? 0 : long.Parse((string)proxy.status_code); status_detail = proxy.status_detail == null ? null : (string)proxy.status_detail; runtime_properties = proxy.runtime_properties == null ? null : Maps.convert_from_proxy_string_string(proxy.runtime_properties); qos_algorithm_type = proxy.qos_algorithm_type == null ? null : (string)proxy.qos_algorithm_type; qos_algorithm_params = proxy.qos_algorithm_params == null ? null : Maps.convert_from_proxy_string_string(proxy.qos_algorithm_params); qos_supported_algorithms = proxy.qos_supported_algorithms == null ? new string[] {} : (string [])proxy.qos_supported_algorithms; metrics = proxy.metrics == null ? null : XenRef<VBD_metrics>.Create(proxy.metrics); } public Proxy_VBD ToProxy() { Proxy_VBD result_ = new Proxy_VBD(); result_.uuid = uuid ?? ""; result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {}; result_.current_operations = Maps.convert_to_proxy_string_vbd_operations(current_operations); result_.VM = VM ?? ""; result_.VDI = VDI ?? ""; result_.device = device ?? ""; result_.userdevice = userdevice ?? ""; result_.bootable = bootable; result_.mode = vbd_mode_helper.ToString(mode); result_.type = vbd_type_helper.ToString(type); result_.unpluggable = unpluggable; result_.storage_lock = storage_lock; result_.empty = empty; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.currently_attached = currently_attached; result_.status_code = status_code.ToString(); result_.status_detail = status_detail ?? ""; result_.runtime_properties = Maps.convert_to_proxy_string_string(runtime_properties); result_.qos_algorithm_type = qos_algorithm_type ?? ""; result_.qos_algorithm_params = Maps.convert_to_proxy_string_string(qos_algorithm_params); result_.qos_supported_algorithms = qos_supported_algorithms; result_.metrics = metrics ?? ""; return result_; } /// <summary> /// Creates a new VBD from a Hashtable. /// </summary> /// <param name="table"></param> public VBD(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); allowed_operations = Helper.StringArrayToEnumList<vbd_operations>(Marshalling.ParseStringArray(table, "allowed_operations")); current_operations = Maps.convert_from_proxy_string_vbd_operations(Marshalling.ParseHashTable(table, "current_operations")); VM = Marshalling.ParseRef<VM>(table, "VM"); VDI = Marshalling.ParseRef<VDI>(table, "VDI"); device = Marshalling.ParseString(table, "device"); userdevice = Marshalling.ParseString(table, "userdevice"); bootable = Marshalling.ParseBool(table, "bootable"); mode = (vbd_mode)Helper.EnumParseDefault(typeof(vbd_mode), Marshalling.ParseString(table, "mode")); type = (vbd_type)Helper.EnumParseDefault(typeof(vbd_type), Marshalling.ParseString(table, "type")); unpluggable = Marshalling.ParseBool(table, "unpluggable"); storage_lock = Marshalling.ParseBool(table, "storage_lock"); empty = Marshalling.ParseBool(table, "empty"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); currently_attached = Marshalling.ParseBool(table, "currently_attached"); status_code = Marshalling.ParseLong(table, "status_code"); status_detail = Marshalling.ParseString(table, "status_detail"); runtime_properties = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "runtime_properties")); qos_algorithm_type = Marshalling.ParseString(table, "qos_algorithm_type"); qos_algorithm_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "qos_algorithm_params")); qos_supported_algorithms = Marshalling.ParseStringArray(table, "qos_supported_algorithms"); metrics = Marshalling.ParseRef<VBD_metrics>(table, "metrics"); } public bool DeepEquals(VBD other, bool ignoreCurrentOperations) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) return false; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._VDI, other._VDI) && Helper.AreEqual2(this._device, other._device) && Helper.AreEqual2(this._userdevice, other._userdevice) && Helper.AreEqual2(this._bootable, other._bootable) && Helper.AreEqual2(this._mode, other._mode) && Helper.AreEqual2(this._type, other._type) && Helper.AreEqual2(this._unpluggable, other._unpluggable) && Helper.AreEqual2(this._storage_lock, other._storage_lock) && Helper.AreEqual2(this._empty, other._empty) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._currently_attached, other._currently_attached) && Helper.AreEqual2(this._status_code, other._status_code) && Helper.AreEqual2(this._status_detail, other._status_detail) && Helper.AreEqual2(this._runtime_properties, other._runtime_properties) && Helper.AreEqual2(this._qos_algorithm_type, other._qos_algorithm_type) && Helper.AreEqual2(this._qos_algorithm_params, other._qos_algorithm_params) && Helper.AreEqual2(this._qos_supported_algorithms, other._qos_supported_algorithms) && Helper.AreEqual2(this._metrics, other._metrics); } public override string SaveChanges(Session session, string opaqueRef, VBD server) { if (opaqueRef == null) { Proxy_VBD p = this.ToProxy(); return session.proxy.vbd_create(session.uuid, p).parse(); } else { if (!Helper.AreEqual2(_userdevice, server._userdevice)) { VBD.set_userdevice(session, opaqueRef, _userdevice); } if (!Helper.AreEqual2(_bootable, server._bootable)) { VBD.set_bootable(session, opaqueRef, _bootable); } if (!Helper.AreEqual2(_mode, server._mode)) { VBD.set_mode(session, opaqueRef, _mode); } if (!Helper.AreEqual2(_type, server._type)) { VBD.set_type(session, opaqueRef, _type); } if (!Helper.AreEqual2(_unpluggable, server._unpluggable)) { VBD.set_unpluggable(session, opaqueRef, _unpluggable); } if (!Helper.AreEqual2(_other_config, server._other_config)) { VBD.set_other_config(session, opaqueRef, _other_config); } if (!Helper.AreEqual2(_qos_algorithm_type, server._qos_algorithm_type)) { VBD.set_qos_algorithm_type(session, opaqueRef, _qos_algorithm_type); } if (!Helper.AreEqual2(_qos_algorithm_params, server._qos_algorithm_params)) { VBD.set_qos_algorithm_params(session, opaqueRef, _qos_algorithm_params); } return null; } } /// <summary> /// Get a record containing the current state of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static VBD get_record(Session session, string _vbd) { return new VBD((Proxy_VBD)session.proxy.vbd_get_record(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get a reference to the VBD instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VBD> get_by_uuid(Session session, string _uuid) { return XenRef<VBD>.Create(session.proxy.vbd_get_by_uuid(session.uuid, _uuid ?? "").parse()); } /// <summary> /// Create a new VBD instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<VBD> create(Session session, VBD _record) { return XenRef<VBD>.Create(session.proxy.vbd_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Create a new VBD instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, VBD _record) { return XenRef<Task>.Create(session.proxy.async_vbd_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified VBD instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static void destroy(Session session, string _vbd) { session.proxy.vbd_destroy(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Destroy the specified VBD instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<Task> async_destroy(Session session, string _vbd) { return XenRef<Task>.Create(session.proxy.async_vbd_destroy(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the uuid field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static string get_uuid(Session session, string _vbd) { return (string)session.proxy.vbd_get_uuid(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the allowed_operations field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static List<vbd_operations> get_allowed_operations(Session session, string _vbd) { return Helper.StringArrayToEnumList<vbd_operations>(session.proxy.vbd_get_allowed_operations(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the current_operations field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static Dictionary<string, vbd_operations> get_current_operations(Session session, string _vbd) { return Maps.convert_from_proxy_string_vbd_operations(session.proxy.vbd_get_current_operations(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the VM field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<VM> get_VM(Session session, string _vbd) { return XenRef<VM>.Create(session.proxy.vbd_get_vm(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the VDI field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<VDI> get_VDI(Session session, string _vbd) { return XenRef<VDI>.Create(session.proxy.vbd_get_vdi(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the device field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static string get_device(Session session, string _vbd) { return (string)session.proxy.vbd_get_device(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the userdevice field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static string get_userdevice(Session session, string _vbd) { return (string)session.proxy.vbd_get_userdevice(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the bootable field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static bool get_bootable(Session session, string _vbd) { return (bool)session.proxy.vbd_get_bootable(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the mode field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static vbd_mode get_mode(Session session, string _vbd) { return (vbd_mode)Helper.EnumParseDefault(typeof(vbd_mode), (string)session.proxy.vbd_get_mode(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the type field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static vbd_type get_type(Session session, string _vbd) { return (vbd_type)Helper.EnumParseDefault(typeof(vbd_type), (string)session.proxy.vbd_get_type(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the unpluggable field of the given VBD. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static bool get_unpluggable(Session session, string _vbd) { return (bool)session.proxy.vbd_get_unpluggable(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the storage_lock field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static bool get_storage_lock(Session session, string _vbd) { return (bool)session.proxy.vbd_get_storage_lock(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the empty field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static bool get_empty(Session session, string _vbd) { return (bool)session.proxy.vbd_get_empty(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the other_config field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static Dictionary<string, string> get_other_config(Session session, string _vbd) { return Maps.convert_from_proxy_string_string(session.proxy.vbd_get_other_config(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the currently_attached field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static bool get_currently_attached(Session session, string _vbd) { return (bool)session.proxy.vbd_get_currently_attached(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the status_code field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static long get_status_code(Session session, string _vbd) { return long.Parse((string)session.proxy.vbd_get_status_code(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the status_detail field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static string get_status_detail(Session session, string _vbd) { return (string)session.proxy.vbd_get_status_detail(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the runtime_properties field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static Dictionary<string, string> get_runtime_properties(Session session, string _vbd) { return Maps.convert_from_proxy_string_string(session.proxy.vbd_get_runtime_properties(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the qos/algorithm_type field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static string get_qos_algorithm_type(Session session, string _vbd) { return (string)session.proxy.vbd_get_qos_algorithm_type(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the qos/algorithm_params field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static Dictionary<string, string> get_qos_algorithm_params(Session session, string _vbd) { return Maps.convert_from_proxy_string_string(session.proxy.vbd_get_qos_algorithm_params(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Get the qos/supported_algorithms field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static string[] get_qos_supported_algorithms(Session session, string _vbd) { return (string [])session.proxy.vbd_get_qos_supported_algorithms(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Get the metrics field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<VBD_metrics> get_metrics(Session session, string _vbd) { return XenRef<VBD_metrics>.Create(session.proxy.vbd_get_metrics(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Set the userdevice field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_userdevice">New value to set</param> public static void set_userdevice(Session session, string _vbd, string _userdevice) { session.proxy.vbd_set_userdevice(session.uuid, _vbd ?? "", _userdevice ?? "").parse(); } /// <summary> /// Set the bootable field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_bootable">New value to set</param> public static void set_bootable(Session session, string _vbd, bool _bootable) { session.proxy.vbd_set_bootable(session.uuid, _vbd ?? "", _bootable).parse(); } /// <summary> /// Set the mode field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_mode">New value to set</param> public static void set_mode(Session session, string _vbd, vbd_mode _mode) { session.proxy.vbd_set_mode(session.uuid, _vbd ?? "", vbd_mode_helper.ToString(_mode)).parse(); } /// <summary> /// Set the type field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_type">New value to set</param> public static void set_type(Session session, string _vbd, vbd_type _type) { session.proxy.vbd_set_type(session.uuid, _vbd ?? "", vbd_type_helper.ToString(_type)).parse(); } /// <summary> /// Set the unpluggable field of the given VBD. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_unpluggable">New value to set</param> public static void set_unpluggable(Session session, string _vbd, bool _unpluggable) { session.proxy.vbd_set_unpluggable(session.uuid, _vbd ?? "", _unpluggable).parse(); } /// <summary> /// Set the other_config field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vbd, Dictionary<string, string> _other_config) { session.proxy.vbd_set_other_config(session.uuid, _vbd ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vbd, string _key, string _value) { session.proxy.vbd_add_to_other_config(session.uuid, _vbd ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VBD. If the key is not in that Map, then do nothing. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vbd, string _key) { session.proxy.vbd_remove_from_other_config(session.uuid, _vbd ?? "", _key ?? "").parse(); } /// <summary> /// Set the qos/algorithm_type field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_algorithm_type">New value to set</param> public static void set_qos_algorithm_type(Session session, string _vbd, string _algorithm_type) { session.proxy.vbd_set_qos_algorithm_type(session.uuid, _vbd ?? "", _algorithm_type ?? "").parse(); } /// <summary> /// Set the qos/algorithm_params field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_algorithm_params">New value to set</param> public static void set_qos_algorithm_params(Session session, string _vbd, Dictionary<string, string> _algorithm_params) { session.proxy.vbd_set_qos_algorithm_params(session.uuid, _vbd ?? "", Maps.convert_to_proxy_string_string(_algorithm_params)).parse(); } /// <summary> /// Add the given key-value pair to the qos/algorithm_params field of the given VBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_qos_algorithm_params(Session session, string _vbd, string _key, string _value) { session.proxy.vbd_add_to_qos_algorithm_params(session.uuid, _vbd ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the qos/algorithm_params field of the given VBD. If the key is not in that Map, then do nothing. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_key">Key to remove</param> public static void remove_from_qos_algorithm_params(Session session, string _vbd, string _key) { session.proxy.vbd_remove_from_qos_algorithm_params(session.uuid, _vbd ?? "", _key ?? "").parse(); } /// <summary> /// Remove the media from the device and leave it empty /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static void eject(Session session, string _vbd) { session.proxy.vbd_eject(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Remove the media from the device and leave it empty /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<Task> async_eject(Session session, string _vbd) { return XenRef<Task>.Create(session.proxy.async_vbd_eject(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Insert new media into the device /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_vdi">The new VDI to 'insert'</param> public static void insert(Session session, string _vbd, string _vdi) { session.proxy.vbd_insert(session.uuid, _vbd ?? "", _vdi ?? "").parse(); } /// <summary> /// Insert new media into the device /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> /// <param name="_vdi">The new VDI to 'insert'</param> public static XenRef<Task> async_insert(Session session, string _vbd, string _vdi) { return XenRef<Task>.Create(session.proxy.async_vbd_insert(session.uuid, _vbd ?? "", _vdi ?? "").parse()); } /// <summary> /// Hotplug the specified VBD, dynamically attaching it to the running VM /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static void plug(Session session, string _vbd) { session.proxy.vbd_plug(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Hotplug the specified VBD, dynamically attaching it to the running VM /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<Task> async_plug(Session session, string _vbd) { return XenRef<Task>.Create(session.proxy.async_vbd_plug(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Hot-unplug the specified VBD, dynamically unattaching it from the running VM /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static void unplug(Session session, string _vbd) { session.proxy.vbd_unplug(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Hot-unplug the specified VBD, dynamically unattaching it from the running VM /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<Task> async_unplug(Session session, string _vbd) { return XenRef<Task>.Create(session.proxy.async_vbd_unplug(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Forcibly unplug the specified VBD /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static void unplug_force(Session session, string _vbd) { session.proxy.vbd_unplug_force(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Forcibly unplug the specified VBD /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<Task> async_unplug_force(Session session, string _vbd) { return XenRef<Task>.Create(session.proxy.async_vbd_unplug_force(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Throws an error if this VBD could not be attached to this VM if the VM were running. Intended for debugging. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static void assert_attachable(Session session, string _vbd) { session.proxy.vbd_assert_attachable(session.uuid, _vbd ?? "").parse(); } /// <summary> /// Throws an error if this VBD could not be attached to this VM if the VM were running. Intended for debugging. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd">The opaque_ref of the given vbd</param> public static XenRef<Task> async_assert_attachable(Session session, string _vbd) { return XenRef<Task>.Create(session.proxy.async_vbd_assert_attachable(session.uuid, _vbd ?? "").parse()); } /// <summary> /// Return a list of all the VBDs known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VBD>> get_all(Session session) { return XenRef<VBD>.Create(session.proxy.vbd_get_all(session.uuid).parse()); } /// <summary> /// Get all the VBD Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VBD>, VBD> get_all_records(Session session) { return XenRef<VBD>.Create<Proxy_VBD>(session.proxy.vbd_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. /// </summary> public virtual List<vbd_operations> allowed_operations { get { return _allowed_operations; } set { if (!Helper.AreEqual(value, _allowed_operations)) { _allowed_operations = value; Changed = true; NotifyPropertyChanged("allowed_operations"); } } } private List<vbd_operations> _allowed_operations; /// <summary> /// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. /// </summary> public virtual Dictionary<string, vbd_operations> current_operations { get { return _current_operations; } set { if (!Helper.AreEqual(value, _current_operations)) { _current_operations = value; Changed = true; NotifyPropertyChanged("current_operations"); } } } private Dictionary<string, vbd_operations> _current_operations; /// <summary> /// the virtual machine /// </summary> public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; Changed = true; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM; /// <summary> /// the virtual disk /// </summary> public virtual XenRef<VDI> VDI { get { return _VDI; } set { if (!Helper.AreEqual(value, _VDI)) { _VDI = value; Changed = true; NotifyPropertyChanged("VDI"); } } } private XenRef<VDI> _VDI; /// <summary> /// device seen by the guest e.g. hda1 /// </summary> public virtual string device { get { return _device; } set { if (!Helper.AreEqual(value, _device)) { _device = value; Changed = true; NotifyPropertyChanged("device"); } } } private string _device; /// <summary> /// user-friendly device name e.g. 0,1,2,etc. /// </summary> public virtual string userdevice { get { return _userdevice; } set { if (!Helper.AreEqual(value, _userdevice)) { _userdevice = value; Changed = true; NotifyPropertyChanged("userdevice"); } } } private string _userdevice; /// <summary> /// true if this VBD is bootable /// </summary> public virtual bool bootable { get { return _bootable; } set { if (!Helper.AreEqual(value, _bootable)) { _bootable = value; Changed = true; NotifyPropertyChanged("bootable"); } } } private bool _bootable; /// <summary> /// the mode the VBD should be mounted with /// </summary> public virtual vbd_mode mode { get { return _mode; } set { if (!Helper.AreEqual(value, _mode)) { _mode = value; Changed = true; NotifyPropertyChanged("mode"); } } } private vbd_mode _mode; /// <summary> /// how the VBD will appear to the guest (e.g. disk or CD) /// </summary> public virtual vbd_type type { get { return _type; } set { if (!Helper.AreEqual(value, _type)) { _type = value; Changed = true; NotifyPropertyChanged("type"); } } } private vbd_type _type; /// <summary> /// true if this VBD will support hot-unplug /// First published in XenServer 4.1. /// </summary> public virtual bool unpluggable { get { return _unpluggable; } set { if (!Helper.AreEqual(value, _unpluggable)) { _unpluggable = value; Changed = true; NotifyPropertyChanged("unpluggable"); } } } private bool _unpluggable; /// <summary> /// true if a storage level lock was acquired /// </summary> public virtual bool storage_lock { get { return _storage_lock; } set { if (!Helper.AreEqual(value, _storage_lock)) { _storage_lock = value; Changed = true; NotifyPropertyChanged("storage_lock"); } } } private bool _storage_lock; /// <summary> /// if true this represents an empty drive /// </summary> public virtual bool empty { get { return _empty; } set { if (!Helper.AreEqual(value, _empty)) { _empty = value; Changed = true; NotifyPropertyChanged("empty"); } } } private bool _empty; /// <summary> /// additional configuration /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; /// <summary> /// is the device currently attached (erased on reboot) /// </summary> public virtual bool currently_attached { get { return _currently_attached; } set { if (!Helper.AreEqual(value, _currently_attached)) { _currently_attached = value; Changed = true; NotifyPropertyChanged("currently_attached"); } } } private bool _currently_attached; /// <summary> /// error/success code associated with last attach-operation (erased on reboot) /// </summary> public virtual long status_code { get { return _status_code; } set { if (!Helper.AreEqual(value, _status_code)) { _status_code = value; Changed = true; NotifyPropertyChanged("status_code"); } } } private long _status_code; /// <summary> /// error/success information associated with last attach-operation status (erased on reboot) /// </summary> public virtual string status_detail { get { return _status_detail; } set { if (!Helper.AreEqual(value, _status_detail)) { _status_detail = value; Changed = true; NotifyPropertyChanged("status_detail"); } } } private string _status_detail; /// <summary> /// Device runtime properties /// </summary> public virtual Dictionary<string, string> runtime_properties { get { return _runtime_properties; } set { if (!Helper.AreEqual(value, _runtime_properties)) { _runtime_properties = value; Changed = true; NotifyPropertyChanged("runtime_properties"); } } } private Dictionary<string, string> _runtime_properties; /// <summary> /// QoS algorithm to use /// </summary> public virtual string qos_algorithm_type { get { return _qos_algorithm_type; } set { if (!Helper.AreEqual(value, _qos_algorithm_type)) { _qos_algorithm_type = value; Changed = true; NotifyPropertyChanged("qos_algorithm_type"); } } } private string _qos_algorithm_type; /// <summary> /// parameters for chosen QoS algorithm /// </summary> public virtual Dictionary<string, string> qos_algorithm_params { get { return _qos_algorithm_params; } set { if (!Helper.AreEqual(value, _qos_algorithm_params)) { _qos_algorithm_params = value; Changed = true; NotifyPropertyChanged("qos_algorithm_params"); } } } private Dictionary<string, string> _qos_algorithm_params; /// <summary> /// supported QoS algorithms for this VBD /// </summary> public virtual string[] qos_supported_algorithms { get { return _qos_supported_algorithms; } set { if (!Helper.AreEqual(value, _qos_supported_algorithms)) { _qos_supported_algorithms = value; Changed = true; NotifyPropertyChanged("qos_supported_algorithms"); } } } private string[] _qos_supported_algorithms; /// <summary> /// metrics associated with this VBD /// </summary> public virtual XenRef<VBD_metrics> metrics { get { return _metrics; } set { if (!Helper.AreEqual(value, _metrics)) { _metrics = value; Changed = true; NotifyPropertyChanged("metrics"); } } } private XenRef<VBD_metrics> _metrics; } }
// // HMACSHA256Test.cs - NUnit Test Cases for HMACSHA256 // // Author: // Sebastien Pouliot (spouliot@motus.com) // // (C) 2003 Motus Technologies Inc. (http://www.motus.com) // #if NET_2_0 using NUnit.Framework; using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace MonoTests.System.Security.Cryptography { // References: // a. The HMAC-SHA-256-128 Algorithm and Its Use With IPsec // http://www.ietf.org/proceedings/02jul/I-D/draft-ietf-ipsec-ciph-sha-256-01.txt [TestFixture] public class HMACSHA256Test : KeyedHashAlgorithmTest { protected HMACSHA256 algo; [Test] public void Constructors () { algo = new HMACSHA256 (); AssertNotNull ("HMACSHA256 ()", algo); byte[] key = new byte [8]; algo = new HMACSHA256 (key); AssertNotNull ("HMACSHA256 (key)", algo); try { algo = new HMACSHA256 (null); Fail ("HMACSHA256 (null) - Expected NullReferenceException but got none"); } catch (NullReferenceException) { // well ArgumentNullException would have been more appropriate } catch (Exception e) { Fail ("HMACSHA256 (null) - Expected NullReferenceException but got: " + e.ToString ()); } } [Test] public void Invariants () { algo = new HMACSHA256 (); AssertEquals ("HMACSHA256.CanReuseTransform", true, algo.CanReuseTransform); AssertEquals ("HMACSHA256.CanTransformMultipleBlocks", true, algo.CanTransformMultipleBlocks); AssertEquals ("HMACSHA256.HashName", "SHA256", algo.HashName); AssertEquals ("HMACSHA256.HashSize", 256, algo.HashSize); AssertEquals ("HMACSHA256.InputBlockSize", 1, algo.InputBlockSize); AssertEquals ("HMACSHA256.OutputBlockSize", 1, algo.OutputBlockSize); AssertEquals ("HMACSHA256.ToString()", "System.Security.Cryptography.HMACSHA256", algo.ToString ()); } public void Check (string testName, byte[] key, byte[] data, byte[] result) { string classTestName = "HMACSHA256-" + testName; CheckA (testName, key, data, result); CheckB (testName, key, data, result); CheckC (testName, key, data, result); CheckD (testName, key, data, result); CheckE (testName, key, data, result); } public void CheckA (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACSHA256 (); algo.Key = key; byte[] hmac = algo.ComputeHash (data); AssertEquals (testName + "a1", result, hmac); AssertEquals (testName + "a2", result, algo.Hash); } public void CheckB (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACSHA256 (); algo.Key = key; byte[] hmac = algo.ComputeHash (data, 0, data.Length); AssertEquals (testName + "b1", result, hmac); AssertEquals (testName + "b2", result, algo.Hash); } public void CheckC (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACSHA256 (); algo.Key = key; MemoryStream ms = new MemoryStream (data); byte[] hmac = algo.ComputeHash (ms); AssertEquals (testName + "c1", result, hmac); AssertEquals (testName + "c2", result, algo.Hash); } public void CheckD (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACSHA256 (); algo.Key = key; // LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue ! algo.TransformFinalBlock (data, 0, data.Length); AssertEquals (testName + "d", result, algo.Hash); } public void CheckE (string testName, byte[] key, byte[] data, byte[] result) { algo = new HMACSHA256 (); algo.Key = key; byte[] copy = new byte [data.Length]; // LAMESPEC or FIXME: TransformFinalBlock doesn't return HashValue ! for (int i=0; i < data.Length - 1; i++) algo.TransformBlock (data, i, 1, copy, i); algo.TransformFinalBlock (data, data.Length - 1, 1); AssertEquals (testName + "e", result, algo.Hash); } [Test] // Test Case #1: HMAC-SHA-256 with 3-byte input and 32-byte key public void HMACSHA256_TC1 () { byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 }; byte[] data = Encoding.Default.GetBytes ("abc"); byte[] digest = { 0xa2, 0x1b, 0x1f, 0x5d, 0x4c, 0xf4, 0xf7, 0x3a, 0x4d, 0xd9, 0x39, 0x75, 0x0f, 0x7a, 0x06, 0x6a, 0x7f, 0x98, 0xcc, 0x13, 0x1c, 0xb1, 0x6a, 0x66, 0x92, 0x75, 0x90, 0x21, 0xcf, 0xab, 0x81, 0x81 }; Check ("HMACSHA256-TC1", key, data, digest); } [Test] // HMAC-SHA-256 with 56-byte input and 32-byte key public void HMACSHA256_TC2 () { byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 }; byte[] data = Encoding.Default.GetBytes ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); byte[] digest = { 0x10, 0x4f, 0xdc, 0x12, 0x57, 0x32, 0x8f, 0x08, 0x18, 0x4b, 0xa7, 0x31, 0x31, 0xc5, 0x3c, 0xae, 0xe6, 0x98, 0xe3, 0x61, 0x19, 0x42, 0x11, 0x49, 0xea, 0x8c, 0x71, 0x24, 0x56, 0x69, 0x7d, 0x30 }; Check ("HMACSHA256-TC2", key, data, digest); } [Test] // Test Case #3: HMAC-SHA-256 with 112-byte (multi-block) input and 32-byte key public void HMACSHA256_TC3 () { byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20 }; byte[] data = Encoding.Default.GetBytes ("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopqabcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); byte[] digest = { 0x47, 0x03, 0x05, 0xfc, 0x7e, 0x40, 0xfe, 0x34, 0xd3, 0xee, 0xb3, 0xe7, 0x73, 0xd9, 0x5a, 0xab, 0x73, 0xac, 0xf0, 0xfd, 0x06, 0x04, 0x47, 0xa5, 0xeb, 0x45, 0x95, 0xbf, 0x33, 0xa9, 0xd1, 0xa3 }; Check ("HMACSHA256-TC3", key, data, digest); } [Test] // Test Case #4: HMAC-SHA-256 with 8-byte input and 32-byte key public void HMACSHA256_TC4 () { byte[] key = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; byte[] data = Encoding.Default.GetBytes ("Hi There"); byte[] digest = { 0x19, 0x8a, 0x60, 0x7e, 0xb4, 0x4b, 0xfb, 0xc6, 0x99, 0x03, 0xa0, 0xf1, 0xcf, 0x2b, 0xbd, 0xc5, 0xba, 0x0a, 0xa3, 0xf3, 0xd9, 0xae, 0x3c, 0x1c, 0x7a, 0x3b, 0x16, 0x96, 0xa0, 0xb6, 0x8c, 0xf7 }; Check ("HMACSHA256-TC4", key, data, digest); } [Test] // Test Case #5: HMAC-SHA-256 with 28-byte input and 4-byte key public void HMACSHA256_TC5 () { byte[] key = Encoding.Default.GetBytes ("Jefe"); byte[] data = Encoding.Default.GetBytes ("what do ya want for nothing?"); byte[] digest = { 0x5b, 0xdc, 0xc1, 0x46, 0xbf, 0x60, 0x75, 0x4e, 0x6a, 0x04, 0x24, 0x26, 0x08, 0x95, 0x75, 0xc7, 0x5a, 0x00, 0x3f, 0x08, 0x9d, 0x27, 0x39, 0x83, 0x9d, 0xec, 0x58, 0xb9, 0x64, 0xec, 0x38, 0x43 }; Check ("HMACSHA256-TC5", key, data, digest); } [Test] // Test Case #6: HMAC-SHA-256 with 50-byte input and 32-byte key public void HMACSHA256_TC6 () { byte[] key = { 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa }; byte[] data = new byte [50]; for (int i = 0; i < data.Length; i++) data[i] = 0xdd; byte[] digest = { 0xcd, 0xcb, 0x12, 0x20, 0xd1, 0xec, 0xcc, 0xea, 0x91, 0xe5, 0x3a, 0xba, 0x30, 0x92, 0xf9, 0x62, 0xe5, 0x49, 0xfe, 0x6c, 0xe9, 0xed, 0x7f, 0xdc, 0x43, 0x19, 0x1f, 0xbd, 0xe4, 0x5c, 0x30, 0xb0 }; Check ("HMACSHA256-TC6", key, data, digest); } [Test] // Test Case #7: HMAC-SHA-256 with 50-byte input and 37-byte key public void HMACSHA256_TC7 () { byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25 }; byte[] data = new byte [50]; for (int i = 0; i < data.Length; i++) data[i] = 0xcd; byte[] digest = { 0xd4, 0x63, 0x3c, 0x17, 0xf6, 0xfb, 0x8d, 0x74, 0x4c, 0x66, 0xde, 0xe0, 0xf8, 0xf0, 0x74, 0x55, 0x6e, 0xc4, 0xaf, 0x55, 0xef, 0x07, 0x99, 0x85, 0x41, 0x46, 0x8e, 0xb4, 0x9b, 0xd2, 0xe9, 0x17 }; Check ("HMACSHA256-TC7", key, data, digest); } [Test] // Test Case #8: HMAC-SHA-256 with 20-byte input and 32-byte key public void HMACSHA256_TC8 () { byte[] key = { 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c }; byte[] data = Encoding.Default.GetBytes ("Test With Truncation"); byte[] digest = { 0x75, 0x46, 0xaf, 0x01, 0x84, 0x1f, 0xc0, 0x9b, 0x1a, 0xb9, 0xc3, 0x74, 0x9a, 0x5f, 0x1c, 0x17, 0xd4, 0xf5, 0x89, 0x66, 0x8a, 0x58, 0x7b, 0x27, 0x00, 0xa9, 0xc9, 0x7c, 0x11, 0x93, 0xcf, 0x42 }; Check ("HMACSHA256-TC8", key, data, digest); } [Test] // Test Case #9: HMAC-SHA-256 with 54-byte input and 80-byte key public void HMACSHA256_TC9 () { byte[] key = new byte [80]; for (int i = 0; i < key.Length; i++) key[i] = 0xaa; byte[] data = Encoding.Default.GetBytes ("Test Using Larger Than Block-Size Key - Hash Key First"); byte[] digest = { 0x69, 0x53, 0x02, 0x5e, 0xd9, 0x6f, 0x0c, 0x09, 0xf8, 0x0a, 0x96, 0xf7, 0x8e, 0x65, 0x38, 0xdb, 0xe2, 0xe7, 0xb8, 0x20, 0xe3, 0xdd, 0x97, 0x0e, 0x7d, 0xdd, 0x39, 0x09, 0x1b, 0x32, 0x35, 0x2f }; Check ("HMACSHA256-TC9", key, data, digest); } [Test] // Test Case #10: HMAC-SHA-256 with 73-byte (multi-block) input and 80-byte key public void HMACSHA256_TC10 () { byte[] key = new byte [80]; for (int i = 0; i < key.Length; i++) key[i] = 0xaa; byte[] data = Encoding.Default.GetBytes ("Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data"); byte[] digest = { 0x63, 0x55, 0xac, 0x22, 0xe8, 0x90, 0xd0, 0xa3, 0xc8, 0x48, 0x1a, 0x5c, 0xa4, 0x82, 0x5b, 0xc8, 0x84, 0xd3, 0xe7, 0xa1, 0xff, 0x98, 0xa2, 0xfc, 0x2a, 0xc7, 0xd8, 0xe0, 0x64, 0xc3, 0xb2, 0xe6 }; Check ("HMACSHA256-TC10", key, data, digest); } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Runtime.InteropServices; using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Holds property values of any type. For common value types, we have inline storage so that we don't need /// to box the values. For all other types, we store the value in a single object reference field. /// /// To get the value of a property quickly, use a delegate produced by <see cref="PropertyValue.GetPropertyGetter(PropertyInfo)"/>. /// </summary> #if ES_BUILD_PN [CLSCompliant(false)] public #else internal #endif unsafe readonly struct PropertyValue { /// <summary> /// Union of well-known value types, to avoid boxing those types. /// </summary> [StructLayout(LayoutKind.Explicit)] public struct Scalar { [FieldOffset(0)] public bool AsBoolean; [FieldOffset(0)] public byte AsByte; [FieldOffset(0)] public sbyte AsSByte; [FieldOffset(0)] public char AsChar; [FieldOffset(0)] public short AsInt16; [FieldOffset(0)] public ushort AsUInt16; [FieldOffset(0)] public int AsInt32; [FieldOffset(0)] public uint AsUInt32; [FieldOffset(0)] public long AsInt64; [FieldOffset(0)] public ulong AsUInt64; [FieldOffset(0)] public IntPtr AsIntPtr; [FieldOffset(0)] public UIntPtr AsUIntPtr; [FieldOffset(0)] public float AsSingle; [FieldOffset(0)] public double AsDouble; [FieldOffset(0)] public Guid AsGuid; [FieldOffset(0)] public DateTime AsDateTime; [FieldOffset(0)] public DateTimeOffset AsDateTimeOffset; [FieldOffset(0)] public TimeSpan AsTimeSpan; [FieldOffset(0)] public decimal AsDecimal; } // Anything not covered by the Scalar union gets stored in this reference. readonly object _reference; readonly Scalar _scalar; readonly int _scalarLength; private PropertyValue(object value) { _reference = value; _scalar = default; _scalarLength = 0; } private PropertyValue(Scalar scalar, int scalarLength) { _reference = null; _scalar = scalar; _scalarLength = scalarLength; } private PropertyValue(bool value) : this(new Scalar() { AsBoolean = value }, sizeof(bool)) { } private PropertyValue(byte value) : this(new Scalar() { AsByte = value }, sizeof(byte)) { } private PropertyValue(sbyte value) : this(new Scalar() { AsSByte = value }, sizeof(sbyte)) { } private PropertyValue(char value) : this(new Scalar() { AsChar = value }, sizeof(char)) { } private PropertyValue(short value) : this(new Scalar() { AsInt16 = value }, sizeof(short)) { } private PropertyValue(ushort value) : this(new Scalar() { AsUInt16 = value }, sizeof(ushort)) { } private PropertyValue(int value) : this(new Scalar() { AsInt32 = value }, sizeof(int)) { } private PropertyValue(uint value) : this(new Scalar() { AsUInt32 = value }, sizeof(uint)) { } private PropertyValue(long value) : this(new Scalar() { AsInt64 = value }, sizeof(long)) { } private PropertyValue(ulong value) : this(new Scalar() { AsUInt64 = value }, sizeof(ulong)) { } private PropertyValue(IntPtr value) : this(new Scalar() { AsIntPtr = value }, sizeof(IntPtr)) { } private PropertyValue(UIntPtr value) : this(new Scalar() { AsUIntPtr = value }, sizeof(UIntPtr)) { } private PropertyValue(float value) : this(new Scalar() { AsSingle = value }, sizeof(float)) { } private PropertyValue(double value) : this(new Scalar() { AsDouble = value }, sizeof(double)) { } private PropertyValue(Guid value) : this(new Scalar() { AsGuid = value }, sizeof(Guid)) { } private PropertyValue(DateTime value) : this(new Scalar() { AsDateTime = value }, sizeof(DateTime)) { } private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffset = value }, sizeof(DateTimeOffset)) { } private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { } private PropertyValue(decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(decimal)) { } public static Func<object, PropertyValue> GetFactory(Type type) { if (type == typeof(bool)) return value => new PropertyValue((bool)value); if (type == typeof(byte)) return value => new PropertyValue((byte)value); if (type == typeof(sbyte)) return value => new PropertyValue((sbyte)value); if (type == typeof(char)) return value => new PropertyValue((char)value); if (type == typeof(short)) return value => new PropertyValue((short)value); if (type == typeof(ushort)) return value => new PropertyValue((ushort)value); if (type == typeof(int)) return value => new PropertyValue((int)value); if (type == typeof(uint)) return value => new PropertyValue((uint)value); if (type == typeof(long)) return value => new PropertyValue((long)value); if (type == typeof(ulong)) return value => new PropertyValue((ulong)value); if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value); if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value); if (type == typeof(float)) return value => new PropertyValue((float)value); if (type == typeof(double)) return value => new PropertyValue((double)value); if (type == typeof(Guid)) return value => new PropertyValue((Guid)value); if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value); if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value); if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value); if (type == typeof(decimal)) return value => new PropertyValue((decimal)value); return value => new PropertyValue(value); } public object ReferenceValue { get { Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); return _reference; } } public Scalar ScalarValue { get { Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalar; } } public int ScalarLength { get { Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalarLength; } } /// <summary> /// Gets a delegate that gets the value of a given property. /// </summary> public static Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property) { if (property.DeclaringType.GetTypeInfo().IsValueType) return GetBoxedValueTypePropertyGetter(property); else return GetReferenceTypePropertyGetter(property); } /// <summary> /// Gets a delegate that gets the value of a property of a value type. We unfortunately cannot avoid boxing the value type, /// without making this generic over the value type. That would result in a large number of generic instantiations, and furthermore /// does not work correctly on .Net Native (we cannot express the needed instantiations in an rd.xml file). We expect that user-defined /// value types will be rare, and in any case the boxing only happens for events that are actually enabled. /// </summary> private static Func<PropertyValue, PropertyValue> GetBoxedValueTypePropertyGetter(PropertyInfo property) { var type = property.PropertyType; if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); var factory = GetFactory(type); return container => factory(property.GetValue(container.ReferenceValue)); } /// <summary> /// For properties of reference types, we use a generic helper class to get the value. This enables us to use MethodInfo.CreateDelegate /// to build a fast getter. We can get away with this on .Net Native, because we really only need one runtime instantiation of the /// generic type, since it's only instantiated over reference types (and thus all instances are shared). /// </summary> /// <param name="property"></param> /// <returns></returns> private static Func<PropertyValue, PropertyValue> GetReferenceTypePropertyGetter(PropertyInfo property) { var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType)); return helper.GetPropertyGetter(property); } #if ES_BUILD_PN public #else private #endif abstract class TypeHelper { public abstract Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property); protected Delegate GetGetMethod(PropertyInfo property, Type propertyType) { return property.GetMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType, propertyType)); } } #if ES_BUILD_PN public #else private #endif sealed class ReferenceTypeHelper<TContainer> : TypeHelper where TContainer : class { public override Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property) { var type = property.PropertyType; if (!Statics.IsValueType(type)) { var getter = (Func<TContainer, object>)GetGetMethod(property, type); return container => new PropertyValue(getter((TContainer)container.ReferenceValue)); } else { if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); if (type == typeof(bool)) { var f = (Func<TContainer, bool>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(byte)) { var f = (Func<TContainer, byte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(sbyte)) { var f = (Func<TContainer, sbyte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(char)) { var f = (Func<TContainer, char>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(short)) { var f = (Func<TContainer, short>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(ushort)) { var f = (Func<TContainer, ushort>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(int)) { var f = (Func<TContainer, int>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(uint)) { var f = (Func<TContainer, uint>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(long)) { var f = (Func<TContainer, long>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(ulong)) { var f = (Func<TContainer, ulong>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(IntPtr)) { var f = (Func<TContainer, IntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UIntPtr)) { var f = (Func<TContainer, UIntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(float)) { var f = (Func<TContainer, float>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(double)) { var f = (Func<TContainer, double>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Guid)) { var f = (Func<TContainer, Guid>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTime)) { var f = (Func<TContainer, DateTime>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTimeOffset)) { var f = (Func<TContainer, DateTimeOffset>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(TimeSpan)) { var f = (Func<TContainer, TimeSpan>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(decimal)) { var f = (Func<TContainer, decimal>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } return container => new PropertyValue(property.GetValue(container.ReferenceValue)); } } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.PythonTools.Analysis.Analyzer { /// <summary> /// Performs the 1st pass over the AST to gather all of the classes and /// function definitions. /// </summary> internal class OverviewWalker : PythonWalker { private InterpreterScope _scope; private readonly ProjectEntry _entry; private readonly PythonAst _tree; private readonly Stack<AnalysisUnit> _analysisStack = new Stack<AnalysisUnit>(); private AnalysisUnit _curUnit; private SuiteStatement _curSuite; public OverviewWalker(ProjectEntry entry, AnalysisUnit topAnalysis, PythonAst tree) { _entry = entry; _curUnit = topAnalysis; _tree = tree; Debug.Assert(_tree != null); _scope = topAnalysis.Scope; } // TODO: What about names being redefined? // remember classes/functions as they start new scopes public override bool Walk(ClassDefinition node) { var cls = AddClass(node, _curUnit); if (cls != null) { _analysisStack.Push(_curUnit); _curUnit = cls.AnalysisUnit; Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(cls.AnalysisUnit.Scope.OuterScope)); _scope = cls.AnalysisUnit.Scope; return true; } return false; } internal ClassInfo AddClass(ClassDefinition node, AnalysisUnit outerUnit) { InterpreterScope scope; var declScope = outerUnit.Scope; if (!declScope.TryGetNodeScope(node, out scope)) { if (node.Body == null || node.Name == null) { return null; } var unit = new ClassAnalysisUnit(node, declScope, outerUnit); var classScope = (ClassScope)unit.Scope; var classVar = declScope.AddLocatedVariable(node.Name, node.NameExpression, unit); classVar.AddTypes(unit, classScope.Class.SelfSet); declScope.Children.Add(classScope); declScope.AddNodeScope(node, classScope); unit.Enqueue(); scope = classScope; } return scope.AnalysisValue as ClassInfo; } public override void PostWalk(ClassDefinition node) { if (node.Body != null && node.Name != null) { Debug.Assert(_scope.Node == node); Debug.Assert(_scope.OuterScope.Node != node); _scope = _scope.OuterScope; _curUnit = _analysisStack.Pop(); Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(_curUnit.Scope)); } } public override bool Walk(FunctionDefinition node) { var function = AddFunction(node, _curUnit); if (function != null) { _analysisStack.Push(_curUnit); _curUnit = function.AnalysisUnit; Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(function.AnalysisUnit.Scope.OuterScope)); _scope = function.AnalysisUnit.Scope; return true; } return false; } public override void PostWalk(FunctionDefinition node) { if (node.Body != null && node.Name != null) { Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(_curUnit.Scope.OuterScope)); _scope = _curUnit.Scope.OuterScope; _curUnit = _analysisStack.Pop(); Debug.Assert(_scope.EnumerateTowardsGlobal.Contains(_curUnit.Scope)); } } public override bool Walk(GlobalStatement node) { foreach (var name in node.Names) { if (name.Name != null) { // set the variable in the local scope to be the real variable in the global scope _scope.AddVariable(name.Name, _scope.GlobalScope.CreateVariable(node, _curUnit, name.Name, false)); } } return false; } public override bool Walk(NonlocalStatement node) { foreach (var name in node.Names) { if (name.Name != null) { _scope.AddVariable(name.Name, CreateVariableInDeclaredScope(name)); } } return false; } private VariableDef CreateVariableInDeclaredScope(NameExpression name) { var reference = name.GetVariableReference(_tree); if (reference != null && reference.Variable != null) { var declNode = reference.Variable.Scope; var declScope = _scope.EnumerateTowardsGlobal.FirstOrDefault(s => s.Node == declNode); if (declScope != null) { return declScope.CreateVariable(name, _curUnit, name.Name, false); } } return _scope.CreateVariable(name, _curUnit, name.Name, false); } internal FunctionInfo AddFunction(FunctionDefinition node, AnalysisUnit outerUnit) { return AddFunction(node, outerUnit, _scope); } internal static FunctionInfo AddFunction(FunctionDefinition node, AnalysisUnit outerUnit, InterpreterScope prevScope) { InterpreterScope scope; if (!prevScope.TryGetNodeScope(node, out scope)) { if (node.Body == null || node.Name == null) { return null; } var func = new FunctionInfo(node, outerUnit, prevScope); var unit = func.AnalysisUnit; scope = unit.Scope; prevScope.Children.Add(scope); prevScope.AddNodeScope(node, scope); if (!node.IsLambda && node.Name != "<genexpr>") { // lambdas don't have their names published var funcVar = prevScope.AddLocatedVariable(node.Name, node.NameExpression, unit); // Decorated functions don't have their type set yet if (node.Decorators == null) { funcVar.AddTypes(unit, func.SelfSet); } } unit.Enqueue(); } return scope.AnalysisValue as FunctionInfo; } public override bool Walk(GeneratorExpression node) { EnsureComprehensionScope(node, MakeGeneratorComprehensionScope); Debug.Assert(_scope is ComprehensionScope); return base.Walk(node); } public override void PostWalk(GeneratorExpression node) { Debug.Assert(_scope is ComprehensionScope); _scope = _scope.OuterScope; base.PostWalk(node); } public override bool Walk(ListComprehension node) { // List comprehension runs in a new scope in 3.x, runs in the same // scope in 2.x. But these don't get their own analysis units // because they are still just expressions. if (_curUnit.ProjectState.LanguageVersion.Is3x()) { EnsureComprehensionScope(node, MakeListComprehensionScope); } return base.Walk(node); } public override void PostWalk(ListComprehension node) { if (_curUnit.ProjectState.LanguageVersion.Is3x()) { Debug.Assert(_scope is ComprehensionScope); _scope = _scope.OuterScope; } base.PostWalk(node); } public override bool Walk(SetComprehension node) { EnsureComprehensionScope(node, MakeSetComprehensionScope); Debug.Assert(_scope is ComprehensionScope); return base.Walk(node); } public override void PostWalk(SetComprehension node) { Debug.Assert(_scope is ComprehensionScope); _scope = _scope.OuterScope; base.PostWalk(node); } public override bool Walk(DictionaryComprehension node) { EnsureComprehensionScope(node, MakeDictComprehensionScope); Debug.Assert(_scope is ComprehensionScope); return base.Walk(node); } public override void PostWalk(DictionaryComprehension node) { Debug.Assert(_scope is ComprehensionScope); _scope = _scope.OuterScope; base.PostWalk(node); } /// <summary> /// Makes sure we create a scope for a comprehension (generator, set, dict, or list comprehension in 3.x) where /// the variables which are assigned will be stored. /// </summary> private void EnsureComprehensionScope(Comprehension node, Func<Comprehension, ComprehensionScope> makeScope) { InterpreterScope scope, declScope = _scope; if (!declScope.TryGetNodeScope(node, out scope)) { scope = makeScope(node); declScope.AddNodeScope(node, scope); declScope.Children.Add(scope); } _scope = scope; } private ComprehensionScope MakeGeneratorComprehensionScope(Comprehension node) { var unit = new GeneratorComprehensionAnalysisUnit(node, _tree, _curUnit, _scope); unit.Enqueue(); return (ComprehensionScope)unit.Scope; } private ComprehensionScope MakeListComprehensionScope(Comprehension node) { var unit = new ListComprehensionAnalysisUnit(node, _tree, _curUnit, _scope); unit.Enqueue(); return (ComprehensionScope)unit.Scope; } private ComprehensionScope MakeSetComprehensionScope(Comprehension node) { var unit = new SetComprehensionAnalysisUnit(node, _tree, _curUnit, _scope); unit.Enqueue(); return (ComprehensionScope)unit.Scope; } private ComprehensionScope MakeDictComprehensionScope(Comprehension node) { var unit = new DictionaryComprehensionAnalysisUnit(node, _tree, _curUnit, _scope); unit.Enqueue(); return (ComprehensionScope)unit.Scope; } private void UpdateChildRanges(Statement node) { var declScope = _curUnit.Scope; var prevScope = declScope.Children.LastOrDefault(); StatementScope prevStmtScope; IsInstanceScope prevInstanceScope; if ((prevStmtScope = prevScope as StatementScope) != null) { prevStmtScope.EndIndex = node.EndIndex; } else if ((prevInstanceScope = prevScope as IsInstanceScope) != null) { prevInstanceScope.EndIndex = node.EndIndex; } else { declScope.Children.Add(new StatementScope(node.StartIndex, declScope)); } } internal static KeyValuePair<NameExpression, Expression>[] GetIsInstanceNamesAndExpressions(Expression node) { List<KeyValuePair<NameExpression, Expression>> names = null; GetIsInstanceNamesAndExpressions(ref names, node); if (names != null) { return names.ToArray(); } return null; } /// <summary> /// Gets the names which should be in a new scope for isinstance(...) checks. We don't /// use a walker here because we only support a very limited set of assertions (e.g. isinstance(x, type) and ... /// or a bare isinstance(...). /// </summary> internal static void GetIsInstanceNamesAndExpressions(ref List<KeyValuePair<NameExpression, Expression>> names, Expression node) { CallExpression callExpr = node as CallExpression; if (callExpr != null && callExpr.Args.Count == 2) { NameExpression nameExpr = callExpr.Target as NameExpression; if (nameExpr != null && nameExpr.Name == "isinstance") { nameExpr = callExpr.Args[0].Expression as NameExpression; if (nameExpr != null) { if (names == null) { names = new List<KeyValuePair<NameExpression, Expression>>(); } var type = callExpr.Args[1].Expression; names.Add(new KeyValuePair<NameExpression, Expression>(nameExpr, type)); } } } AndExpression andExpr = node as AndExpression; OrExpression orExpr = node as OrExpression; if (andExpr != null) { GetIsInstanceNamesAndExpressions(ref names, andExpr.Left); GetIsInstanceNamesAndExpressions(ref names, andExpr.Right); } else if (orExpr != null) { GetIsInstanceNamesAndExpressions(ref names, orExpr.Left); GetIsInstanceNamesAndExpressions(ref names, orExpr.Right); } } public override bool Walk(AssertStatement node) { // check if the assert statement contains any isinstance calls. CallExpression callExpr = node.Test as CallExpression; var isInstanceNames = GetIsInstanceNamesAndExpressions(node.Test); if (isInstanceNames != null) { // we need to introduce a new scope PushIsInstanceScope(node, isInstanceNames, _curSuite); } else { UpdateChildRanges(node); } return base.Walk(node); } private void PushIsInstanceScope(Node node, KeyValuePair<NameExpression, Expression>[] isInstanceNames, SuiteStatement effectiveSuite) { InterpreterScope scope; if (!_curUnit.Scope.TryGetNodeScope(node, out scope)) { // find our parent scope, it may not be just the last entry in _scopes // because that can be a StatementScope and we would start a new range. var declScope = _scope.EnumerateTowardsGlobal.FirstOrDefault(s => !(s is StatementScope)); scope = new IsInstanceScope(node.StartIndex, effectiveSuite, declScope); declScope.Children.Add(scope); declScope.AddNodeScope(node, scope); _scope = scope; } } public override bool Walk(AssignmentStatement node) { UpdateChildRanges(node); foreach (var nameExpr in node.Left.OfType<NameExpression>()) { _scope.AddVariable(nameExpr.Name, CreateVariableInDeclaredScope(nameExpr)); } return base.Walk(node); } public override bool Walk(AugmentedAssignStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(BreakStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(ContinueStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(DelStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(ErrorStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(EmptyStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(ExpressionStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(ExecStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(ForStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(FromImportStatement node) { UpdateChildRanges(node); var asNames = node.AsNames ?? node.Names; int len = Math.Min(node.Names.Count, asNames.Count); for (int i = 0; i < len; i++) { var nameNode = asNames[i] ?? node.Names[i]; if (nameNode != null) { if (nameNode.Name == "*") { _scope.ContainsImportStar = true; } else { CreateVariableInDeclaredScope(nameNode); } } } return base.Walk(node); } public override bool Walk(IfStatement node) { UpdateChildRanges(node); if (node.Tests != null) { foreach (var test in node.Tests) { var isInstanceNames = GetIsInstanceNamesAndExpressions(test.Test); if (isInstanceNames != null) { if (test.Test != null) { test.Test.Walk(this); } if (test.Body != null && !(test.Body is ErrorStatement)) { Debug.Assert(test.Body is SuiteStatement); PushIsInstanceScope(test, isInstanceNames, (SuiteStatement)test.Body); test.Body.Walk(this); } } else { test.Walk(this); } } } if (node.ElseStatement != null) { node.ElseStatement.Walk(this); } return false; } public override bool Walk(ImportStatement node) { for (int i = 0; i < node.Names.Count; i++) { NameExpression name = null; if (i < node.AsNames.Count && node.AsNames[i] != null) { name = node.AsNames[i]; } else if (node.Names[i].Names.Count > 0) { name = node.Names[i].Names[0]; } if (name != null) { CreateVariableInDeclaredScope(name); } } UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(PrintStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(RaiseStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(ReturnStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(TryStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(WhileStatement node) { UpdateChildRanges(node); return base.Walk(node); } public override bool Walk(WithStatement node) { UpdateChildRanges(node); foreach (var item in node.Items) { var assignTo = item.Variable as NameExpression; if (assignTo != null) { _scope.AddVariable(assignTo.Name, CreateVariableInDeclaredScope(assignTo)); } } return base.Walk(node); } public override bool Walk(SuiteStatement node) { var prevSuite = _curSuite; _curSuite = node; // recursively walk the statements in the suite if (node.Statements != null) { foreach (var innerNode in node.Statements) { innerNode.Walk(this); } } _curSuite = prevSuite; // then check if we encountered an assert which added an isinstance scope. IsInstanceScope isInstanceScope = _scope as IsInstanceScope; if (isInstanceScope != null && isInstanceScope._effectiveSuite == node) { // pop the isinstance scope _scope = _scope.OuterScope; // transform back into a line number and start the new statement scope on the line // after the suite statement. var lineNo = _tree.IndexToLocation(node.EndIndex).Line; int offset; if (_tree._lineLocations.Length == 0) { // single line input offset = 0; } else { offset = lineNo < _tree._lineLocations.Length ? _tree._lineLocations[lineNo].EndIndex : _tree._lineLocations[_tree._lineLocations.Length - 1].EndIndex; } var closingScope = new StatementScope(offset, _scope); _scope.Children.Add(closingScope); _scope = closingScope; } return false; } public override void PostWalk(SuiteStatement node) { while (_scope is StatementScope) { _scope = _scope.OuterScope; } base.PostWalk(node); } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using static Tests.Core.Serialization.SerializationTestHelper; namespace Tests.CommonOptions.TimeUnit { public class TimeUnits { /**[[time-units]] * === Time units * Whenever durations need to be specified, eg for a timeout parameter, the duration can be specified * as a whole number representing time in milliseconds, or as a time value like `2d` for 2 days. * * NEST uses a `Time` type to strongly type this and there are several ways to construct one. * * ==== Constructor * The most straight forward way to construct a `Time` is through its constructor */ [U] public void Constructor() { var unitString = new Time("2d"); var unitComposed = new Time(2, Elastic.Clients.Elasticsearch.TimeUnit.Days); var unitTimeSpan = new Time(TimeSpan.FromDays(2)); var unitMilliseconds = new Time(1000 * 60 * 60 * 24 * 2); /** * When serializing Time constructed from * - a string * - milliseconds (as a double) * - composition of factor and interval * - a `TimeSpan` * * the expression will be serialized to a time unit string composed of the factor and interval e.g. `2d` */ Expect("2d") .WhenSerializing(unitString) .WhenSerializing(unitComposed) .WhenSerializing(unitTimeSpan) .WhenSerializing(unitMilliseconds); /** * The `Milliseconds` property on `Time` is calculated even when not using the constructor that takes a `double` */ unitMilliseconds.Milliseconds.Should().Be(1000*60*60*24*2); unitComposed.Milliseconds.Should().Be(1000*60*60*24*2); unitTimeSpan.Milliseconds.Should().Be(1000*60*60*24*2); unitString.Milliseconds.Should().Be(1000*60*60*24*2); } /** * ==== Implicit conversion * There are implicit conversions from `string`, `TimeSpan` and `double` to an instance of `Time`, making them * easier to work with */ [U] public void ImplicitConversion() { Time oneMinute = "1m"; Time fourteenDays = TimeSpan.FromDays(14); Time twoDays = 1000*60*60*24*2; Expect("1m").WhenSerializing(oneMinute); Expect("14d").WhenSerializing(fourteenDays); Expect("2d").WhenSerializing(twoDays); } /** * ==== Equality and Comparison */ [U] [SuppressMessage("ReSharper", "SuggestVarOrType_SimpleTypes")] public void EqualityAndComparable() { /** * Comparisons on the expressions can be performed since Milliseconds are calculated * even when values are not passed as `double` milliseconds */ Time fourteenDays = TimeSpan.FromDays(14); fourteenDays.Milliseconds.Should().Be(1209600000); Time twoDays = 1000*60*60*24*2; fourteenDays.Should().BeGreaterThan(twoDays); (fourteenDays > twoDays).Should().BeTrue(); (twoDays != null).Should().BeTrue(); (twoDays >= new Time("2d")).Should().BeTrue(); twoDays.Should().BeLessThan(fourteenDays); (twoDays < fourteenDays).Should().BeTrue(); (twoDays <= fourteenDays).Should().BeTrue(); (twoDays <= new Time("2d")).Should().BeTrue(); /** * Equality can also be performed */ twoDays.Should().Be(new Time("2d")); (twoDays == new Time("2d")).Should().BeTrue(); (twoDays != new Time("2.1d")).Should().BeTrue(); (new Time("2.1d") == new Time(TimeSpan.FromDays(2.1))).Should().BeTrue(); /** * Equality has down to 1/10 nanosecond precision */ Time oneNanosecond = new Time(1, Elastic.Clients.Elasticsearch.TimeUnit.Nanoseconds); Time onePointNoughtNineNanoseconds = "1.09nanos"; Time onePointOneNanoseconds = "1.1nanos"; (oneNanosecond == onePointNoughtNineNanoseconds).Should().BeTrue(); (oneNanosecond == onePointOneNanoseconds).Should().BeFalse(); } /** ==== Special Time values * * Elasticsearch has two special values that can sometimes be passed where a `Time` is accepted * * - `0` represented as `Time.Zero` * - `-1` represented as `Time.MinusOne` */ [U] public void SpecialTimeValues() { /** * The following are all equal to `Time.MinusOne` */ Time.MinusOne.Should().Be(Time.MinusOne); new Time("-1").Should().Be(Time.MinusOne); new Time(-1).Should().Be(Time.MinusOne); ((Time) (-1)).Should().Be(Time.MinusOne); ((Time) "-1").Should().Be(Time.MinusOne); ((Time) (-1)).Should().Be((Time) "-1"); /** * Similarly, the following are all equal to `Time.Zero` */ Time.Zero.Should().Be(Time.Zero); new Time("0").Should().Be(Time.Zero); new Time(0).Should().Be(Time.Zero); ((Time) 0).Should().Be(Time.Zero); ((Time) "0").Should().Be(Time.Zero); ((Time) 0).Should().Be((Time) "0"); /** Special Time values `0` and `-1` can be compared against other Time values * although admittedly, this is a tad nonsensical. */ var twoDays = new Time(2, Elastic.Clients.Elasticsearch.TimeUnit.Days); Time.MinusOne.Should().BeLessThan(Time.Zero); Time.Zero.Should().BeGreaterThan(Time.MinusOne); Time.Zero.Should().BeLessThan(twoDays); Time.MinusOne.Should().BeLessThan(twoDays); /** * If there is a need to construct a time of -1ms or 0ms, use the constructor * that accepts a factor and time unit, or specify a string with ms time units */ (new Time(-1, Elastic.Clients.Elasticsearch.TimeUnit.Milliseconds) == new Time("-1ms")).Should().BeTrue(); (new Time(0, Elastic.Clients.Elasticsearch.TimeUnit.Milliseconds) == new Time("0ms")).Should().BeTrue(); } // hide private class StringParsingTestCases : List<Tuple<string, TimeSpan, string>> { public void Add(string original, TimeSpan expect, string toString) => Add(Tuple.Create(original, expect, toString)); public void Add(string bad, string argumentExceptionContains) => Add(Tuple.Create(bad, TimeSpan.FromDays(1), argumentExceptionContains)); } // hide [U]public void StringImplicitConversionParsing() { var testCases = new StringParsingTestCases { { "2.000000000e-06ms", TimeSpan.FromMilliseconds(2.000000000e-06), "0.000002ms"}, { "3.1e-11ms", TimeSpan.FromMilliseconds(3.1e-11), "0.000000000031ms"}, { "1000 nanos", new TimeSpan(10) , "1000nanos"}, { "1000nanos", new TimeSpan(10), "1000nanos"}, { "1000 NANOS", new TimeSpan(10), "1000nanos" }, { "1000NANOS", new TimeSpan(10), "1000nanos" }, { "10micros", new TimeSpan(100), "10micros" }, { "10 MS", new TimeSpan(0, 0, 0, 0, 10), "10ms" }, { "10ms", new TimeSpan(0, 0, 0, 0, 10), "10ms" }, { "10 ms", new TimeSpan(0, 0, 0, 0, 10), "10ms" }, { "10s", new TimeSpan(0, 0, 10), "10s" }, { "-10s", new TimeSpan(0, 0, -10), "-10s" }, { "-10S", new TimeSpan(0, 0, -10), "-10s" }, { "10m", new TimeSpan(0, 10, 0) , "10m"}, { "10M", new TimeSpan(0, 10, 0), "10m" }, // 300 days not minutes { "10h", new TimeSpan(10, 0, 0), "10h" }, { "10H", new TimeSpan(10, 0, 0) , "10h"}, { "10d", new TimeSpan(10, 0, 0, 0) , "10d"}, }; foreach (var testCase in testCases) { var time = new Time(testCase.Item1); time.ToTimeSpan().Should().Be(testCase.Item2, "we passed in {0}", testCase.Item1); time.ToString().Should().Be(testCase.Item3); } } // hide [U]public void StringParseExceptions() { var testCases = new StringParsingTestCases { { "1000", "cannot be parsed to an interval"}, { "1000x", "is invalid"}, }; foreach (var testCase in testCases) { Action create = () => new Time(testCase.Item1); var e = create.Invoking((a) => a()).Should().Throw<ArgumentException>(testCase.Item1).Subject.First(); e.Message.Should().Contain(testCase.Item3); } } // hide private class DoubleParsingTestCases : List<Tuple<double, TimeSpan, string>> { public void Add(double original, TimeSpan expect, string toString) => Add(Tuple.Create(original, expect, toString)); } // hide [U]public void DoubleImplicitConversionParsing() { // from: https://msdn.microsoft.com/en-us/library/system.timespan.frommilliseconds.aspx // The value parameter is converted to ticks, and that number of ticks is used to initialize the new TimeSpan. // Therefore, value will only be considered accurate to the nearest millisecond. This means that // fractional millisecond values with TimeSpan.FromMilliseconds(fraction) will be rounded. var testCases = new DoubleParsingTestCases { { 1e-4, new TimeSpan(1) , "100nanos"}, // smallest value that can be represented with ticks { 1e-3, new TimeSpan(10), "1micros"}, { 0.1, TimeSpan.FromTicks(1000), "100micros"}, { 1, TimeSpan.FromMilliseconds(1), "1ms"}, { 1.2, TimeSpan.FromTicks(12000), "1200micros"}, { 10, TimeSpan.FromMilliseconds(10), "10ms"}, { 100, TimeSpan.FromMilliseconds(100), "100ms"}, { 1000, TimeSpan.FromSeconds(1), "1s" }, { 60000, TimeSpan.FromMinutes(1), "1m" }, { 3.6e+6, TimeSpan.FromHours(1), "1h" }, { 8.64e+7, TimeSpan.FromDays(1), "1d" }, { 1.296e+8, TimeSpan.FromDays(1.5), "36h" }, }; foreach (var testCase in testCases) { var time = new Time(testCase.Item1); time.ToTimeSpan().Should().Be(testCase.Item2, "we passed in {0}", testCase.Item1); time.ToString().Should().Be(testCase.Item3); } } // hide [U] public void DoubleImplicitConversionOneNanosecond() { Time oneNanosecond = 1e-6; // cannot be expressed as a TimeSpan using ToTimeSpan(), as smaller than a one tick. oneNanosecond.ToTimeSpan().Should().Be(TimeSpan.Zero); oneNanosecond.ToString().Should().Be("1nanos"); } //[U] public void UsingInterval() //{ // /** // * ==== Units of Time // * // * Where Units of Time can be specified as a union of either a `DateInterval` or `Time`, // * a `DateInterval` or `Time` may be passed which will be implicitly converted to a // * `Union<DateInterval, Time>`, the serialized form of which represents the initial value // * passed // */ // Expect("month").WhenSerializing<Union<Elastic.Clients.Elasticsearch.DateInterval, Time>>(DateInterval.Month); // Expect("day").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Day); // Expect("hour").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Hour); // Expect("minute").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Minute); // Expect("quarter").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Quarter); // Expect("second").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Second); // Expect("week").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Week); // Expect("year").WhenSerializing<Union<DateInterval, Time>>(DateInterval.Year); // Expect("2d").WhenSerializing<Union<DateInterval, Time>>((Time)"2d"); // Expect("11664m").WhenSerializing<Union<DateInterval, Time>>((Time)TimeSpan.FromDays(8.1)); //} //hide [U] public void MillisecondsNeverSerializeToMonthsOrYears() { double millisecondsInAMonth = 2592000000; Expect("30d").WhenSerializing(new Time(millisecondsInAMonth)); Expect("60d").WhenSerializing(new Time(millisecondsInAMonth * 2)); Expect("360d").WhenSerializing(new Time(millisecondsInAMonth * 12)); Expect("720d").WhenSerializing(new Time(millisecondsInAMonth * 24)); } //hide [U] public void ExpectedValues() { Expect(0).WhenSerializing(new Time(0)); Expect(0).WhenSerializing((Time)0); Expect(0).WhenSerializing(new Time("0")); Expect(0).WhenSerializing(Time.Zero); Expect(-1).WhenSerializing(new Time(-1)); Expect(-1).WhenSerializing((Time)(-1)); Expect(-1).WhenSerializing(new Time("-1")); Expect(-1).WhenSerializing(Time.MinusOne); Assert( 1, Elastic.Clients.Elasticsearch.TimeUnit.Days, TimeSpan.FromDays(1).TotalMilliseconds, "1d", new Time(1, Elastic.Clients.Elasticsearch.TimeUnit.Days), new Time("1d"), new Time(TimeSpan.FromDays(1).TotalMilliseconds) ); Assert( 1, Elastic.Clients.Elasticsearch.TimeUnit.Hours, TimeSpan.FromHours(1).TotalMilliseconds, "1h", new Time(1, Elastic.Clients.Elasticsearch.TimeUnit.Hours), new Time("1h"), new Time(TimeSpan.FromHours(1).TotalMilliseconds) ); Assert( 1, Elastic.Clients.Elasticsearch.TimeUnit.Minutes, TimeSpan.FromMinutes(1).TotalMilliseconds, "1m", new Time(1, Elastic.Clients.Elasticsearch.TimeUnit.Minutes), new Time("1m"), new Time(TimeSpan.FromMinutes(1).TotalMilliseconds) ); Assert( 1, Elastic.Clients.Elasticsearch.TimeUnit.Seconds, TimeSpan.FromSeconds(1).TotalMilliseconds, "1s", new Time(1, Elastic.Clients.Elasticsearch.TimeUnit.Seconds), new Time("1s"), new Time(TimeSpan.FromSeconds(1).TotalMilliseconds) ); } //hide private void Assert(double expectedFactor, Elastic.Clients.Elasticsearch.TimeUnit expectedInterval, double expectedMilliseconds, string expectedSerialized, params Time[] times) { foreach (var time in times) { time.Factor.Should().Be(expectedFactor); time.Interval.Should().Be(expectedInterval); time.Milliseconds.Should().Be(expectedMilliseconds); Expect(expectedSerialized).WhenSerializing(time); } } } }
//------------------------------------------------------------------------------ // <copyright file="Debug.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ //#define DEBUG namespace System.Diagnostics { using System; using System.Collections; using System.Security.Permissions; using System.Globalization; /// <devdoc> /// <para>Provides a set of properties and /// methods /// for debugging code.</para> /// </devdoc> public static class Debug { /// <devdoc> /// <para>Gets /// the collection of listeners that is monitoring the debug /// output.</para> /// </devdoc> public static TraceListenerCollection Listeners { [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] [HostProtection( SharedState = true )] get { return TraceInternal.Listeners; } } /// <devdoc> /// <para>Gets or sets a value indicating whether <see cref='System.Diagnostics.Debug.Flush'/> should be called on the /// <see cref='System.Diagnostics.Debug.Listeners'/> /// after every write.</para> /// </devdoc> public static bool AutoFlush { [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] get { return TraceInternal.AutoFlush; } [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] set { TraceInternal.AutoFlush = value; } } /// <devdoc> /// <para>Gets or sets /// the indent level.</para> /// </devdoc> public static int IndentLevel { get { return TraceInternal.IndentLevel; } set { TraceInternal.IndentLevel = value; } } /// <devdoc> /// <para>Gets or sets the number of spaces in an indent.</para> /// </devdoc> public static int IndentSize { get { return TraceInternal.IndentSize; } set { TraceInternal.IndentSize = value; } } /// <devdoc> /// <para>Clears the output buffer, and causes buffered data to /// be written to the <see cref='System.Diagnostics.Debug.Listeners'/>.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Flush( ) { TraceInternal.Flush( ); } /// <devdoc> /// <para>Clears the output buffer, and then closes the <see cref='System.Diagnostics.Debug.Listeners'/> so that they no longer receive /// debugging output.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode )] public static void Close( ) { TraceInternal.Close( ); } /// <devdoc> /// <para>Checks for a condition, and outputs the callstack if the condition is <see langword='false'/>.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Assert( bool condition ) { if(condition == false) { throw new ArgumentException(); } TraceInternal.Assert( condition ); } /// <devdoc> /// <para>Checks for a condition, and displays a message if the condition is /// <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Assert( bool condition , string message ) { if(condition == false) { #if EXCEPTION_STRINGS throw new ArgumentException( message ); #else throw new ArgumentException(); #endif } TraceInternal.Assert( condition, message ); } /// <devdoc> /// <para>Checks for a condition, and displays both the specified messages if the condition /// is <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Assert( bool condition , string message , string detailMessage ) { if(condition == false) { #if EXCEPTION_STRINGS throw new ArgumentException( message ); #else throw new ArgumentException(); #endif } TraceInternal.Assert( condition, message, detailMessage ); } /// <devdoc> /// <para>Emits or displays a message for an assertion that always fails.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Fail( string message ) { TraceInternal.Fail( message ); } /// <devdoc> /// <para>Emits or displays both messages for an assertion that always fails.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Fail( string message , string detailMessage ) { TraceInternal.Fail( message, detailMessage ); } [System.Diagnostics.Conditional( "DEBUG" )] public static void Print( string message ) { TraceInternal.WriteLine( message ); } [System.Diagnostics.Conditional( "DEBUG" )] public static void Print( string format , params object[] args ) { TraceInternal.WriteLine( String.Format( CultureInfo.InvariantCulture, format, args ) ); } /// <devdoc> /// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( string message ) { TraceInternal.Write( message ); } /// <devdoc> /// <para>Writes the name of the value /// parameter to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( object value ) { TraceInternal.Write( value ); } /// <devdoc> /// <para>Writes a category name and message /// to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( string message , string category ) { TraceInternal.Write( message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the value parameter to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Write( object value , string category ) { TraceInternal.Write( value, category ); } /// <devdoc> /// <para>Writes a message followed by a line terminator to the trace listeners in the /// <see cref='System.Diagnostics.Debug.Listeners'/> collection. The default line terminator /// is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( string message ) { TraceInternal.WriteLine( message ); } /// <devdoc> /// <para>Writes the name of the value /// parameter followed by a line terminator to the /// trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( object value ) { TraceInternal.WriteLine( value ); } /// <devdoc> /// <para>Writes a category name and message followed by a line terminator to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( string message , string category ) { TraceInternal.WriteLine( message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the value /// parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The /// default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLine( object value , string category ) { TraceInternal.WriteLine( value, category ); } /// <devdoc> /// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection /// if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , string message ) { TraceInternal.WriteIf( condition, message ); } /// <devdoc> /// <para>Writes the name of the value /// parameter to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> /// collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , object value ) { TraceInternal.WriteIf( condition, value ); } /// <devdoc> /// <para>Writes a category name and message /// to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> /// collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , string message , string category ) { TraceInternal.WriteIf( condition, message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the value /// parameter to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteIf( bool condition , object value , string category ) { TraceInternal.WriteIf( condition, value, category ); } /// <devdoc> /// <para>Writes a message followed by a line terminator to the trace listeners in the /// <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , string message ) { TraceInternal.WriteLineIf( condition, message ); } /// <devdoc> /// <para>Writes the name of the value /// parameter followed by a line terminator to the /// trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , object value ) { TraceInternal.WriteLineIf( condition, value ); } /// <devdoc> /// <para>Writes a category name and message /// followed by a line terminator to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , string message , string category ) { TraceInternal.WriteLineIf( condition, message, category ); } /// <devdoc> /// <para>Writes a category name and the name of the value parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection /// if a condition is <see langword='true'/>. The default line terminator is a carriage /// return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void WriteLineIf( bool condition , object value , string category ) { TraceInternal.WriteLineIf( condition, value, category ); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Indent() { TraceInternal.Indent(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.Conditional( "DEBUG" )] public static void Unindent() { TraceInternal.Unindent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Imported.PeanutButter.Utils; using Imported.PeanutButter.Utils.Dictionaries; using PeanutButter.DuckTyping.AutoConversion; using PeanutButter.DuckTyping.AutoConversion.Converters; using PeanutButter.DuckTyping.Comparers; using PeanutButter.DuckTyping.Exceptions; using PeanutButter.DuckTyping.Extensions; namespace PeanutButter.DuckTyping.Shimming { /// <summary> /// Provides the required shimming to duck a dictionary object to an interface /// </summary> public class DictionaryShimSham : ShimShamBase, IShimSham { private readonly Type _typeToMimic; private readonly IDictionary<string, object> _data; private readonly Dictionary<string, PropertyInfo> _mimickedProperties; private readonly bool _isFuzzy; /// <summary> /// Constructs an instance of the DictionaryShimSham /// </summary> /// <param name="toWrap">Dictionary to wrap</param> /// <param name="typeToMimic">Interface that must be mimicked</param> // ReSharper disable once UnusedMember.Global public DictionaryShimSham( IDictionary<string, object> toWrap, Type typeToMimic) : this(new[] { toWrap }, typeToMimic) { } /// <summary> /// Constructs an instance of the DictionaryShimSham /// </summary> /// <param name="toWrap">Dictionaries to wrap (wip: only the first is considered)</param> /// <param name="typeToMimic">Interface that must be mimicked</param> public DictionaryShimSham( IDictionary<string, object>[] toWrap, Type typeToMimic) { _typeToMimic = typeToMimic; var incoming = (toWrap?.ToArray() ?? new Dictionary<string, object>[0]) .Where(d => d != null) .ToArray(); _data = incoming.Length == 0 ? new Dictionary<string, object>() : incoming.Length == 1 ? incoming[0] : new MergeDictionary<string, object>(incoming); _isFuzzy = IsFuzzy(_data); _mimickedProperties = typeToMimic .GetAllImplementedInterfaces() .And(typeToMimic) .SelectMany(interfaceType => interfaceType.GetProperties()) .Distinct(new PropertyInfoComparer()) .ToDictionary(pi => pi.Name, pi => pi, _isFuzzy ? Comparers.Comparers.FuzzyComparer : Comparers.Comparers.NonFuzzyComparer); ShimShimmableProperties(); } private readonly Dictionary<string, object> _shimmedProperties = new Dictionary<string, object>(); private void ShimShimmableProperties() { foreach (var kvp in _mimickedProperties) { if (kvp.Value.PropertyType.ShouldTreatAsPrimitive()) { continue; } if (!_data.ContainsKey(kvp.Key)) { _data[kvp.Key] = new Dictionary<string, object>(); } var type = MakeTypeToImplement(kvp.Value.PropertyType, _isFuzzy); var toWrap = _data[kvp.Key]; var asDict = toWrap as IDictionary<string, object>; // ReSharper disable RedundantExplicitArrayCreation var firstArg = asDict == null ? new object[] { new object[] { toWrap } } : new object[] { new IDictionary<string, object>[] { asDict } }; // ReSharper restore RedundantExplicitArrayCreation _shimmedProperties[kvp.Key] = Activator.CreateInstance(type, firstArg); } } /// <summary> /// Gets the value of a property by name /// </summary> /// <param name="propertyName">Name of the property to get the value of</param> /// <returns>The value of the property, where possible. /// May return the default value for the property type when it is not found /// and may attempt automatic conversion when the type to represent does not /// match the underlying type</returns> public object GetPropertyValue(string propertyName) { CheckPropertyExists(propertyName); if (_shimmedProperties.TryGetValue(propertyName, out var propValue)) { return propValue; } var mimickedProperty = GetMimickedProperty(propertyName); var key = _isFuzzy ? FuzzyFindKeyFor(propertyName) ?? propertyName : propertyName; if (!_data.TryGetValue(key, out propValue)) { return GetDefaultValueFor(mimickedProperty.PropertyType); } if (propValue is null) { return TryResolveNullValueFOr(mimickedProperty); } // ReSharper disable once UseMethodIsInstanceOfType var propType = propValue.GetType(); if (mimickedProperty.PropertyType.IsAssignableFrom(propType)) { return propValue; } var converter = ConverterLocator.GetConverter(propType, mimickedProperty.PropertyType); if (converter != null) { return ConvertWith(converter, propValue, mimickedProperty.PropertyType); } return EnumConverter.TryConvert(propType, mimickedProperty.PropertyType, propValue, out var result) ? result : GetDefaultValueFor(mimickedProperty.PropertyType); } private object TryResolveNullValueFOr(PropertyInfo mimickedProperty) { if (mimickedProperty.PropertyType.IsNullableType()) { return null; } if (_isFuzzy) { return GetDefaultValueFor(mimickedProperty.PropertyType); } throw new InvalidOperationException( $"Somehow a strict duck has been constructed around a non-nullable property with null backing value at {mimickedProperty.Name}" ); } private readonly Dictionary<string, string> _keyResolutionCache = new Dictionary<string, string>(); private string FuzzyFindKeyFor(string propertyName) { lock (_keyResolutionCache) { if (_keyResolutionCache.TryGetValue(propertyName, out var resolvedKey)) { return resolvedKey; } resolvedKey = _data.FuzzyFindKeyFor(propertyName); if (resolvedKey != null) { _keyResolutionCache[propertyName] = resolvedKey; } return resolvedKey; } } /// <summary> /// Attempts to set the value of the named property /// </summary> /// <param name="propertyName">Name of the property to set</param> /// <param name="newValue">Value to set. The value may be converted to match the underlying type when required.</param> public void SetPropertyValue(string propertyName, object newValue) { CheckPropertyExists(propertyName); var mimickedProperty = GetMimickedProperty(propertyName); var newValueType = newValue?.GetType(); if (newValueType == null) { SetDefaultValueForType(_data, propertyName, mimickedProperty); } else if (mimickedProperty.PropertyType.IsAssignableFrom(newValueType)) { _data[propertyName] = newValue; } else { var converter = ConverterLocator.GetConverter( newValueType, mimickedProperty.PropertyType ); if (converter is null) { SetDefaultValueForType( _data, propertyName, mimickedProperty ); return; } _data[propertyName] = ConvertWith( converter, newValue, mimickedProperty.PropertyType ); } } private void SetDefaultValueForType( IDictionary<string, object> data, string propertyName, PropertyInfo mimickedProperty ) { data[propertyName] = GetDefaultValueFor(mimickedProperty.PropertyType); } private bool IsFuzzy(IDictionary<string, object> data) { var current = data; var keys = current.Keys; var first = keys.FirstOrDefault(k => k.ToLower() != k.ToUpper()); if (first == null) { return true; } var lower = first.ToLower(); var upper = first.ToUpper(); return current.TryGetValue(lower, out _) && data.TryGetValue(upper, out _); } private PropertyInfo GetMimickedProperty(string propertyName) { return _mimickedProperties.TryGetValue(propertyName, out var result) ? result : throw new PropertyNotFoundException(_typeToMimic, propertyName); } private void CheckPropertyExists(string propertyName) { if (!_mimickedProperties.ContainsKey(propertyName)) { throw new PropertyNotFoundException(_data.GetType(), propertyName); } } /// <summary> /// Required to implement the IShimSham interface, but not implemented for /// dictionaries as the concept doesn't make sense /// </summary> /// <param name="methodName">Name of the method to not call through to</param> /// <param name="arguments">Parameters to ignore</param> /// <exception cref="NotImplementedException">Exception which is always thrown</exception> public void CallThroughVoid(string methodName, params object[] arguments) { if (!_data.TryGetValue(methodName, out var func) || func is null || !VoidFunctionAccepts( func, arguments, out var parameterTypes ) ) { // TODO: this should be caught at duck-time throw new MethodNotFoundException(_typeToMimic, methodName); } var preparedArguments = PrepareArguments(arguments, parameterTypes); InvokeNonVoidFunc(func, preparedArguments, null); } /// <summary> /// Required to implement the IShimSham interface, but not implemented for /// dictionaries as the concept doesn't make sense /// </summary> /// <param name="methodName">Name of the method to not call through to</param> /// <param name="arguments">Parameters to ignore</param> /// <exception cref="NotImplementedException">Exception which is always thrown</exception> public object CallThrough(string methodName, object[] arguments) { if (!_data.TryGetValue(methodName, out var func) || func is null || !NonVoidFunctionAccepts( func, arguments, out var parameterTypes, out _ ) ) { // TODO: this should be caught at duck-time throw new NotImplementedException( func is null ? $"{_typeToMimic.Name}.{methodName} not implemented in underlying dictionary" : $"{_typeToMimic.Name}.{methodName} not fully in underlying dictionary: arguments must be in order and args and return type must either have identical type or be easily convertable" ); } var preparedArguments = PrepareArguments(arguments, parameterTypes); var argumentTypes = arguments.Select(a => a?.GetType()).ToArray(); var returnType = DetermineReturnTypeFor(methodName, argumentTypes); return InvokeNonVoidFunc(func, preparedArguments, returnType); } private Type DetermineReturnTypeFor( string methodName, Type[] argumentTypes ) { // FIXME: should be able to fuzzy-duck to method // with unique types in different order var method = _typeToMimic.GetMethods() .Where(mi => mi.Name == methodName) .FirstOrDefault(mi => { var parameterTypes = mi.GetParameters().Select(p => p.ParameterType).ToArray(); if (parameterTypes.Length != argumentTypes.Length) { return false; } var idx = -1; foreach (var pt in parameterTypes) { idx++; var argType = argumentTypes[idx]; if (pt == argType) { continue; } if (argType.IsAssignableOrUpCastableTo(pt)) { continue; } if (argType is null && pt.IsNullableType()) { continue; } return false; } return true; }); return method?.ReturnType ?? throw new InvalidOperationException( $"Can't determine return type for {methodName} with provided parameters" ); } private object[] PrepareArguments( object[] arguments, Type[] parameterTypes) { return arguments.Select((arg, idx) => { var argType = arg?.GetType(); if (arg is null || arg.GetType() == parameterTypes[idx]) { return arg; } if (parameterTypes[idx].IsAssignableFrom(argType)) { return arg; } var converter = ConverterLocator.GetConverter(argType, parameterTypes[idx]); return converter.Convert(arg); }).ToArray(); } private object InvokeNonVoidFunc( object func, object[] arguments, Type returnType ) { var invokeMethod = func.GetType().GetMethod(nameof(Func<int>.Invoke)); var result = invokeMethod?.Invoke(func, arguments); if (returnType is null) { return null; } if (result is null) { return returnType.IsNullableType() ? null : returnType.DefaultValue(); } var resultType = result.GetType(); if (resultType == returnType) { return result; } var converter = ConverterLocator.GetConverter(resultType, returnType); return converter?.Convert(result) ?? throw new InvalidOperationException( $"Can't convert result from {resultType} to {returnType}" ); } // TODO: should be moved out into a shared location & used at duck-type // to prevent erroneous ducks private bool NonVoidFunctionAccepts( object value, object[] arguments, out Type[] parameterTypes, out Type returnType ) { parameterTypes = null; returnType = null; var funcType = value.GetType(); if (!funcType.IsGenericType) { return false; } var parameterCount = Array.IndexOf(FuncGenerics, funcType.GetGenericTypeDefinition()); if (parameterCount != arguments.Length) { if (parameterCount > FuncGenerics.Length) { throw new NotSupportedException( $"methods with more than {FuncGenerics.Length} parameters are not supported"); } return false; } var genericParameters = funcType.GetGenericArguments(); parameterTypes = genericParameters.Take(genericParameters.Length - 1).ToArray(); returnType = genericParameters.Last(); var zipped = arguments.Zip( parameterTypes, (argument, parameterType) => new { argumentType = argument?.GetType(), parameterType } ); return zipped.Aggregate( true, (acc, cur) => { if (!acc) { return false; } if (cur.argumentType is null && cur.parameterType.IsNullableType()) { return true; } if (cur.argumentType.IsAssignableOrUpCastableTo(cur.parameterType)) { return true; } return cur.argumentType == cur.parameterType || ConverterLocator.HaveConverterFor(cur.argumentType, cur.parameterType); }); } private bool VoidFunctionAccepts( object value, object[] arguments, out Type[] parameterTypes ) { parameterTypes = null; var actionType = value.GetType(); if (!actionType.IsGenericType) { return false; } var parameterCount = Array.IndexOf( ActionGenerics, actionType.GetGenericTypeDefinition() ) + 1; if (parameterCount != arguments.Length) { if (parameterCount > ActionGenerics.Length) { throw new NotSupportedException( $"methods with more than {ActionGenerics.Length} parameters are not supported"); } return false; } parameterTypes = actionType.GetGenericArguments(); var zipped = arguments.Zip( parameterTypes, (argument, parameterType) => new { argumentType = argument?.GetType(), parameterType } ); return zipped.Aggregate( true, (acc, cur) => { if (!acc) { return false; } if (cur.argumentType is null && cur.parameterType.IsNullableType()) { return true; } if (cur.argumentType.IsAssignableOrUpCastableTo(cur.parameterType)) { return true; } return cur.argumentType == cur.parameterType || ConverterLocator.HaveConverterFor(cur.argumentType, cur.parameterType); }); } private static readonly Type[] FuncGenerics = { typeof(Func<>), typeof(Func<,>), typeof(Func<,,>), typeof(Func<,,,>), typeof(Func<,,,,>), typeof(Func<,,,,,>), typeof(Func<,,,,,,>), typeof(Func<,,,,,,,>), typeof(Func<,,,,,,,,>), typeof(Func<,,,,,,,,,>), typeof(Func<,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,,,>), typeof(Func<,,,,,,,,,,,,,,,>) }; private static readonly Type[] ActionGenerics = { typeof(Action<>), typeof(Action<,>), typeof(Action<,,>), typeof(Action<,,,>), typeof(Action<,,,,>), typeof(Action<,,,,,>), typeof(Action<,,,,,,>), typeof(Action<,,,,,,,>), typeof(Action<,,,,,,,,>), typeof(Action<,,,,,,,,,>), typeof(Action<,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,,,>), typeof(Action<,,,,,,,,,,,,,,,>) }; } }
/* * 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.Runtime.Visitor { using Parser; using Parser.Node; /// <summary> This class is simply a visitor implementation /// that traverses the AST, produced by the Velocity /// parsing process, and creates a visual structure /// of the AST. This is primarily used for /// debugging, but it useful for documentation /// as well. /// /// </summary> /// <author> <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> /// </author> /// <version> $Id: NodeViewMode.java 685685 2008-08-13 21:43:27Z nbubna $ /// </version> public class NodeViewMode : BaseVisitor { private int indent = 0; private bool showTokens = true; /// <summary>Indent child nodes to help visually identify /// the structure of the AST. /// </summary> private string IndentString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < indent; ++i) { sb.Append(" "); } return sb.ToString(); } /// <summary> Display the type of nodes and optionally the /// first token. /// </summary> private object ShowNode(INode node, object data) { string tokens = ""; string special = ""; Token t; if (showTokens) { t = node.FirstToken; if (t.SpecialToken != null && !t.SpecialToken.Image.StartsWith("##")) special = t.SpecialToken.Image; tokens = " -> " + special + t.Image; } ++indent; data = node.ChildrenAccept(this, data); --indent; return data; } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.SimpleNode, java.lang.Object)"> /// </seealso> public override object Visit(SimpleNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTprocess, java.lang.Object)"> /// </seealso> public override object Visit(ASTprocess node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTExpression, java.lang.Object)"> /// </seealso> public override object Visit(ASTExpression node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTAssignment, java.lang.Object)"> /// </seealso> public override object Visit(ASTAssignment node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTOrNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTOrNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTAndNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTAndNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTEQNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTEQNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTNENode, java.lang.Object)"> /// </seealso> public override object Visit(ASTNENode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTLTNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTLTNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTGTNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTGTNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTLENode, java.lang.Object)"> /// </seealso> public override object Visit(ASTLENode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTGENode, java.lang.Object)"> /// </seealso> public override object Visit(ASTGENode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTAddNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTAddNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTSubtractNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTSubtractNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTMulNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTMulNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTDivNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTDivNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTModNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTModNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTNotNode, java.lang.Object)"> /// </seealso> public override object Visit(ASTNotNode node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTFloatingPointLiteral, java.lang.Object)"> /// </seealso> public override object Visit(ASTFloatingPointLiteral node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTIntegerLiteral, java.lang.Object)"> /// </seealso> /// <since> 1.5 /// </since> public override object Visit(ASTIntegerLiteral node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTStringLiteral, java.lang.Object)"> /// </seealso> public override object Visit(ASTStringLiteral node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTIdentifier, java.lang.Object)"> /// </seealso> public override object Visit(ASTIdentifier node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTMethod, java.lang.Object)"> /// </seealso> public override object Visit(ASTMethod node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTReference, java.lang.Object)"> /// </seealso> public override object Visit(ASTReference node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTTrue, java.lang.Object)"> /// </seealso> public override object Visit(ASTTrue node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTFalse, java.lang.Object)"> /// </seealso> public override object Visit(ASTFalse node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTBlock, java.lang.Object)"> /// </seealso> public override object Visit(ASTBlock node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTText, java.lang.Object)"> /// </seealso> public override object Visit(ASTText node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTIfStatement, java.lang.Object)"> /// </seealso> public override object Visit(ASTIfStatement node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTElseStatement, java.lang.Object)"> /// </seealso> public override object Visit(ASTElseStatement node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTElseIfStatement, java.lang.Object)"> /// </seealso> public override object Visit(ASTElseIfStatement node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTObjectArray, java.lang.Object)"> /// </seealso> public override object Visit(ASTObjectArray node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTDirective, java.lang.Object)"> /// </seealso> public override object Visit(ASTDirective node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTWord, java.lang.Object)"> /// </seealso> public override object Visit(ASTWord node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTSetDirective, java.lang.Object)"> /// </seealso> public override object Visit(ASTSetDirective node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTEscapedDirective, java.lang.Object)"> /// </seealso> /// <since> 1.5 /// </since> public override object Visit(ASTEscapedDirective node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTEscape, java.lang.Object)"> /// </seealso> /// <since> 1.5 /// </since> public override object Visit(ASTEscape node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTMap, java.lang.Object)"> /// </seealso> /// <since> 1.5 /// </since> public override object Visit(ASTMap node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTIntegerRange, java.lang.Object)"> /// </seealso> public override object Visit(ASTIntegerRange node, object data) { return ShowNode(node, data); } /// <seealso cref="org.apache.velocity.runtime.visitor.BaseVisitor.visit(NVelocity.Runtime.Paser.Node.ASTStop, java.lang.Object)"> /// </seealso> /// <since> 1.5 /// </since> public override object Visit(ASTStop node, object data) { return ShowNode(node, data); } } }
using System; using System.Globalization; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Threading; using jk.plaveninycz; using jk.plaveninycz.DataSources; using jk.plaveninycz.Observations; public partial class station_list : System.Web.UI.Page { protected override void InitializeCulture() { //Response.Cache.SetNoStore(); string lang = "en"; string cult = "en-US"; VariableEnum varEnum = VariableEnum.Stage; //VariableInfo varInfo = new VariableInfo(varEnum); Variable var = new Variable(varEnum); if ( Context.Request.QueryString["lang"] != null ) { lang = Context.Request.QueryString["lang"]; switch ( lang ) { case "cz": cult = "cs-CZ"; break; default: cult = "en-US"; break; } } Thread.CurrentThread.CurrentCulture = new CultureInfo(cult); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cult); // this code is invoked, when the form is posted back. // (after pressing the "OK" button) // The page is then redirected to a different URL if ( Context.Request.Form.Count > 0 ) { //set culture according to the language of request string requestPath = Context.Request.UrlReferrer.AbsolutePath; if ( requestPath.IndexOf("/cz/") >= 0 ) { cult = "cs-CZ"; } else { cult = "en-US"; } Thread.CurrentThread.CurrentCulture = new CultureInfo(cult); Thread.CurrentThread.CurrentUICulture = new CultureInfo(cult); //string ctlHeading = @"ctl00$cph_main$"; string varName = Context.Request.Form[@"ctl00$cph_main$select_station_type"]; string orderBy = Context.Request.Form[@"ctl00$cph_main$select_order"]; if ( varName == "discharge" ) varName = "flow"; //special case.. var = new Variable(VariableProperty.Name, varName); string varUrl = var.Url; int orderId = Convert.ToInt32(orderBy) + 1; string newUrl = String.Format(@"~/{0}/{1}/{2}/", var.UrlLang, Resources.global.Url_Stations, varUrl); if ( orderId > 1 ) { newUrl = String.Format(@"{0}o{1}.aspx", newUrl, orderId); } // redirect the browser to the new page! Context.Response.Redirect(newUrl); } } protected void Page_Load(object sender, EventArgs e) { // local variables VariableEnum varEnum = VariableEnum.Stage; Variable varInfo = new Variable(4); string cultureStr = Thread.CurrentThread.CurrentCulture.ToString(); int order = 1; DateTime t = DateTime.Now.Date; if ( !( Page.IsPostBack ) ) { // resolve query string parameters this.resolveVariable(varInfo); varEnum = varInfo.VarEnum; order = this.resolveOrder(); // initialize control values and set page metadata this.initialize(varEnum); this.setMetaData(varEnum); // set value of select_station_type control this.selectVariable(varInfo); this.selectOrder(order); // create the table of stations! this.createStationTable(varInfo, order); // set the correct page title! Master.PageTitle = Resources.global.Link_List_Of_Stations + " - " + varInfo.Name; // set right url of the language hyperlink Master.LanguageUrl = CreateLanguageLink(varInfo); } } /// <summary> /// generates a correct URL to be used in the 'language' link /// </summary> /// <param name="varInfo"></param> /// <returns></returns> private string CreateLanguageLink(Variable varInfo) { string LangPath = Context.Request.AppRelativeCurrentExecutionFilePath.ToLower(); string LangPathStart; string lang = Thread.CurrentThread.CurrentCulture.ToString(); string tempLang = lang; //the different culture string(to be changed) //resolve language of the link switch ( lang ) { case "en-US": tempLang = "cs-CZ"; break; case "cs-CZ": tempLang = "en-US"; break; default: tempLang = "cs-CZ"; break; } //temporarily change the culture CultureInfo pageCulture = Thread.CurrentThread.CurrentUICulture; Thread.CurrentThread.CurrentCulture = new CultureInfo(tempLang); Thread.CurrentThread.CurrentUICulture = new CultureInfo(tempLang); varInfo.Culture = Thread.CurrentThread.CurrentUICulture; LangPathStart = "/" + varInfo.UrlLang + "/" + Resources.global.Url_Stations + "/" + varInfo.Url + "/"; //switch back to original culture Thread.CurrentThread.CurrentCulture = pageCulture; Thread.CurrentThread.CurrentUICulture = pageCulture; if ( LangPath.EndsWith("/default.aspx") ) { LangPath = LangPath.Remove(LangPath.IndexOf("/default.aspx")); } //string LangPath2 = System.Text.RegularExpressions.Regex.Replace //(LangPath, "(/[czen]{2}/[a-z_-]+/[a-z_-]*)", LangPathStart, System.Text.RegularExpressions.RegexOptions.IgnoreCase); if ( LangPath.EndsWith(".aspx")) { LangPathStart = LangPathStart + LangPath.Substring(LangPath.LastIndexOf("/")); } if ( !( LangPathStart.EndsWith(".aspx") || LangPathStart.EndsWith("/") ) ) { LangPathStart = LangPathStart + "/"; } return "~/" + LangPathStart; } // sets initial values to dropdownlists in the page form private void initialize(VariableEnum varEnum) { string cultStr = Thread.CurrentThread.CurrentCulture.ToString(); SetNavigationMenu(); string[] variableList; variableList = new string[4] { Resources.global.Var_Snow, Resources.global.Var_Precip, Resources.global.Var_Stage, Resources.global.Var_Discharge }; int orderListCount = 4; Dictionary<int,string> orderList = new Dictionary<int,string>(); for ( int i = 0; i < orderListCount; ++i ) { // special case: recognize river/territory if ( i == 1 & ( varEnum == VariableEnum.Stage | varEnum == VariableEnum.Discharge ) ) { orderList.Add(i, GetLocalResourceObject("StationOrderType_River").ToString()); } else { orderList.Add(i, GetLocalResourceObject("StationOrderType_" + ( i + 1 ).ToString()).ToString()); } } select_station_type.DataSource = variableList; select_station_type.DataBind(); select_order.DataSource = orderList; select_order.DataTextField = "Value"; select_order.DataValueField = "Key"; select_order.DataBind(); if ( varEnum == VariableEnum.Stage | varEnum == VariableEnum.Discharge ) { th_location.Text = GetLocalResourceObject("LocationHeader2.Text").ToString(); } } // set the active (current) menu item in master page // also create a correct language url link private void SetNavigationMenu() { Master.ActiveMenuItem = "link_stations"; //Master.LanguageUrl = GetLocalResourceObject("LanguageLink.NavigateUrl").ToString(); } private void resolveVariable(Variable varInfo) { string varName; if ( Request.QueryString["var"] != null ) { varName = Request.QueryString["var"]; varInfo.Url = varName; } } // returns the index indicating the order of // displayed stations private int resolveOrder() { int order = 1; if ( Request.QueryString["order"] != null ) { order = Convert.ToInt32(Request.QueryString["order"]); } return order; } // selects the variable in select_station_type DropDownList // also sets correct variable to page title, heading and graph // hyperlink private void selectVariable(Variable varInfo) { VariableEnum varEnum = varInfo.VarEnum; // first, set the table caption label string varName = varInfo.Name; LblCaption2.Text = varName; // second, set the main page heading lbl_h1.Text = GetLocalResourceObject("PageTitle1.Text").ToString() + ": " + varName; // third, set correct variable for the graph hyperlink Master.GraphUrl = Resources.global.Url_Graphs + "/" + varInfo.Url + "/"; //link_graphs.NavigateUrl = Resources.global.Url_Graphs + "/" + varInfo.Url + "/"; // third, select the right index in the variable listbox int index = 0; switch ( varEnum ) { case VariableEnum.Snow: index = 0; break; case VariableEnum.Precip: index = 1; break; case VariableEnum.Stage: index = 2; break; case VariableEnum.Discharge: index = 3; break; default: break; } select_station_type.SelectedIndex = index; } // set the caption and headers of station table! //private void StationList_OnItemDataBound() // select the order in select_order DropDownList private void selectOrder(int order) { if ( order < 1 | order > 4 ) { order = 1; } select_order.SelectedIndex = order - 1; } // the main function: fill the table of stations with data! private void createStationTable(Variable varInfo, int order) { int varId = varInfo.Id; StationListDataSource.SelectParameters["variableId"].DefaultValue = varId.ToString(); StationListDataSource.SelectParameters["orderBy"].DefaultValue = order.ToString(); } // set the metadata in page header from local resource file! private void setMetaData(VariableEnum varEnum) { string varName = varEnum.ToString() + ".text"; // meta_language Master.MetaLanguage = String.Format("<meta http-equiv='content-language' content='{0}' />", Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName); // meta_description Master.MetaDescription = "<meta name='description' content='" + GetLocalResourceObject("MetaDescription_" + varName) + "' />"; // meta_keywords Master.MetaKeywords = "<meta name='keywords' content='" + GetLocalResourceObject("MetaKeywords_" + varName) + "' />"; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace TheBraverest.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Licensed according to the MIT License: * * Copyright (c) 2015 Jeff Lindberg * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace Clouseau { /// <summary> /// Pipeline class - an instance of a particular pipeline consisting of multiple stations. /// /// These stations might represent sequential steps in the pipeline, /// or they might be alternate stations representation parallel steps. /// An entity might visit any stations in any order; /// no sequence or particular flow is enforced or assumed by the pipeline. /// The same entity can also reside at multiple stations concurrently. /// The entity doesn't need to still "reside" at a station; the station might also know /// about the history of an entity as it passed through, e.g. log entries. /// /// There might be multiple entity types (e.g. products, orders, documents) that travel /// between stations in a pipeline, or there might be just a single entity type that is /// tracked in a system. /// /// author: Jeff Lindberg /// </summary> public class Pipeline : PipelineBase, Resolver { // keep the stations in the same order as in the config file private List<ConfiguredStation> configuredStations = new List<ConfiguredStation>(); // keep the stationCommands in the same order as in the config file private List<ConfiguredStationCommand> configuredCommands = new List<ConfiguredStationCommand>(); private ClassFactory classFactory; private InstanceMemory memory; /// <summary> /// Error messages from pipeline creation (summary) /// </summary> public string Errors { get { return errors; } } private string errors; /// <summary> /// Error messages from pipeline creation (detail stack trace) /// </summary> public string ErrorsDetail { get { return errorsDetail; } } private string errorsDetail; /// <summary> /// Was there an error creating the pipeline and its stations? /// </summary> public bool HasError { get { return Errors.Length > 0; } } /// <summary> /// Aggregate set of roles supported by the stations in this pipeline. /// </summary> public List<string> Roles { get { return Stations.SelectMany(s => s.Roles).Distinct().OrderBy(s => s.ToUpper()).ToList(); } } /// <summary> /// constructor -- performs the initialization, including reading the config /// file, instantiating and initializing the configured stations. /// </summary> /// <param name="configName">name of configuration file which describes this specific pipeline</param> /// <param name="memory">instance memory to be associated with this pipeline</param> public Pipeline(string configName, InstanceMemory memory) : this(configName, memory, new DefaultClassFactory()) { } /// <summary> /// alternate constructor -- performs the initialization, including reading the config /// file, instantiating and initializing the configured stations, /// specifying an alternate class factory to instantiate stations. /// </summary> /// <param name="configName">name of configuration file which describes this specific pipeline</param> /// <param name="memory">instance memory to be associated with this pipeline</param> /// <param name="stationCreator">used when we had problems finding classes in a different assembly</param> public Pipeline(string configName, InstanceMemory memory, ClassFactory stationCreator) { this.classFactory = stationCreator; this.memory = memory; // read config file Stream configStream = new FileStream(configName, FileMode.Open, FileAccess.Read); // TODO new way to get the resource file -- actually should use IOC / Dependency Injection // also accept a stream instead of a file ConfigData config = new ConfigData(configStream); errors = ""; errorsDetail = ""; ConfigureCommands(config); ConfigureStations(memory, config); ConfigFile = (configName); Description = (config.RequiredValue("description")); if (errors.Length > 0) { //Console.Error.WriteLine("WARNING: " + _errors); // leave it to the app to decide how to present error messages //throw new StationFailedException(_errors); // allow the constructor to succeed, caller can check HasError } } private void ConfigureStations(InstanceMemory mem, ConfigData config) { // for each station element in the configStream file, // create a station and add it to the stations list List<ConfigData> stationConfigs = config.GetConfigSections(Constants.StationConfig); int index = 0; foreach (ConfigData sConfig in stationConfigs) { ConfiguredStation cs = new ConfiguredStation(index++, sConfig); cs.Description = sConfig.Value(Constants.StationDescription); if (string.IsNullOrWhiteSpace(cs.Description)) cs.Description = sConfig.Value(Constants.StationClassName); configuredStations.Add(cs); // if the Station is configured to be inactive, don't initialize bool active = sConfig.BoolValue(Constants.ActiveStation, true); if (active) { InitializeStation(mem, cs); } } } private void InitializeStation(InstanceMemory mem, ConfiguredStation cs) { Station s = null; try { s = NewStation(cs.ConfigData, mem); if (s != null) { s.Connect(); cs.Station = s; cs.Description = s.StationDescription; // allow station to provide an updated description cs.Enabled = true; } } catch (Exception e) { cs.Error = e.Message; errors += "Station not available: "; errorsDetail += "Station not available: "; if (s != null) { errors += s.ToString(); errorsDetail += s.ToString(); } errors += "\n"; errors += e.Message + "\n"; errorsDetail += "\n"; errorsDetail += e + "\n"; } } /// <summary> /// Ensure any newly enabled stations are initialized. /// If any fail during initialization, the ConfiguredStation will contain the error. /// </summary> public void InitializeEnabledStations() { foreach (var cs in ConfiguredStations.Where(s => s.Enabled && s.Station == null)) { InitializeStation(memory, cs); } } /// <summary> /// create a new Station, based on the station entityName specified in the portion of the config file. /// </summary> /// <param name="configData">portion of a config file describing this particular station</param> /// <param name="mem"></param> /// <returns>a new Station of object, of the desired flavor; returns null if the station is inactive</returns> private Station NewStation(ConfigData configData, InstanceMemory mem) { Station s; string stationClassName = configData.RequiredValue(Constants.StationClassName); //Console.Error.WriteLine("Creating new station: " + stationClassName); try { s = classFactory.InstantiateStationClass(stationClassName); if (s != null) { s.Initialize(configData, mem, this); } else { throw new Exception("Unable to create Station Class " + stationClassName); } } catch (Exception e) { throw new Exception("Unable to create Station Class " + stationClassName, e); } //log.WriteLine("Station type "+s.getStationDescription()+" successfully initialized"); return s; } private void ConfigureCommands(ConfigData config) { // for each command element in the configStream file, // create a StationCommand and add it to the Commands list List<ConfigData> commandConfigs = config.GetConfigSections(Constants.CommandConfig); int index = 0; foreach (ConfigData cmdConfig in commandConfigs) { ConfiguredStationCommand cc = new ConfiguredStationCommand(index++); cc.Description = cmdConfig.Value(Constants.CommandDescription); if (string.IsNullOrWhiteSpace(cc.Description)) cc.Description = cmdConfig.Value(Constants.CommandClassName); configuredCommands.Add(cc); InitializeCommand(cmdConfig, cc); //// if the Command is configured to be inactive, don't initialize //String active = cmdConfig.value(Constants.ACTIVE_STATION); //if (active == null || !active.Equals(Constants.FALSE, StringComparison.InvariantCultureIgnoreCase)) //{ // InitializeCommand(cmdConfig, cc); //} } } private void InitializeCommand(ConfigData cmdConfig, ConfiguredStationCommand cc) { StationCommand cmd = null; try { cmd = NewStationCommand(cmdConfig); if (cmd != null) { cc.StationCommand = cmd; cc.Description = cmd.Description; // allow command to provide an updated description //cc.enabled = true; } } catch (Exception e) { cc.Error = e.Message; errors += "Command not available: "; errorsDetail += "Command not available: "; if (cmd != null) { errors += cmd.ToString(); errorsDetail += cmd.ToString(); } errors += "\n"; errors += e.Message + "\n"; errorsDetail += "\n"; errorsDetail += e + "\n"; } } /// <summary> /// create a new StationCommand, based on the StationCommand class name specified in the /// portion of the config file. /// </summary> /// <param name="configData">portion of a config file describing this particular stationCommand</param> /// <returns> a new StationCommand of object, of the desired flavor; /// returns null if the stationCommand is inactive</returns> private StationCommand NewStationCommand(ConfigData configData) { StationCommand cmd; string stationCommandClassName = configData.RequiredValue(Constants.CommandClassName); //// if the command is configured to be inactive, just return null //String active = configData.value(Constants.ACTIVE_COMMAND); //if (!String.IsNullOrEmpty(active) && active.Equals(Constants.FALSE, StringComparison.InvariantCultureIgnoreCase)) //{ // //Console.Error.WriteLine("ignoring inactive command: " + stationCommandClassName); // return null; //} //Console.Error.WriteLine("Creating new stationCommand: " + stationCommandClassName); try { cmd = classFactory.InstantiateStationCommandClass(stationCommandClassName); if (cmd != null) { cmd.Initialize(configData); } else { throw new Exception("Unable to create StationCommand Class " + stationCommandClassName); } } catch (Exception e) { throw new Exception("Unable to create StationCommand Class " + stationCommandClassName, e); } //log.WriteLine("Command type "+s.getStationCommandDescription()+" successfully initialized"); return cmd; } /// <summary> /// Shut down a pipeline and disconnect all Stations. /// </summary> public void Shutdown() { foreach (Station s in Stations) { try { s.Disconnect(); } catch (Exception e) { Console.Error.WriteLine("Error in disconnecting station: " + s + " - " + e); } } } /// <summary> /// Full description of the pipeline, including a description of all active stations /// </summary> public string GetFullString() { string s = ToString() + "\n"; s += "\nActive Stations: \n"; foreach (Station station in Stations) { s += station + "\n"; } return s; } /// <summary> /// Full description of the pipeline, including a description of all active stations /// </summary> public string GetFullStringHtml() { return Util.ConvertTextToHtml(GetFullString()); } /// <summary> /// A readable description of this Pipeline. /// </summary> public override string ToString() { string s = ""; if (Description != null) s += Description + ": "; s += ConfigFile; return s; } public List<Station> Stations { get { var query = from cs in ConfiguredStations where cs.Enabled && cs.Station != null select cs.Station; return query.ToList(); } } public List<ConfiguredStation> ConfiguredStations { get { return configuredStations; } } public List<StationCommand> Commands { get { var query = from cs in ConfiguredStationCommands where //cs.enabled && cs.StationCommand != null select cs.StationCommand; return query.ToList(); } } /// <summary> /// Get the command object with the specified official name /// </summary> /// <param name="name"></param> /// <returns>null if not found</returns> public StationCommand GetCommandByName(string name) { var query = from c in Commands where c.Name == name select c; return query.FirstOrDefault(); } public List<ConfiguredStationCommand> ConfiguredStationCommands { get { return configuredCommands; } } /// <summary> /// Union of all Supported Search Operations for all Stations - distinct set /// </summary> public List<OperationDefinition> ConfiguredOperations { get { var query = (from s in Stations select s).SelectMany(s => s.Operations); return query.Distinct().ToList(); } } /// <summary> /// Union of all Searchable Custom Fields for all Stations - distinct set /// </summary> public List<CustomFieldDefinition> ConfiguredSearchableCustomFields { get { var query = (from s in Stations select s).SelectMany(s => s.SearchableFields); return query.Distinct().ToList(); } } } /// <summary> /// The same logical station might exist in multiple configurations at the same time. /// (e.g. located on multiple servers) /// This combines the station class with the particular configuration. /// </summary> public class ConfiguredStation { public Station Station; public string Description; public bool Enabled; public string Error; public ConfigData ConfigData; private int id; public int Id { get { return id; } } public ConfiguredStation(int id, ConfigData configData) { this.id = id; this.ConfigData = configData; } } public class ConfiguredStationCommand { public StationCommand StationCommand; public string Description; //public bool enabled; // not currently used public string Error; private int id; public int Id { get { return id; } } public ConfiguredStationCommand(int id) { this.id = id; } } public class DefaultClassFactory : ClassFactory { public Station InstantiateStationClass(string stationClassName) { Station s = null; Type stationType = Type.GetType(stationClassName); if (stationType != null) { s = (Station)Activator.CreateInstance(stationType); } else { // try going through all assemblies Assembly[] assems = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assems) { try { s = (Station)a.CreateInstance(stationClassName); if (s != null) break; } catch { // continue and try the next Assembly } } } return s; } public StationCommand InstantiateStationCommandClass(string stationCommandClassName) { StationCommand s = null; Type stationCommandType = Type.GetType(stationCommandClassName); if (stationCommandType != null) { s = (StationCommand)Activator.CreateInstance(stationCommandType); } else { // try going through all assemblies Assembly[] assems = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assems) { try { s = (StationCommand)a.CreateInstance(stationCommandClassName); if (s != null) break; } catch { // continue and try the next Assembly } } } return s; } } public interface ClassFactory { Station InstantiateStationClass(string stationClassName); StationCommand InstantiateStationCommandClass(string stationCommandClassName); } }
// 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 Fixtures.Azure.AcceptanceTestsAzureReport { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestReportServiceForAzureClient : ServiceClient<AutoRestReportServiceForAzureClient>, IAutoRestReportServiceForAzureClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzureClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzureClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzureClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzureClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzureClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzureClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Get test coverage report /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IDictionary<string, int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, int?>>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
namespace TQVaultAE.GUI { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Windows.Forms; using TQVaultAE.Domain.Contracts.Providers; using TQVaultAE.Domain.Contracts.Services; using TQVaultAE.Domain.Entities; using TQVaultAE.Domain.Search; using TQVaultAE.GUI.Components; using TQVaultAE.GUI.Helpers; using TQVaultAE.Presentation; using TQVaultAE.Domain.Helpers; using System.Drawing; using Microsoft.Extensions.Logging; using TQVaultAE.GUI.Models.SearchDialogAdvanced; using TQVaultAE.GUI.Tooltip; using Newtonsoft.Json; /// <summary> /// Class for the Search Dialog box. /// </summary> public partial class SearchDialogAdvanced : VaultForm { private readonly SessionContext Ctx; private readonly ITranslationService TranslationService; private readonly List<Result> ItemDatabase = new List<Result>(); private readonly ILogger Log; private readonly Bitmap ButtonImageUp; private readonly Bitmap ButtonImageDown; private readonly (ScalingButton Button, FlowLayoutPanel Panel)[] _NavMap; private readonly List<BoxItem> _SelectedFilters = new List<BoxItem>(); private readonly List<SearchQuery> _Queries = new List<SearchQuery>(); public Result[] QueryResults { get; private set; } = new Result[] { }; private bool scalingCheckBoxReduceDuringSelection_LastChecked; /// <summary> /// Initializes a new instance of the SearchDialog class. /// </summary> public SearchDialogAdvanced( MainForm instance , SessionContext sessionContext , IItemProvider itemProvider , ITranslationService translationService , ILogger<SearchDialogAdvanced> log ) : base(instance.ServiceProvider) { this.Owner = instance; this.Ctx = sessionContext; this.TranslationService = translationService; this.Log = log; this.InitializeComponent(); this.MinimizeBox = false; this.NormalizeBox = false; this.MaximizeBox = true; #region Apply custom font this.ProcessAllControls(c => { if (c is IScalingControl || c is NumericUpDown) c.Font = FontService.GetFont(9F); }); this.applyButton.Font = FontService.GetFontLight(12F); this.cancelButton.Font = FontService.GetFontLight(12F); this.Font = FontService.GetFont(9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (byte)(0)); #endregion #region Load localized strings this.Text = Resources.SearchDialogCaption; this.applyButton.Text = TranslationService.TranslateXTag("tagMenuButton07"); this.cancelButton.Text = TranslationService.TranslateXTag("tagMenuButton06"); this.scalingLabelFiltersSelected.Tag = Resources.SearchFiltersSelected; this.scalingLabelFiltersSelected.Text = string.Empty; this.scalingLabelOperator.Text = $"{Resources.SearchOperator} :"; this.buttonExpandAll.Text = Resources.GlobalExpandAll; this.buttonCollapseAll.Text = Resources.GlobalCollapseAll; this.scalingLabelMaxVisibleElement.Text = $"{Resources.SearchVisibleElementsPerCategory} :"; this.scalingLabelSearchTerm.Text = $"{TranslationService.TranslateXTag("xtagLobbySearchSearch")} :"; this.scalingButtonReset.Text = TranslationService.TranslateXTag("tagSkillReset"); this.scalingLabelQueries.Text = $"{Resources.SearchQueries} :"; this.scalingButtonQuerySave.Text = Resources.GlobalSave; this.scalingButtonQueryDelete.Text = TranslationService.TranslateXTag("tagMenuButton03"); this.scalingCheckBoxReduceDuringSelection.Text = Resources.SearchReduceCategoriesDuringSelection; this.scalingComboBoxOperator.Items.Clear(); this.scalingComboBoxOperator.Items.AddRange(new[] { Resources.SearchOperatorAnd, Resources.SearchOperatorOr }); this.scalingButtonMenuAttribute.Text = this.scalingLabelItemAttributes.Text = TranslationService.TranslateXTag("tagCAttributes"); this.scalingButtonMenuBaseAttribute.Text = this.scalingLabelBaseAttributes.Text = Resources.GlobalBaseAttribute; this.scalingButtonMenuCharacters.Text = this.scalingLabelCharacters.Text = TranslationService.TranslateXTag("tagWindowName01"); this.scalingButtonMenuPrefixAttribute.Text = this.scalingLabelPrefixAttributes.Text = Resources.GlobalPrefix; this.scalingButtonMenuPrefixName.Text = this.scalingLabelPrefixName.Text = Resources.GlobalPrefixName; this.scalingButtonMenuQuality.Text = this.scalingLabelQuality.Text = Resources.ResultsQuality; this.scalingButtonMenuRarity.Text = this.scalingLabelRarity.Text = Resources.GlobalRarity; this.scalingButtonMenuStyle.Text = this.scalingLabelStyle.Text = Resources.GlobalStyle; this.scalingButtonMenuSuffixAttribute.Text = this.scalingLabelSuffixAttributes.Text = Resources.GlobalSuffix; this.scalingButtonMenuSuffixName.Text = this.scalingLabelSuffixName.Text = Resources.GlobalSuffixName; this.scalingButtonMenuType.Text = this.scalingLabelItemType.Text = Resources.GlobalType; this.scalingButtonMenuVaults.Text = this.scalingLabelInVaults.Text = Resources.GlobalVaults; this.scalingButtonMenuWithCharm.Text = this.scalingLabelWithCharm.Text = Resources.SearchHavingCharm; this.scalingButtonMenuWithRelic.Text = this.scalingLabelWithRelic.Text = Resources.SearchHavingRelic; #endregion // Mapping between nav button & content component if (_NavMap is null) { _NavMap = new (ScalingButton Button, FlowLayoutPanel Panel)[] { (this.scalingButtonMenuAttribute, this.flowLayoutPanelItemAttributes), (this.scalingButtonMenuBaseAttribute, this.flowLayoutPanelBaseAttributes), (this.scalingButtonMenuCharacters, this.flowLayoutPanelCharacters), (this.scalingButtonMenuPrefixAttribute, this.flowLayoutPanelPrefixAttributes), (this.scalingButtonMenuPrefixName, this.flowLayoutPanelPrefixName), (this.scalingButtonMenuRarity, this.flowLayoutPanelRarity), (this.scalingButtonMenuStyle, this.flowLayoutPanelStyle), (this.scalingButtonMenuSuffixAttribute, this.flowLayoutPanelSuffixAttributes), (this.scalingButtonMenuSuffixName, this.flowLayoutPanelSuffixName), (this.scalingButtonMenuType, this.flowLayoutPanelItemType), (this.scalingButtonMenuVaults, this.flowLayoutPanelInVaults), (this.scalingButtonMenuWithCharm, this.flowLayoutPanelWithCharm), (this.scalingButtonMenuWithRelic, this.flowLayoutPanelWithRelic), (this.scalingButtonMenuQuality, this.flowLayoutPanelQuality), }; } // Keep reference of base Up & Down button image this.ButtonImageUp = this.scalingButtonMenuAttribute.UpBitmap; this.ButtonImageDown = this.scalingButtonMenuAttribute.DownBitmap; this.scalingComboBoxOperator.SelectedIndex = (int)SearchOperator.And; // Remove design time fake elements scalingComboBoxQueryList.Items.Clear(); CleanAllCheckBoxes(); } private void CleanAllCheckBoxes() { this.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { lb.BeginUpdate(); lb.Items.Clear(); lb.EndUpdate(); } }); } private void SetSearchBoxVisibility(bool isVisible) => _NavMap.ToList().ForEach(m => m.Panel.Visible = isVisible); #region Apply & Cancel /// <summary> /// Handler for clicking the apply button on the form. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void ApplyButtonClicked(object sender, EventArgs e) { if (!_SelectedFilters.Any()) { scalingLabelProgress.Text = $"{Resources.SearchTermRequired} - {string.Format(Resources.SearchItemCountIs, ItemDatabase.Count())}"; return; }; this.DialogResult = DialogResult.OK; this.Close(); } /// <summary> /// Handler for clicking the cancel button on the form. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void CancelButtonClicked(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } #endregion /// <summary> /// Handler for showing the search dialog. /// </summary> /// <param name="sender">sender object</param> /// <param name="e">EventArgs data</param> private void SearchDialogShown(object sender, EventArgs e) { Application.DoEvents();// Force control rendering (VaultForm stuff like custom borders etc...) // Init Data Base scalingLabelProgress.Text = Resources.SearchBuildingData; scalingLabelProgress.Visible = true; vaultProgressBar.Minimum = 0; vaultProgressBar.Maximum = ItemDatabase.Count(); vaultProgressBar.Visible = true; this.backgroundWorkerBuildDB.RunWorkerAsync(); } #region Load & Init private void SearchDialogAdvanced_Load(object sender, EventArgs e) => BuildItemDatabase(); /// <summary> /// Seek for all available items /// </summary> private void BuildItemDatabase() { foreach (KeyValuePair<string, Lazy<PlayerCollection>> kvp in Ctx.Vaults) { string vaultFile = kvp.Key; PlayerCollection vault = kvp.Value.Value; if (vault == null) continue; int vaultNumber = -1; foreach (SackCollection sack in vault) { vaultNumber++; if (sack == null) continue; foreach (var item in sack.Cast<Item>()) { ItemDatabase.Add(new Result( vaultFile , Path.GetFileNameWithoutExtension(vaultFile) , vaultNumber , SackType.Vault , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } } foreach (KeyValuePair<string, Lazy<PlayerCollection>> kvp in Ctx.Players) { string playerFile = kvp.Key; PlayerCollection player = kvp.Value.Value; if (player == null) continue; string playerName = this.GamePathResolver.GetNameFromFile(playerFile); if (playerName == null) continue; int sackNumber = -1; foreach (SackCollection sack in player) { sackNumber++; if (sack == null) continue; foreach (var item in sack.Cast<Item>()) { this.ItemDatabase.Add(new Result( playerFile , playerName , sackNumber , SackType.Player , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } // Now search the Equipment panel var equipmentSack = player.EquipmentSack; if (equipmentSack == null) continue; foreach (var item in equipmentSack.Cast<Item>()) { ItemDatabase.Add(new Result( playerFile , playerName , 0 , SackType.Equipment , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } foreach (KeyValuePair<string, Lazy<Stash>> kvp in Ctx.Stashes) { string stashFile = kvp.Key; Stash stash = kvp.Value.Value; // Make sure we have a valid name and stash. if (stash == null) continue; string stashName = this.GamePathResolver.GetNameFromFile(stashFile); if (stashName == null) continue; SackCollection sack = stash.Sack; if (sack == null) continue; int sackNumber = 2; SackType sackType = SackType.Stash; if (stashName == Resources.GlobalTransferStash) { sackNumber = 1; sackType = SackType.TransferStash; } else if (stashName == Resources.GlobalRelicVaultStash) { sackNumber = 3; sackType = SackType.RelicVaultStash; } foreach (var item in sack.Cast<Item>()) { ItemDatabase.Add(new Result( stashFile , stashName , sackNumber , sackType , new Lazy<Domain.Results.ToFriendlyNameResult>( () => ItemProvider.GetFriendlyNames(item, FriendlyNamesExtraScopes.ItemFullDisplay) , LazyThreadSafetyMode.ExecutionAndPublication ) )); } } } /// <summary> /// Load item data & display progress /// </summary> private void InitItemDatabase() { // Must not change UI Controls. Just update backgroundWorker which handle this for you through his event pipeline. foreach (var item in ItemDatabase) { item.LazyLoad(); this.backgroundWorkerBuildDB.ReportProgress(1); } // Cleanup zombies ItemDatabase.RemoveAll(id => string.IsNullOrWhiteSpace(id.ItemName)); } #endregion #region backgroundWorkerBuildDB private void backgroundWorkerBuildDB_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) => InitItemDatabase(); private void backgroundWorkerBuildDB_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) => vaultProgressBar.Increment(1); private void backgroundWorkerBuildDB_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { SearchEngineReady(); LoadPersonnalQueries(); } #endregion private void SearchEngineReady() { scalingLabelProgress.Text = $"{Resources.SearchEngineReady} - {string.Format(Resources.SearchItemCountIs, ItemDatabase.Count())}"; PopulateCheckBoxes(); AdjustCheckBoxesWidth(); AdjustCheckBoxesHeight(); SetSearchBoxVisibility(true); SyncNaveButton(); // Start this.scalingTextBoxSearchTerm.Focus(); } private void AdjustCheckBoxesHeight() { flowLayoutPanelMain.ProcessAllControls(c => { // Adjust to current UI setting if (c is ScalingCheckedListBox lb) { var maxRow = (int)this.numericUpDownMaxElement.Value; int height = 0, currrow = 0; foreach (var line in lb.Items) { if (currrow == maxRow) break; height += lb.GetItemHeight(currrow); currrow++; } height += SystemInformation.HorizontalScrollBarHeight; lb.Height = height; } }); } private void AdjustCheckBoxesWidth() { flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.AdjustToMaxTextWidth((int)this.numericUpDownMaxElement.Value); }); } #region Populate private void PopulateCheckBoxes() { PopulateCharacters(); PopulateItemType(); PopulateRarity(); PopulateStyle(); PopulateQuality(); PopulateVaults(); PopulateWithCharm(); PopulateWithRelic(); PopulateItemAttributes(); PopulateBaseAttributes(); PopulatePrefixName(); PopulatePrefixAttributes(); PopulateSuffixName(); PopulateSuffixAttributes(); } private void PopulateWithRelic() { var clb = scalingCheckedListBoxWithRelic; var WithRelic = from id in ItemDatabase let itm = id.FriendlyNames.Item where itm.HasRelicSlot1 && !itm.IsRelic1Charm || itm.HasRelicSlot2 && !itm.IsRelic2Charm from reldesc in new[] { id.FriendlyNames.RelicInfo1Description, id.FriendlyNames.RelicInfo2Description } where !string.IsNullOrWhiteSpace(reldesc) let attClean = reldesc.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, WithRelic); } private static void PopulateInit(ScalingCheckedListBox clb, IEnumerable<BoxItem> items) { var (_, tag) = clb.GetBoxTag(); tag.DataSource = items.ToArray(); clb.BeginUpdate(); clb.Items.AddRange(tag.DataSource); clb.EndUpdate(); } private void PopulateWithCharm() { var clb = scalingCheckedListBoxWithCharm; var WithCharm = from id in ItemDatabase let itm = id.FriendlyNames.Item where itm.HasRelicSlot1 && itm.IsRelic1Charm || itm.HasRelicSlot2 && itm.IsRelic2Charm from reldesc in new[] { id.FriendlyNames.RelicInfo1Description, id.FriendlyNames.RelicInfo2Description } where !string.IsNullOrWhiteSpace(reldesc) let attClean = reldesc.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, WithCharm); } private void PopulateVaults() { var clb = scalingCheckedListBoxVaults; var Vaults = from id in ItemDatabase.Where(i => i.SackType == SackType.Vault) let att = id.ContainerName orderby att group id by att into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Vaults); } private void PopulateQuality() { var clb = scalingCheckedListBoxQuality; var Quality = from id in ItemDatabase let att = id.FriendlyNames.BaseItemInfoQuality where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Quality); } private void PopulateSuffixName() { var clb = scalingCheckedListBoxSuffixName; var SuffixName = from id in ItemDatabase let att = id.FriendlyNames.SuffixInfoDescription where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, SuffixName); } private void PopulateSuffixAttributes() { var clb = scalingCheckedListBoxSuffixAttributes; var SuffixAttributes = from id in ItemDatabase from att in id.FriendlyNames.SuffixAttributes where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, SuffixAttributes); } private void PopulateStyle() { var clb = scalingCheckedListBoxStyle; var Style = from id in ItemDatabase let att = id.FriendlyNames.BaseItemInfoStyle where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Style); } private void PopulateRarity() { var equipmentOnly = new[] { ItemStyle.Broken , ItemStyle.Mundane , ItemStyle.Common , ItemStyle.Rare , ItemStyle.Epic , ItemStyle.Legendary }; var clb = scalingCheckedListBoxRarity; var Rarity = from id in ItemDatabase where equipmentOnly.Contains(id.ItemStyle) let att = id.FriendlyNames.BaseItemRarity where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Rarity); } private void PopulatePrefixName() { var clb = scalingCheckedListBoxPrefixName; var PrefixName = from id in ItemDatabase let att = id.FriendlyNames.PrefixInfoDescription where !string.IsNullOrWhiteSpace(att) let attClean = att.TQCleanup().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, PrefixName); } private void PopulatePrefixAttributes() { var clb = scalingCheckedListBoxPrefixAttributes; var PrefixAttributes = from id in ItemDatabase from att in id.FriendlyNames.PrefixAttributes where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, PrefixAttributes); } private void PopulateCharacters() { var clb = scalingCheckedListBoxCharacters; var Players = from id in ItemDatabase where id.SackType == SackType.Player || id.SackType == SackType.Equipment let att = id.ContainerName orderby att group id by att into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, Players); } private void PopulateItemType() { var clb = scalingCheckedListBoxItemType; var ItemType = from id in ItemDatabase let att = id.FriendlyNames.BaseItemInfoClass ?? id.FriendlyNames.Item.ItemClass where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, ItemType); } private void PopulateItemAttributes() { var clb = scalingCheckedListBoxItemAttributes; var ItemAttributes = from id in ItemDatabase from att in id.FriendlyNames.AttributesAll where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, ItemAttributes); } private void PopulateBaseAttributes() { var clb = scalingCheckedListBoxBaseAttributes; var BaseAttributes = from id in ItemDatabase from att in id.FriendlyNames.BaseAttributes where !string.IsNullOrWhiteSpace(att) let attClean = att.RemoveAllTQTags().Trim() orderby attClean group id by attClean into grp select new BoxItem { DisplayValue = grp.Key, MatchingResults = grp, CheckedList = clb, Category = clb.Parent.Controls.OfType<ScalingLabel>().First(), }; PopulateInit(clb, BaseAttributes); } #endregion private void numericUpDownMaxElement_ValueChanged(object sender, EventArgs e) => AdjustCheckBoxesHeight(); private void scalingCheckedListBox_MouseMove(object sender, MouseEventArgs e) { var ctr = sender as Control; var (lstBox, tag) = ctr.GetBoxTag(); var focusedIdx = lstBox.IndexFromPoint(e.Location); if (tag.LastTooltipIndex != focusedIdx) { tag.LastTooltipIndex = focusedIdx; if (tag.LastTooltipIndex > -1) { var item = lstBox.Items[focusedIdx] as BoxItem; toolTip.SetToolTip(lstBox, string.Format(Resources.SearchMatchingItemsTT, item.MatchingResults.Count())); } } lstBox.Tag = tag; } private void buttonCollapseAll_Click(object sender, EventArgs e) { flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.Visible = false; }); } private void buttonExpandAll_Click(object sender, EventArgs e) { flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.Visible = true; }); } private void scalingButtonMenu_Click(object sender, EventArgs e) { // Toggle var (button, panel) = _NavMap.First(m => object.ReferenceEquals(m.Button, sender)); panel.Visible = !panel.Visible; SyncNaveButton(); } private void SyncNaveButton() { /// Push invisible categories at the end of <see cref="flowLayoutPanelMain"/> so nav buttons define categories order in flowpanel var trail = _NavMap.Where(map => !map.Panel.Visible).Select(map => map.Panel).ToList(); // Remove trail.ForEach(c => this.flowLayoutPanelMain.Controls.Remove(c)); // Then Put it back at the end this.flowLayoutPanelMain.Controls.AddRange(trail.ToArray()); SyncNavButtonImage(); } private void SyncNavButtonImage() { foreach (var map in _NavMap) { // Invert Up & Down each time you click to make it behave like a toggle if (map.Panel.Visible) { map.Button.UpBitmap = this.ButtonImageDown; map.Button.OverBitmap = this.ButtonImageUp; map.Button.Image = map.Button.DownBitmap; } else { map.Button.UpBitmap = this.ButtonImageUp; map.Button.OverBitmap = this.ButtonImageDown; map.Button.Image = map.Button.UpBitmap; } } } private void scalingCheckedListBox_SelectedValueChanged(object sender, EventArgs e) => Sync_SelectedFilters(); private void Sync_SelectedFilters() { _SelectedFilters.Clear(); // Add the SearchTerm on top var (_, searchTermBoxItem) = this.scalingTextBoxSearchTerm.GetBoxItem(false); // if i get something to filter with if (!string.IsNullOrWhiteSpace(searchTermBoxItem.DisplayValue)) _SelectedFilters.Add(searchTermBoxItem); // Crawl winform graf for selected BoxItem flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) _SelectedFilters.AddRange(lb.CheckedItems.Cast<BoxItem>()); }); this.Apply_SelectedFilters(); } private void scalingLabelCategory_MouseClick(object sender, MouseEventArgs e) { var label = sender as ScalingLabel; var flowpanel = label.Parent; if (e.Button == MouseButtons.Left) { // Individual Expand/Collapse flowpanel.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) lb.Visible = !lb.Visible; }); } // Uncheck if (e.Button == MouseButtons.Right) { UncheckCategories(flowpanel); Sync_SelectedFilters(); } } private void UncheckCategories(Control flowpanel) { flowpanel.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { lb.BeginUpdate(); lb.CheckedIndices.Cast<int>().ToList().ForEach(idx => lb.SetItemChecked(idx, false)); lb.EndUpdate(); } }); } private void scalingLabelFiltersSelected_MouseEnter(object sender, EventArgs e) { var ctrl = sender as Control; SearchFiltersTooltip.ShowTooltip(this.ServiceProvider, ctrl, this._SelectedFilters, (SearchOperator)scalingComboBoxOperator.SelectedIndex); } private void scalingLabelFiltersSelected_MouseLeave(object sender, EventArgs e) => SearchFiltersTooltip.HideTooltip(); private void Apply_SelectedFilters() { this.scalingLabelFiltersSelected.Text = string.Format(this.scalingLabelFiltersSelected.Tag.ToString(), _SelectedFilters.Count()); var query = ItemDatabase.AsQueryable(); if (this.scalingComboBoxOperator.SelectedIndex == (int)SearchOperator.And) { // AND operator => item must exist in every filter foreach (var filter in _SelectedFilters) query = query.Intersect(filter.MatchingResults);// Reducing result at every step } else { // OR Operator => Accumulate & Distinct query = _SelectedFilters.AsQueryable().SelectMany(f => f.MatchingResults).Distinct(); } this.QueryResults = query.ToArray(); scalingLabelProgress.Text = $"{string.Format(Resources.SearchItemCountIs, QueryResults.Count())}"; ApplyCategoriesReducer(); } private void scalingComboBoxOperator_SelectionChangeCommitted(object sender, EventArgs e) { if (scalingCheckBoxReduceDuringSelection.Checked) ResetCheckBoxesToFirstLoad(); Apply_SelectedFilters(); } private void scalingCheckBoxReduceDuringSelection_CheckedChanged(object sender, EventArgs e) { scalingCheckBoxReduceDuringSelection_LastChecked = !scalingCheckBoxReduceDuringSelection.Checked; ApplyCategoriesReducer(); scalingCheckBoxReduceDuringSelection_LastChecked = scalingCheckBoxReduceDuringSelection.Checked; } private void ApplyCategoriesReducer() { // Category Reduced Display if (scalingCheckBoxReduceDuringSelection.Checked) { ReduceCheckBoxesToQueryResult(); return; } if ( // Category Full Display !scalingCheckBoxReduceDuringSelection.Checked /// But comes from <see cref="scalingCheckBoxReduceDuringSelection_CheckedChanged"/> meaning "from a Category Reduced Display" && scalingCheckBoxReduceDuringSelection.Checked != scalingCheckBoxReduceDuringSelection_LastChecked ) { ResetCheckBoxesToFirstLoad();// Restore Full Display } } private void ResetCheckBoxesToFirstLoad() { // Reset to FirstLoad CleanAllCheckBoxes(); flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { var (_, tag) = lb.GetBoxTag(); lb.BeginUpdate(); foreach (var item in tag.DataSource) lb.Items.Add(item, _SelectedFilters.Contains(item)); lb.EndUpdate(); } }); } private void ReduceCheckBoxesToQueryResult() { if (this.QueryResults.Any()) { CleanAllCheckBoxes(); // Reset to QueryResult. flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { var (_, tag) = lb.GetBoxTag(); var DSvsQR = // Does boxitems match queryresult ? from boxitem in tag.DataSource from boxitemresult in boxitem.MatchingResults join QR in this.QueryResults on boxitemresult equals QR // distinct boxitems group boxitem by boxitem into grp select grp; lb.BeginUpdate(); foreach (var item in DSvsQR) lb.Items.Add(item.Key, _SelectedFilters.Contains(item.Key)); lb.EndUpdate(); } }); } } private void scalingButtonReset_Click(object sender, EventArgs e) => ResetSelectedFilters(); private void ResetSelectedFilters() { this.scalingComboBoxQueryList.ResetText(); UncheckCategories(flowLayoutPanelMain); TextBoxSearchTerm_UpdateText_Notrigger(string.Empty); TextBoxSearchTerm_TextChanged_Logic(); } private void TextBoxSearchTerm_UpdateText_Notrigger(string newText) { this.scalingTextBoxSearchTerm.TextChanged -= new System.EventHandler(this.scalingTextBoxSearchTerm_TextChanged); this.scalingTextBoxSearchTerm.Text = newText; this.scalingTextBoxSearchTerm.TextChanged += new System.EventHandler(this.scalingTextBoxSearchTerm_TextChanged); } private void scalingTextBoxSearchTerm_TextChanged(object sender, EventArgs e) /// Wait for the end of typing by delaying the call to <see cref="scalingTextBoxSearchTerm_TextChanged_Idled"/> => this.typeAssistant.TextChanged(); private void scalingTextBoxSearchTerm_TextChanged_Idled(object sender, EventArgs e) => TextBoxSearchTerm_TextChanged_Logic(); private void TextBoxSearchTerm_TextChanged_Logic() { MakeSearchTermBoxItem(); /// Wrapped into an Invoke() because i'm currently in the thread of the /// <see cref="typeAssistant"> and i need <see cref="Sync_SelectedFilters"/> to be executed from the main thread to avoid concurrent access exception this.Invoke(new MethodInvoker(() => Sync_SelectedFilters())); } private BoxItem MakeSearchTermBoxItem(string searchTerm = null) { // Init a special BoxItem for the search term var txt = searchTerm is null ? scalingTextBoxSearchTerm.Text.Trim() : searchTerm.Trim(); var (_, searchTermBoxItem) = scalingTextBoxSearchTerm.GetBoxItem(true);// true : i need to make a new intance here to make the SearchQuery remember search term (must not share same object reference) searchTermBoxItem.Category = scalingLabelSearchTerm; searchTermBoxItem.DisplayValue = txt; if (string.IsNullOrWhiteSpace(txt)) searchTermBoxItem.MatchingResults = Enumerable.Empty<Result>(); else { // Item fulltext search searchTermBoxItem.MatchingResults = ( from id in ItemDatabase where id.FriendlyNames.FullText.IndexOf(txt, StringComparison.OrdinalIgnoreCase) > -1 select id ).ToArray(); } // When this method is used as a BoxItem factory, i don't want the textbox to keep the reference. if (searchTerm != null) scalingTextBoxSearchTerm.Tag = null; return searchTermBoxItem; } private void scalingLabelProgress_MouseEnter(object sender, EventArgs e) { var ctrl = sender as Control; FoundResultsTooltip.ShowTooltip(this.ServiceProvider, ctrl, this.QueryResults); } private void scalingLabelProgress_MouseLeave(object sender, EventArgs e) => FoundResultsTooltip.HideTooltip(); private void scalingLabelProgress_TextChanged(object sender, EventArgs e) { var ctrl = sender as Control; ScalingLabelProgressAdjustSizeAndPosition(ctrl); } private static void ScalingLabelProgressAdjustSizeAndPosition(Control ctrl) { // Adjust Control Size & position manualy because center align the control in it's container doesn't work with AutoSize = true ctrl.Size = TextRenderer.MeasureText(ctrl.Text, ctrl.Font); var loc = ctrl.Location; loc.X = (ctrl.Parent.Size.Width / 2) - (ctrl.Width / 2); ctrl.Location = loc; } private void scalingLabelProgressPanelAlignText_SizeChanged(object sender, EventArgs e) { // Prevent child text truncation during resize var ctrl = sender as Control; var label = ctrl.Controls.OfType<ScalingLabel>().First(); ScalingLabelProgressAdjustSizeAndPosition(label); } private void SearchDialogAdvanced_FormClosing(object sender, FormClosingEventArgs e) => SavePersonnalQueries(); private void SavePersonnalQueries() { Config.Settings.Default.SearchQueries = JsonConvert.SerializeObject(this._Queries); Config.Settings.Default.Save(); } private void LoadPersonnalQueries() { var save = Config.Settings.Default.SearchQueries; if (string.IsNullOrWhiteSpace(save)) return; var queries = JsonConvert.DeserializeObject<SearchQuery[]>(save); // Try to retrieve actual instantiated BoxItems related to saved data. if (queries.Any()) { var matrix = ( from query in queries from boxi in query.CheckedItems select new { // Source query, query.QueryName, boxiSave = boxi, // Join boxi.DisplayValue, boxi.CategoryName, boxi.CheckedListName, found = new List<BoxItem>() // Late binding placeholder because anonymous types are immutable } ).ToArray(); // Retrieve CheckBoxes flowLayoutPanelMain.ProcessAllControls(c => { if (c is ScalingCheckedListBox lb) { var (_, tag) = lb.GetBoxTag(); ( // Align Saved & Live BoxItems from ds in tag.DataSource join m in matrix on new { ds.CategoryName, ds.CheckedListName, ds.DisplayValue } equals new { m.CategoryName, m.CheckedListName, m.DisplayValue } select new { boxiLive = ds, matrix = m } ).ToList().ForEach(r => r.matrix.found.Add(r.boxiLive));// Bind } }); // Make Search terms ( from m in matrix where m.CategoryName == scalingLabelSearchTerm.Name select new { boxiLive = MakeSearchTermBoxItem(m.DisplayValue), matrix = m } ).ToList().ForEach(r => r.matrix.found.Add(r.boxiLive));// Bind // Make newList var newList = ( from m in matrix where m.found.Any() // Saved boxitems may not be retrieved if you have lost the items that carry the corresponding properties. group m by m.QueryName into grp select new SearchQuery { QueryName = grp.Key, CheckedItems = grp.SelectMany(i => i.found).ToArray() } ).ToList(); SearchQueriesInit(newList); } } private void scalingButtonQuerySave_Click(object sender, EventArgs e) { var input = scalingComboBoxQueryList.Text.Trim(); DialogResult? overrideIt = null; SearchQuery foundIt = null; #region Validation // You must have text if (string.IsNullOrWhiteSpace(input)) { MessageBox.Show( Resources.SearchQueryNameMustBeSet , Resources.GlobalInputWarning , MessageBoxButtons.OK , MessageBoxIcon.Error , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); return; } // You must have filters if (!this._SelectedFilters.Any()) { MessageBox.Show( Resources.SearchTermRequired , Resources.GlobalInputWarning , MessageBoxButtons.OK , MessageBoxIcon.Error , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); return; } // Name conflict foundIt = this._Queries.FirstOrDefault(q => q.QueryName.Equals(input, StringComparison.OrdinalIgnoreCase)); if (foundIt != null) { overrideIt = MessageBox.Show( Resources.SearchQueryNameAlreadyExist , Resources.GlobalInputWarning , MessageBoxButtons.YesNo , MessageBoxIcon.Warning , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); if (overrideIt == DialogResult.No) return; } #endregion if (overrideIt == DialogResult.Yes) { foundIt.QueryName = input; foundIt.CheckedItems = this._SelectedFilters.ToArray();// i need a clone here so ToArray() do the job scalingComboBoxQueryList.Refresh(); return; } // Add scenario var newList = new IEnumerable<SearchQuery>[] { this._Queries , new[] { new SearchQuery { QueryName = input, CheckedItems = this._SelectedFilters.ToArray(),// i need a clone here so ToArray() do the job } } } .SelectMany(s => s) .OrderBy(s => s.QueryName) .ToArray(); SearchQueriesInit(newList); } private void SearchQueriesInit(IEnumerable<SearchQuery> newList) { this._Queries.Clear(); this._Queries.AddRange(newList); scalingComboBoxQueryList.BeginUpdate(); scalingComboBoxQueryList.Items.Clear(); scalingComboBoxQueryList.Items.AddRange(this._Queries.ToArray()); scalingComboBoxQueryList.EndUpdate(); } private void scalingButtonQueryDelete_Click(object sender, EventArgs e) { var idx = scalingComboBoxQueryList.SelectedIndex; if (idx == -1) return; var item = scalingComboBoxQueryList.SelectedItem; var deleteIt = MessageBox.Show( string.Format(Resources.GlobalDeleteConfirm, item) , Resources.GlobalInputWarning , MessageBoxButtons.YesNo , MessageBoxIcon.Question , MessageBoxDefaultButton.Button1 , RightToLeftOptions ); if (deleteIt == DialogResult.No) return; scalingComboBoxQueryList.Items.RemoveAt(idx); this._Queries.RemoveAt(idx); } private void scalingComboBoxQueryList_SelectedIndexChanged(object sender, EventArgs e) { var idx = scalingComboBoxQueryList.SelectedIndex; Make_SelectedFilters(this._Queries[idx]); } private void Make_SelectedFilters(SearchQuery searchQuery) { // Make _SelectedFilters from saved query _SelectedFilters.Clear(); _SelectedFilters.AddRange(searchQuery.CheckedItems); ResetCheckBoxesToFirstLoad(); // Restore SearchTerm ? var term = searchQuery.CheckedItems.FirstOrDefault(i => i.CheckedList is null); /// Avoid trigger of <see cref="scalingTextBoxSearchTerm_TextChanged"/> if (term is null) TextBoxSearchTerm_UpdateText_Notrigger(string.Empty); else { TextBoxSearchTerm_UpdateText_Notrigger(term.DisplayValue); this.scalingTextBoxSearchTerm.Tag = term; } MakeSearchTermBoxItem(); this.Apply_SelectedFilters(); } } public static class SearchDialogAdvancedExtension { public static (ScalingCheckedListBox, BoxTag) GetBoxTag(this Control obj) { var ctr = obj as ScalingCheckedListBox; if (ctr is null) return (null, null); var Tag = ctr.Tag as BoxTag ?? new BoxTag(); ctr.Tag = Tag; return (ctr, Tag); } public static (ScalingTextBox, BoxItem) GetBoxItem(this Control obj, bool newInstance) { var ctr = obj as ScalingTextBox; if (ctr is null) return (null, null); var Tag = newInstance ? new BoxItem() : ctr.Tag as BoxItem ?? new BoxItem(); ctr.Tag = Tag; return (ctr, Tag); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Webrtc { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']" [global::Android.Runtime.Register ("org/webrtc/MediaStreamTrack", DoNotGenerateAcw=true)] public partial class MediaStreamTrack : global::Java.Lang.Object { // Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']" [global::Android.Runtime.Register ("org/webrtc/MediaStreamTrack$State", DoNotGenerateAcw=true)] public sealed partial class State : global::Java.Lang.Enum { static IntPtr ENDED_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']/field[@name='ENDED']" [Register ("ENDED")] public static global::Org.Webrtc.MediaStreamTrack.State Ended { get { if (ENDED_jfieldId == IntPtr.Zero) ENDED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "ENDED", "Lorg/webrtc/MediaStreamTrack$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, ENDED_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr FAILED_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']/field[@name='FAILED']" [Register ("FAILED")] public static global::Org.Webrtc.MediaStreamTrack.State Failed { get { if (FAILED_jfieldId == IntPtr.Zero) FAILED_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "FAILED", "Lorg/webrtc/MediaStreamTrack$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, FAILED_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr INITIALIZING_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']/field[@name='INITIALIZING']" [Register ("INITIALIZING")] public static global::Org.Webrtc.MediaStreamTrack.State Initializing { get { if (INITIALIZING_jfieldId == IntPtr.Zero) INITIALIZING_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "INITIALIZING", "Lorg/webrtc/MediaStreamTrack$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, INITIALIZING_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (__ret, JniHandleOwnership.TransferLocalRef); } } static IntPtr LIVE_jfieldId; // Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']/field[@name='LIVE']" [Register ("LIVE")] public static global::Org.Webrtc.MediaStreamTrack.State Live { get { if (LIVE_jfieldId == IntPtr.Zero) LIVE_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "LIVE", "Lorg/webrtc/MediaStreamTrack$State;"); IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, LIVE_jfieldId); return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (__ret, JniHandleOwnership.TransferLocalRef); } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/MediaStreamTrack$State", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (State); } } internal State (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_valueOf_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]" [Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/MediaStreamTrack$State;", "")] public static unsafe global::Org.Webrtc.MediaStreamTrack.State ValueOf (string p0) { if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero) id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/MediaStreamTrack$State;"); IntPtr native_p0 = JNIEnv.NewString (p0); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (native_p0); global::Org.Webrtc.MediaStreamTrack.State __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef); return __ret; } finally { JNIEnv.DeleteLocalRef (native_p0); } } static IntPtr id_values; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack.State']/method[@name='values' and count(parameter)=0]" [Register ("values", "()[Lorg/webrtc/MediaStreamTrack$State;", "")] public static unsafe global::Org.Webrtc.MediaStreamTrack.State[] Values () { if (id_values == IntPtr.Zero) id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/MediaStreamTrack$State;"); try { return (global::Org.Webrtc.MediaStreamTrack.State[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.MediaStreamTrack.State)); } finally { } } } internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("org/webrtc/MediaStreamTrack", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (MediaStreamTrack); } } protected MediaStreamTrack (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_J; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/constructor[@name='MediaStreamTrack' and count(parameter)=1 and parameter[1][@type='long']]" [Register (".ctor", "(J)V", "")] public unsafe MediaStreamTrack (long p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () != typeof (MediaStreamTrack)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(J)V", __args), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(J)V", __args); return; } if (id_ctor_J == IntPtr.Zero) id_ctor_J = JNIEnv.GetMethodID (class_ref, "<init>", "(J)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_J, __args), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_J, __args); } finally { } } static Delegate cb_dispose; #pragma warning disable 0169 static Delegate GetDisposeHandler () { if (cb_dispose == null) cb_dispose = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Dispose); return cb_dispose; } static void n_Dispose (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Dispose (); } #pragma warning restore 0169 static IntPtr id_dispose; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='dispose' and count(parameter)=0]" [Register ("dispose", "()V", "GetDisposeHandler")] public virtual unsafe void Dispose () { if (id_dispose == IntPtr.Zero) id_dispose = JNIEnv.GetMethodID (class_ref, "dispose", "()V"); try { if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_dispose); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "dispose", "()V")); } finally { } } static Delegate cb_enabled; #pragma warning disable 0169 static Delegate GetEnabledHandler () { if (cb_enabled == null) cb_enabled = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool>) n_Enabled); return cb_enabled; } static bool n_Enabled (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.Enabled (); } #pragma warning restore 0169 static IntPtr id_enabled; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='enabled' and count(parameter)=0]" [Register ("enabled", "()Z", "GetEnabledHandler")] public virtual unsafe bool Enabled () { if (id_enabled == IntPtr.Zero) id_enabled = JNIEnv.GetMethodID (class_ref, "enabled", "()Z"); try { if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_enabled); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "enabled", "()Z")); } finally { } } static Delegate cb_id; #pragma warning disable 0169 static Delegate GetIdHandler () { if (cb_id == null) cb_id = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Id); return cb_id; } static IntPtr n_Id (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Id ()); } #pragma warning restore 0169 static IntPtr id_id; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='id' and count(parameter)=0]" [Register ("id", "()Ljava/lang/String;", "GetIdHandler")] public virtual unsafe string Id () { if (id_id == IntPtr.Zero) id_id = JNIEnv.GetMethodID (class_ref, "id", "()Ljava/lang/String;"); try { if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_id), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "id", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_kind; #pragma warning disable 0169 static Delegate GetKindHandler () { if (cb_kind == null) cb_kind = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_Kind); return cb_kind; } static IntPtr n_Kind (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.Kind ()); } #pragma warning restore 0169 static IntPtr id_kind; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='kind' and count(parameter)=0]" [Register ("kind", "()Ljava/lang/String;", "GetKindHandler")] public virtual unsafe string Kind () { if (id_kind == IntPtr.Zero) id_kind = JNIEnv.GetMethodID (class_ref, "kind", "()Ljava/lang/String;"); try { if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_kind), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "kind", "()Ljava/lang/String;")), JniHandleOwnership.TransferLocalRef); } finally { } } static Delegate cb_setEnabled_Z; #pragma warning disable 0169 static Delegate GetSetEnabled_ZHandler () { if (cb_setEnabled_Z == null) cb_setEnabled_Z = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, bool, bool>) n_SetEnabled_Z); return cb_setEnabled_Z; } static bool n_SetEnabled_Z (IntPtr jnienv, IntPtr native__this, bool p0) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.SetEnabled (p0); } #pragma warning restore 0169 static IntPtr id_setEnabled_Z; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='setEnabled' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setEnabled", "(Z)Z", "GetSetEnabled_ZHandler")] public virtual unsafe bool SetEnabled (bool p0) { if (id_setEnabled_Z == IntPtr.Zero) id_setEnabled_Z = JNIEnv.GetMethodID (class_ref, "setEnabled", "(Z)Z"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); if (GetType () == ThresholdType) return JNIEnv.CallBooleanMethod (Handle, id_setEnabled_Z, __args); else return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setEnabled", "(Z)Z"), __args); } finally { } } static Delegate cb_setState_Lorg_webrtc_MediaStreamTrack_State_; #pragma warning disable 0169 static Delegate GetSetState_Lorg_webrtc_MediaStreamTrack_State_Handler () { if (cb_setState_Lorg_webrtc_MediaStreamTrack_State_ == null) cb_setState_Lorg_webrtc_MediaStreamTrack_State_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_SetState_Lorg_webrtc_MediaStreamTrack_State_); return cb_setState_Lorg_webrtc_MediaStreamTrack_State_; } static bool n_SetState_Lorg_webrtc_MediaStreamTrack_State_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Org.Webrtc.MediaStreamTrack.State p0 = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (native_p0, JniHandleOwnership.DoNotTransfer); bool __ret = __this.SetState (p0); return __ret; } #pragma warning restore 0169 static IntPtr id_setState_Lorg_webrtc_MediaStreamTrack_State_; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='setState' and count(parameter)=1 and parameter[1][@type='org.webrtc.MediaStreamTrack.State']]" [Register ("setState", "(Lorg/webrtc/MediaStreamTrack$State;)Z", "GetSetState_Lorg_webrtc_MediaStreamTrack_State_Handler")] public virtual unsafe bool SetState (global::Org.Webrtc.MediaStreamTrack.State p0) { if (id_setState_Lorg_webrtc_MediaStreamTrack_State_ == IntPtr.Zero) id_setState_Lorg_webrtc_MediaStreamTrack_State_ = JNIEnv.GetMethodID (class_ref, "setState", "(Lorg/webrtc/MediaStreamTrack$State;)Z"); try { JValue* __args = stackalloc JValue [1]; __args [0] = new JValue (p0); bool __ret; if (GetType () == ThresholdType) __ret = JNIEnv.CallBooleanMethod (Handle, id_setState_Lorg_webrtc_MediaStreamTrack_State_, __args); else __ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "setState", "(Lorg/webrtc/MediaStreamTrack$State;)Z"), __args); return __ret; } finally { } } static Delegate cb_state; #pragma warning disable 0169 static Delegate GetInvokeStateHandler () { if (cb_state == null) cb_state = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_InvokeState); return cb_state; } static IntPtr n_InvokeState (IntPtr jnienv, IntPtr native__this) { global::Org.Webrtc.MediaStreamTrack __this = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.ToLocalJniHandle (__this.InvokeState ()); } #pragma warning restore 0169 static IntPtr id_state; // Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaStreamTrack']/method[@name='state' and count(parameter)=0]" [Register ("state", "()Lorg/webrtc/MediaStreamTrack$State;", "GetInvokeStateHandler")] public virtual unsafe global::Org.Webrtc.MediaStreamTrack.State InvokeState () { if (id_state == IntPtr.Zero) id_state = JNIEnv.GetMethodID (class_ref, "state", "()Lorg/webrtc/MediaStreamTrack$State;"); try { if (GetType () == ThresholdType) return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (JNIEnv.CallObjectMethod (Handle, id_state), JniHandleOwnership.TransferLocalRef); else return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaStreamTrack.State> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "state", "()Lorg/webrtc/MediaStreamTrack$State;")), JniHandleOwnership.TransferLocalRef); } finally { } } } }
/// QAS Pro Web integration code /// (c) Experian, www.edq.com namespace Experian.Qas.Prowebintegration { using System; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using Experian.Qas.Proweb; /// <summary> /// Scenario "Address Capture on the Intranet" - hierarchical picklists /// Retrieve the final formatted address, display to user for confirmation /// This page is based on HierBasePage, which provides functionality common to the scenario /// </summary> public partial class HierAddress : HierBasePage { // page controls protected void Page_Load(object sender, System.EventArgs e) { Page_BaseLoad(sender, e); if (!IsPostBack) { // Store values in transit from other pages StoredDataID = StoredPage.StoredDataID; StoredCountryName = StoredPage.StoredCountryName; StoredUserInput = StoredPage.StoredUserInput; SetStoredHistory(StoredPage.GetStoredHistory()); // Pick up values we need StoredRoute = StoredPage.StoredRoute; StoredMoniker = StoredPage.StoredMoniker; StoredWarning = StoredPage.StoredWarning; StoredErrorInfo = StoredPage.StoredErrorInfo; // Address result string[] asLabels = null; string[] asLines = null; // Retrieve address FormatAddress(ref asLabels, ref asLines); // Set welcome message SetWelcomeMessage(StoredRoute); // Set stepin warning message SetWarningMessage(StoredWarning); // Display address lines DisplayAddress(asLabels, asLines); // Set integrator information: route and error SetErrorMessage(); } // Else leave it to the event handlers (New, Back, Accept) } /** Search operations **/ /// <summary> /// Retrieve the formatted address based on the StoredMoniker, or create a set of blank lines /// </summary> /// <param name="asLabels">Array of labels for each line (address type descriptions)</param> /// <param name="asLines">Array of address lines</param> protected void FormatAddress(ref string[] asLabels, ref string[] asLines) { // Retrieve formatted address if (StoredRoute.Equals(Constants.Routes.Okay)) { try { IAddressLookup addressLookup = QAS.GetSearchService(); // Perform address formatting FormattedAddress objAddress = addressLookup.GetFormattedAddress(StoredMoniker, GetLayout()); List<AddressLine> lines = objAddress.AddressLines; // Build display address arrays int iSize = lines.Count; asLabels = new string[iSize]; asLines = new String[iSize]; for (int i = 0; i < iSize; i++) { asLabels[i] = lines[i].Label; asLines[i] = lines[i].Line; } } catch (Exception x) { StoredRoute = Constants.Routes.Failed; StoredErrorInfo = x.Message; } } // Provide default (empty) address for manual entry if (!StoredRoute.Equals(Constants.Routes.Okay)) { asLabels = new string[] { "Address Line 1", "Address Line 2", "Address Line 3", "City", "State or Province", "ZIP or Postal Code" }; asLines = new string[] { "", "", "", "", "", "" }; } } /** Page updating **/ /// <summary> /// Dynamically populate the TableAddress table control from the arguments /// </summary> protected void DisplayAddress(string[] asLabels, string[] asLines) { for (int iIndex = 0; iIndex < asLines.Length; ++iIndex) { AddAddressLine(asLabels[iIndex], asLines[iIndex]); } // Add country row HtmlInputText InputCountry = AddAddressLine("Datamap or Country", StoredCountryName); // Modify country field ID and look InputCountry.ID = Constants.FIELD_COUNTRY_NAME; InputCountry.Attributes["readonly"] = "readonly"; InputCountry.Attributes["class"] = "readonly"; } /// <summary> /// Add a table row, with cells for the label, a gap, and a text input control /// </summary> /// <returns>The text input control</returns> protected HtmlInputText AddAddressLine(string sLabel, string sLine) { TableRow row = new TableRow(); TableCell cellLabel = new TableCell(); LiteralControl label = new LiteralControl(sLabel); cellLabel.Controls.Add(label); row.Cells.Add(cellLabel); TableCell cellGap = new TableCell(); cellGap.Width = new Unit(1, UnitType.Em); row.Cells.Add(cellGap); TableCell cellAddress = new TableCell(); HtmlInputText addressLine = new HtmlInputText(); addressLine.Value = sLine; addressLine.ID = Constants.FIELD_ADDRESS_LINES; addressLine.Size = 50; cellAddress.Controls.Add(addressLine); row.Cells.Add(cellAddress); TableAddress.Rows.Add(row); return addressLine; } /** Page event handlers **/ #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion /// <summary> /// 'New' button clicked: go to the first page /// </summary> protected void ButtonNew_ServerClick(object sender, System.EventArgs e) { // Clear the search terms (but retain the country selection) StoredUserInput = ""; GoFirstPage(); } /// <summary> /// 'Back' button clicked: recreate last picklist or go to the first page /// </summary> protected void ButtonBack_ServerClick(object sender, System.EventArgs e) { if (StoredRoute.Equals(Constants.Routes.Okay)) { GoSearchPage(); } else { GoFirstPage(); } } /// <summary> /// 'Accept' button clicked: move out of this scenario /// </summary> protected void ButtonAccept_Click(object sender, System.EventArgs e) { GoFinalPage(); } /** Page controls **/ private void SetWelcomeMessage(Constants.Routes eRoute) { // Set the welcome message depending on how we got here (the route) switch (eRoute) { case Constants.Routes.Okay: LiteralMessage.Text = "Please confirm your address below."; break; case Constants.Routes.NoMatches: case Constants.Routes.Timeout: case Constants.Routes.TooManyMatches: LiteralMessage.Text = "Automatic address capture did not succeed.<br /><br />Please search again or enter your address below."; break; default: LiteralMessage.Text = "Automatic address capture is not available.<br /><br />Please enter your address below."; break; } } private void SetWarningMessage(StepinWarnings eWarn) { // Make the panel visible as appropriate PlaceHolderWarning.Visible = (eWarn != StepinWarnings.None); // Set the step-in message depending on the warning switch (eWarn) { case StepinWarnings.CloseMatches: LiteralWarning.Text = "There are also close matches available &#8211; click <a href=\"javascript:goBack();\">back</a> to see them"; break; case StepinWarnings.CrossBorder: LiteralWarning.Text = "Address selected is outside of the entered locality"; break; case StepinWarnings.PostcodeRecode: LiteralWarning.Text = "Postal code has been updated by the Postal Authority"; break; default: LiteralWarning.Text = ""; break; } } private void SetErrorMessage() { // Make the panel visible as appropriate PlaceholderInfo.Visible = !StoredRoute.Equals(Constants.Routes.Okay); // Update the content LiteralRoute.Text = StoredRoute.ToString(); if (StoredErrorInfo != null) { LiteralError.Text = "<br />" + StoredErrorInfo; } } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.InlineDeclaration; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineInNestedCall() { await TestAsync( @"class C { void M() { [|int|] i; if (Foo(int.TryParse(v, out i))) { } } }", @"class C { void M() { if (Foo(int.TryParse(v, out int i))) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableWithConstructor1() { await TestAsync( @"class C { void M() { [|int|] i; if (new C1(v, out i)) { } } }", @"class C { void M() { if (new C1(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableMissingWithIndexer1() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (this[out i]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut2() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVar1() { await TestAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out var i)) { } } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVarExceptForPredefinedTypes1() { await TestAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out int i)) { } } }", options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableWhenWrittenAfter1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } i = 0; } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenWrittenBetween1() { await TestMissingAsync( @"class C { void M() { [|int|] i; i = 0; if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenReadBetween1() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; M1(i); if (int.TryParse(v, out i)) { } } void M1(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWithComplexInitializer() { await TestMissingAsync( @"class C { void M() { [|int|] i = M1(); if (int.TryParse(v, out i)) { } } int M1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInOuterScopeIfNotWrittenOutside() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenAfterInOuterScope() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenBetweenInOuterScope() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { i = 1; if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonOut() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField() { await TestMissingAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out this.i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField2() { await TestMissingAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonLocalStatement() { await TestMissingAsync( @"class C { void M() { foreach ([|int|] i in e) { if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() { await TestMissingAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInEmbeddedStatement() { await TestAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { i = 1; } } }", @"class C { void M() { while (true) if (int.TryParse(v, out int i)) { i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInNestedBlock() { await TestAsync( @"class C { void M() { [|int|] i; while (true) { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { while (true) { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar1() { await TestAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar2() { await TestAsync( @"class C { void M() { [|var|] i = 0; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestGenericInferenceDoNotUseVar3() { await TestAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2<T>(out T i) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2<T>(out T i) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments1() { await TestAsync( @"class C { void M() { // prefix comment [|int|] i; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // prefix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments2() { await TestAsync( @"class C { void M() { [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // suffix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments3() { await TestAsync( @"class C { void M() { // prefix comment [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // prefix comment // suffix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments4() { await TestAsync( @"class C { void M() { int [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments5() { await TestAsync( @"class C { void M() { int /*prefix*/ [|i|], j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments6() { await TestAsync( @"class C { void M() { int /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments7() { await TestAsync( @"class C { void M() { int j, /*prefix*/ [|i|] /*suffix*/; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments8() { await TestAsync( @"class C { void M() { // prefix int j, [|i|]; // suffix { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix int j; // suffix { if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments9() { await TestAsync( @"class C { void M() { int /*int comment*/ /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int /*int comment*/ j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards() { await TestAsync( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); } void Baz(out string s) { } void Bar(Action a) { } }", @" using System; class C { void M() { Bar(() => Baz(out string s)); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards() { await TestMissingAsync( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); Console.WriteLine(s); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow1() { await TestMissingAsync( @" using System; class C { void Foo(string x) { object [|s|] = null; if (x != null || TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow2() { await TestAsync( @" using System; class C { void Foo(string x) { object [|s|] = null; if (x != null && TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }", @" using System; class C { void Foo(string x) { if (x != null && TryBaz(out object s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // PublisherIdentityPermission.cs // // <OWNER>[....]</OWNER> // namespace System.Security.Permissions { using System; using SecurityElement = System.Security.SecurityElement; using X509Certificate = System.Security.Cryptography.X509Certificates.X509Certificate; using System.Security.Util; using System.IO; using System.Collections; using System.Globalization; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] sealed public class PublisherIdentityPermission : CodeAccessPermission, IBuiltInPermission { //------------------------------------------------------ // // PRIVATE STATE DATA // //------------------------------------------------------ private bool m_unrestricted; private X509Certificate[] m_certs; //------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ public PublisherIdentityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { m_unrestricted = true; } else if (state == PermissionState.None) { m_unrestricted = false; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } public PublisherIdentityPermission( X509Certificate certificate ) { Certificate = certificate; } //------------------------------------------------------ // // PUBLIC ACCESSOR METHODS // //------------------------------------------------------ public X509Certificate Certificate { set { CheckCertificate(value); m_unrestricted = false; m_certs = new X509Certificate[1]; m_certs[0] = new X509Certificate(value); } get { if(m_certs == null || m_certs.Length < 1) return null; if(m_certs.Length > 1) throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); if(m_certs[0] == null) return null; return new X509Certificate(m_certs[0]); } } //------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ private static void CheckCertificate( X509Certificate certificate ) { if (certificate == null) { throw new ArgumentNullException( "certificate" ); } if (certificate.GetRawCertData() == null) { throw new ArgumentException(Environment.GetResourceString("Argument_UninitializedCertificate")); } } //------------------------------------------------------ // // CODEACCESSPERMISSION IMPLEMENTATION // //------------------------------------------------------ //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public override IPermission Copy() { PublisherIdentityPermission perm = new PublisherIdentityPermission(PermissionState.None); perm.m_unrestricted = m_unrestricted; if(this.m_certs != null) { perm.m_certs = new X509Certificate[this.m_certs.Length]; int n; for(n = 0; n < this.m_certs.Length; n++) perm.m_certs[n] = (m_certs[n] == null ? null : new X509Certificate(m_certs[n])); } return perm; } public override bool IsSubsetOf(IPermission target) { if (target == null) { if(m_unrestricted) return false; if(m_certs == null) return true; if(m_certs.Length == 0) return true; return false; } PublisherIdentityPermission that = target as PublisherIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(that.m_unrestricted) return true; if(m_unrestricted) return false; if(this.m_certs != null) { foreach(X509Certificate certThis in this.m_certs) { bool bOK = false; if(that.m_certs != null) { foreach(X509Certificate certThat in that.m_certs) { if(certThis.Equals(certThat)) { bOK = true; break; } } } if(!bOK) return false; } } return true; } public override IPermission Intersect(IPermission target) { if (target == null) return null; PublisherIdentityPermission that = target as PublisherIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(this.m_unrestricted && that.m_unrestricted) { PublisherIdentityPermission res = new PublisherIdentityPermission(PermissionState.None); res.m_unrestricted = true; return res; } if(this.m_unrestricted) return that.Copy(); if(that.m_unrestricted) return this.Copy(); if(this.m_certs == null || that.m_certs == null || this.m_certs.Length == 0 || that.m_certs.Length == 0) return null; ArrayList alCerts = new ArrayList(); foreach(X509Certificate certThis in this.m_certs) { foreach(X509Certificate certThat in that.m_certs) { if(certThis.Equals(certThat)) alCerts.Add(new X509Certificate(certThis)); } } if(alCerts.Count == 0) return null; PublisherIdentityPermission result = new PublisherIdentityPermission(PermissionState.None); result.m_certs = (X509Certificate[])alCerts.ToArray(typeof(X509Certificate)); return result; } public override IPermission Union(IPermission target) { if (target == null) { if((this.m_certs == null || this.m_certs.Length == 0) && !this.m_unrestricted) return null; return this.Copy(); } PublisherIdentityPermission that = target as PublisherIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(this.m_unrestricted || that.m_unrestricted) { PublisherIdentityPermission res = new PublisherIdentityPermission(PermissionState.None); res.m_unrestricted = true; return res; } if (this.m_certs == null || this.m_certs.Length == 0) { if(that.m_certs == null || that.m_certs.Length == 0) return null; return that.Copy(); } if(that.m_certs == null || that.m_certs.Length == 0) return this.Copy(); ArrayList alCerts = new ArrayList(); foreach(X509Certificate certThis in this.m_certs) alCerts.Add(certThis); foreach(X509Certificate certThat in that.m_certs) { bool bDupe = false; foreach(X509Certificate cert in alCerts) { if(certThat.Equals(cert)) { bDupe = true; break; } } if(!bDupe) alCerts.Add(certThat); } PublisherIdentityPermission result = new PublisherIdentityPermission(PermissionState.None); result.m_certs = (X509Certificate[])alCerts.ToArray(typeof(X509Certificate)); return result; } #if FEATURE_CAS_POLICY public override void FromXml(SecurityElement esd) { m_unrestricted = false; m_certs = null; CodeAccessPermission.ValidateElement( esd, this ); String unr = esd.Attribute( "Unrestricted" ); if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) { m_unrestricted = true; return; } String elem = esd.Attribute( "X509v3Certificate" ); ArrayList al = new ArrayList(); if(elem != null) al.Add(new X509Certificate(System.Security.Util.Hex.DecodeHexString(elem))); ArrayList alChildren = esd.Children; if(alChildren != null) { foreach(SecurityElement child in alChildren) { elem = child.Attribute( "X509v3Certificate" ); if(elem != null) al.Add(new X509Certificate(System.Security.Util.Hex.DecodeHexString(elem))); } } if(al.Count != 0) m_certs = (X509Certificate[])al.ToArray(typeof(X509Certificate)); } public override SecurityElement ToXml() { SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.PublisherIdentityPermission" ); if (m_unrestricted) esd.AddAttribute( "Unrestricted", "true" ); else if (m_certs != null) { if (m_certs.Length == 1) esd.AddAttribute( "X509v3Certificate", m_certs[0].GetRawCertDataString() ); else { int n; for(n = 0; n < m_certs.Length; n++) { SecurityElement child = new SecurityElement("Cert"); child.AddAttribute( "X509v3Certificate", m_certs[n].GetRawCertDataString() ); esd.AddChild(child); } } } return esd; } #endif // FEATURE_CAS_POLICY /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return PublisherIdentityPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.PublisherIdentityPermissionIndex; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Threading.Tasks; using System.Collections.Generic; using NUnit.Framework; using Sensus.Concurrent; namespace Sensus.Tests.Concurrent { public abstract class IConcurrentTests { #region Fields private const int DelayTime = 2; private readonly IConcurrent _concurrent; #endregion #region Constructors protected IConcurrentTests(IConcurrent concurrent) { _concurrent = concurrent; } #endregion [Test(Description = "If this fails the DelayTime likely isn't large enough to cause a failure if future tests break.")] public void DelayIsLongEnough() { var test = new List<int> { 1, 2, 3 }; var task1 = Task.Run(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } }); var task2 = Task.Run(() => { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); }); Assert.Throws<AggregateException>(() => Task.WaitAll(task1, task2)); } [Test] public void ExecuteThreadSafeActionThrowsNoException() { var test = new List<int> { 1, 2, 3 }; Assert.DoesNotThrow(() => { _concurrent.ExecuteThreadSafe(() => { test.Add(4); foreach (var i in test) { Task.Delay(DelayTime).Wait(); } test.Add(5); }); }); } [Test] public void ExecuteThreadSafeFuncThrowsNoException() { var test = new List<int> { 1, 2, 3 }; Assert.DoesNotThrow(() => { _concurrent.ExecuteThreadSafe(() => { test.Add(4); foreach (var i in test) { Task.Delay(DelayTime).Wait(); } test.Add(5); return test; }); }); } [Test] public void ExecuteThreadSafeActionIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var task1 = Task.Run(() => { _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } }); }); var task2 = Task.Run(() => { _concurrent.ExecuteThreadSafe(() => { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); }); }); Task.WaitAll(task1, task2); } [Test] public void ExecuteThreadSafeFuncIsThreadSafe() { var test = new List<int> { 1, 2, 3 }; var task1 = Task.Run(() => { var output = _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } return test; }); Assert.AreSame(output, test); }); var task2 = Task.Run(() => { var output = _concurrent.ExecuteThreadSafe(() => { test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); return test; }); Assert.AreSame(output, test); }); Task.WaitAll(task1, task2); } [Test] public void ExecuteThreadSafeActionIsSynchronous() { var test = new List<int> { 1, 2, 3 }; _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } }); test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); Assert.Contains(4, test); Assert.Contains(5, test); } [Test] public void ExecuteThreadSafeFuncIsSynchronous() { var test = new List<int> { 1, 2, 3 }; _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } return test; }); test.Add(4); Task.Delay(DelayTime).Wait(); test.Add(5); Assert.Contains(4, test); Assert.Contains(5, test); } [Test] public void ExecuteThreadSafeFuncReturnsCorrectly() { var test = new List<int> { 1, 2, 3 }; var output = _concurrent.ExecuteThreadSafe(() => { foreach (var i in test) { Task.Delay(DelayTime).Wait(); } return test; }); Assert.AreSame(output, test); } [Test] public void InnerExecuteThreadSafeActionNoDeadlock() { var test = new List<int> { 1, 2, 3 }; _concurrent.ExecuteThreadSafe(() => { _concurrent.ExecuteThreadSafe(() => { for (var i = 4; i <= 6; i++) { test.Add(i); Task.Delay(DelayTime).Wait(); } }); }); Assert.AreEqual(6, test.Count, "It appears that we deadlocked because the action didn't finish adding items"); } [Test] public void InnerExecuteThreadSafeFuncNoDeadlock() { var test = new List<int> { 1, 2, 3 }; _concurrent.ExecuteThreadSafe(() => { return _concurrent.ExecuteThreadSafe(() => { for (var i = 4; i <= 6; i++) { test.Add(i); Task.Delay(DelayTime).Wait(); } return test; }); }); //we check test because in the case of a deadlock I'm not sure what output will be returned... Assert.AreEqual(6, test.Count, "It appears that we deadlocked because the func didn't finish adding items"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace BalticAmadeus.FluentMdx { /// <summary> /// /// </summary> public enum MdxAxisType { /// <summary> /// /// </summary> Columns = 0, /// <summary> /// /// </summary> Rows = 1, /// <summary> /// /// </summary> Pages = 2, /// <summary> /// /// </summary> Chapters = 3, /// <summary> /// /// </summary> Sections = 4 } /// <summary> /// Represents Mdx query axis specification. /// </summary> public sealed class MdxAxis : MdxExpressionBase { private readonly IList<string> _properties; /// <summary> /// Initializes a new instance of <see cref="MdxAxis"/>. /// </summary> public MdxAxis() { _properties = new List<string>(); AxisIdentifier = MdxAxisType.Columns; AxisSlicer = null; IsNonEmpty = false; } /// <summary> /// Gets the axis number. /// </summary> public MdxAxisType AxisIdentifier { get; private set; } /// <summary> /// Gets the axis slicer. /// </summary> public MdxTuple AxisSlicer { get; private set; } /// <summary> /// Gets the value if the axis is specified as non-empty. /// </summary> public bool IsNonEmpty { get; private set; } /// <summary> /// Gets the collection of axis properties. /// </summary> public IEnumerable<string> Properties { get { return _properties; } } /// <summary> /// Sets the slicer for axis and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <param name="slicer">Axis slicer.</param> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis WithSlicer(MdxTuple slicer) { AxisSlicer = slicer; return this; } /// <summary> /// Sets the title for axis and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <param name="title">Axis title.</param> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis Titled(string title) { int number; if (int.TryParse(title, out number)) return Titled(number); MdxAxisType type; if (Enum.TryParse(title, true, out type)) return Titled(type); if (!Regex.IsMatch(title, "^AXIS\\(\\d+\\)$", RegexOptions.IgnoreCase)) throw new ArgumentException("Invalid title specified!"); var numberMatch = Regex.Match(title, "\\d+"); if (int.TryParse(numberMatch.Value, out number)) return Titled((MdxAxisType) number); return this; } /// <summary> /// Sets the title for axis and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <param name="type">Axis type.</param> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis Titled(MdxAxisType type) { AxisIdentifier = type; return this; } /// <summary> /// Sets the title for axis and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <param name="number">Axis number.</param> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis Titled(int number) { AxisIdentifier = (MdxAxisType)number; return this; } /// <summary> /// Marks axis as non-empty and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis AsNonEmpty() { IsNonEmpty = true; return this; } /// <summary> /// Marks axis as empty and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis AsEmpty() { IsNonEmpty = false; return this; } /// <summary> /// Applies axis properties and returns the updated current instance of <see cref="MdxAxis"/>. /// </summary> /// <param name="properties">Collection of axis properties.</param> /// <returns>Returns the updated current instance of <see cref="MdxAxis"/>.</returns> public MdxAxis WithProperties(params string[] properties) { foreach (var property in properties) _properties.Add(property); return this; } /// <summary> /// Get set member by member name /// </summary> /// <param name="memberName"></param> /// <returns>Returns set member</returns> public MdxMember GetMember(string memberName) { return AxisSlicer.GetMember(memberName); } protected override string GetStringExpression() { if (!IsNonEmpty) { if (!Properties.Any()) return string.Format(@"{0} ON {1}", AxisSlicer, AxisIdentifier); return string.Format(@"{0} DIMENSION PROPERTIES {1} ON {2}", AxisSlicer, string.Join(", ", Properties), AxisIdentifier); } if (!Properties.Any()) return string.Format(@"NON EMPTY {0} ON {1}", AxisSlicer, AxisIdentifier); return string.Format(@"NON EMPTY {0} DIMENSION PROPERTIES {1} ON {2}", AxisSlicer, string.Join(", ", Properties), AxisIdentifier); } } }
#define USE_TRACING using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Contacts { /// <summary> /// short table to hold the namespace and the prefix /// </summary> public class ContactsNameTable { /// <summary>static string to specify the Contacts namespace supported</summary> public const string NSContacts = "http://schemas.google.com/contact/2008"; /// <summary>static string to specify the Google Contacts prefix used</summary> public const string contactsPrefix = "gContact"; /// <summary> /// Group Member ship info element string /// </summary> public const string GroupMembershipInfo = "groupMembershipInfo"; /// <summary> /// SystemGroup element, indicating that this entry is a system group /// </summary> public const string SystemGroupElement = "systemGroup"; /// <summary> /// Specifies billing information of the entity represented by the contact. The element cannot be repeated /// </summary> public const string BillingInformationElement = "billingInformation"; /// <summary> /// Stores birthday date of the person represented by the contact. The element cannot be repeated /// </summary> public const string BirthdayElement = "birthday"; /// <summary> /// Storage for URL of the contact's calendar. The element can be repeated /// </summary> public const string CalendarLinkElement = "calendarLink"; /// <summary> /// A directory server associated with this contact. May not be repeated /// </summary> public const string DirectoryServerElement = "directoryServer"; /// <summary> /// An event associated with a contact. May be repeated. /// </summary> public const string EventElement = "event"; /// <summary> /// Describes an ID of the contact in an external system of some kind. This element may be repeated. /// </summary> public const string ExternalIdElement = "externalId"; /// <summary> /// Specifies the gender of the person represented by the contact. The element cannot be repeated. /// </summary> public const string GenderElement = "gender"; /// <summary> /// Specifies hobbies or interests of the person specified by the contact. The element can be repeated /// </summary> public const string HobbyElement = "hobby"; /// <summary> /// Specifies the initials of the person represented by the contact. The element cannot be repeated. /// </summary> public const string InitialsElement = "initials"; /// <summary> /// Storage for arbitrary pieces of information about the contact. Each jot has a type specified by the rel attribute and a text value. The element can be repeated. /// </summary> public const string JotElement = "jot"; /// <summary> /// Specifies the preferred languages of the contact. The element can be repeated /// </summary> public const string LanguageElement = "language"; /// <summary> /// Specifies maiden name of the person represented by the contact. The element cannot be repeated. /// </summary> public const string MaidenNameElement = "maidenName"; /// <summary> /// Specifies the mileage for the entity represented by the contact. Can be used for example to document distance needed for reimbursement purposes. /// The value is not interpreted. The element cannot be repeated /// </summary> public const string MileageElement = "mileage"; /// <summary> /// Specifies the nickname of the person represented by the contact. The element cannot be repeated /// </summary> public const string NicknameElement = "nickname"; /// <summary> /// Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated. /// </summary> public const string OccupationElement = "occupation"; /// <summary> /// Classifies importance into 3 categories. can not be repeated /// </summary> public const string PriorityElement = "priority"; /// <summary> /// Describes the relation to another entity. may be repeated /// </summary> public const string RelationElement = "relation"; /// <summary> /// Classifies sensitifity of the contact /// </summary> public const string SensitivityElement = "sensitivity"; /// <summary> /// Specifies short name of the person represented by the contact. The element cannot be repeated. /// </summary> public const string ShortNameElement = "shortName"; /// <summary> /// Specifies status of the person. /// </summary> public const string StatusElement = "status"; /// <summary> /// Specifies the subject of the contact. The element cannot be repeated. /// </summary> public const string SubjectElement = "subject"; /// <summary> /// Represents an arbitrary key-value pair attached to the contact. /// </summary> public const string UserDefinedFieldElement = "userDefinedField"; /// <summary> /// Websites associated with the contact. May be repeated /// </summary> public const string WebsiteElement = "website"; /// <summary> /// rel Attribute /// </summary> /// <returns></returns> public static string AttributeRel = "rel"; /// <summary> /// label Attribute /// </summary> /// <returns></returns> public static string AttributeLabel = "label"; } /// <summary> /// an element is defined that represents a group to which the contact belongs /// </summary> public class GroupMembership : SimpleElement { /// <summary>the href attribute </summary> public const string XmlAttributeHRef = "href"; /// <summary>the deleted attribute </summary> public const string XmlAttributeDeleted = "deleted"; /// <summary> /// default constructor /// </summary> public GroupMembership() : base(ContactsNameTable.GroupMembershipInfo, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts ) { Attributes.Add(XmlAttributeHRef, null); Attributes.Add(XmlAttributeDeleted, null); } /// <summary>Identifies the group to which the contact belongs or belonged. /// The group is referenced by its id.</summary> public string HRef { get { return Attributes[XmlAttributeHRef] as string; } set { Attributes[XmlAttributeHRef] = value; } } /// <summary>Means that the group membership was removed for the contact. /// This attribute will only be included if showdeleted is specified /// as query parameter, otherwise groupMembershipInfo for groups a contact /// does not belong to anymore is simply not returned.</summary> public string Deleted { get { return Attributes[XmlAttributeDeleted] as string; } } } /// <summary> /// extension element to represent a system group /// </summary> public class SystemGroup : SimpleElement { /// <summary> /// id attribute for the system group element /// </summary> /// <returns></returns> public const string XmlAttributeId = "id"; /// <summary> /// default constructor /// </summary> public SystemGroup() : base(ContactsNameTable.SystemGroupElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(XmlAttributeId, null); } /// <summary>Identifies the system group. Note that you still need /// to use the group entries href membership to retrieve the group /// </summary> public string Id { get { return Attributes[XmlAttributeId] as string; } } } /// <summary> /// abstract class for a basecontactentry, used for contacts and groups /// </summary> public abstract class BaseContactEntry : AbstractEntry, IContainsDeleted { private ExtensionCollection<ExtendedProperty> xproperties; /// <summary> /// Constructs a new BaseContactEntry instance /// to indicate that it is an event. /// </summary> protected BaseContactEntry() { Tracing.TraceMsg("Created BaseContactEntry Entry"); AddExtension(new ExtendedProperty()); AddExtension(new Deleted()); } /// <summary> /// returns the extended properties on this object /// </summary> /// <returns></returns> public ExtensionCollection<ExtendedProperty> ExtendedProperties { get { if (xproperties == null) { xproperties = new ExtensionCollection<ExtendedProperty>(this); } return xproperties; } } /// <summary> /// if this is a previously deleted contact, returns true /// to delete a contact, use the delete method /// </summary> public bool Deleted { get { if (FindExtension(GDataParserNameTable.XmlDeletedElement, BaseNameTable.gNamespace) != null) { return true; } return false; } } } /// <summary> /// Specifies billing information of the entity represented by the contact. The element cannot be repeated /// </summary> public class BillingInformation : SimpleElement { /// <summary> /// default constructor for BillingInformation /// </summary> public BillingInformation() : base(ContactsNameTable.BillingInformationElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for BillingInformation with an initial value /// </summary> /// <param name="initValue"/> public BillingInformation(string initValue) : base(ContactsNameTable.BillingInformationElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Stores birthday date of the person represented by the contact. The element cannot be repeated. /// </summary> public class Birthday : SimpleElement { /// <summary> /// When Attribute /// </summary> /// <returns></returns> public static string AttributeWhen = "when"; /// <summary> /// default constructor for Birthday /// </summary> public Birthday() : base(ContactsNameTable.BirthdayElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(AttributeWhen, null); } /// <summary> /// default constructor for Birthday with an initial value /// </summary> /// <param name="initValue"/> public Birthday(string initValue) : base(ContactsNameTable.BirthdayElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(AttributeWhen, initValue); } /// <summary>Birthday date, given in format YYYY-MM-DD (with the year), or --MM-DD (without the year)</summary> /// <returns> </returns> public string When { get { return Attributes[AttributeWhen] as string; } set { Attributes[AttributeWhen] = value; } } } /// <summary> /// Storage for URL of the contact's information. The element can be repeated. /// </summary> public class ContactsLink : LinkAttributesElement { /// <summary> /// href Attribute /// </summary> /// <returns></returns> public static string AttributeHref = "href"; /// <summary> /// default constructor for CalendarLink /// </summary> public ContactsLink(string elementName, string elementPrefix, string elementNamespace) : base(elementName, elementPrefix, elementNamespace) { Attributes.Add(AttributeHref, null); } /// <summary>The URL of the the related link.</summary> /// <returns> </returns> public string Href { get { return Attributes[AttributeHref] as string; } set { Attributes[AttributeHref] = value; } } } /// <summary> /// Storage for URL of the contact's calendar. The element can be repeated. /// </summary> public class CalendarLink : ContactsLink { public CalendarLink() : base(ContactsNameTable.CalendarLinkElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } } /// <summary> /// DirectoryServer schema extension /// </summary> public class DirectoryServer : SimpleElement { /// <summary> /// default constructor for DirectoryServer /// </summary> public DirectoryServer() : base(ContactsNameTable.DirectoryServerElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for DirectoryServer with an initial value /// </summary> /// <param name="initValue"/> public DirectoryServer(string initValue) : base(ContactsNameTable.DirectoryServerElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Event schema extension /// </summary> public class Event : SimpleContainer { /// <summary> /// default constructor for Event /// </summary> public Event() : base(ContactsNameTable.EventElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, null); Attributes.Add(ContactsNameTable.AttributeLabel, null); ExtensionFactories.Add(new When()); } /// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary> /// <returns> </returns> public string Relation { get { return Attributes[ContactsNameTable.AttributeRel] as string; } set { Attributes[ContactsNameTable.AttributeRel] = value; } } /// <summary>User-defined calendar link type.</summary> /// <returns> </returns> public string Label { get { return Attributes[ContactsNameTable.AttributeLabel] as string; } set { Attributes[ContactsNameTable.AttributeLabel] = value; } } /// <summary> /// exposes the When element for this event /// </summary> /// <returns></returns> public When When { get { return FindExtension(GDataParserNameTable.XmlWhenElement, BaseNameTable.gNamespace) as When; } set { ReplaceExtension(GDataParserNameTable.XmlWhenElement, BaseNameTable.gNamespace, value); } } } /// <summary> /// ExternalId schema extension /// </summary> public class ExternalId : SimpleAttribute { /// <summary> /// default constructor for ExternalId /// </summary> public ExternalId() : base(ContactsNameTable.ExternalIdElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, null); Attributes.Add(ContactsNameTable.AttributeLabel, null); } /// <summary> /// default constructor for ExternalId with an initial value /// </summary> /// <param name="initValue"/> public ExternalId(string initValue) : base(ContactsNameTable.ExternalIdElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { Attributes.Add(ContactsNameTable.AttributeRel, null); Attributes.Add(ContactsNameTable.AttributeLabel, null); } /// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary> /// <returns> </returns> public string Relation { get { return Attributes[ContactsNameTable.AttributeRel] as string; } set { Attributes[ContactsNameTable.AttributeRel] = value; } } /// <summary>User-defined calendar link type.</summary> /// <returns> </returns> public string Label { get { return Attributes[ContactsNameTable.AttributeLabel] as string; } set { Attributes[ContactsNameTable.AttributeLabel] = value; } } } /// <summary> /// Gender schema extension /// </summary> public class Gender : SimpleAttribute { /// <summary> /// default constructor for Gender /// </summary> public Gender() : base(ContactsNameTable.GenderElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Gender with an initial value /// </summary> /// <param name="initValue"/> public Gender(string initValue) : base(ContactsNameTable.GenderElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Hobby schema extension /// </summary> public class Hobby : SimpleElement { /// <summary> /// default constructor for Hobby /// </summary> public Hobby() : base(ContactsNameTable.HobbyElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Hobby with an initial value /// </summary> /// <param name="initValue"/> public Hobby(string initValue) : base(ContactsNameTable.HobbyElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Initials schema extension /// </summary> public class Initials : SimpleElement { /// <summary> /// default constructor for Initials /// </summary> public Initials() : base(ContactsNameTable.InitialsElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Initials with an initial value /// </summary> /// <param name="initValue"/> public Initials(string initValue) : base(ContactsNameTable.InitialsElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Jot schema extension /// </summary> public class Jot : SimpleElement { /// <summary> /// default constructor for Jot /// </summary> public Jot() : base(ContactsNameTable.JotElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, null); } /// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary> /// <returns> </returns> public string Relation { get { return Attributes[ContactsNameTable.AttributeRel] as string; } set { Attributes[ContactsNameTable.AttributeRel] = value; } } } /// <summary> /// Language schema extension /// </summary> public class Language : SimpleElement { /// <summary> /// the code attribute /// </summary> /// <returns></returns> public static string AttributeCode = "code"; /// <summary> /// default constructor for Language /// </summary> public Language() : base(ContactsNameTable.LanguageElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeLabel, null); Attributes.Add(AttributeCode, null); } /// <summary> /// default constructor for Language with an initial value /// </summary> /// <param name="initValue"/> public Language(string initValue) : base(ContactsNameTable.LanguageElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { Attributes.Add(ContactsNameTable.AttributeLabel, null); Attributes.Add(AttributeCode, null); } /// <summary>A freeform name of a language. Must not be empty or all whitespace.</summary> /// <returns> </returns> public string Label { get { return Attributes[ContactsNameTable.AttributeLabel] as string; } set { Attributes[ContactsNameTable.AttributeLabel] = value; } } /// <summary>A language code conforming to the IETF BCP 47 specification.</summary> /// <returns> </returns> public string Code { get { return Attributes[AttributeCode] as string; } set { Attributes[AttributeCode] = value; } } } /// <summary> /// Specifies maiden name of the person represented by the contact. The element cannot be repeated. /// </summary> public class MaidenName : SimpleElement { /// <summary> /// default constructor for MaidenName /// </summary> public MaidenName() : base(ContactsNameTable.MaidenNameElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for MaidenName with an initial value /// </summary> /// <param name="initValue"/> public MaidenName(string initValue) : base(ContactsNameTable.MaidenNameElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Specifies the mileage for the entity represented by the contact. Can be used for example to /// document distance needed for reimbursement purposes. The value is not interpreted. The element cannot be repeated. /// </summary> public class Mileage : SimpleElement { /// <summary> /// default constructor for Mileage /// </summary> public Mileage() : base(ContactsNameTable.MileageElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Mileage with an initial value /// </summary> /// <param name="initValue"/> public Mileage(string initValue) : base(ContactsNameTable.MileageElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Specifies the nickname of the person represented by the contact. The element cannot be repeated /// </summary> public class Nickname : SimpleElement { /// <summary> /// default constructor for Nickname /// </summary> public Nickname() : base(ContactsNameTable.NicknameElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Nickname with an initial value /// </summary> /// <param name="initValue"/> public Nickname(string initValue) : base(ContactsNameTable.NicknameElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated. /// </summary> public class Occupation : SimpleElement { /// <summary> /// default constructor for Occupation /// </summary> public Occupation() : base(ContactsNameTable.OccupationElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Occupation with an initial value /// </summary> /// <param name="initValue"/> public Occupation(string initValue) : base(ContactsNameTable.OccupationElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Classifies importance of the contact into 3 categories, low, normal and high /// </summary> public class Priority : SimpleElement { /// <summary> /// default constructor for Priority /// </summary> public Priority() : base(ContactsNameTable.PriorityElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, null); } /// <summary> /// default constructor for Priority with an initial value /// </summary> /// <param name="initValue"/> public Priority(string initValue) : base(ContactsNameTable.OccupationElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, initValue); } /// <summary>Predefined calendar link type. Can be one of work, home or free-busy</summary> /// <returns> </returns> public string Relation { get { return Attributes[ContactsNameTable.AttributeRel] as string; } set { Attributes[ContactsNameTable.AttributeRel] = value; } } } /// <summary> /// Relation schema extension /// </summary> public class Relation : SimpleElement { /// <summary> /// default constructor for Relation /// </summary> public Relation() : base(ContactsNameTable.RelationElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeLabel, null); Attributes.Add(ContactsNameTable.AttributeRel, null); } /// <summary>A freeform name of a language. Must not be empty or all whitespace.</summary> /// <returns> </returns> public string Label { get { return Attributes[ContactsNameTable.AttributeLabel] as string; } set { Attributes[ContactsNameTable.AttributeLabel] = value; } } /// <summary>defines the link type.</summary> /// <returns> </returns> public string Rel { get { return Attributes[ContactsNameTable.AttributeRel] as string; } set { Attributes[ContactsNameTable.AttributeRel] = value; } } } /// <summary> /// Classifies sensitivity of the contact into the following categories: /// confidential, normal, personal or private /// </summary> public class Sensitivity : SimpleElement { /// <summary> /// default constructor for Sensitivity /// </summary> public Sensitivity() : base(ContactsNameTable.SensitivityElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, null); } /// <summary> /// default constructor for Sensitivity with an initial value /// </summary> /// <param name="initValue"/> public Sensitivity(string initValue) : base(ContactsNameTable.SensitivityElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(ContactsNameTable.AttributeRel, initValue); } /// <summary>returns the relationship value</summary> /// <returns> </returns> public string Relation { get { return Attributes[ContactsNameTable.AttributeRel] as string; } set { Attributes[ContactsNameTable.AttributeRel] = value; } } } /// <summary> /// Specifies short name of the person represented by the contact. The element cannot be repeated. /// </summary> public class ShortName : SimpleElement { /// <summary> /// default constructor for ShortName /// </summary> public ShortName() : base(ContactsNameTable.ShortNameElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for ShortName with an initial value /// </summary> /// <param name="initValue"/> public ShortName(string initValue) : base(ContactsNameTable.ShortNameElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Specifies the status element of the person. /// </summary> public class Status : SimpleElement { /// <summary> /// indexed attribute for the status element /// </summary> /// <returns></returns> public const string XmlAttributeIndexed = "indexed"; /// <summary> /// default constructor for Status /// </summary> public Status() : base(ContactsNameTable.StatusElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(XmlAttributeIndexed, null); } /// <summary> /// default constructor for Status with an initial value /// </summary> /// <param name="initValue"/> public Status(bool initValue) : base(ContactsNameTable.StatusElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(XmlAttributeIndexed, initValue ? Utilities.XSDTrue : Utilities.XSDFalse); } /// <summary>Indexed attribute.</summary> /// <returns> </returns> public bool Indexed { get { bool result; if (!bool.TryParse(Attributes[XmlAttributeIndexed] as string, out result)) { result = false; } return result; } set { Attributes[XmlAttributeIndexed] = value ? Utilities.XSDTrue : Utilities.XSDFalse; } } } /// <summary> /// Specifies the subject of the contact. The element cannot be repeated. /// </summary> public class Subject : SimpleElement { /// <summary> /// default constructor for Subject /// </summary> public Subject() : base(ContactsNameTable.SubjectElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } /// <summary> /// default constructor for Subject with an initial value /// </summary> /// <param name="initValue"/> public Subject(string initValue) : base(ContactsNameTable.SubjectElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { } } /// <summary> /// Represents an arbitrary key-value pair attached to the contact. /// </summary> public class UserDefinedField : SimpleAttribute { /// <summary> /// key attribute /// </summary> /// <returns></returns> public static string AttributeKey = "key"; /// <summary> /// default constructor for UserDefinedField /// </summary> public UserDefinedField() : base(ContactsNameTable.UserDefinedFieldElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { Attributes.Add(AttributeKey, null); } /// <summary> /// default constructor for UserDefinedField with an initial value /// </summary> /// <param name="initValue"/> /// <param name="initKey"/> public UserDefinedField(string initValue, string initKey) : base(ContactsNameTable.UserDefinedFieldElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts, initValue) { Attributes.Add(AttributeKey, initKey); } /// <summary>A simple string value used to name this field. Case-sensitive</summary> /// <returns> </returns> public string Key { get { return Attributes[AttributeKey] as string; } set { Attributes[AttributeKey] = value; } } } /// <summary> /// WebSite schema extension /// </summary> public class Website : ContactsLink { /// <summary> /// default constructor for WebSite /// </summary> public Website() : base(ContactsNameTable.WebsiteElement, ContactsNameTable.contactsPrefix, ContactsNameTable.NSContacts) { } } }
//------------------------------------------------------------------------------ // <copyright file="_NTAuthentication.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Runtime.InteropServices; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading; using System.Globalization; using System.Security.Authentication.ExtendedProtection; using System.Security.Principal; using System.Security.Permissions; using System.Net.Security; // #define ISC_REQ_DELEGATE 0x00000001 // #define ISC_REQ_MUTUAL_AUTH 0x00000002 // #define ISC_REQ_REPLAY_DETECT 0x00000004 // #define ISC_REQ_SEQUENCE_DETECT 0x00000008 // #define ISC_REQ_CONFIDENTIALITY 0x00000010 // #define ISC_REQ_USE_SESSION_KEY 0x00000020 // #define ISC_REQ_PROMPT_FOR_CREDS 0x00000040 // #define ISC_REQ_USE_SUPPLIED_CREDS 0x00000080 // #define ISC_REQ_ALLOCATE_MEMORY 0x00000100 // #define ISC_REQ_USE_DCE_STYLE 0x00000200 // #define ISC_REQ_DATAGRAM 0x00000400 // #define ISC_REQ_CONNECTION 0x00000800 // #define ISC_REQ_CALL_LEVEL 0x00001000 // #define ISC_REQ_FRAGMENT_SUPPLIED 0x00002000 // #define ISC_REQ_EXTENDED_ERROR 0x00004000 // #define ISC_REQ_STREAM 0x00008000 // #define ISC_REQ_INTEGRITY 0x00010000 // #define ISC_REQ_IDENTIFY 0x00020000 // #define ISC_REQ_NULL_SESSION 0x00040000 // #define ISC_REQ_MANUAL_CRED_VALIDATION 0x00080000 // #define ISC_REQ_RESERVED1 0x00100000 // #define ISC_REQ_FRAGMENT_TO_FIT 0x00200000 // #define ISC_REQ_HTTP 0x10000000 // Win7 SP1 + // #define ISC_REQ_UNVERIFIED_TARGET_NAME 0x20000000 // #define ASC_REQ_DELEGATE 0x00000001 // #define ASC_REQ_MUTUAL_AUTH 0x00000002 // #define ASC_REQ_REPLAY_DETECT 0x00000004 // #define ASC_REQ_SEQUENCE_DETECT 0x00000008 // #define ASC_REQ_CONFIDENTIALITY 0x00000010 // #define ASC_REQ_USE_SESSION_KEY 0x00000020 // #define ASC_REQ_ALLOCATE_MEMORY 0x00000100 // #define ASC_REQ_USE_DCE_STYLE 0x00000200 // #define ASC_REQ_DATAGRAM 0x00000400 // #define ASC_REQ_CONNECTION 0x00000800 // #define ASC_REQ_CALL_LEVEL 0x00001000 // #define ASC_REQ_EXTENDED_ERROR 0x00008000 // #define ASC_REQ_STREAM 0x00010000 // #define ASC_REQ_INTEGRITY 0x00020000 // #define ASC_REQ_LICENSING 0x00040000 // #define ASC_REQ_IDENTIFY 0x00080000 // #define ASC_REQ_ALLOW_NULL_SESSION 0x00100000 // #define ASC_REQ_ALLOW_NON_USER_LOGONS 0x00200000 // #define ASC_REQ_ALLOW_CONTEXT_REPLAY 0x00400000 // #define ASC_REQ_FRAGMENT_TO_FIT 0x00800000 // #define ASC_REQ_FRAGMENT_SUPPLIED 0x00002000 // #define ASC_REQ_NO_TOKEN 0x01000000 // #define ASC_REQ_HTTP 0x10000000 [Flags] internal enum ContextFlags { Zero = 0, // The server in the transport application can // build new security contexts impersonating the // client that will be accepted by other servers // as the client's contexts. Delegate = 0x00000001, // The communicating parties must authenticate // their identities to each other. Without MutualAuth, // the client authenticates its identity to the server. // With MutualAuth, the server also must authenticate // its identity to the client. MutualAuth = 0x00000002, // The security package detects replayed packets and // notifies the caller if a packet has been replayed. // The use of this flag implies all of the conditions // specified by the Integrity flag. ReplayDetect = 0x00000004, // The context must be allowed to detect out-of-order // delivery of packets later through the message support // functions. Use of this flag implies all of the // conditions specified by the Integrity flag. SequenceDetect = 0x00000008, // The context must protect data while in transit. // Confidentiality is supported for NTLM with Microsoft // Windows NT version 4.0, SP4 and later and with the // Kerberos protocol in Microsoft Windows 2000 and later. Confidentiality = 0x00000010, UseSessionKey = 0x00000020, AllocateMemory = 0x00000100, // Connection semantics must be used. Connection = 0x00000800, // Client applications requiring extended error messages specify the // ISC_REQ_EXTENDED_ERROR flag when calling the InitializeSecurityContext // Server applications requiring extended error messages set // the ASC_REQ_EXTENDED_ERROR flag when calling AcceptSecurityContext. InitExtendedError = 0x00004000, AcceptExtendedError = 0x00008000, // A transport application requests stream semantics // by setting the ISC_REQ_STREAM and ASC_REQ_STREAM // flags in the calls to the InitializeSecurityContext // and AcceptSecurityContext functions InitStream = 0x00008000, AcceptStream = 0x00010000, // Buffer integrity can be verified; however, replayed // and out-of-sequence messages will not be detected InitIntegrity = 0x00010000, // ISC_REQ_INTEGRITY AcceptIntegrity = 0x00020000, // ASC_REQ_INTEGRITY InitManualCredValidation = 0x00080000, // ISC_REQ_MANUAL_CRED_VALIDATION InitUseSuppliedCreds = 0x00000080, // ISC_REQ_USE_SUPPLIED_CREDS InitIdentify = 0x00020000, // ISC_REQ_IDENTIFY AcceptIdentify = 0x00080000, // ASC_REQ_IDENTIFY ProxyBindings = 0x04000000, // ASC_REQ_PROXY_BINDINGS AllowMissingBindings = 0x10000000, // ASC_REQ_ALLOW_MISSING_BINDINGS UnverifiedTargetName = 0x20000000, // ISC_REQ_UNVERIFIED_TARGET_NAME } #if MONO_NOT_IMPLEMENTED internal class NTAuthentication { static private int s_UniqueGroupId = 1; static private ContextCallback s_InitializeCallback = new ContextCallback(InitializeCallback); private bool m_IsServer; private SafeFreeCredentials m_CredentialsHandle; private SafeDeleteContext m_SecurityContext; private string m_Spn; private string m_ClientSpecifiedSpn; private int m_TokenSize; private ContextFlags m_RequestedContextFlags; private ContextFlags m_ContextFlags; private string m_UniqueUserId; private bool m_IsCompleted; private string m_ProtocolName; private SecSizes m_Sizes; private string m_LastProtocolName; private string m_Package; private ChannelBinding m_ChannelBinding; // // Properties // internal string UniqueUserId { get { return m_UniqueUserId; } } // The semantic of this propoerty is "Don't call me again". // It can be completed either with success or error // The latest case is signalled by IsValidContext==false internal bool IsCompleted { get { return m_IsCompleted; } } internal bool IsValidContext { get { return !(m_SecurityContext == null || m_SecurityContext.IsInvalid); } } internal string AssociatedName { get { if (!(IsValidContext && IsCompleted)) throw new Win32Exception((int)SecurityStatus.InvalidHandle); string name = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, m_SecurityContext, ContextAttribute.Names) as string; GlobalLog.Print("NTAuthentication: The context is associated with [" + name + "]"); return name; } } internal bool IsConfidentialityFlag { get { return (m_ContextFlags & ContextFlags.Confidentiality) != 0; } } internal bool IsIntegrityFlag { get { return (m_ContextFlags & (m_IsServer?ContextFlags.AcceptIntegrity:ContextFlags.InitIntegrity)) != 0; } } internal bool IsMutualAuthFlag { get { return (m_ContextFlags & ContextFlags.MutualAuth) != 0; } } internal bool IsDelegationFlag { get { return (m_ContextFlags & ContextFlags.Delegate) != 0; } } internal bool IsIdentifyFlag { get { return (m_ContextFlags & (m_IsServer?ContextFlags.AcceptIdentify:ContextFlags.InitIdentify)) != 0; } } internal string Spn { get { return m_Spn; } } internal string ClientSpecifiedSpn { get { if (m_ClientSpecifiedSpn == null) { m_ClientSpecifiedSpn = GetClientSpecifiedSpn(); } return m_ClientSpecifiedSpn; } } internal bool OSSupportsExtendedProtection { get { GlobalLog.Assert(IsCompleted && IsValidContext, "NTAuthentication#{0}::OSSupportsExtendedProtection|The context is not completed or invalid.", ValidationHelper.HashString(this)); int errorCode; SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, m_SecurityContext, ContextAttribute.ClientSpecifiedSpn, out errorCode); // We consider any error other than Unsupported to mean that the underlying OS // supports extended protection. Most likely it will be TargetUnknown. return ((SecurityStatus)errorCode != SecurityStatus.Unsupported); } } // // True indicates this instance is for Server and will use AcceptSecurityContext SSPI API // internal bool IsServer { get { return m_IsServer; } } // internal bool IsKerberos { get { if (m_LastProtocolName == null) m_LastProtocolName = ProtocolName; return (object) m_LastProtocolName == (object) NegotiationInfoClass.Kerberos; } } internal bool IsNTLM { get { if (m_LastProtocolName == null) m_LastProtocolName = ProtocolName; return (object) m_LastProtocolName == (object) NegotiationInfoClass.NTLM; } } internal string Package { get { return m_Package; } } internal string ProtocolName { get { // NB: May return string.Empty if the auth is not done yet or failed if (m_ProtocolName==null) { NegotiationInfoClass negotiationInfo = null; if (IsValidContext) { negotiationInfo = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, m_SecurityContext, ContextAttribute.NegotiationInfo) as NegotiationInfoClass; if (IsCompleted) { if (negotiationInfo != null) { //cache it only when it's completed m_ProtocolName = negotiationInfo.AuthenticationPackage; } } } return negotiationInfo == null? string.Empty: negotiationInfo.AuthenticationPackage; } return m_ProtocolName; } } internal SecSizes Sizes { get { GlobalLog.Assert(IsCompleted && IsValidContext, "NTAuthentication#{0}::MaxDataSize|The context is not completed or invalid.", ValidationHelper.HashString(this)); if (m_Sizes == null) { m_Sizes = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPIAuth, m_SecurityContext, ContextAttribute.Sizes ) as SecSizes; } return m_Sizes; } } internal ChannelBinding ChannelBinding { get { return m_ChannelBinding; } } // // .Ctors // // // Use only for client HTTP authentication // internal NTAuthentication(string package, NetworkCredential networkCredential, SpnToken spnToken, WebRequest request, ChannelBinding channelBinding) : this(false, package, networkCredential, spnToken.Spn, GetHttpContextFlags(request, spnToken.IsTrusted), request.GetWritingContext(), channelBinding) { // // In order to prevent a race condition where one request could // steal a connection from another request, before a handshake is // complete, we create a new Group for each authentication request. // if (package == NtlmClient.AuthType || package == NegotiateClient.AuthType) { m_UniqueUserId = (Interlocked.Increment(ref s_UniqueGroupId)).ToString(NumberFormatInfo.InvariantInfo) + m_UniqueUserId; } } // private static ContextFlags GetHttpContextFlags(WebRequest request, bool trustedSpn) { ContextFlags contextFlags = ContextFlags.Connection; if (request.ImpersonationLevel == TokenImpersonationLevel.Anonymous) throw new NotSupportedException(SR.GetString(SR.net_auth_no_anonymous_support)); else if(request.ImpersonationLevel == TokenImpersonationLevel.Identification) contextFlags |= ContextFlags.InitIdentify; else if(request.ImpersonationLevel == TokenImpersonationLevel.Delegation) contextFlags |= ContextFlags.Delegate; if (request.AuthenticationLevel == AuthenticationLevel.MutualAuthRequested || request.AuthenticationLevel == AuthenticationLevel.MutualAuthRequired) contextFlags |= ContextFlags.MutualAuth; // CBT: If the SPN came from an untrusted source we should tell the server by setting this flag if (!trustedSpn && ComNetOS.IsWin7Sp1orLater) contextFlags |= ContextFlags.UnverifiedTargetName; return contextFlags; } // // This constructor is for a general (non-HTTP) authentication handshake using SSPI // Works for both client and server sides. // // Security: we may need to impersonate on user behalf as to temporarily restore original thread token. [SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.ControlPrincipal)] internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ContextAwareResult context, ChannelBinding channelBinding) { // // check if we're using DefaultCredentials // if (credential is SystemNetworkCredential) { // #if DEBUG GlobalLog.Assert(context == null || context.IdentityRequested, "NTAuthentication#{0}::.ctor|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)", ValidationHelper.HashString(this)); #endif WindowsIdentity w = context == null ? null : context.Identity; try { IDisposable ctx = w == null ? null : w.Impersonate(); if (ctx != null) { using (ctx) { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } } else { ExecutionContext x = context == null ? null : context.ContextCopy; if (x == null) { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } else { ExecutionContext.Run(x, s_InitializeCallback, new InitializeCallbackContext(this, isServer, package, credential, spn, requestedContextFlags, channelBinding)); } } } catch { // Prevent the impersonation from leaking to upstack exception filters. throw; } } else { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } } // // This overload does not attmept to impersonate because the caller either did it already or the original thread context is still preserved // internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } // // This overload always uses the default credentials for the process. // [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.ControlPrincipal)] internal NTAuthentication(bool isServer, string package, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) { try { using (WindowsIdentity.Impersonate(IntPtr.Zero)) { Initialize(isServer, package, SystemNetworkCredential.defaultCredential, spn, requestedContextFlags, channelBinding); } } catch { // Avoid exception filter attacks. throw; } } private class InitializeCallbackContext { internal InitializeCallbackContext(NTAuthentication thisPtr, bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) { this.thisPtr = thisPtr; this.isServer = isServer; this.package = package; this.credential = credential; this.spn = spn; this.requestedContextFlags = requestedContextFlags; this.channelBinding = channelBinding; } internal readonly NTAuthentication thisPtr; internal readonly bool isServer; internal readonly string package; internal readonly NetworkCredential credential; internal readonly string spn; internal readonly ContextFlags requestedContextFlags; internal readonly ChannelBinding channelBinding; } private static void InitializeCallback(object state) { InitializeCallbackContext context = (InitializeCallbackContext)state; context.thisPtr.Initialize(context.isServer, context.package, context.credential, context.spn, context.requestedContextFlags, context.channelBinding); } // private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ChannelBinding channelBinding) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor() package:" + ValidationHelper.ToString(package) + " spn:" + ValidationHelper.ToString(spn) + " flags :" + requestedContextFlags.ToString()); m_TokenSize = SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPIAuth, package, true).MaxToken; m_IsServer = isServer; m_Spn = spn; m_SecurityContext = null; m_RequestedContextFlags = requestedContextFlags; m_Package = package; m_ChannelBinding = channelBinding; GlobalLog.Print("Peer SPN-> '" + m_Spn + "'"); // // check if we're using DefaultCredentials // if (credential is SystemNetworkCredential) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor(): using DefaultCredentials"); m_CredentialsHandle = SSPIWrapper.AcquireDefaultCredential( GlobalSSPI.SSPIAuth, package, (m_IsServer? CredentialUse.Inbound: CredentialUse.Outbound)); m_UniqueUserId = "/S"; // save off for unique connection marking ONLY used by HTTP client } else if (ComNetOS.IsWin7orLater) { unsafe { SafeSspiAuthDataHandle authData = null; try { SecurityStatus result = UnsafeNclNativeMethods.SspiHelper.SspiEncodeStringsAsAuthIdentity( credential.InternalGetUserName(), credential.InternalGetDomain(), credential.InternalGetPassword(), out authData); if (result != SecurityStatus.OK) { if (Logging.On) Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "SspiEncodeStringsAsAuthIdentity()", String.Format(CultureInfo.CurrentCulture, "0x{0:X}", (int)result))); throw new Win32Exception((int)result); } m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPIAuth, package, (m_IsServer ? CredentialUse.Inbound : CredentialUse.Outbound), ref authData); } finally { if (authData != null) { authData.Close(); } } } } else { // // we're not using DefaultCredentials, we need a // AuthIdentity struct to contain credentials // SECREVIEW: // we'll save username/domain in temp strings, to avoid decrypting multiple times. // password is only used once // string username = credential.InternalGetUserName(); string domain = credential.InternalGetDomain(); // ATTN: // NetworkCredential class does not differentiate between null and "" but SSPI packages treat these cases differently // For NTLM we want to keep "" for Wdigest.Dll we should use null. AuthIdentity authIdentity = new AuthIdentity(username, credential.InternalGetPassword(), (object)package == (object)NegotiationInfoClass.WDigest && (domain == null || domain.Length == 0)? null: domain); m_UniqueUserId = domain + "/" + username + "/U"; // save off for unique connection marking ONLY used by HTTP client GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::.ctor(): using authIdentity:" + authIdentity.ToString()); m_CredentialsHandle = SSPIWrapper.AcquireCredentialsHandle( GlobalSSPI.SSPIAuth, package, (m_IsServer? CredentialUse.Inbound: CredentialUse.Outbound), ref authIdentity ); } } // // Methods // // This will return an client token when conducted authentication on server side' // This token can be used ofr impersanation // We use it to create a WindowsIdentity and hand it out to the server app. internal SafeCloseHandle GetContextToken(out SecurityStatus status) { GlobalLog.Assert(IsCompleted && IsValidContext, "NTAuthentication#{0}::GetContextToken|Should be called only when completed with success, currently is not!", ValidationHelper.HashString(this)); GlobalLog.Assert(IsServer, "NTAuthentication#{0}::GetContextToken|The method must not be called by the client side!", ValidationHelper.HashString(this)); if (!IsValidContext) { throw new Win32Exception((int)SecurityStatus.InvalidHandle); } SafeCloseHandle token = null; status = (SecurityStatus) SSPIWrapper.QuerySecurityContextToken( GlobalSSPI.SSPIAuth, m_SecurityContext, out token); return token; } internal SafeCloseHandle GetContextToken() { SecurityStatus status; SafeCloseHandle token = GetContextToken(out status); if (status != SecurityStatus.OK) { throw new Win32Exception((int)status); } return token; } internal void CloseContext() { if (m_SecurityContext != null && !m_SecurityContext.IsClosed) m_SecurityContext.Close(); } // // NTAuth::GetOutgoingBlob() // Created: 12-01-1999: L.M. // Description: // Accepts a base64 encoded incoming security blob and returns // a base 64 encoded outgoing security blob // // This method is for HttpWebRequest usage only as it has semantic bound to it internal string GetOutgoingBlob(string incomingBlob) { GlobalLog.Enter("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", incomingBlob); byte[] decodedIncomingBlob = null; if (incomingBlob != null && incomingBlob.Length > 0) { decodedIncomingBlob = Convert.FromBase64String(incomingBlob); } byte[] decodedOutgoingBlob = null; if ((IsValidContext || IsCompleted) && decodedIncomingBlob == null) { // we tried auth previously, now we got a null blob, we're done. this happens // with Kerberos & valid credentials on the domain but no ACLs on the resource GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() null blob AND m_SecurityContext#" + ValidationHelper.HashString(m_SecurityContext) + "::Handle:[0x" + m_SecurityContext.ToString() + "]"); m_IsCompleted = true; } else { SecurityStatus statusCode; #if TRAVE try { #endif decodedOutgoingBlob = GetOutgoingBlob(decodedIncomingBlob, true, out statusCode); #if TRAVE } catch (Exception exception) { if (NclUtilities.IsFatal(exception)) throw; GlobalLog.LeaveException("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", exception); throw; } #endif } string outgoingBlob = null; if (decodedOutgoingBlob != null && decodedOutgoingBlob.Length > 0) { outgoingBlob = Convert.ToBase64String(decodedOutgoingBlob); } //This is only for HttpWebRequest that does not need security context anymore if (IsCompleted) { string name = ProtocolName; // cache the only info needed from a completed context before closing it CloseContext(); } GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", outgoingBlob); return outgoingBlob; } // NTAuth::GetOutgoingBlob() // Created: 12-01-1999: L.M. // Description: // Accepts an incoming binary security blob and returns // an outgoing binary security blob internal byte[] GetOutgoingBlob(byte[] incomingBlob, bool throwOnError, out SecurityStatus statusCode) { GlobalLog.Enter("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", ((incomingBlob == null) ? "0" : incomingBlob.Length.ToString(NumberFormatInfo.InvariantInfo)) + " bytes"); List<SecurityBuffer> list = new List<SecurityBuffer>(2); if (incomingBlob != null) { list.Add(new SecurityBuffer(incomingBlob, BufferType.Token)); } if (m_ChannelBinding != null) { list.Add(new SecurityBuffer(m_ChannelBinding)); } SecurityBuffer[] inSecurityBufferArray = null; if (list.Count > 0) { inSecurityBufferArray = list.ToArray(); } SecurityBuffer outSecurityBuffer = new SecurityBuffer(m_TokenSize, BufferType.Token); bool firstTime = m_SecurityContext == null; try { if (!m_IsServer) { // client session statusCode = (SecurityStatus)SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPIAuth, m_CredentialsHandle, ref m_SecurityContext, m_Spn, m_RequestedContextFlags, Endianness.Network, inSecurityBufferArray, outSecurityBuffer, ref m_ContextFlags); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.InitializeSecurityContext() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); if (statusCode == SecurityStatus.CompleteNeeded) { SecurityBuffer[] inSecurityBuffers = new SecurityBuffer[1]; inSecurityBuffers[0] = outSecurityBuffer; statusCode = (SecurityStatus) SSPIWrapper.CompleteAuthToken( GlobalSSPI.SSPIAuth, ref m_SecurityContext, inSecurityBuffers ); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.CompleteAuthToken() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); outSecurityBuffer.token = null; } } else { // server session statusCode = (SecurityStatus)SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPIAuth, m_CredentialsHandle, ref m_SecurityContext, m_RequestedContextFlags, Endianness.Network, inSecurityBufferArray, outSecurityBuffer, ref m_ContextFlags); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() SSPIWrapper.AcceptSecurityContext() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); } } finally { // // Assuming the ISC or ASC has referenced the credential on the first successful call, // we want to decrement the effective ref count by "disposing" it. // The real dispose will happen when the security context is closed. // Note if the first call was not successfull the handle is physically destroyed here // if (firstTime && m_CredentialsHandle != null) m_CredentialsHandle.Close(); } if (((int) statusCode & unchecked((int) 0x80000000)) != 0) { CloseContext(); m_IsCompleted = true; if (throwOnError) { Win32Exception exception = new Win32Exception((int) statusCode); GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", "Win32Exception:" + exception); throw exception; } GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", "null statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); return null; } else if (firstTime && m_CredentialsHandle != null) { // cache until it is pushed out by newly incoming handles SSPIHandleCache.CacheCredential(m_CredentialsHandle); } // the return value from SSPI will tell us correctly if the // handshake is over or not: http://msdn.microsoft.com/library/psdk/secspi/sspiref_67p0.htm // we also have to consider the case in which SSPI formed a new context, in this case we're done as well. if (statusCode == SecurityStatus.OK) { // we're sucessfully done GlobalLog.Assert(statusCode == SecurityStatus.OK, "NTAuthentication#{0}::GetOutgoingBlob()|statusCode:[0x{1:x8}] ({2}) m_SecurityContext#{3}::Handle:[{4}] [STATUS != OK]", ValidationHelper.HashString(this), (int)statusCode, statusCode, ValidationHelper.HashString(m_SecurityContext), ValidationHelper.ToString(m_SecurityContext)); m_IsCompleted = true; } else { // we need to continue GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob() need continue statusCode:[0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + "] (" + statusCode.ToString() + ") m_SecurityContext#" + ValidationHelper.HashString(m_SecurityContext) + "::Handle:" + ValidationHelper.ToString(m_SecurityContext) + "]"); } // GlobalLog.Print("out token = " + outSecurityBuffer.ToString()); // GlobalLog.Dump(outSecurityBuffer.token); GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingBlob", "IsCompleted:" + IsCompleted.ToString()); return outSecurityBuffer.token; } // for Server side (IIS 6.0) see: \\netindex\Sources\inetsrv\iis\iisrearc\iisplus\ulw3\digestprovider.cxx // for Client side (HTTP.SYS) see: \\netindex\Sources\net\http\sys\ucauth.c internal string GetOutgoingDigestBlob(string incomingBlob, string requestMethod, string requestedUri, string realm, bool isClientPreAuth, bool throwOnError, out SecurityStatus statusCode) { GlobalLog.Enter("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", incomingBlob); // second time call with 3 incoming buffers to select HTTP client. // we should get back a SecurityStatus.OK and a non null outgoingBlob. SecurityBuffer[] inSecurityBuffers = null; SecurityBuffer outSecurityBuffer = new SecurityBuffer(m_TokenSize, isClientPreAuth ? BufferType.Parameters : BufferType.Token); bool firstTime = m_SecurityContext == null; try { if (!m_IsServer) { // client session if (!isClientPreAuth) { if (incomingBlob != null) { List<SecurityBuffer> list = new List<SecurityBuffer>(5); list.Add(new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(incomingBlob), BufferType.Token)); list.Add(new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters)); list.Add(new SecurityBuffer(null, BufferType.Parameters)); list.Add(new SecurityBuffer(Encoding.Unicode.GetBytes(m_Spn), BufferType.TargetHost)); if (m_ChannelBinding != null) { list.Add(new SecurityBuffer(m_ChannelBinding)); } inSecurityBuffers = list.ToArray(); } statusCode = (SecurityStatus) SSPIWrapper.InitializeSecurityContext( GlobalSSPI.SSPIAuth, m_CredentialsHandle, ref m_SecurityContext, requestedUri, // this must match the Uri in the HTTP status line for the current request m_RequestedContextFlags, Endianness.Network, inSecurityBuffers, outSecurityBuffer, ref m_ContextFlags ); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.InitializeSecurityContext() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); } else { #if WDIGEST_PREAUTH inSecurityBuffers = new SecurityBuffer[] { new SecurityBuffer(null, BufferType.Token), new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters), new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestedUri), BufferType.Parameters), new SecurityBuffer(null, BufferType.Parameters), outSecurityBuffer, }; statusCode = (SecurityStatus) SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, m_SecurityContext, inSecurityBuffers, 0); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.MakeSignature() returns statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); #else statusCode = SecurityStatus.OK; GlobalLog.Assert("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob()", "Invalid code path."); #endif } } else { // server session List<SecurityBuffer> list = new List<SecurityBuffer>(6); list.Add(incomingBlob == null ? new SecurityBuffer(0, BufferType.Token) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(incomingBlob), BufferType.Token)); list.Add(requestMethod == null ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestMethod), BufferType.Parameters)); list.Add(requestedUri == null ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(WebHeaderCollection.HeaderEncoding.GetBytes(requestedUri), BufferType.Parameters)); list.Add(new SecurityBuffer(0, BufferType.Parameters)); list.Add(realm == null ? new SecurityBuffer(0, BufferType.Parameters) : new SecurityBuffer(Encoding.Unicode.GetBytes(realm), BufferType.Parameters)); if (m_ChannelBinding != null) { list.Add(new SecurityBuffer(m_ChannelBinding)); } inSecurityBuffers = list.ToArray(); statusCode = (SecurityStatus) SSPIWrapper.AcceptSecurityContext( GlobalSSPI.SSPIAuth, m_CredentialsHandle, ref m_SecurityContext, m_RequestedContextFlags, Endianness.Network, inSecurityBuffers, outSecurityBuffer, ref m_ContextFlags ); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.AcceptSecurityContext() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); if (statusCode == SecurityStatus.CompleteNeeded) { inSecurityBuffers[4] = outSecurityBuffer; statusCode = (SecurityStatus) SSPIWrapper.CompleteAuthToken( GlobalSSPI.SSPIAuth, ref m_SecurityContext, inSecurityBuffers ); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() SSPIWrapper.CompleteAuthToken() returns statusCode:0x" + ((int)statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); outSecurityBuffer.token = null; } } } finally { // // Assuming the ISC or ASC has referenced the credential on the first successful call, // we want to decrement the effective ref count by "disposing" it. // The real dispose will happen when the security context is closed. // Note if the first call was not successfull the handle is physically destroyed here // if (firstTime && m_CredentialsHandle != null) m_CredentialsHandle.Close(); } if (((int) statusCode & unchecked((int) 0x80000000)) != 0) { CloseContext(); if (throwOnError) { Win32Exception exception = new Win32Exception((int) statusCode); GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", "Win32Exception:" + exception); throw exception; } GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", "null statusCode:0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + " (" + statusCode.ToString() + ")"); return null; } else if (firstTime && m_CredentialsHandle != null) { // cache until it is pushed out by newly incoming handles SSPIHandleCache.CacheCredential(m_CredentialsHandle); } // the return value from SSPI will tell us correctly if the // handshake is over or not: http://msdn.microsoft.com/library/psdk/secspi/sspiref_67p0.htm if (statusCode == SecurityStatus.OK) { // we're done, cleanup m_IsCompleted = true; } else { // we need to continue GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() need continue statusCode:[0x" + ((int) statusCode).ToString("x8", NumberFormatInfo.InvariantInfo) + "] (" + statusCode.ToString() + ") m_SecurityContext#" + ValidationHelper.HashString(m_SecurityContext) + "::Handle:" + ValidationHelper.ToString(m_SecurityContext) + "]"); } GlobalLog.Print("out token = " + outSecurityBuffer.ToString()); GlobalLog.Dump(outSecurityBuffer.token); GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob() IsCompleted:" + IsCompleted.ToString()); byte[] decodedOutgoingBlob = outSecurityBuffer.token; string outgoingBlob = null; if (decodedOutgoingBlob!=null && decodedOutgoingBlob.Length>0) { outgoingBlob = WebHeaderCollection.HeaderEncoding.GetString(decodedOutgoingBlob, 0, outSecurityBuffer.size); } GlobalLog.Leave("NTAuthentication#" + ValidationHelper.HashString(this) + "::GetOutgoingDigestBlob", outgoingBlob); return outgoingBlob; } internal int Encrypt(byte[] buffer, int offset, int count, ref byte[] output, uint sequenceNumber) { SecSizes sizes = Sizes; try { int maxCount = checked(Int32.MaxValue - 4 - sizes.BlockSize - sizes.SecurityTrailer); if (count > maxCount || count < 0) { throw new ArgumentOutOfRangeException("count", SR.GetString(SR.net_io_out_range, maxCount)); } } catch(Exception e) { if (!NclUtilities.IsFatal(e)){ GlobalLog.Assert(false, "NTAuthentication#" + ValidationHelper.HashString(this) + "::Encrypt", "Arguments out of range."); } throw; } int resultSize = count + sizes.SecurityTrailer + sizes.BlockSize; if (output == null || output.Length < resultSize+4) { output = new byte[resultSize+4]; } // make a copy of user data for in-place encryption Buffer.BlockCopy(buffer, offset, output, 4 + sizes.SecurityTrailer, count); // prepare buffers TOKEN(signautre), DATA and Padding SecurityBuffer[] securityBuffer = new SecurityBuffer[3]; securityBuffer[0] = new SecurityBuffer(output, 4, sizes.SecurityTrailer, BufferType.Token); securityBuffer[1] = new SecurityBuffer(output, 4 + sizes.SecurityTrailer, count, BufferType.Data); securityBuffer[2] = new SecurityBuffer(output, 4 + sizes.SecurityTrailer + count, sizes.BlockSize, BufferType.Padding); int errorCode; if (IsConfidentialityFlag) { errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, sequenceNumber); } else { if (IsNTLM) securityBuffer[1].type |= BufferType.ReadOnlyFlag; errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, 0); } if (errorCode != 0) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::Encrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo)); throw new Win32Exception(errorCode); } // Compacting the result... resultSize = securityBuffer[0].size; bool forceCopy = false; if (resultSize != sizes.SecurityTrailer) { forceCopy = true; Buffer.BlockCopy(output, securityBuffer[1].offset, output, 4 + resultSize, securityBuffer[1].size); } resultSize += securityBuffer[1].size; if (securityBuffer[2].size != 0 && (forceCopy || resultSize != (count + sizes.SecurityTrailer))) Buffer.BlockCopy(output, securityBuffer[2].offset, output, 4 + resultSize, securityBuffer[2].size); resultSize += securityBuffer[2].size; unchecked { output[0] = (byte)((resultSize) & 0xFF); output[1] = (byte)(((resultSize)>>8) & 0xFF); output[2] = (byte)(((resultSize)>>16) & 0xFF); output[3] = (byte)(((resultSize)>>24) & 0xFF); } return resultSize+4; } internal int Decrypt(byte[] payload, int offset, int count, out int newOffset, uint expectedSeqNumber) { if (offset < 0 || offset > (payload == null ? 0 : payload.Length)) { GlobalLog.Assert(false, "NTAuthentication#" + ValidationHelper.HashString(this) + "::Decrypt", "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || count > (payload == null ? 0 : payload.Length - offset)) { GlobalLog.Assert(false, "NTAuthentication#" + ValidationHelper.HashString(this) + "::Decrypt", "Argument 'count' out of range."); throw new ArgumentOutOfRangeException("count"); } if (IsNTLM) return DecryptNtlm(payload, offset, count, out newOffset, expectedSeqNumber); // // Kerberos and up // SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(payload, offset, count, BufferType.Stream); securityBuffer[1] = new SecurityBuffer(0, BufferType.Data); int errorCode; if (IsConfidentialityFlag) { errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, expectedSeqNumber); } else { errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, expectedSeqNumber); } if (errorCode != 0) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo)); throw new Win32Exception(errorCode); } if (securityBuffer[1].type != BufferType.Data) throw new InternalException(); newOffset = securityBuffer[1].offset; return securityBuffer[1].size; } private string GetClientSpecifiedSpn() { GlobalLog.Assert(IsValidContext && IsCompleted, "NTAuthentication: Trying to get the client SPN before handshaking is done!"); string spn = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, m_SecurityContext, ContextAttribute.ClientSpecifiedSpn) as string; GlobalLog.Print("NTAuthentication: The client specified SPN is [" + spn + "]"); return spn; } // private int DecryptNtlm(byte[] payload, int offset, int count, out int newOffset, uint expectedSeqNumber) { // For the most part the arguments are verified in Encrypt(). if (count < 16) { GlobalLog.Assert(false, "NTAuthentication#" + ValidationHelper.HashString(this) + "::DecryptNtlm", "Argument 'count' out of range."); throw new ArgumentOutOfRangeException("count"); } SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(payload, offset, 16, BufferType.Token); securityBuffer[1] = new SecurityBuffer(payload, offset + 16, count-16, BufferType.Data); int errorCode; BufferType realDataType = BufferType.Data; if (IsConfidentialityFlag) { errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, expectedSeqNumber); } else { realDataType |= BufferType.ReadOnlyFlag; securityBuffer[1].type = realDataType; errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, expectedSeqNumber); } if (errorCode != 0) { GlobalLog.Print("NTAuthentication#" + ValidationHelper.HashString(this) + "::Decrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo)); throw new Win32Exception(errorCode); } if (securityBuffer[1].type != realDataType) throw new InternalException(); newOffset = securityBuffer[1].offset; return securityBuffer[1].size; } // // VerifySignature // // Adapted from Decrypt method above as a more generic message // signature verify method for SMTP AUTH GSSAPI (SASL). // Decrypt method, used NegotiateStream, couldn't be used due // to special cases for NTLM. // // See SmtpNegotiateAuthenticationModule class for caller. // internal int VerifySignature(byte[] buffer, int offset, int count) { // validate offset within length if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { GlobalLog.Assert( false, "NTAuthentication#" + ValidationHelper.HashString(this) + "::VerifySignature", "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException("offset"); } // validate count within offset and end of buffer if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) { GlobalLog.Assert( false, "NTAuthentication#" + ValidationHelper.HashString(this) + "::VerifySignature", "Argument 'count' out of range."); throw new ArgumentOutOfRangeException("count"); } // setup security buffers for ssp call // one points at signed data // two will receive payload if signature is valid SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(buffer, offset, count, BufferType.Stream); securityBuffer[1] = new SecurityBuffer(0, BufferType.Data); // call SSP function int errorCode = SSPIWrapper.VerifySignature( GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, 0); // throw if error if (errorCode != 0) { GlobalLog.Print( "NTAuthentication#" + ValidationHelper.HashString(this) + "::VerifySignature() threw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo)); throw new Win32Exception(errorCode); } // not sure why this is here - retained from Encrypt code above if (securityBuffer[1].type != BufferType.Data) throw new InternalException(); // return validated payload size return securityBuffer[1].size; } // // MakeSignature // // Adapted from Encrypt method above as a more generic message // signing method for SMTP AUTH GSSAPI (SASL). // Encrypt method, used for NegotiateStream, put size at head of // message. Don't need that // // See SmtpNegotiateAuthenticationModule class for caller. // internal int MakeSignature( byte[] buffer, int offset, int count, ref byte[] output) { SecSizes sizes = Sizes; // alloc new output buffer if not supplied or too small int resultSize = count + sizes.MaxSignature; if (output == null || output.Length < resultSize) { output = new byte[resultSize]; } // make a copy of user data for in-place encryption Buffer.BlockCopy(buffer, offset, output, sizes.MaxSignature, count); // setup security buffers for ssp call SecurityBuffer[] securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(output, 0, sizes.MaxSignature, BufferType.Token); securityBuffer[1] = new SecurityBuffer(output, sizes.MaxSignature, count, BufferType.Data); // call SSP Function int errorCode = SSPIWrapper.MakeSignature( GlobalSSPI.SSPIAuth, m_SecurityContext, securityBuffer, 0); // throw if error if (errorCode != 0) { GlobalLog.Print( "NTAuthentication#" + ValidationHelper.HashString(this) + "::Encrypt() throw Error = " + errorCode.ToString("x", NumberFormatInfo.InvariantInfo)); throw new Win32Exception(errorCode); } // return signed size return securityBuffer[0].size + securityBuffer[1].size; } } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)] internal struct AuthIdentity { // see SEC_WINNT_AUTH_IDENTITY_W internal string UserName; internal int UserNameLength; internal string Domain; internal int DomainLength; internal string Password; internal int PasswordLength; internal int Flags; internal AuthIdentity(string userName, string password, string domain) { UserName = userName; UserNameLength = userName==null ? 0 : userName.Length; Password = password; PasswordLength = password==null ? 0 : password.Length; Domain = domain; DomainLength = domain==null ? 0 : domain.Length; // Flags are 2 for Unicode and 1 for ANSI. We use 2 on NT and 1 on Win9x. Flags = 2; } public override string ToString() { return ValidationHelper.ToString(Domain) + "\\" + ValidationHelper.ToString(UserName); } } #endif }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006 by Hugh Pyle, inguzaudio.com namespace DSPUtil { public interface ISample { ushort NumChannels { get; } double this[int arg] { get; set; } } [Serializable] public struct Sample2 : ISample { double _0; double _1; public Sample2(double a, double b) { _0 = a; _1 = b; } public ushort NumChannels { get { return 2; } } public double this[int arg] { get { return (arg == 0) ? _0 : _1; } set { if (arg == 0) _0 = value; else _1 = value; } } public override bool Equals(object obj) { ISample o = obj as ISample; if (o == null) { return false; } return o.NumChannels == 2 && o[0] == _0 && o[1] == _1; } public override int GetHashCode() { return _0.GetHashCode() ^ _1.GetHashCode(); } } [Serializable] public struct Sample : ISample { // A multi-channel sample value. Each data point is a double-precision float. double[] _value; public Sample(ushort numChannels) { _value = new double[numChannels]; } // Single-channel constructor public Sample(double val) { _value = new double[1]; _value[0] = val; } // Copy constructor public Sample(ISample sample) { ushort nc = sample.NumChannels; _value = new double[nc]; for (int n = 0; n < nc; n++) { _value[n] = sample[n]; } } public Sample(ISample sample, double gain) { ushort nc = sample.NumChannels; _value = new double[nc]; for (int n = 0; n < nc; n++) { _value[n] = sample[n] * gain; } } public ushort NumChannels { get { return (ushort)_value.Length; } } public double this[int arg] { get { return _value[arg]; } set { _value[arg] = value; } } public override bool Equals(object obj) { ISample o = obj as ISample; if (o == null) { return false; } ushort nc = NumChannels; if (o.NumChannels != nc) { return false; } for (int n = 0; n < nc; n++) { if (o[n] != _value[n]) { return false; } } return true; } public override int GetHashCode() { int h = 0; ushort nc = NumChannels; for (int n = 0; n < nc; n++) { h = h ^ _value[n].GetHashCode(); } return h; } public static Sample operator +(Sample c1, Sample c2) { if (c1.NumChannels != c2.NumChannels) { throw new ArgumentException("Samples must have the same number of channels"); } Sample s = new Sample(c1.NumChannels); for (int n = 0; n < c1.NumChannels; n++) { s[n] = c1[n] + c2[n]; } return s; } public static Sample operator -(Sample c1, Sample c2) { if (c1.NumChannels != c2.NumChannels) { throw new ArgumentException("Samples must have the same number of channels"); } Sample s = new Sample(c1.NumChannels); for (int n = 0; n < c1.NumChannels; n++) { s[n] = c1[n] - c2[n]; } return s; } // Multiplication operator (needed for convolution) public static Sample operator *(Sample c1, Sample c2) { ushort nc = c1.NumChannels; if (nc != c2.NumChannels) { throw new ArgumentException("Samples must have the same number of channels"); } Sample s = new Sample(nc); for (int n = 0; n < nc; n++) { s[n] = c1[n] * c2[n]; } return s; } // Multiply by scalar (gain) public static Sample operator *(double gain, Sample c) { ushort nc = c.NumChannels; Sample s = new Sample( nc ); for (int n = 0; n < nc; n++) { s[n] = c[n] * gain; } return s; } } /* [Serializable] public struct ComplexSample : ISample<Complex> { // A multi-channel sample value. Each data point is a double-precision complex number. Complex[] _value; public ComplexSample(ushort numChannels) { _value = new Complex[numChannels]; } // Copy constructor public ComplexSample(Sample sample) { ushort nc = sample.NumChannels; _value = new Complex[nc]; for (int n = 0; n < nc; n++) { _value[n] = new Complex(sample[n],0); } } public ushort NumChannels { get { return (ushort)_value.Length; } } public Complex[] Value { get { return _value; } } public Complex this[int arg] { get { return _value[arg]; } set { _value[arg] = value; } } public static ComplexSample operator +(ComplexSample c1, ComplexSample c2) { if (c1.NumChannels != c2.NumChannels) { throw new ArgumentException("Samples must have the same number of channels"); } ComplexSample s = new ComplexSample(c1.NumChannels); for (int n = 0; n < c1.NumChannels; n++) { s[n] = c1[n] + c2[n]; } return s; } public static ComplexSample operator -(ComplexSample c1, ComplexSample c2) { if (c1.NumChannels != c2.NumChannels) { throw new ArgumentException("Samples must have the same number of channels"); } ComplexSample s = new ComplexSample(c1.NumChannels); for (int n = 0; n < c1.NumChannels; n++) { s[n] = c1[n] - c2[n]; } return s; } // Multiplication operator (needed for convolution) public static ComplexSample operator *(ComplexSample c1, ComplexSample c2) { if (c1.NumChannels != c2.NumChannels) { throw new ArgumentException("Samples must have the same number of channels"); } ComplexSample s = new ComplexSample(c1.NumChannels); for (int n = 0; n < c1.NumChannels; n++) { s[n] = c1[n] * c2[n]; } return s; } // Multiply by scalar (gain) public static ComplexSample operator *(double gain, ComplexSample c) { ComplexSample s = new ComplexSample(c.NumChannels); for (int n = 0; n < c.NumChannels; n++) { s[n] = c[n] * gain; } return s; } } */ }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using Alphaleonis.Win32; using Alphaleonis.Win32.Filesystem; using Alphaleonis.Win32.Network; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.ComponentModel; using System.IO; using System.Linq; using System.Net.NetworkInformation; using Directory = Alphaleonis.Win32.Filesystem.Directory; using DirectoryInfo = Alphaleonis.Win32.Filesystem.DirectoryInfo; using DriveInfo = Alphaleonis.Win32.Filesystem.DriveInfo; using File = Alphaleonis.Win32.Filesystem.File; using FileInfo = Alphaleonis.Win32.Filesystem.FileInfo; using OperatingSystem = Alphaleonis.Win32.OperatingSystem; using Path = Alphaleonis.Win32.Filesystem.Path; namespace AlphaFS.UnitTest { /// <summary>This is a test class for several AlphaFS instance classes.</summary> [TestClass] public partial class AlphaFS_ClassesTest { #region Unit Tests #region DumpClassByHandleFileInfo private void DumpClassByHandleFileInfo(bool isLocal) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPath = Path.GetTempPath("File.GetFileInfoByHandle()-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput File Path: [{0}]", tempPath); FileStream stream = File.Create(tempPath); stream.WriteByte(1); UnitTestConstants.StopWatcher(true); ByHandleFileInfo bhfi = File.GetFileInfoByHandle(stream.SafeFileHandle); Console.WriteLine(UnitTestConstants.Reporter()); Assert.IsTrue(UnitTestConstants.Dump(bhfi, -18)); Assert.AreEqual(System.IO.File.GetCreationTimeUtc(tempPath), bhfi.CreationTimeUtc); Assert.AreEqual(System.IO.File.GetLastAccessTimeUtc(tempPath), bhfi.LastAccessTimeUtc); Assert.AreEqual(System.IO.File.GetLastWriteTimeUtc(tempPath), bhfi.LastWriteTimeUtc); stream.Close(); File.Delete(tempPath, true); Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed."); Console.WriteLine(); } #endregion // DumpClassByHandleFileInfo #region DumpClassDeviceInfo private void DumpClassDeviceInfo(string host) { Console.WriteLine("\n=== TEST ==="); bool allOk = false; try { #region DeviceGuid.Volume Console.Write("\nEnumerating volumes from host: [{0}]\n", host); int cnt = 0; UnitTestConstants.StopWatcher(true); foreach (DeviceInfo device in Device.EnumerateDevices(host, DeviceGuid.Volume)) { Console.WriteLine("\n#{0:000}\tClass: [{1}]", ++cnt, device.Class); UnitTestConstants.Dump(device, -24); try { string getDriveLetter = Volume.GetDriveNameForNtDeviceName(device.PhysicalDeviceObjectName); string dosdeviceGuid = Volume.GetVolumeGuidForNtDeviceName(device.PhysicalDeviceObjectName); Console.WriteLine("\n\tVolume.GetDriveNameForNtDeviceName() : [{0}]", getDriveLetter ?? "null"); Console.WriteLine("\tVolume.GetVolumeGuidForNtDeviceName(): [{0}]", dosdeviceGuid ?? "null"); } catch (Exception ex) { Console.WriteLine("\nCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } } Console.WriteLine(UnitTestConstants.Reporter()); Console.WriteLine(); #endregion // DeviceGuid.Volume #region DeviceGuid.Disk Console.Write("\nEnumerating disks from host: [{0}]\n", host); cnt = 0; UnitTestConstants.StopWatcher(true); foreach (DeviceInfo device in Device.EnumerateDevices(host, DeviceGuid.Disk)) { Console.WriteLine("\n#{0:000}\tClass: [{1}]", ++cnt, device.Class); UnitTestConstants.Dump(device, -24); try { string getDriveLetter = Volume.GetDriveNameForNtDeviceName(device.PhysicalDeviceObjectName); string dosdeviceGuid = Volume.GetVolumeGuidForNtDeviceName(device.PhysicalDeviceObjectName); Console.WriteLine("\n\tVolume.GetDriveNameForNtDeviceName() : [{0}]", getDriveLetter ?? "null"); Console.WriteLine("\tVolume.GetVolumeGuidForNtDeviceName(): [{0}]", dosdeviceGuid ?? "null"); } catch (Exception ex) { Console.WriteLine("\nCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } } Console.WriteLine(UnitTestConstants.Reporter()); #endregion // DeviceGuid.Disk allOk = true; } catch (Exception ex) { Console.WriteLine("\tCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(allOk, "Could (probably) not connect to host: [{0}]", host); Console.WriteLine(); } #endregion // DumpClassDeviceInfo #region DumpClassDirectoryInfo private void DumpClassDirectoryInfo(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPath = Path.Combine(Path.GetTempPath(), "DirectoryInfo()-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); int expectedLastError; string expectedException; string nonExistingDirectory = UnitTestConstants.SysRoot32 + @"\NonExistingDirectory-" + Path.GetRandomFileName(); if (!isLocal) nonExistingDirectory = Path.LocalToUnc(nonExistingDirectory); string sysDrive = UnitTestConstants.SysDrive; if (!isLocal) sysDrive = Path.LocalToUnc(sysDrive); string sysRoot = UnitTestConstants.SysRoot; if (!isLocal) sysRoot = Path.LocalToUnc(sysRoot); string letter = DriveInfo.GetFreeDriveLetter() + @":\"; if (!isLocal) letter = Path.LocalToUnc(letter); #endregion // Setup #region NotSupportedException expectedLastError = (int) (isLocal ? Win32Errors.ERROR_ENVVAR_NOT_FOUND : Win32Errors.NERR_UseNotFound); expectedException = "System.NotSupportedException"; bool exception = false; try { Console.WriteLine("\nCatch: [{0}]: The given path's format is not supported.", expectedException); string invalidPath = UnitTestConstants.SysDrive + @"\:a"; if (!isLocal) invalidPath = Path.LocalToUnc(invalidPath) + @":a"; DirectoryInfo di = new DirectoryInfo(invalidPath); } catch (Exception ex) { // Not reliable. //var win32Error = new Win32Exception("", ex); //Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); //Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // NotSupportedException #region Current Directory tempPath = Path.CurrentDirectoryPrefix; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Directory Path (Current directory): [{0}]\n", tempPath); UnitTestConstants.StopWatcher(true); System.IO.DirectoryInfo expected = new System.IO.DirectoryInfo(tempPath); Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", UnitTestConstants.Reporter()); UnitTestConstants.StopWatcher(true); DirectoryInfo actual = new DirectoryInfo(tempPath); Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", UnitTestConstants.Reporter()); // Compare values of both instances. CompareDirectoryInfos(expected, actual); #endregion // Current Directory #region Non-Existing Directory Console.WriteLine("\nInput Directory Path: [{0}]\n", nonExistingDirectory); UnitTestConstants.StopWatcher(true); expected = new System.IO.DirectoryInfo(tempPath); Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", UnitTestConstants.Reporter()); UnitTestConstants.StopWatcher(true); actual = new DirectoryInfo(tempPath); Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", UnitTestConstants.Reporter()); // Compare values of both instances. CompareDirectoryInfos(expected, actual); #endregion // Non-Existing Directory #region Existing Directory tempPath = Path.Combine(Path.GetTempPath(), "DirectoryInfo()-Directory-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); try { Directory.CreateDirectory(tempPath); Console.WriteLine("\n\nInput Directory Path: [{0}]\n", tempPath); UnitTestConstants.StopWatcher(true); expected = new System.IO.DirectoryInfo(tempPath); Console.WriteLine("\tSystem.IO DirectoryInfo(){0}", UnitTestConstants.Reporter()); UnitTestConstants.StopWatcher(true); actual = new DirectoryInfo(tempPath); Console.WriteLine("\tAlphaFS DirectoryInfo(){0}", UnitTestConstants.Reporter()); // Compare values of both instances. CompareDirectoryInfos(expected, actual); } finally { if (Directory.Exists(tempPath)) Directory.Delete(tempPath); Assert.IsFalse(Directory.Exists(tempPath), "Cleanup failed: Directory should have been removed."); } #endregion // Existing Directory #region Method .ToString() Console.WriteLine("\nMethod .ToString()"); Console.WriteLine("Both strings should be the same.\n"); expected = new System.IO.DirectoryInfo("ToString()-TestDirectory"); actual = new DirectoryInfo("ToString()-TestDirectory"); string expectedToString = expected.ToString(); string actualToString = actual.ToString(); Console.WriteLine("\tSystem.IO: [{0}]", expectedToString); Console.WriteLine("\tAlphaFS : [{0}]", actualToString); Assert.AreEqual(expectedToString, actualToString, false); Console.WriteLine(); #endregion Method .ToString() } private void CompareDirectoryInfos(System.IO.DirectoryInfo expected, DirectoryInfo actual) { if (expected == null || actual == null) Assert.AreEqual(expected, actual, "Mismatch"); UnitTestConstants.Dump(expected, -17); UnitTestConstants.Dump(actual, -17); int errorCnt = 0; int cnt = -1; while (cnt != 13) { cnt++; if (expected == null || actual == null) Assert.AreEqual(expected, actual, "One or both of the DirectoryInfo instances is/are null."); else { try { // Compare values of both instances. switch (cnt) { case 0: Assert.AreEqual(expected.Attributes, actual.Attributes, "Attributes AlphaFS != System.IO"); break; case 1: Assert.AreEqual(expected.CreationTime, actual.CreationTime, "CreationTime AlphaFS != System.IO"); break; case 2: Assert.AreEqual(expected.CreationTimeUtc, actual.CreationTimeUtc, "CreationTimeUtc AlphaFS != System.IO"); break; case 3: Assert.AreEqual(expected.Exists, actual.Exists, "Exists AlphaFS != System.IO"); break; case 4: Assert.AreEqual(expected.Extension, actual.Extension, "Extension AlphaFS != System.IO"); break; case 5: Assert.AreEqual(expected.FullName, actual.FullName, "FullName AlphaFS != System.IO"); break; case 6: Assert.AreEqual(expected.LastAccessTime, actual.LastAccessTime, "LastAccessTime AlphaFS != System.IO"); break; case 7: Assert.AreEqual(expected.LastAccessTimeUtc, actual.LastAccessTimeUtc, "LastAccessTimeUtc AlphaFS != System.IO"); break; case 8: Assert.AreEqual(expected.LastWriteTime, actual.LastWriteTime, "LastWriteTime AlphaFS != System.IO"); break; case 9: Assert.AreEqual(expected.LastWriteTimeUtc, actual.LastWriteTimeUtc, "LastWriteTimeUtc AlphaFS != System.IO"); break; case 10: Assert.AreEqual(expected.Name, actual.Name, "Name AlphaFS != System.IO"); break; // Need .ToString() here since the object types are obviously not the same. case 11: Assert.AreEqual(expected.Parent.ToString(), actual.Parent.ToString(), "Parent AlphaFS != System.IO"); break; case 12: Assert.AreEqual(expected.Root.ToString(), actual.Root.ToString(), "Root AlphaFS != System.IO"); break; } } catch (Exception ex) { errorCnt++; Console.WriteLine("\n\t\tProperty cnt #{0}\tCaught {1}: [{2}]", (cnt + 1), ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } } } //Assert.IsTrue(errorCnt == 0, "\tEncountered: [{0}] DirectoryInfo Properties where AlphaFS != System.IO", errorCnt); Console.WriteLine(); } #endregion // DumpClassDirectoryInfo #region DumpClassDiskSpaceInfo private void DumpClassDiskSpaceInfo(bool isLocal) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPath = UnitTestConstants.SysDrive; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput Path: [{0}]", tempPath); int cnt = 0; int errorCount = 0; // Get only .IsReady drives. foreach (var drv in Directory.EnumerateLogicalDrives(false, true)) { if (drv.DriveType == DriveType.NoRootDirectory) continue; string drive = isLocal ? drv.Name : Path.LocalToUnc(drv.Name); UnitTestConstants.StopWatcher(true); try { // null (default) == All information. DiskSpaceInfo dsi = drv.DiskSpaceInfo; string report = UnitTestConstants.Reporter(true); Console.WriteLine("\n#{0:000}\tInput Path: [{1}]{2}", ++cnt, drive, report); Assert.IsTrue(UnitTestConstants.Dump(dsi, -26)); Assert.AreNotEqual((int) 0, (int) dsi.BytesPerSector); Assert.AreNotEqual((int) 0, (int) dsi.SectorsPerCluster); Assert.AreNotEqual((int) 0, (int) dsi.TotalNumberOfClusters); Assert.AreNotEqual((int) 0, (int) dsi.TotalNumberOfBytes); if (drv.DriveType == DriveType.CDRom) { Assert.AreEqual((int) 0, (int) dsi.FreeBytesAvailable); Assert.AreEqual((int) 0, (int) dsi.NumberOfFreeClusters); Assert.AreEqual((int) 0, (int) dsi.TotalNumberOfFreeBytes); } else { Assert.AreNotEqual((int) 0, (int) dsi.FreeBytesAvailable); Assert.AreNotEqual((int) 0, (int) dsi.NumberOfFreeClusters); Assert.AreNotEqual((int) 0, (int) dsi.TotalNumberOfFreeBytes); } // false == Size information only. dsi = Volume.GetDiskFreeSpace(drive, false); Assert.AreEqual((int)0, (int)dsi.BytesPerSector); Assert.AreEqual((int)0, (int)dsi.NumberOfFreeClusters); Assert.AreEqual((int)0, (int)dsi.SectorsPerCluster); Assert.AreEqual((int)0, (int)dsi.TotalNumberOfClusters); // true == Cluster information only. dsi = Volume.GetDiskFreeSpace(drive, true); Assert.AreEqual((int)0, (int)dsi.FreeBytesAvailable); Assert.AreEqual((int)0, (int)dsi.TotalNumberOfBytes); Assert.AreEqual((int)0, (int)dsi.TotalNumberOfFreeBytes); } catch (Exception ex) { Console.WriteLine("\n\nCaught (unexpected) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); errorCount++; } } if (cnt == 0) Assert.Inconclusive("Nothing was enumerated."); Assert.AreEqual(0, errorCount, "No errors were expected."); Console.WriteLine(); } #endregion // DumpClassDiskSpaceInfo #region DumpClassDriveInfo private void DumpClassDriveInfo(bool isLocal, string drive) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPath = drive; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); UnitTestConstants.StopWatcher(true); DriveInfo actual = new DriveInfo(tempPath); Console.WriteLine("\nInput Path: [{0}]{1}", tempPath, UnitTestConstants.Reporter()); #region UnitTestConstants.Local Drive if (isLocal) { // System.IO.DriveInfo() can not handle UNC paths. System.IO.DriveInfo expected = new System.IO.DriveInfo(tempPath); //Dump(expected, -21); // Even 1 byte more or less results in failure, so do these tests asap. Assert.AreEqual(expected.AvailableFreeSpace, actual.AvailableFreeSpace, "AvailableFreeSpace AlphaFS != System.IO"); Assert.AreEqual(expected.TotalFreeSpace, actual.TotalFreeSpace, "TotalFreeSpace AlphaFS != System.IO"); Assert.AreEqual(expected.TotalSize, actual.TotalSize, "TotalSize AlphaFS != System.IO"); Assert.AreEqual(expected.DriveFormat, actual.DriveFormat, "DriveFormat AlphaFS != System.IO"); Assert.AreEqual(expected.DriveType, actual.DriveType, "DriveType AlphaFS != System.IO"); Assert.AreEqual(expected.IsReady, actual.IsReady, "IsReady AlphaFS != System.IO"); Assert.AreEqual(expected.Name, actual.Name, "Name AlphaFS != System.IO"); Assert.AreEqual(expected.RootDirectory.ToString(), actual.RootDirectory.ToString(), "RootDirectory AlphaFS != System.IO"); Assert.AreEqual(expected.VolumeLabel, actual.VolumeLabel, "VolumeLabel AlphaFS != System.IO"); } #region Class Equality ////int getHashCode1 = actual.GetHashCode(); //DriveInfo driveInfo2 = new DriveInfo(tempPath); ////int getHashCode2 = driveInfo2.GetHashCode(); //DriveInfo clone = actual; ////int getHashCode3 = clone.GetHashCode(); //bool isTrue1 = clone.Equals(actual); //bool isTrue2 = clone == actual; //bool isTrue3 = !(clone != actual); //bool isTrue4 = actual == driveInfo2; //bool isTrue5 = !(actual != driveInfo2); ////Console.WriteLine("\n\t\t actual.GetHashCode() : [{0}]", getHashCode1); ////Console.WriteLine("\t\t clone.GetHashCode() : [{0}]", getHashCode3); ////Console.WriteLine("\t\tdriveInfo2.GetHashCode() : [{0}]\n", getHashCode2); ////Console.WriteLine("\t\t obj clone.ToString() == [{0}]", clone.ToString()); ////Console.WriteLine("\t\t obj clone.Equals() == [{0}] : {1}", TextTrue, isTrue1); ////Console.WriteLine("\t\t obj clone == == [{0}] : {1}", TextTrue, isTrue2); ////Console.WriteLine("\t\t obj clone != == [{0}]: {1}\n", TextFalse, isTrue3); ////Console.WriteLine("\t\tdriveInfo == driveInfo2 == [{0}] : {1}", TextTrue, isTrue4); ////Console.WriteLine("\t\tdriveInfo != driveInfo2 == [{0}] : {1}", TextFalse, isTrue5); //Assert.IsTrue(isTrue1, "clone.Equals(actual)"); //Assert.IsTrue(isTrue2, "clone == actual"); //Assert.IsTrue(isTrue3, "!(clone != actual)"); //Assert.IsTrue(isTrue4, "actual == driveInfo2"); //Assert.IsTrue(isTrue5, "!(actual != driveInfo2)"); #endregion // Class Equality #endregion // UnitTestConstants.Local Drive UnitTestConstants.StopWatcher(true); UnitTestConstants.Dump(actual, -21); UnitTestConstants.Dump(actual.DiskSpaceInfo, -26); //if (expected != null) Dump(expected.RootDirectory, -17); //Dump(actual.RootDirectory, -17); UnitTestConstants.Dump(actual.VolumeInfo, -26); Console.WriteLine(UnitTestConstants.Reporter()); Console.WriteLine(); } #endregion // DumpClassDriveInfo #region DumpClassFileInfo private void DumpClassFileInfo(bool isLocal) { #region Setup Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPath = Path.Combine(Path.GetTempPath(), "FileInfo()-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); int expectedLastError; string expectedException; string nonExistingFile = UnitTestConstants.SysRoot32 + @"\NonExistingFile-" + Path.GetRandomFileName(); if (!isLocal) nonExistingFile = Path.LocalToUnc(nonExistingFile); string sysDrive = UnitTestConstants.SysDrive; if (!isLocal) sysDrive = Path.LocalToUnc(sysDrive); string sysRoot = UnitTestConstants.SysRoot; if (!isLocal) sysRoot = Path.LocalToUnc(sysRoot); string letter = DriveInfo.GetFreeDriveLetter() + @":\"; if (!isLocal) letter = Path.LocalToUnc(letter); #endregion // Setup #region NotSupportedException expectedLastError = (int) (isLocal ? Win32Errors.ERROR_ENVVAR_NOT_FOUND : Win32Errors.NERR_UseNotFound); expectedException = "System.NotSupportedException"; bool exception = false; try { Console.WriteLine("\nCatch: [{0}]: The given path's format is not supported.", expectedException); string invalidPath = UnitTestConstants.SysDrive + @"\:a"; if (!isLocal) invalidPath = Path.LocalToUnc(invalidPath) + @":a"; FileInfo fi = new FileInfo(invalidPath); } catch (Exception ex) { // Not reliable. //var win32Error = new Win32Exception("", ex); //Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); //Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // NotSupportedException #region Length Property #region FileNotFoundException #1 expectedLastError = (int) Win32Errors.ERROR_FILE_NOT_FOUND; expectedException = "System.IO.FileNotFoundException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Length property is called, the file does not exist.", expectedException); Console.WriteLine(new FileInfo(nonExistingFile).Length); } catch (Exception ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // FileNotFoundException #1 #region FileNotFoundException #2 expectedLastError = (int) (isLocal ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_BAD_NET_NAME); expectedException = isLocal ? "System.IO.FileNotFoundException" : "System.IO.IOException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Length property is called, the file does not exist (Unmapped drive).", expectedException); Console.WriteLine(new FileInfo(nonExistingFile.Replace(sysDrive + @"\", letter)).Length); } catch (Exception ex) { var win32Error = new Win32Exception("", ex); Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); //Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // FileNotFoundException #1 #region FileNotFoundException #3 expectedLastError = (int) Win32Errors.ERROR_FILE_NOT_FOUND; expectedException = "System.IO.FileNotFoundException"; exception = false; try { Console.WriteLine("\nCatch: [{0}]: Length property is called, the file is a directory.", expectedException); Console.WriteLine(new FileInfo(sysRoot).Length); } catch (Exception ex) { // win32Error is always 0 //var win32Error = new Win32Exception("", ex); //Assert.IsTrue(win32Error.NativeErrorCode == expectedLastError, string.Format("Expected Win32Exception error should be: [{0}], got: [{1}]", expectedLastError, win32Error.NativeErrorCode)); Assert.IsTrue(ex.Message.StartsWith("(" + expectedLastError + ")"), string.Format("Expected Win32Exception error is: [{0}]", expectedLastError)); string exceptionTypeName = ex.GetType().FullName; if (exceptionTypeName.Equals(expectedException)) { exception = true; Console.WriteLine("\n\t[{0}]: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } else Console.WriteLine("\n\tCaught (unexpected) {0}: [{1}]", exceptionTypeName, ex.Message.Replace(Environment.NewLine, " ")); } Assert.IsTrue(exception, "[{0}] should have been caught.", expectedException); Console.WriteLine(); #endregion // FileNotFoundException #3 #endregion // Length Property #region Current Directory tempPath = Path.CurrentDirectoryPrefix; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput File Path (Current directory): [{0}]\n", tempPath); UnitTestConstants.StopWatcher(true); System.IO.FileInfo expected = new System.IO.FileInfo(tempPath); Console.WriteLine("\tSystem.IO FileInfo(){0}", UnitTestConstants.Reporter()); UnitTestConstants.StopWatcher(true); FileInfo actual = new FileInfo(tempPath); Console.WriteLine("\tAlphaFS FileInfo(){0}", UnitTestConstants.Reporter()); // Compare values of both instances. CompareFileInfos(expected, actual); #endregion // Current Directory #region Non-Existing File Console.WriteLine("\nInput File Path: [{0}]\n", nonExistingFile); UnitTestConstants.StopWatcher(true); expected = new System.IO.FileInfo(nonExistingFile); Console.WriteLine("\tSystem.IO FileInfo(){0}", UnitTestConstants.Reporter()); UnitTestConstants.StopWatcher(true); actual = new FileInfo(nonExistingFile); Console.WriteLine("\tAlphaFS FileInfo(){0}", UnitTestConstants.Reporter()); // Compare values of both instances. CompareFileInfos(expected, actual); #endregion // Non-Existing File #region Existing File tempPath = Path.Combine(Path.GetTempPath(), "FileInfo()-File-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); try { using (File.Create(tempPath)) {} Console.WriteLine("\nInput File Path: [{0}]\n", tempPath); UnitTestConstants.StopWatcher(true); expected = new System.IO.FileInfo(tempPath); Console.WriteLine("\tSystem.IO FileInfo(){0}", UnitTestConstants.Reporter()); UnitTestConstants.StopWatcher(true); actual = new FileInfo(tempPath); Console.WriteLine("\tAlphaFS FileInfo(){0}", UnitTestConstants.Reporter()); // Compare values of both instances. CompareFileInfos(expected, actual); } finally { File.Delete(tempPath); Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed."); } #endregion // Existing File #region Method .ToString() Console.WriteLine("\nMethod .ToString()"); Console.WriteLine("Both strings should be the same.\n"); expected = new System.IO.FileInfo("ToString()-TestFile"); actual = new FileInfo("ToString()-TestFile"); string expectedToString = expected.ToString(); string actualToString = actual.ToString(); Console.WriteLine("\tSystem.IO: [{0}]", expectedToString); Console.WriteLine("\tAlphaFS : [{0}]", actualToString); Assert.AreEqual(expectedToString, actualToString, false); Console.WriteLine(); #endregion Method .ToString() } private void CompareFileInfos(System.IO.FileInfo expected, FileInfo actual) { if (expected == null || actual == null) Assert.AreEqual(expected, actual, "Mismatch"); UnitTestConstants.Dump(expected, -17); UnitTestConstants.Dump(actual, -17); int errorCnt = 0; int cnt = -1; while (cnt != 15) { cnt++; try { // Compare values of both instances. switch (cnt) { case 0: Assert.AreEqual(expected.Attributes, actual.Attributes, "Attributes AlphaFS != System.IO"); break; case 1: Assert.AreEqual(expected.CreationTime, actual.CreationTime, "CreationTime AlphaFS != System.IO"); break; case 2: Assert.AreEqual(expected.CreationTimeUtc, actual.CreationTimeUtc, "CreationTimeUtc AlphaFS != System.IO"); break; // Need .ToString() here since the object types are obviously not the same. case 3: Assert.AreEqual(expected.Directory.ToString(), actual.Directory.ToString(), "Directory AlphaFS != System.IO"); break; case 4: Assert.AreEqual(expected.DirectoryName, actual.DirectoryName, "DirectoryName AlphaFS != System.IO"); break; case 5: Assert.AreEqual(expected.Exists, actual.Exists, "Exists AlphaFS != System.IO"); break; case 6: Assert.AreEqual(expected.Extension, actual.Extension, "Extension AlphaFS != System.IO"); break; case 7: Assert.AreEqual(expected.FullName, actual.FullName, "FullName AlphaFS != System.IO"); break; case 8: Assert.AreEqual(expected.IsReadOnly, actual.IsReadOnly, "IsReadOnly AlphaFS != System.IO"); break; case 9: Assert.AreEqual(expected.LastAccessTime, actual.LastAccessTime, "LastAccessTime AlphaFS != System.IO"); break; case 10: Assert.AreEqual(expected.LastAccessTimeUtc, actual.LastAccessTimeUtc, "LastAccessTimeUtc AlphaFS != System.IO"); break; case 11: Assert.AreEqual(expected.LastWriteTime, actual.LastWriteTime, "LastWriteTime AlphaFS != System.IO"); break; case 12: Assert.AreEqual(expected.LastWriteTimeUtc, actual.LastWriteTimeUtc, "LastWriteTimeUtc AlphaFS != System.IO"); break; case 13: Assert.AreEqual(expected.Length, actual.Length, "Length AlphaFS != System.IO"); break; case 14: Assert.AreEqual(expected.Name, actual.Name, "Name AlphaFS != System.IO"); break; } } catch (Exception ex) { errorCnt++; Console.WriteLine("\n\t\t\tProperty cnt #{0}\tCaught {1}: [{2}]", (cnt + 1), ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } } //Assert.IsTrue(errorCnt == 0, "\tEncountered: [{0}] FileInfo Properties where AlphaFS != System.IO", errorCnt); Console.WriteLine(); } #endregion // DumpClassFileInfo #region DumpClassFileSystemEntryInfo private void DumpClassFileSystemEntryInfo(bool isLocal) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); Console.WriteLine("\nThe return type is based on C# inference. Possible return types are:"); Console.WriteLine("string (full path), FileSystemInfo (DiskInfo / FileInfo) or FileSystemEntryInfo instance.\n"); #region Directory string path = UnitTestConstants.SysRoot; if (!isLocal) path = Path.LocalToUnc(path); Console.WriteLine("\nInput Directory Path: [{0}]", path); Console.WriteLine("\n\nvar fsei = Directory.GetFileSystemEntry(path);"); var asFileSystemEntryInfo = File.GetFileSystemEntryInfo(path); Assert.IsTrue((asFileSystemEntryInfo.GetType().IsEquivalentTo(typeof(FileSystemEntryInfo)))); Assert.IsTrue(UnitTestConstants.Dump(asFileSystemEntryInfo, -17)); Console.WriteLine(); #endregion // Directory #region File path = UnitTestConstants.NotepadExe; if (!isLocal) path = Path.LocalToUnc(path); Console.WriteLine("\nInput File Path: [{0}]", path); Console.WriteLine("\n\nvar fsei = File.GetFileSystemEntry(path);"); asFileSystemEntryInfo = File.GetFileSystemEntryInfo(path); Assert.IsTrue((asFileSystemEntryInfo.GetType().IsEquivalentTo(typeof(FileSystemEntryInfo)))); Assert.IsTrue(UnitTestConstants.Dump(asFileSystemEntryInfo, -17)); Console.WriteLine(); #endregion // File } #endregion // DumpClassFileSystemEntryInfo #region DumpClassShell32Info private void DumpClassShell32Info(bool isLocal) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); string tempPath = Path.GetTempPath("Class.Shell32Info()-" + Path.GetRandomFileName()); if (!isLocal) tempPath = Path.LocalToUnc(tempPath); Console.WriteLine("\nInput File Path: [{0}]\n", tempPath); using (File.Create(tempPath)) {} UnitTestConstants.StopWatcher(true); Shell32Info shell32Info = Shell32.GetShell32Info(tempPath); string report = UnitTestConstants.Reporter(); Console.WriteLine("\tMethod: Shell32Info.Refresh()"); Console.WriteLine("\tMethod: Shell32Info.GetIcon()"); string cmd = "print"; Console.WriteLine("\tMethod: Shell32Info.GetVerbCommand(\"{0}\") == [{1}]", cmd, shell32Info.GetVerbCommand(cmd)); Assert.IsTrue(UnitTestConstants.Dump(shell32Info, -15)); File.Delete(tempPath, true); Assert.IsFalse(File.Exists(tempPath), "Cleanup failed: File should have been removed."); Console.WriteLine("\n{0}", report); Console.WriteLine(); } #endregion // DumpClassShell32Info #region DumpClassVolumeInfo private void DumpClassVolumeInfo(bool isLocal) { Console.WriteLine("\n=== TEST {0} ===", isLocal ? UnitTestConstants.Local : UnitTestConstants.Network); Console.WriteLine("\nEnumerating logical drives."); int cnt = 0; foreach (string drive in Directory.GetLogicalDrives()) { string tempPath = drive; if (!isLocal) tempPath = Path.LocalToUnc(tempPath); UnitTestConstants.StopWatcher(true); try { VolumeInfo volInfo = Volume.GetVolumeInfo(tempPath); Console.WriteLine("\n#{0:000}\tLogical Drive: [{1}]", ++cnt, tempPath); UnitTestConstants.Dump(volInfo, -26); } catch (Exception ex) { Console.WriteLine("#{0:000}\tLogical Drive: [{1}]\n\tCaught: {2}: {3}", ++cnt, tempPath, ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Console.WriteLine(); } if (cnt == 0) Assert.Inconclusive("Nothing was enumerated."); Console.WriteLine(); } #endregion // DumpClassVolumeInfo #region DumpClassDfsInfo private void DumpClassDfsInfo() { int cnt = 0; bool noDomainConnection = true; UnitTestConstants.StopWatcher(true); try { foreach (string dfsNamespace in Host.EnumerateDomainDfsRoot()) { noDomainConnection = false; try { Console.Write("\n#{0:000}\tDFS Root: [{1}]\n", ++cnt, dfsNamespace); DfsInfo dfsInfo = Host.GetDfsInfo(dfsNamespace); UnitTestConstants.Dump(dfsInfo, -21); Console.Write("\n\tNumber of Storages: [{0}]\n", dfsInfo.StorageInfoCollection.Count()); foreach (DfsStorageInfo store in dfsInfo.StorageInfoCollection) UnitTestConstants.Dump(store, -19); Console.WriteLine(); } catch (NetworkInformationException ex) { Console.WriteLine("\n\tNetworkInformationException #1: [{0}]", ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\t(1) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } } Console.Write("\n{0}", UnitTestConstants.Reporter()); if (cnt == 0) Assert.Inconclusive("Nothing was enumerated."); } catch (NetworkInformationException ex) { Console.WriteLine("\n\tNetworkInformationException #2: [{0}]", ex.Message.Replace(Environment.NewLine, " ")); } catch (Exception ex) { Console.WriteLine("\n\t(2) {0}: [{1}]", ex.GetType().FullName, ex.Message.Replace(Environment.NewLine, " ")); } Console.WriteLine("\n\n\t{0}", UnitTestConstants.Reporter(true)); if (noDomainConnection) Assert.Inconclusive("Test ignored because the computer is probably not connected to a domain."); if (cnt == 0) Assert.Inconclusive("Nothing was enumerated."); Console.WriteLine(); } #endregion // DumpClassDfsInfo #region DumpOpenConnectionInfo private void DumpOpenConnectionInfo(string host) { Console.WriteLine("\n=== TEST ==="); Console.WriteLine("\nNetwork.Host.EnumerateOpenResources() from host: [{0}]", host); UnitTestConstants.StopWatcher(true); foreach (OpenConnectionInfo connectionInfo in Host.EnumerateOpenConnections(host, "IPC$", false)) UnitTestConstants.Dump(connectionInfo, -16); Console.WriteLine(UnitTestConstants.Reporter(true)); Console.WriteLine(); } #endregion // DumpClassOpenResourceInfo #region DumpClassOpenResourceInfo private void DumpClassOpenResourceInfo(string host, string share) { Console.WriteLine("\n=== TEST ==="); string tempPath = Path.LocalToUnc(share); Console.WriteLine("\nNetwork.Host.EnumerateOpenResources() from host: [{0}]", tempPath); Directory.SetCurrentDirectory(tempPath); UnitTestConstants.StopWatcher(true); int cnt = 0; foreach (OpenResourceInfo openResource in Host.EnumerateOpenResources(host, null, null, false)) { if (UnitTestConstants.Dump(openResource, -11)) { Console.Write("\n"); cnt++; } } Console.WriteLine(UnitTestConstants.Reporter()); if (cnt == 0) Assert.Inconclusive("Nothing was enumerated."); Console.WriteLine(); } #endregion // DumpClassOpenResourceInfo #region DumpClassShareInfo #endregion // DumpClassShareInfo #endregion // Unit Tests #region Unit Test Callers #region Filesystem #region Filesystem_Class_ByHandleFileInfo [TestMethod] public void Filesystem_Class_ByHandleFileInfo() { Console.WriteLine("Class Filesystem.ByHandleFileInfo()"); DumpClassByHandleFileInfo(true); DumpClassByHandleFileInfo(false); } #endregion // Filesystem_Class_ByHandleFileInfo #region Filesystem_Class_DeviceInfo [TestMethod] public void Filesystem_Class_DeviceInfo() { Console.WriteLine("Class Filesystem.DeviceInfo()"); Console.WriteLine("\nMSDN Note: Beginning in Windows 8 and Windows Server 2012 functionality to access remote machines has been removed."); Console.WriteLine("You cannot access remote machines when running on these versions of Windows.\n"); DumpClassDeviceInfo(UnitTestConstants.LocalHost); } #endregion // Filesystem_Class_Shell32Info #region Filesystem_Class_DirectoryInfo [TestMethod] public void Filesystem_Class_DirectoryInfo() { Console.WriteLine("Class Filesystem.DirectoryInfo()"); DumpClassDirectoryInfo(true); DumpClassDirectoryInfo(false); } #endregion // Filesystem_Class_DirectoryInfo #region Filesystem_Class_DiskSpaceInfo [TestMethod] public void Filesystem_Class_DiskSpaceInfo() { Console.WriteLine("Class Filesystem.DiskSpaceInfo()"); DumpClassDiskSpaceInfo(true); DumpClassDiskSpaceInfo(false); } #endregion // Filesystem_Class_DiskSpaceInfo #region Filesystem_Class_DriveInfo [TestMethod] public void Filesystem_Class_DriveInfo() { Console.WriteLine("Class Filesystem.DriveInfo()"); DumpClassDriveInfo(true, UnitTestConstants.SysDrive); DumpClassDriveInfo(false, UnitTestConstants.SysDrive); } #endregion // Filesystem_Class_DriveInfo #region Filesystem_Class_FileInfo [TestMethod] public void Filesystem_Class_FileInfo() { Console.WriteLine("Class Filesystem.FileInfo()"); DumpClassFileInfo(true); DumpClassFileInfo(false); } #endregion // Filesystem_Class_FileInfo #region Filesystem_Class_FileSystemEntryInfo [TestMethod] public void Filesystem_Class_FileSystemEntryInfo() { Console.WriteLine("Class Filesystem.FileSystemEntryInfo()"); DumpClassFileSystemEntryInfo(true); DumpClassFileSystemEntryInfo(false); } #endregion // Filesystem_Class_FileSystemEntryInfo #region Filesystem_Class_Shell32Info [TestMethod] public void Filesystem_Class_Shell32Info() { Console.WriteLine("Class Filesystem.Shell32Info()"); DumpClassShell32Info(true); DumpClassShell32Info(false); } #endregion // Filesystem_Class_Shell32Info #region Filesystem_Class_VolumeInfo [TestMethod] public void Filesystem_Class_VolumeInfo() { Console.WriteLine("Class Filesystem.VolumeInfo()"); DumpClassVolumeInfo(true); DumpClassVolumeInfo(false); } #endregion // Filesystem_Class_VolumeInfo #endregion Filesystem #region Network #region Network_Class_DfsXxx [TestMethod] public void Network_Class_DfsXxx() { Console.WriteLine("Class Network.DfsInfo()"); Console.WriteLine("Class Network.DfsStorageInfo()"); DumpClassDfsInfo(); } #endregion // Network_Class_DfsXxx #region Network_Class_OpenConnectionInfo [TestMethod] public void Network_Class_OpenConnectionInfo() { Console.WriteLine("Class Network.OpenConnectionInfo()"); if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); DumpOpenConnectionInfo(UnitTestConstants.LocalHost); } #endregion // Network_Class_OpenConnectionInfo #region Network_Class_OpenResourceInfo [TestMethod] public void Network_Class_OpenResourceInfo() { Console.WriteLine("Class Network.OpenResourceInfo()"); if (!UnitTestConstants.IsAdmin()) Assert.Inconclusive(); DumpClassOpenResourceInfo(UnitTestConstants.LocalHost, UnitTestConstants.LocalHostShare); } #endregion // Network_Class_OpenResourceInfo #region Network_Class_ShareInfo [TestMethod] public void Network_Class_ShareInfo() { Console.WriteLine("Class Network.ShareInfo()"); string host = UnitTestConstants.LocalHost; Console.WriteLine("\n=== TEST ==="); Console.Write("\nNetwork.Host.EnumerateShares() from host: [{0}]\n", host); int cnt = 0; UnitTestConstants.StopWatcher(true); foreach (ShareInfo share in Host.EnumerateShares(host, true)) { Console.WriteLine("\n\t#{0:000}\tShare: [{1}]", ++cnt, share); UnitTestConstants.Dump(share, -18); } Console.WriteLine("\n{0}", UnitTestConstants.Reporter(true)); if (cnt == 0) Assert.Inconclusive("Nothing was enumerated."); } #endregion // Network_Class_ShareInfo #endregion // Network #region OperatingSystem #region Class_OperatingSystem [TestMethod] public void Class_OperatingSystem() { Console.WriteLine("Class Win32.OperatingSystem()\n"); UnitTestConstants.StopWatcher(true); Console.WriteLine("VersionName : [{0}]", OperatingSystem.VersionName); Console.WriteLine("OsVersion : [{0}]", OperatingSystem.OSVersion); Console.WriteLine("ServicePackVersion : [{0}]", OperatingSystem.ServicePackVersion); Console.WriteLine("IsServer : [{0}]", OperatingSystem.IsServer); Console.WriteLine("IsWow64Process : [{0}]", OperatingSystem.IsWow64Process); Console.WriteLine("ProcessorArchitecture: [{0}]", OperatingSystem.ProcessorArchitecture); Console.WriteLine("\nOperatingSystem.IsAtLeast()\n"); Console.WriteLine("\tOS Earlier : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Earlier)); Console.WriteLine("\tWindows 2000 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows2000)); Console.WriteLine("\tWindows XP : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsXP)); Console.WriteLine("\tWindows Vista : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsVista)); Console.WriteLine("\tWindows 7 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows7)); Console.WriteLine("\tWindows 8 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows8)); Console.WriteLine("\tWindows 8.1 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows81)); Console.WriteLine("\tWindows 10 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Windows10)); Console.WriteLine("\tWindows Server 2003 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsServer2003)); Console.WriteLine("\tWindows Server 2008 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsServer2008)); Console.WriteLine("\tWindows Server 2008R2: [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsServer2008R2)); Console.WriteLine("\tWindows Server 2012 : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsServer2012)); Console.WriteLine("\tWindows Server 2012R2: [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsServer2012R2)); Console.WriteLine("\tWindows Server : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.WindowsServer)); Console.WriteLine("\tOS Later : [{0}]", OperatingSystem.IsAtLeast(OperatingSystem.EnumOsName.Later)); Console.WriteLine(); Console.WriteLine(UnitTestConstants.Reporter()); } #endregion // Class_OperatingSystem #endregion // OperatingSystem #endregion Unit Test Callers } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using ESRI.ArcGIS.Geometry; using System; namespace MultiPatchExamples { public static class CompositeExamples { private static object _missing = Type.Missing; public static IGeometry GetExample1() { //Composite: Multiple, Disjoint Geometries Contained Within A Single MultiPatch IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Vector3D Example 2 IGeometry vector3DExample2Geometry = Vector3DExamples.GetExample2(); ITransform3D vector3DExample2Transform3D = vector3DExample2Geometry as ITransform3D; vector3DExample2Transform3D.Move3D(5, 5, 0); IGeometryCollection vector3DExample2GeometryCollection = vector3DExample2Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample2GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample2GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } //Vector3D Example 3 IGeometry vector3DExample3Geometry = Vector3DExamples.GetExample3(); ITransform3D vector3DExample3Transform3D = vector3DExample3Geometry as ITransform3D; vector3DExample3Transform3D.Move3D(5, -5, 0); IGeometryCollection vector3DExample3GeometryCollection = vector3DExample3Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample3GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample3GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } //Vector3D Example 4 IGeometry vector3DExample4Geometry = Vector3DExamples.GetExample4(); ITransform3D vector3DExample4Transform3D = vector3DExample4Geometry as ITransform3D; vector3DExample4Transform3D.Move3D(-5, -5, 0); IGeometryCollection vector3DExample4GeometryCollection = vector3DExample4Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample4GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample4GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } //Vector3D Example 5 IGeometry vector3DExample5Geometry = Vector3DExamples.GetExample5(); ITransform3D vector3DExample5Transform3D = vector3DExample5Geometry as ITransform3D; vector3DExample5Transform3D.Move3D(-5, 5, 0); IGeometryCollection vector3DExample5GeometryCollection = vector3DExample5Geometry as IGeometryCollection; for (int i = 0; i < vector3DExample5GeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(vector3DExample5GeometryCollection.get_Geometry(i), ref _missing, ref _missing); } return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample2() { //Composite: Cutaway Of Building With Multiple Floors Composed Of 1 TriangleStrip And 5 Ring Parts IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Walls IPointCollection wallsPointCollection = new TriangleStripClass(); //Start wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 0), ref _missing, ref _missing); wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 16), ref _missing, ref _missing); //Right Wall wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 0), ref _missing, ref _missing); wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 16), ref _missing, ref _missing); //Back Wall wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 0), ref _missing, ref _missing); wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 16), ref _missing, ref _missing); //Left Wall wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 0), ref _missing, ref _missing); wallsPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 16), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(wallsPointCollection as IGeometry, ref _missing, ref _missing); //Floors //Base IPointCollection basePointCollection = new RingClass(); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 0), ref _missing, ref _missing); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 0), ref _missing, ref _missing); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 0), ref _missing, ref _missing); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 0), ref _missing, ref _missing); IRing baseRing = basePointCollection as IRing; baseRing.Close(); multiPatchGeometryCollection.AddGeometry(baseRing as IGeometry, ref _missing, ref _missing); //First Floor IPointCollection firstFloorPointCollection = new RingClass(); firstFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 4), ref _missing, ref _missing); firstFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 4), ref _missing, ref _missing); firstFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 4), ref _missing, ref _missing); firstFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 4), ref _missing, ref _missing); IRing firstFloorRing = firstFloorPointCollection as IRing; firstFloorRing.Close(); multiPatchGeometryCollection.AddGeometry(firstFloorRing as IGeometry, ref _missing, ref _missing); //Second Floor IPointCollection secondFloorPointCollection = new RingClass(); secondFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 8), ref _missing, ref _missing); secondFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 8), ref _missing, ref _missing); secondFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 8), ref _missing, ref _missing); secondFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 8), ref _missing, ref _missing); IRing secondFloorRing = secondFloorPointCollection as IRing; secondFloorRing.Close(); multiPatchGeometryCollection.AddGeometry(secondFloorRing as IGeometry, ref _missing, ref _missing); //Third Floor IPointCollection thirdFloorPointCollection = new RingClass(); thirdFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 12), ref _missing, ref _missing); thirdFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 12), ref _missing, ref _missing); thirdFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 12), ref _missing, ref _missing); thirdFloorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 12), ref _missing, ref _missing); IRing thirdFloorRing = thirdFloorPointCollection as IRing; thirdFloorRing.Close(); multiPatchGeometryCollection.AddGeometry(thirdFloorRing as IGeometry, ref _missing, ref _missing); //Roof IPointCollection roofPointCollection = new RingClass(); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, 3, 16), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(3, -3, 16), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, -3, 16), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-3, 3, 16), ref _missing, ref _missing); IRing roofRing = roofPointCollection as IRing; roofRing.Close(); multiPatchGeometryCollection.AddGeometry(roofRing as IGeometry, ref _missing, ref _missing); return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample3() { //Composite: House Composed Of 7 Ring, 1 TriangleStrip, And 1 Triangles Parts IGeometryCollection multiPatchGeometryCollection = new MultiPatchClass(); IMultiPatch multiPatch = multiPatchGeometryCollection as IMultiPatch; //Base (Exterior Ring) IPointCollection basePointCollection = new RingClass(); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 0), ref _missing, ref _missing); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 0), ref _missing, ref _missing); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 0), ref _missing, ref _missing); basePointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 0), ref _missing, ref _missing); basePointCollection.AddPoint(basePointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(basePointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(basePointCollection as IRing, esriMultiPatchRingType.esriMultiPatchOuterRing); //Front With Cutaway For Door (Exterior Ring) IPointCollection frontPointCollection = new RingClass(); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 6), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 0), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 1, 0), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 1, 4), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -1, 4), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -1, 0), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 0), ref _missing, ref _missing); frontPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 6), ref _missing, ref _missing); frontPointCollection.AddPoint(frontPointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(frontPointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(frontPointCollection as IRing, esriMultiPatchRingType.esriMultiPatchOuterRing); //Back (Exterior Ring) IPointCollection backPointCollection = new RingClass(); backPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 6), ref _missing, ref _missing); backPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 6), ref _missing, ref _missing); backPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 0), ref _missing, ref _missing); backPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 0), ref _missing, ref _missing); backPointCollection.AddPoint(backPointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(backPointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(backPointCollection as IRing, esriMultiPatchRingType.esriMultiPatchOuterRing); //Right Side (Ring Group) //Exterior Ring IPointCollection rightSideExteriorPointCollection = new RingClass(); rightSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 6), ref _missing, ref _missing); rightSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 6), ref _missing, ref _missing); rightSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 0), ref _missing, ref _missing); rightSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 0), ref _missing, ref _missing); rightSideExteriorPointCollection.AddPoint(rightSideExteriorPointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(rightSideExteriorPointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(rightSideExteriorPointCollection as IRing, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring IPointCollection rightSideInteriorPointCollection = new RingClass(); rightSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 4, 4), ref _missing, ref _missing); rightSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, 4, 2), ref _missing, ref _missing); rightSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 4, 2), ref _missing, ref _missing); rightSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, 4, 4), ref _missing, ref _missing); rightSideInteriorPointCollection.AddPoint(rightSideInteriorPointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(rightSideInteriorPointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(rightSideInteriorPointCollection as IRing, esriMultiPatchRingType.esriMultiPatchInnerRing); //Left Side (Ring Group) //Exterior Ring IPointCollection leftSideExteriorPointCollection = new RingClass(); leftSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 6), ref _missing, ref _missing); leftSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 0), ref _missing, ref _missing); leftSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 0), ref _missing, ref _missing); leftSideExteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 6), ref _missing, ref _missing); leftSideExteriorPointCollection.AddPoint(leftSideExteriorPointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(leftSideExteriorPointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(leftSideExteriorPointCollection as IRing, esriMultiPatchRingType.esriMultiPatchOuterRing); //Interior Ring IPointCollection leftSideInteriorPointCollection = new RingClass(); leftSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, -4, 4), ref _missing, ref _missing); leftSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, -4, 4), ref _missing, ref _missing); leftSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-1, -4, 2), ref _missing, ref _missing); leftSideInteriorPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(1, -4, 2), ref _missing, ref _missing); leftSideInteriorPointCollection.AddPoint(leftSideInteriorPointCollection.get_Point(0), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(leftSideInteriorPointCollection as IGeometry, ref _missing, ref _missing); multiPatch.PutRingType(leftSideInteriorPointCollection as IRing, esriMultiPatchRingType.esriMultiPatchInnerRing); //Roof IPointCollection roofPointCollection = new TriangleStripClass(); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 6), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 6), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 0, 9), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 9), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 6), ref _missing, ref _missing); roofPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 6), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(roofPointCollection as IGeometry, ref _missing, ref _missing); //Triangular Area Between Roof And Front/Back IPointCollection triangularAreaPointCollection = new TrianglesClass(); //Area Between Roof And Front triangularAreaPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 0, 9), ref _missing, ref _missing); triangularAreaPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, 4, 6), ref _missing, ref _missing); triangularAreaPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(5, -4, 6), ref _missing, ref _missing); //Area Between Roof And Back triangularAreaPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 0, 9), ref _missing, ref _missing); triangularAreaPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, -4, 6), ref _missing, ref _missing); triangularAreaPointCollection.AddPoint(GeometryUtilities.ConstructPoint3D(-5, 4, 6), ref _missing, ref _missing); multiPatchGeometryCollection.AddGeometry(triangularAreaPointCollection as IGeometry, ref _missing, ref _missing); return multiPatchGeometryCollection as IGeometry; } public static IGeometry GetExample4() { const double CircleDegrees = 360.0; const int CircleDivisions = 18; const double VectorComponentOffset = 0.0000001; const double InnerBuildingRadius = 3.0; const double OuterBuildingExteriorRingRadius = 9.0; const double OuterBuildingInteriorRingRadius = 6.0; const double BaseZ = 0.0; const double InnerBuildingZ = 16.0; const double OuterBuildingZ = 6.0; //Composite: Tall Building Protruding Through Outer Ring-Shaped Building IMultiPatch multiPatch = new MultiPatchClass(); IGeometryCollection multiPatchGeometryCollection = multiPatch as IGeometryCollection; IPoint originPoint = GeometryUtilities.ConstructPoint3D(0, 0, 0); IVector3D upperAxisVector3D = GeometryUtilities.ConstructVector3D(0, 0, 10); IVector3D lowerAxisVector3D = GeometryUtilities.ConstructVector3D(0, 0, -10); lowerAxisVector3D.XComponent += VectorComponentOffset; IVector3D normalVector3D = upperAxisVector3D.CrossProduct(lowerAxisVector3D) as IVector3D; double rotationAngleInRadians = GeometryUtilities.GetRadians(CircleDegrees / CircleDivisions); //Inner Building IGeometry innerBuildingBaseGeometry = new PolygonClass(); IPointCollection innerBuildingBasePointCollection = innerBuildingBaseGeometry as IPointCollection; //Outer Building IGeometry outerBuildingBaseGeometry = new PolygonClass(); IGeometryCollection outerBuildingBaseGeometryCollection = outerBuildingBaseGeometry as IGeometryCollection; IPointCollection outerBuildingBaseExteriorRingPointCollection = new RingClass(); IPointCollection outerBuildingBaseInteriorRingPointCollection = new RingClass(); for (int i = 0; i < CircleDivisions; i++) { normalVector3D.Rotate(-1 * rotationAngleInRadians, upperAxisVector3D); //Inner Building normalVector3D.Magnitude = InnerBuildingRadius; IPoint innerBuildingBaseVertexPoint = GeometryUtilities.ConstructPoint2D(originPoint.X + normalVector3D.XComponent, originPoint.Y + normalVector3D.YComponent); innerBuildingBasePointCollection.AddPoint(innerBuildingBaseVertexPoint, ref _missing, ref _missing); //Outer Building //Exterior Ring normalVector3D.Magnitude = OuterBuildingExteriorRingRadius; IPoint outerBuildingBaseExteriorRingVertexPoint = GeometryUtilities.ConstructPoint2D(originPoint.X + normalVector3D.XComponent, originPoint.Y + normalVector3D.YComponent); outerBuildingBaseExteriorRingPointCollection.AddPoint(outerBuildingBaseExteriorRingVertexPoint, ref _missing, ref _missing); //Interior Ring normalVector3D.Magnitude = OuterBuildingInteriorRingRadius; IPoint outerBuildingBaseInteriorRingVertexPoint = GeometryUtilities.ConstructPoint2D(originPoint.X + normalVector3D.XComponent, originPoint.Y + normalVector3D.YComponent); outerBuildingBaseInteriorRingPointCollection.AddPoint(outerBuildingBaseInteriorRingVertexPoint, ref _missing, ref _missing); } IPolygon innerBuildingBasePolygon = innerBuildingBaseGeometry as IPolygon; innerBuildingBasePolygon.Close(); IRing outerBuildingBaseExteriorRing = outerBuildingBaseExteriorRingPointCollection as IRing; outerBuildingBaseExteriorRing.Close(); IRing outerBuildingBaseInteriorRing = outerBuildingBaseInteriorRingPointCollection as IRing; outerBuildingBaseInteriorRing.Close(); outerBuildingBaseInteriorRing.ReverseOrientation(); outerBuildingBaseGeometryCollection.AddGeometry(outerBuildingBaseExteriorRing as IGeometry, ref _missing, ref _missing); outerBuildingBaseGeometryCollection.AddGeometry(outerBuildingBaseInteriorRing as IGeometry, ref _missing, ref _missing); ITopologicalOperator topologicalOperator = outerBuildingBaseGeometry as ITopologicalOperator; topologicalOperator.Simplify(); IConstructMultiPatch innerBuildingConstructMultiPatch = new MultiPatchClass(); innerBuildingConstructMultiPatch.ConstructExtrudeFromTo(BaseZ, InnerBuildingZ, innerBuildingBaseGeometry); IGeometryCollection innerBuildingMultiPatchGeometryCollection = innerBuildingConstructMultiPatch as IGeometryCollection; for (int i = 0; i < innerBuildingMultiPatchGeometryCollection.GeometryCount; i++) { multiPatchGeometryCollection.AddGeometry(innerBuildingMultiPatchGeometryCollection.get_Geometry(i), ref _missing, ref _missing); } IConstructMultiPatch outerBuildingConstructMultiPatch = new MultiPatchClass(); outerBuildingConstructMultiPatch.ConstructExtrudeFromTo(BaseZ, OuterBuildingZ, outerBuildingBaseGeometry); IMultiPatch outerBuildingMultiPatch = outerBuildingConstructMultiPatch as IMultiPatch; IGeometryCollection outerBuildingMultiPatchGeometryCollection = outerBuildingConstructMultiPatch as IGeometryCollection; for (int i = 0; i < outerBuildingMultiPatchGeometryCollection.GeometryCount; i++) { IGeometry outerBuildingPatchGeometry = outerBuildingMultiPatchGeometryCollection.get_Geometry(i); multiPatchGeometryCollection.AddGeometry(outerBuildingPatchGeometry, ref _missing, ref _missing); if (outerBuildingPatchGeometry.GeometryType == esriGeometryType.esriGeometryRing) { bool isBeginningRing = false; esriMultiPatchRingType multiPatchRingType = outerBuildingMultiPatch.GetRingType(outerBuildingPatchGeometry as IRing, ref isBeginningRing); multiPatch.PutRingType(outerBuildingPatchGeometry as IRing, multiPatchRingType); } } return multiPatchGeometryCollection as IGeometry; } } }
// 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 Fixtures.AcceptanceTestsHttp { using System.Threading.Tasks; using Models; /// <summary> /// Extension methods for HttpClientFailure. /// </summary> public static partial class HttpClientFailureExtensions { /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head400(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head400Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Head400Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Head400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get400(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get400Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Get400Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Get400WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put400Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Put400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Put400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch400Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Patch400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Patch400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post400Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Post400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Post400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete400(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete400Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 400 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Delete400Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Delete400WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head401(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head401Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 401 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Head401Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Head401WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get402(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get402Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 402 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Get402Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Get402WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get403(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get403Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 403 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Get403Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Get403WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put404(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put404Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 404 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Put404Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Put404WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch405(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch405Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 405 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Patch405Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Patch405WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post406(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post406Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 406 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Post406Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Post406WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete407(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete407Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 407 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Delete407Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Delete407WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put409(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put409Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 409 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Put409Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Put409WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head410(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head410Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 410 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Head410Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Head410WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get411(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get411Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 411 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Get411Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Get411WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get412(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get412Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 412 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Get412Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Get412WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Put413(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Put413Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 413 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Put413Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Put413WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Patch414(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Patch414Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 414 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Patch414Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Patch414WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Post415(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Post415Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 415 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Post415Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Post415WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Get416(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Get416Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 416 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Get416Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Get416WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static Error Delete417(this IHttpClientFailure operations, bool? booleanValue = default(bool?)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Delete417Async(booleanValue), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 417 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Delete417Async(this IHttpClientFailure operations, bool? booleanValue = default(bool?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Delete417WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error Head429(this IHttpClientFailure operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IHttpClientFailure)s).Head429Async(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 429 status code - should be represented in the client as an error /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Error> Head429Async(this IHttpClientFailure operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.Head429WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// 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.IO; namespace System.CodeDom.Compiler { // This is an internal helper class which walks the tree for the ValidateIdentifiers API in the CodeGenerator. For the most part the generator code has been copied and // turned into validation code. This code will only validate identifiers and types to check that they are ok in a language // independent manner. By default, this will not be turned on. This gives clients of codedom a mechanism to // protect themselves against certain types of code injection attacks (using identifier and type names). // You can pass in any node in the tree that is a subclass of CodeObject. internal sealed class CodeValidator { private static readonly char[] s_newLineChars = new char[] { '\r', '\n', '\u2028', '\u2029', '\u0085' }; private CodeTypeDeclaration _currentClass; internal void ValidateIdentifiers(CodeObject e) { if (e is CodeCompileUnit) { ValidateCodeCompileUnit((CodeCompileUnit)e); } else if (e is CodeComment) { ValidateComment((CodeComment)e); } else if (e is CodeExpression) { ValidateExpression((CodeExpression)e); } else if (e is CodeNamespace) { ValidateNamespace((CodeNamespace)e); } else if (e is CodeNamespaceImport) { ValidateNamespaceImport((CodeNamespaceImport)e); } else if (e is CodeStatement) { ValidateStatement((CodeStatement)e); } else if (e is CodeTypeMember) { ValidateTypeMember((CodeTypeMember)e); } else if (e is CodeTypeReference) { ValidateTypeReference((CodeTypeReference)e); } else if (e is CodeDirective) { ValidateCodeDirective((CodeDirective)e); } else if (e == null) { throw new ArgumentNullException(nameof(e)); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } private void ValidateTypeMember(CodeTypeMember e) { ValidateCommentStatements(e.Comments); ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); if (e is CodeMemberEvent) { ValidateEvent((CodeMemberEvent)e); } else if (e is CodeMemberField) { ValidateField((CodeMemberField)e); } else if (e is CodeMemberMethod) { ValidateMemberMethod((CodeMemberMethod)e); } else if (e is CodeMemberProperty) { ValidateProperty((CodeMemberProperty)e); } else if (e is CodeSnippetTypeMember) { ValidateSnippetMember((CodeSnippetTypeMember)e); } else if (e is CodeTypeDeclaration) { ValidateTypeDeclaration((CodeTypeDeclaration)e); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } private void ValidateCodeCompileUnit(CodeCompileUnit e) { ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); if (e is CodeSnippetCompileUnit) { ValidateSnippetCompileUnit((CodeSnippetCompileUnit)e); } else { ValidateCompileUnitStart(e); ValidateNamespaces(e); ValidateCompileUnitEnd(e); } } private void ValidateSnippetCompileUnit(CodeSnippetCompileUnit e) { if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); } private void ValidateCompileUnitStart(CodeCompileUnit e) { if (e.AssemblyCustomAttributes.Count > 0) { ValidateAttributes(e.AssemblyCustomAttributes); } } private void ValidateCompileUnitEnd(CodeCompileUnit e) { } private void ValidateNamespaces(CodeCompileUnit e) { foreach (CodeNamespace n in e.Namespaces) { ValidateNamespace(n); } } private void ValidateNamespace(CodeNamespace e) { ValidateCommentStatements(e.Comments); ValidateNamespaceStart(e); ValidateNamespaceImports(e); ValidateTypes(e); } private static void ValidateNamespaceStart(CodeNamespace e) { if (!string.IsNullOrEmpty(e.Name)) { ValidateTypeName(e, nameof(e.Name), e.Name); } } private void ValidateNamespaceImports(CodeNamespace e) { foreach (CodeNamespaceImport imp in e.Imports) { if (imp.LinePragma != null) { ValidateLinePragmaStart(imp.LinePragma); } ValidateNamespaceImport(imp); } } private static void ValidateNamespaceImport(CodeNamespaceImport e) { ValidateTypeName(e, nameof(e.Namespace), e.Namespace); } private void ValidateAttributes(CodeAttributeDeclarationCollection attributes) { if (attributes.Count == 0) return; foreach (CodeAttributeDeclaration current in attributes) { ValidateTypeName(current, nameof(current.Name), current.Name); ValidateTypeReference(current.AttributeType); foreach (CodeAttributeArgument arg in current.Arguments) { ValidateAttributeArgument(arg); } } } private void ValidateAttributeArgument(CodeAttributeArgument arg) { if (!string.IsNullOrEmpty(arg.Name)) { ValidateIdentifier(arg, nameof(arg.Name), arg.Name); } ValidateExpression(arg.Value); } private void ValidateTypes(CodeNamespace e) { foreach (CodeTypeDeclaration type in e.Types) { ValidateTypeDeclaration(type); } } private void ValidateTypeDeclaration(CodeTypeDeclaration e) { // This function can be called recursively and will modify the global variable currentClass // We will save currentClass to a local, modify it to do whatever we want and restore it back when we exit so that it is re-entrant. CodeTypeDeclaration savedClass = _currentClass; _currentClass = e; ValidateTypeStart(e); ValidateTypeParameters(e.TypeParameters); ValidateTypeMembers(e); // Recursive call can come from here. ValidateTypeReferences(e.BaseTypes); _currentClass = savedClass; } private void ValidateTypeMembers(CodeTypeDeclaration e) { foreach (CodeTypeMember currentMember in e.Members) { ValidateTypeMember(currentMember); } } private void ValidateTypeParameters(CodeTypeParameterCollection parameters) { for (int i = 0; i < parameters.Count; i++) { ValidateTypeParameter(parameters[i]); } } private void ValidateTypeParameter(CodeTypeParameter e) { ValidateIdentifier(e, nameof(e.Name), e.Name); ValidateTypeReferences(e.Constraints); ValidateAttributes(e.CustomAttributes); } private void ValidateField(CodeMemberField e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } ValidateIdentifier(e, nameof(e.Name), e.Name); if (!IsCurrentEnum) { ValidateTypeReference(e.Type); } if (e.InitExpression != null) { ValidateExpression(e.InitExpression); } } private void ValidateConstructor(CodeConstructor e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } ValidateParameters(e.Parameters); CodeExpressionCollection baseArgs = e.BaseConstructorArgs; CodeExpressionCollection thisArgs = e.ChainedConstructorArgs; if (baseArgs.Count > 0) { ValidateExpressionList(baseArgs); } if (thisArgs.Count > 0) { ValidateExpressionList(thisArgs); } ValidateStatements(e.Statements); } private void ValidateProperty(CodeMemberProperty e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } ValidateTypeReference(e.Type); ValidateTypeReferences(e.ImplementationTypes); if (e.PrivateImplementationType != null && !IsCurrentInterface) { ValidateTypeReference(e.PrivateImplementationType); } if (e.Parameters.Count > 0 && string.Equals(e.Name, "Item", StringComparison.OrdinalIgnoreCase)) { ValidateParameters(e.Parameters); } else { ValidateIdentifier(e, nameof(e.Name), e.Name); } if (e.HasGet) { if (!(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)) { ValidateStatements(e.GetStatements); } } if (e.HasSet) { if (!(IsCurrentInterface || (e.Attributes & MemberAttributes.ScopeMask) == MemberAttributes.Abstract)) { ValidateStatements(e.SetStatements); } } } private void ValidateMemberMethod(CodeMemberMethod e) { ValidateCommentStatements(e.Comments); if (e.LinePragma != null) ValidateLinePragmaStart(e.LinePragma); ValidateTypeParameters(e.TypeParameters); ValidateTypeReferences(e.ImplementationTypes); if (e is CodeEntryPointMethod) { ValidateStatements(((CodeEntryPointMethod)e).Statements); } else if (e is CodeConstructor) { ValidateConstructor((CodeConstructor)e); } else if (e is CodeTypeConstructor) { ValidateTypeConstructor((CodeTypeConstructor)e); } else { ValidateMethod(e); } } private void ValidateTypeConstructor(CodeTypeConstructor e) { ValidateStatements(e.Statements); } private void ValidateMethod(CodeMemberMethod e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } if (e.ReturnTypeCustomAttributes.Count > 0) { ValidateAttributes(e.ReturnTypeCustomAttributes); } ValidateTypeReference(e.ReturnType); if (e.PrivateImplementationType != null) { ValidateTypeReference(e.PrivateImplementationType); } ValidateIdentifier(e, nameof(e.Name), e.Name); ValidateParameters(e.Parameters); if (!IsCurrentInterface && (e.Attributes & MemberAttributes.ScopeMask) != MemberAttributes.Abstract) { ValidateStatements(e.Statements); } } private void ValidateSnippetMember(CodeSnippetTypeMember e) { } private void ValidateTypeStart(CodeTypeDeclaration e) { ValidateCommentStatements(e.Comments); if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } ValidateIdentifier(e, nameof(e.Name), e.Name); if (e is CodeTypeDelegate del) { ValidateTypeReference(del.ReturnType); ValidateParameters(del.Parameters); } else { foreach (CodeTypeReference typeRef in e.BaseTypes) { ValidateTypeReference(typeRef); } } } private void ValidateCommentStatements(CodeCommentStatementCollection e) { foreach (CodeCommentStatement comment in e) { ValidateCommentStatement(comment); } } private void ValidateCommentStatement(CodeCommentStatement e) { ValidateComment(e.Comment); } private void ValidateComment(CodeComment e) { } private void ValidateStatement(CodeStatement e) { if (e == null) { throw new ArgumentNullException(nameof(e)); } ValidateCodeDirectives(e.StartDirectives); ValidateCodeDirectives(e.EndDirectives); if (e is CodeCommentStatement) { ValidateCommentStatement((CodeCommentStatement)e); } else if (e is CodeMethodReturnStatement) { ValidateMethodReturnStatement((CodeMethodReturnStatement)e); } else if (e is CodeConditionStatement) { ValidateConditionStatement((CodeConditionStatement)e); } else if (e is CodeTryCatchFinallyStatement) { ValidateTryCatchFinallyStatement((CodeTryCatchFinallyStatement)e); } else if (e is CodeAssignStatement) { ValidateAssignStatement((CodeAssignStatement)e); } else if (e is CodeExpressionStatement) { ValidateExpressionStatement((CodeExpressionStatement)e); } else if (e is CodeIterationStatement) { ValidateIterationStatement((CodeIterationStatement)e); } else if (e is CodeThrowExceptionStatement) { ValidateThrowExceptionStatement((CodeThrowExceptionStatement)e); } else if (e is CodeSnippetStatement) { ValidateSnippetStatement((CodeSnippetStatement)e); } else if (e is CodeVariableDeclarationStatement) { ValidateVariableDeclarationStatement((CodeVariableDeclarationStatement)e); } else if (e is CodeAttachEventStatement) { ValidateAttachEventStatement((CodeAttachEventStatement)e); } else if (e is CodeRemoveEventStatement) { ValidateRemoveEventStatement((CodeRemoveEventStatement)e); } else if (e is CodeGotoStatement) { ValidateGotoStatement((CodeGotoStatement)e); } else if (e is CodeLabeledStatement) { ValidateLabeledStatement((CodeLabeledStatement)e); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } private void ValidateStatements(CodeStatementCollection stmts) { foreach (CodeStatement stmt in stmts) { ValidateStatement(stmt); } } private void ValidateExpressionStatement(CodeExpressionStatement e) { ValidateExpression(e.Expression); } private void ValidateIterationStatement(CodeIterationStatement e) { ValidateStatement(e.InitStatement); ValidateExpression(e.TestExpression); ValidateStatement(e.IncrementStatement); ValidateStatements(e.Statements); } private void ValidateThrowExceptionStatement(CodeThrowExceptionStatement e) { if (e.ToThrow != null) { ValidateExpression(e.ToThrow); } } private void ValidateMethodReturnStatement(CodeMethodReturnStatement e) { if (e.Expression != null) { ValidateExpression(e.Expression); } } private void ValidateConditionStatement(CodeConditionStatement e) { ValidateExpression(e.Condition); ValidateStatements(e.TrueStatements); CodeStatementCollection falseStatemetns = e.FalseStatements; if (falseStatemetns.Count > 0) { ValidateStatements(e.FalseStatements); } } private void ValidateTryCatchFinallyStatement(CodeTryCatchFinallyStatement e) { ValidateStatements(e.TryStatements); CodeCatchClauseCollection catches = e.CatchClauses; if (catches.Count > 0) { foreach (CodeCatchClause current in catches) { ValidateTypeReference(current.CatchExceptionType); ValidateIdentifier(current, nameof(current.LocalName), current.LocalName); ValidateStatements(current.Statements); } } CodeStatementCollection finallyStatements = e.FinallyStatements; if (finallyStatements.Count > 0) { ValidateStatements(finallyStatements); } } private void ValidateAssignStatement(CodeAssignStatement e) { ValidateExpression(e.Left); ValidateExpression(e.Right); } private void ValidateAttachEventStatement(CodeAttachEventStatement e) { ValidateEventReferenceExpression(e.Event); ValidateExpression(e.Listener); } private void ValidateRemoveEventStatement(CodeRemoveEventStatement e) { ValidateEventReferenceExpression(e.Event); ValidateExpression(e.Listener); } private static void ValidateGotoStatement(CodeGotoStatement e) { ValidateIdentifier(e, nameof(e.Label), e.Label); } private void ValidateLabeledStatement(CodeLabeledStatement e) { ValidateIdentifier(e, nameof(e.Label), e.Label); if (e.Statement != null) { ValidateStatement(e.Statement); } } private void ValidateVariableDeclarationStatement(CodeVariableDeclarationStatement e) { ValidateTypeReference(e.Type); ValidateIdentifier(e, nameof(e.Name), e.Name); if (e.InitExpression != null) { ValidateExpression(e.InitExpression); } } private void ValidateLinePragmaStart(CodeLinePragma e) { } private void ValidateEvent(CodeMemberEvent e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } if (e.PrivateImplementationType != null) { ValidateTypeReference(e.Type); ValidateIdentifier(e, nameof(e.Name), e.Name); } ValidateTypeReferences(e.ImplementationTypes); } private void ValidateParameters(CodeParameterDeclarationExpressionCollection parameters) { foreach (CodeParameterDeclarationExpression current in parameters) { ValidateParameterDeclarationExpression(current); } } private void ValidateSnippetStatement(CodeSnippetStatement e) { } private void ValidateExpressionList(CodeExpressionCollection expressions) { foreach (CodeExpression current in expressions) { ValidateExpression(current); } } private static void ValidateTypeReference(CodeTypeReference e) { ValidateTypeName(e, nameof(e.BaseType), e.BaseType); ValidateArity(e); ValidateTypeReferences(e.TypeArguments); } private static void ValidateTypeReferences(CodeTypeReferenceCollection refs) { for (int i = 0; i < refs.Count; i++) { ValidateTypeReference(refs[i]); } } private static void ValidateArity(CodeTypeReference e) { // Verify that the number of TypeArguments agrees with the arity on the type. string baseType = e.BaseType; int totalTypeArgs = 0; for (int i = 0; i < baseType.Length; i++) { if (baseType[i] == '`') { i++; // skip the ' int numTypeArgs = 0; while (i < baseType.Length && baseType[i] >= '0' && baseType[i] <= '9') { numTypeArgs = numTypeArgs * 10 + (baseType[i] - '0'); i++; } totalTypeArgs += numTypeArgs; } } // Check if we have zero type args for open types. if ((totalTypeArgs != e.TypeArguments.Count) && (e.TypeArguments.Count != 0)) { throw new ArgumentException(SR.Format(SR.ArityDoesntMatch, baseType, e.TypeArguments.Count), nameof(e)); } } private static void ValidateTypeName(object e, string propertyName, string typeName) { if (!CodeGenerator.IsValidLanguageIndependentTypeName(typeName)) { string message = SR.Format(SR.InvalidTypeName, typeName, propertyName, e.GetType().FullName); throw new ArgumentException(message, nameof(e)); } } private static void ValidateIdentifier(object e, string propertyName, string identifier) { if (!CodeGenerator.IsValidLanguageIndependentIdentifier(identifier)) { string message = SR.Format(SR.InvalidLanguageIdentifier, identifier, propertyName, e.GetType().FullName); throw new ArgumentException(message, nameof(e)); } } private void ValidateExpression(CodeExpression e) { if (e is CodeArrayCreateExpression) { ValidateArrayCreateExpression((CodeArrayCreateExpression)e); } else if (e is CodeBaseReferenceExpression) { ValidateBaseReferenceExpression((CodeBaseReferenceExpression)e); } else if (e is CodeBinaryOperatorExpression) { ValidateBinaryOperatorExpression((CodeBinaryOperatorExpression)e); } else if (e is CodeCastExpression) { ValidateCastExpression((CodeCastExpression)e); } else if (e is CodeDefaultValueExpression) { ValidateDefaultValueExpression((CodeDefaultValueExpression)e); } else if (e is CodeDelegateCreateExpression) { ValidateDelegateCreateExpression((CodeDelegateCreateExpression)e); } else if (e is CodeFieldReferenceExpression) { ValidateFieldReferenceExpression((CodeFieldReferenceExpression)e); } else if (e is CodeArgumentReferenceExpression) { ValidateArgumentReferenceExpression((CodeArgumentReferenceExpression)e); } else if (e is CodeVariableReferenceExpression) { ValidateVariableReferenceExpression((CodeVariableReferenceExpression)e); } else if (e is CodeIndexerExpression) { ValidateIndexerExpression((CodeIndexerExpression)e); } else if (e is CodeArrayIndexerExpression) { ValidateArrayIndexerExpression((CodeArrayIndexerExpression)e); } else if (e is CodeSnippetExpression) { ValidateSnippetExpression((CodeSnippetExpression)e); } else if (e is CodeMethodInvokeExpression) { ValidateMethodInvokeExpression((CodeMethodInvokeExpression)e); } else if (e is CodeMethodReferenceExpression) { ValidateMethodReferenceExpression((CodeMethodReferenceExpression)e); } else if (e is CodeEventReferenceExpression) { ValidateEventReferenceExpression((CodeEventReferenceExpression)e); } else if (e is CodeDelegateInvokeExpression) { ValidateDelegateInvokeExpression((CodeDelegateInvokeExpression)e); } else if (e is CodeObjectCreateExpression) { ValidateObjectCreateExpression((CodeObjectCreateExpression)e); } else if (e is CodeParameterDeclarationExpression) { ValidateParameterDeclarationExpression((CodeParameterDeclarationExpression)e); } else if (e is CodeDirectionExpression) { ValidateDirectionExpression((CodeDirectionExpression)e); } else if (e is CodePrimitiveExpression) { ValidatePrimitiveExpression((CodePrimitiveExpression)e); } else if (e is CodePropertyReferenceExpression) { ValidatePropertyReferenceExpression((CodePropertyReferenceExpression)e); } else if (e is CodePropertySetValueReferenceExpression) { ValidatePropertySetValueReferenceExpression((CodePropertySetValueReferenceExpression)e); } else if (e is CodeThisReferenceExpression) { ValidateThisReferenceExpression((CodeThisReferenceExpression)e); } else if (e is CodeTypeReferenceExpression) { ValidateTypeReference(((CodeTypeReferenceExpression)e).Type); } else if (e is CodeTypeOfExpression) { ValidateTypeOfExpression((CodeTypeOfExpression)e); } else { if (e == null) { throw new ArgumentNullException(nameof(e)); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } } private void ValidateArrayCreateExpression(CodeArrayCreateExpression e) { ValidateTypeReference(e.CreateType); CodeExpressionCollection init = e.Initializers; if (init.Count > 0) { ValidateExpressionList(init); } else { if (e.SizeExpression != null) { ValidateExpression(e.SizeExpression); } } } private void ValidateBaseReferenceExpression(CodeBaseReferenceExpression e) { // Nothing to validate } private void ValidateBinaryOperatorExpression(CodeBinaryOperatorExpression e) { ValidateExpression(e.Left); ValidateExpression(e.Right); } private void ValidateCastExpression(CodeCastExpression e) { ValidateTypeReference(e.TargetType); ValidateExpression(e.Expression); } private static void ValidateDefaultValueExpression(CodeDefaultValueExpression e) { ValidateTypeReference(e.Type); } private void ValidateDelegateCreateExpression(CodeDelegateCreateExpression e) { ValidateTypeReference(e.DelegateType); ValidateExpression(e.TargetObject); ValidateIdentifier(e, nameof(e.MethodName), e.MethodName); } private void ValidateFieldReferenceExpression(CodeFieldReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.FieldName), e.FieldName); } private static void ValidateArgumentReferenceExpression(CodeArgumentReferenceExpression e) { ValidateIdentifier(e, nameof(e.ParameterName), e.ParameterName); } private static void ValidateVariableReferenceExpression(CodeVariableReferenceExpression e) { ValidateIdentifier(e, nameof(e.VariableName), e.VariableName); } private void ValidateIndexerExpression(CodeIndexerExpression e) { ValidateExpression(e.TargetObject); foreach (CodeExpression exp in e.Indices) { ValidateExpression(exp); } } private void ValidateArrayIndexerExpression(CodeArrayIndexerExpression e) { ValidateExpression(e.TargetObject); foreach (CodeExpression exp in e.Indices) { ValidateExpression(exp); } } private void ValidateSnippetExpression(CodeSnippetExpression e) { } private void ValidateMethodInvokeExpression(CodeMethodInvokeExpression e) { ValidateMethodReferenceExpression(e.Method); ValidateExpressionList(e.Parameters); } private void ValidateMethodReferenceExpression(CodeMethodReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.MethodName), e.MethodName); ValidateTypeReferences(e.TypeArguments); } private void ValidateEventReferenceExpression(CodeEventReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.EventName), e.EventName); } private void ValidateDelegateInvokeExpression(CodeDelegateInvokeExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateExpressionList(e.Parameters); } private void ValidateObjectCreateExpression(CodeObjectCreateExpression e) { ValidateTypeReference(e.CreateType); ValidateExpressionList(e.Parameters); } private void ValidateParameterDeclarationExpression(CodeParameterDeclarationExpression e) { if (e.CustomAttributes.Count > 0) { ValidateAttributes(e.CustomAttributes); } ValidateTypeReference(e.Type); ValidateIdentifier(e, nameof(e.Name), e.Name); } private void ValidateDirectionExpression(CodeDirectionExpression e) { ValidateExpression(e.Expression); } private void ValidatePrimitiveExpression(CodePrimitiveExpression e) { } private void ValidatePropertyReferenceExpression(CodePropertyReferenceExpression e) { if (e.TargetObject != null) { ValidateExpression(e.TargetObject); } ValidateIdentifier(e, nameof(e.PropertyName), e.PropertyName); } private void ValidatePropertySetValueReferenceExpression(CodePropertySetValueReferenceExpression e) { // Do nothing } private void ValidateThisReferenceExpression(CodeThisReferenceExpression e) { // Do nothing } private static void ValidateTypeOfExpression(CodeTypeOfExpression e) { ValidateTypeReference(e.Type); } private static void ValidateCodeDirectives(CodeDirectiveCollection e) { for (int i = 0; i < e.Count; i++) ValidateCodeDirective(e[i]); } private static void ValidateCodeDirective(CodeDirective e) { if (e is CodeChecksumPragma) { ValidateChecksumPragma((CodeChecksumPragma)e); } else if (e is CodeRegionDirective) { ValidateRegionDirective((CodeRegionDirective)e); } else { throw new ArgumentException(SR.Format(SR.InvalidElementType, e.GetType().FullName), nameof(e)); } } private static void ValidateChecksumPragma(CodeChecksumPragma e) { if (e.FileName.IndexOfAny(Path.GetInvalidPathChars()) != -1) throw new ArgumentException(SR.Format(SR.InvalidPathCharsInChecksum, e.FileName), nameof(e)); } private static void ValidateRegionDirective(CodeRegionDirective e) { if (e.RegionText.IndexOfAny(s_newLineChars) != -1) throw new ArgumentException(SR.Format(SR.InvalidRegion, e.RegionText), nameof(e)); } private bool IsCurrentInterface => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsInterface : false; private bool IsCurrentEnum => _currentClass != null && !(_currentClass is CodeTypeDelegate) ? _currentClass.IsEnum : false; } }