context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.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 = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// FolderItemResponse /// </summary> [DataContract] public partial class FolderItemResponse : IEquatable<FolderItemResponse>, IValidatableObject { public FolderItemResponse() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="FolderItemResponse" /> class. /// </summary> /// <param name="EndPosition">The last position in the result set. .</param> /// <param name="FolderItems">A list of the envelopes in the specified folder or folders. .</param> /// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param> /// <param name="PreviousUri">The postal code for the billing address..</param> /// <param name="ResultSetSize">The number of results returned in this response. .</param> /// <param name="StartPosition">Starting position of the current result set..</param> /// <param name="TotalRows">TotalRows.</param> public FolderItemResponse(string EndPosition = default(string), List<FolderItemV2> FolderItems = default(List<FolderItemV2>), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalRows = default(string)) { this.EndPosition = EndPosition; this.FolderItems = FolderItems; this.NextUri = NextUri; this.PreviousUri = PreviousUri; this.ResultSetSize = ResultSetSize; this.StartPosition = StartPosition; this.TotalRows = TotalRows; } /// <summary> /// The last position in the result set. /// </summary> /// <value>The last position in the result set. </value> [DataMember(Name="endPosition", EmitDefaultValue=false)] public string EndPosition { get; set; } /// <summary> /// A list of the envelopes in the specified folder or folders. /// </summary> /// <value>A list of the envelopes in the specified folder or folders. </value> [DataMember(Name="folderItems", EmitDefaultValue=false)] public List<FolderItemV2> FolderItems { get; set; } /// <summary> /// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. /// </summary> /// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value> [DataMember(Name="nextUri", EmitDefaultValue=false)] public string NextUri { get; set; } /// <summary> /// The postal code for the billing address. /// </summary> /// <value>The postal code for the billing address.</value> [DataMember(Name="previousUri", EmitDefaultValue=false)] public string PreviousUri { get; set; } /// <summary> /// The number of results returned in this response. /// </summary> /// <value>The number of results returned in this response. </value> [DataMember(Name="resultSetSize", EmitDefaultValue=false)] public string ResultSetSize { get; set; } /// <summary> /// Starting position of the current result set. /// </summary> /// <value>Starting position of the current result set.</value> [DataMember(Name="startPosition", EmitDefaultValue=false)] public string StartPosition { get; set; } /// <summary> /// Gets or Sets TotalRows /// </summary> [DataMember(Name="totalRows", EmitDefaultValue=false)] public string TotalRows { 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 FolderItemResponse {\n"); sb.Append(" EndPosition: ").Append(EndPosition).Append("\n"); sb.Append(" FolderItems: ").Append(FolderItems).Append("\n"); sb.Append(" NextUri: ").Append(NextUri).Append("\n"); sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n"); sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n"); sb.Append(" StartPosition: ").Append(StartPosition).Append("\n"); sb.Append(" TotalRows: ").Append(TotalRows).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as FolderItemResponse); } /// <summary> /// Returns true if FolderItemResponse instances are equal /// </summary> /// <param name="other">Instance of FolderItemResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(FolderItemResponse other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.EndPosition == other.EndPosition || this.EndPosition != null && this.EndPosition.Equals(other.EndPosition) ) && ( this.FolderItems == other.FolderItems || this.FolderItems != null && this.FolderItems.SequenceEqual(other.FolderItems) ) && ( this.NextUri == other.NextUri || this.NextUri != null && this.NextUri.Equals(other.NextUri) ) && ( this.PreviousUri == other.PreviousUri || this.PreviousUri != null && this.PreviousUri.Equals(other.PreviousUri) ) && ( this.ResultSetSize == other.ResultSetSize || this.ResultSetSize != null && this.ResultSetSize.Equals(other.ResultSetSize) ) && ( this.StartPosition == other.StartPosition || this.StartPosition != null && this.StartPosition.Equals(other.StartPosition) ) && ( this.TotalRows == other.TotalRows || this.TotalRows != null && this.TotalRows.Equals(other.TotalRows) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.EndPosition != null) hash = hash * 59 + this.EndPosition.GetHashCode(); if (this.FolderItems != null) hash = hash * 59 + this.FolderItems.GetHashCode(); if (this.NextUri != null) hash = hash * 59 + this.NextUri.GetHashCode(); if (this.PreviousUri != null) hash = hash * 59 + this.PreviousUri.GetHashCode(); if (this.ResultSetSize != null) hash = hash * 59 + this.ResultSetSize.GetHashCode(); if (this.StartPosition != null) hash = hash * 59 + this.StartPosition.GetHashCode(); if (this.TotalRows != null) hash = hash * 59 + this.TotalRows.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// 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.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime; namespace System.Threading { // // Methods for accessing memory with volatile semantics. // public unsafe static class Volatile { #region Boolean private struct VolatileBoolean { public volatile Boolean Value; } public static Boolean Read(ref Boolean location) { return Unsafe.As<Boolean, VolatileBoolean>(ref location).Value; } public static void Write(ref Boolean location, Boolean value) { Unsafe.As<Boolean, VolatileBoolean>(ref location).Value = value; } #endregion #region Byte private struct VolatileByte { public volatile Byte Value; } public static Byte Read(ref Byte location) { return Unsafe.As<Byte, VolatileByte>(ref location).Value; } public static void Write(ref Byte location, Byte value) { Unsafe.As<Byte, VolatileByte>(ref location).Value = value; } #endregion #region Double public static Double Read(ref Double location) { Int64 result = Read(ref Unsafe.As<Double, Int64>(ref location)); return *(double*)&result; } public static void Write(ref Double location, Double value) { Write(ref Unsafe.As<Double, Int64>(ref location), *(Int64*)&value); } #endregion #region Int16 private struct VolatileInt16 { public volatile Int16 Value; } public static Int16 Read(ref Int16 location) { return Unsafe.As<Int16, VolatileInt16>(ref location).Value; } public static void Write(ref Int16 location, Int16 value) { Unsafe.As<Int16, VolatileInt16>(ref location).Value = value; } #endregion #region Int32 private struct VolatileInt32 { public volatile Int32 Value; } public static Int32 Read(ref Int32 location) { return Unsafe.As<Int32, VolatileInt32>(ref location).Value; } public static void Write(ref Int32 location, Int32 value) { Unsafe.As<Int32, VolatileInt32>(ref location).Value = value; } #endregion #region Int64 public static Int64 Read(ref Int64 location) { #if BIT64 return (Int64)Unsafe.As<Int64, VolatileIntPtr>(ref location).Value; #else return Interlocked.CompareExchange(ref location, 0, 0); #endif } public static void Write(ref Int64 location, Int64 value) { #if BIT64 Unsafe.As<Int64, VolatileIntPtr>(ref location).Value = (IntPtr)value; #else Interlocked.Exchange(ref location, value); #endif } #endregion #region IntPtr private struct VolatileIntPtr { public volatile IntPtr Value; } public static IntPtr Read(ref IntPtr location) { return Unsafe.As<IntPtr, VolatileIntPtr>(ref location).Value; } public static void Write(ref IntPtr location, IntPtr value) { fixed (IntPtr* p = &location) { ((VolatileIntPtr*)p)->Value = value; } } #endregion #region SByte private struct VolatileSByte { public volatile SByte Value; } [CLSCompliant(false)] public static SByte Read(ref SByte location) { return Unsafe.As<SByte, VolatileSByte>(ref location).Value; } [CLSCompliant(false)] public static void Write(ref SByte location, SByte value) { Unsafe.As<SByte, VolatileSByte>(ref location).Value = value; } #endregion #region Single private struct VolatileSingle { public volatile Single Value; } public static Single Read(ref Single location) { return Unsafe.As<Single, VolatileSingle>(ref location).Value; } public static void Write(ref Single location, Single value) { Unsafe.As<Single, VolatileSingle>(ref location).Value = value; } #endregion #region UInt16 private struct VolatileUInt16 { public volatile UInt16 Value; } [CLSCompliant(false)] public static UInt16 Read(ref UInt16 location) { return Unsafe.As<UInt16, VolatileUInt16>(ref location).Value; } [CLSCompliant(false)] public static void Write(ref UInt16 location, UInt16 value) { Unsafe.As<UInt16, VolatileUInt16>(ref location).Value = value; } #endregion #region UInt32 private struct VolatileUInt32 { public volatile UInt32 Value; } [CLSCompliant(false)] public static UInt32 Read(ref UInt32 location) { return Unsafe.As<UInt32, VolatileUInt32>(ref location).Value; } [CLSCompliant(false)] public static void Write(ref UInt32 location, UInt32 value) { Unsafe.As<UInt32, VolatileUInt32>(ref location).Value = value; } #endregion #region UInt64 [CLSCompliant(false)] public static UInt64 Read(ref UInt64 location) { return (UInt64)Read(ref Unsafe.As<UInt64, Int64>(ref location)); } [CLSCompliant(false)] public static void Write(ref UInt64 location, UInt64 value) { Write(ref Unsafe.As<UInt64, Int64>(ref location), (Int64)value); } #endregion #region UIntPtr private struct VolatileUIntPtr { public volatile UIntPtr Value; } [CLSCompliant(false)] public static UIntPtr Read(ref UIntPtr location) { return Unsafe.As<UIntPtr, VolatileUIntPtr>(ref location).Value; } [CLSCompliant(false)] public static void Write(ref UIntPtr location, UIntPtr value) { Unsafe.As<UIntPtr, VolatileUIntPtr>(ref location).Value = value; } #endregion #region T private struct VolatileObject { public volatile Object Value; } public static T Read<T>(ref T location) where T : class { return Unsafe.As<T>(Unsafe.As<T, VolatileObject>(ref location).Value); } public static void Write<T>(ref T location, T value) where T : class { Unsafe.As<T, VolatileObject>(ref location).Value = value; } #endregion } }
/* * * (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. * */ namespace ASC.Mail.Net.IMAP { #region usings using System; using System.Collections; using System.Text; using Mime; using MIME; #endregion /// <summary> /// IMAP ENVELOPE STRUCTURE (date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id). /// Defined in RFC 3501 7.4.2. /// </summary> public class IMAP_Envelope { #region Members private MailboxAddress[] m_Bcc; private MailboxAddress[] m_Cc; private DateTime m_Date = DateTime.MinValue; private MailboxAddress[] m_From; private string m_InReplyTo; private string m_MessageID; private MailboxAddress[] m_ReplyTo; private MailboxAddress m_Sender; private string m_Subject; private MailboxAddress[] m_To; #endregion #region Properties /// <summary> /// Gets header field "<b>Date:</b>" value. Returns DateTime.MinValue if no date or date parsing fails. /// </summary> public DateTime Date { get { return m_Date; } } /// <summary> /// Gets header field "<b>Subject:</b>" value. Returns null if value isn't set. /// </summary> public string Subject { get { return m_Subject; } } /// <summary> /// Gets header field "<b>From:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] From { get { return m_From; } } /// <summary> /// Gets header field "<b>Sender:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress Sender { get { return m_Sender; } } /// <summary> /// Gets header field "<b>Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] ReplyTo { get { return m_ReplyTo; } } /// <summary> /// Gets header field "<b>To:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] To { get { return m_To; } } /// <summary> /// Gets header field "<b>Cc:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] Cc { get { return m_Cc; } } /// <summary> /// Gets header field "<b>Bcc:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] Bcc { get { return m_Bcc; } } /// <summary> /// Gets header field "<b>In-Reply-To:</b>" value. Returns null if value isn't set. /// </summary> public string InReplyTo { get { return m_InReplyTo; } } /// <summary> /// Gets header field "<b>Message-ID:</b>" value. Returns null if value isn't set. /// </summary> public string MessageID { get { return m_MessageID; } } #endregion #region Methods /// <summary> /// Construct secified mime entity ENVELOPE string. /// </summary> /// <param name="entity">Mime entity.</param> /// <returns></returns> public static string ConstructEnvelope(MimeEntity entity) { /* RFC 3501 7.4.2 ENVELOPE A parenthesized list that describes the envelope structure of a message. This is computed by the server by parsing the [RFC-2822] header into the component parts, defaulting various fields as necessary. The fields of the envelope structure are in the following order: date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id. The date, subject, in-reply-to, and message-id fields are strings. The from, sender, reply-to, to, cc, and bcc fields are parenthesized lists of address structures. An address structure is a parenthesized list that describes an electronic mail address. The fields of an address structure are in the following order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. [RFC-2822] group syntax is indicated by a special form of address structure in which the host name field is NIL. If the mailbox name field is also NIL, this is an end of group marker (semi-colon in RFC 822 syntax). If the mailbox name field is non-NIL, this is a start of group marker, and the mailbox name field holds the group name phrase. If the Date, Subject, In-Reply-To, and Message-ID header lines are absent in the [RFC-2822] header, the corresponding member of the envelope is NIL; if these header lines are present but empty the corresponding member of the envelope is the empty string. Note: some servers may return a NIL envelope member in the "present but empty" case. Clients SHOULD treat NIL and empty string as identical. Note: [RFC-2822] requires that all messages have a valid Date header. Therefore, the date member in the envelope can not be NIL or the empty string. Note: [RFC-2822] requires that the In-Reply-To and Message-ID headers, if present, have non-empty content. Therefore, the in-reply-to and message-id members in the envelope can not be the empty string. If the From, To, cc, and bcc header lines are absent in the [RFC-2822] header, or are present but empty, the corresponding member of the envelope is NIL. If the Sender or Reply-To lines are absent in the [RFC-2822] header, or are present but empty, the server sets the corresponding member of the envelope to be the same value as the from member (the client is not expected to know to do this). Note: [RFC-2822] requires that all messages have a valid From header. Therefore, the from, sender, and reply-to members in the envelope can not be NIL. ENVELOPE ("date" "subject" from sender reply-to to cc bcc "in-reply-to" "messageID") */ // NOTE: all header fields and parameters must in ENCODED form !!! StringBuilder retVal = new StringBuilder(); retVal.Append("("); // date if (entity.Header.Contains("Date:")) { retVal.Append(TextUtils.QuoteString(MimeUtils.DateTimeToRfc2822(entity.Date))); } else { retVal.Append("NIL"); } // subject if (entity.Subject != null) { retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(entity.Subject))); } else { retVal.Append(" NIL"); } // from if (entity.From != null && entity.From.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.From)); } else { retVal.Append(" NIL"); } // sender // NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList. if (entity.Sender != null) { retVal.Append(" ("); retVal.Append(ConstructAddress(entity.Sender)); retVal.Append(")"); } else if (entity.From != null) { retVal.Append(" " + ConstructAddresses(entity.From)); } else { retVal.Append(" NIL"); } // reply-to if (entity.ReplyTo != null) { retVal.Append(" " + ConstructAddresses(entity.ReplyTo)); } else if (entity.From != null) { retVal.Append(" " + ConstructAddresses(entity.From)); } else { retVal.Append(" NIL"); } // to if (entity.To != null && entity.To.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.To)); } else { retVal.Append(" NIL"); } // cc if (entity.Cc != null && entity.Cc.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.Cc)); } else { retVal.Append(" NIL"); } // bcc if (entity.Bcc != null && entity.Bcc.Count > 0) { retVal.Append(" " + ConstructAddresses(entity.Bcc)); } else { retVal.Append(" NIL"); } // in-reply-to if (entity.InReplyTo != null) { retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(entity.InReplyTo))); } else { retVal.Append(" NIL"); } // message-id if (entity.MessageID != null) { retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(entity.MessageID))); } else { retVal.Append(" NIL"); } retVal.Append(")"); return retVal.ToString(); } /// <summary> /// Parses ENVELOPE from IMAP envelope string. /// </summary> /// <param name="envelopeString">Envelope string.</param> public void Parse(string envelopeString) { if (envelopeString.StartsWith("(")) { envelopeString = envelopeString.Substring(1); } if (envelopeString.EndsWith(")")) { envelopeString = envelopeString.Substring(0, envelopeString.Length - 1); } string word = ""; StringReader r = new StringReader(envelopeString); #region Date // Date word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_Date = DateTime.MinValue; } else { try { m_Date = MimeUtils.ParseDate(word); } catch { // Failed to parse date, return minimum. m_Date = DateTime.MinValue; } } #endregion #region Subject // Subject word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_Subject = null; } else { m_Subject = MIME_Encoding_EncodedWord.DecodeS(word); } #endregion #region From // From m_From = ParseAddresses(r); #endregion #region Sender // Sender // NOTE: There is confusing part, according rfc 2822 Sender: is MailboxAddress and not AddressList. MailboxAddress[] sender = ParseAddresses(r); if (sender != null && sender.Length > 0) { m_Sender = sender[0]; } else { m_Sender = null; } #endregion #region ReplyTo // ReplyTo m_ReplyTo = ParseAddresses(r); #endregion #region To // To m_To = ParseAddresses(r); #endregion #region Cc // Cc m_Cc = ParseAddresses(r); #endregion #region Bcc // Bcc m_Bcc = ParseAddresses(r); #endregion #region InReplyTo // InReplyTo r.ReadToFirstChar(); word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_InReplyTo = null; } else { m_InReplyTo = word; } #endregion #region MessageID // MessageID r.ReadToFirstChar(); word = r.ReadWord(); if (word == null) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } if (word.ToUpper() == "NIL") { m_MessageID = null; } else { m_MessageID = word; } #endregion } #endregion #region Utility methods /// <summary> /// Constructs ENVELOPE addresses structure. /// </summary> /// <param name="addressList">Address list.</param> /// <returns></returns> private static string ConstructAddresses(AddressList addressList) { StringBuilder retVal = new StringBuilder(); retVal.Append("("); foreach (MailboxAddress address in addressList.Mailboxes) { retVal.Append(ConstructAddress(address)); } retVal.Append(")"); return retVal.ToString(); } /// <summary> /// Constructs ENVELOPE address structure. /// </summary> /// <param name="address">Mailbox address.</param> /// <returns></returns> private static string ConstructAddress(MailboxAddress address) { /* An address structure is a parenthesized list that describes an electronic mail address. The fields of an address structure are in the following order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. */ // NOTE: all header fields and parameters must in ENCODED form !!! StringBuilder retVal = new StringBuilder(); retVal.Append("("); // personal name retVal.Append(TextUtils.QuoteString(MimeUtils.EncodeHeaderField(address.DisplayName))); // source route, always NIL (not used nowdays) retVal.Append(" NIL"); // mailbox name retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(address.LocalPart))); // host name retVal.Append(" " + TextUtils.QuoteString(MimeUtils.EncodeHeaderField(address.Domain))); retVal.Append(")"); return retVal.ToString(); } /// <summary> /// Parses addresses from IMAP ENVELOPE addresses structure. /// </summary> /// <param name="r"></param> /// <returns></returns> private MailboxAddress[] ParseAddresses(StringReader r) { r.ReadToFirstChar(); if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); return null; } else { r.ReadToFirstChar(); // This must be ((address)[*(address)]) if (!r.StartsWith("(")) { throw new Exception("Invalid IMAP ENVELOPE structure !"); } else { // Read addresses string addressesString = r.ReadParenthesized(); ArrayList addresses = new ArrayList(); StringReader rAddresses = new StringReader(addressesString.Trim()); // Now we have (address)[*(address)], read addresses while (rAddresses.StartsWith("(")) { addresses.Add(ParseAddress(rAddresses.ReadParenthesized())); rAddresses.ReadToFirstChar(); } MailboxAddress[] retVal = new MailboxAddress[addresses.Count]; addresses.CopyTo(retVal); return retVal; } } } /// <summary> /// Parses address from IMAP ENVELOPE address structure. /// </summary> /// <param name="addressString">Address structure string.</param> /// <returns></returns> private MailboxAddress ParseAddress(string addressString) { /* RFC 3501 7.4.2 ENVELOPE An address structure is a parenthesized list that describes an electronic mail address. The fields of an address structure are in the following order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name. */ StringReader r = new StringReader(addressString.Trim()); string personalName = ""; string emailAddress = ""; // personal name if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); } else { personalName = MIME_Encoding_EncodedWord.DecodeS(r.ReadWord()); } // source route, always NIL (not used nowdays) r.ReadWord(); // mailbox name if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); } else { emailAddress = r.ReadWord() + "@"; } // host name if (r.StartsWith("NIL", false)) { // Remove NIL r.ReadSpecifiedLength("NIL".Length); } else { emailAddress += r.ReadWord(); } return new MailboxAddress(personalName, emailAddress); } #endregion } }
// // PKCS1.cs - Implements PKCS#1 primitives. // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // 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.Security.Cryptography; namespace Mono.Security.Cryptography { // References: // a. PKCS#1: RSA Cryptography Standard // http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/index.html #if INSIDE_CORLIB internal #else public #endif sealed class PKCS1 { private PKCS1 () { } private static bool Compare (byte[] array1, byte[] array2) { bool result = (array1.Length == array2.Length); if (result) { for (int i=0; i < array1.Length; i++) if (array1[i] != array2[i]) return false; } return result; } private static byte[] xor (byte[] array1, byte[] array2) { byte[] result = new byte [array1.Length]; for (int i=0; i < result.Length; i++) result[i] = (byte) (array1[i] ^ array2[i]); return result; } private static byte[] emptySHA1 = { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 }; private static byte[] emptySHA256 = { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 }; private static byte[] emptySHA384 = { 0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b }; private static byte[] emptySHA512 = { 0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e }; private static byte[] GetEmptyHash (HashAlgorithm hash) { if (hash is SHA1) return emptySHA1; else if (hash is SHA256) return emptySHA256; else if (hash is SHA384) return emptySHA384; else if (hash is SHA512) return emptySHA512; else return hash.ComputeHash ((byte[])null); } // PKCS #1 v.2.1, Section 4.1 // I2OSP converts a non-negative integer to an octet string of a specified length. public static byte[] I2OSP (int x, int size) { byte[] array = BitConverterLE.GetBytes (x); Array.Reverse (array, 0, array.Length); return I2OSP (array, size); } public static byte[] I2OSP (byte[] x, int size) { byte[] result = new byte [size]; Buffer.BlockCopy (x, 0, result, (result.Length - x.Length), x.Length); return result; } // PKCS #1 v.2.1, Section 4.2 // OS2IP converts an octet string to a nonnegative integer. public static byte[] OS2IP (byte[] x) { int i = 0; while ((x [i++] == 0x00) && (i < x.Length)) { // confuse compiler into reporting a warning with {} } i--; if (i > 0) { byte[] result = new byte [x.Length - i]; Buffer.BlockCopy (x, i, result, 0, result.Length); return result; } else return x; } // PKCS #1 v.2.1, Section 5.1.1 public static byte[] RSAEP (RSA rsa, byte[] m) { // c = m^e mod n return rsa.EncryptValue (m); } // PKCS #1 v.2.1, Section 5.1.2 public static byte[] RSADP (RSA rsa, byte[] c) { // m = c^d mod n // Decrypt value may apply CRT optimizations return rsa.DecryptValue (c); } // PKCS #1 v.2.1, Section 5.2.1 public static byte[] RSASP1 (RSA rsa, byte[] m) { // first form: s = m^d mod n // Decrypt value may apply CRT optimizations return rsa.DecryptValue (m); } // PKCS #1 v.2.1, Section 5.2.2 public static byte[] RSAVP1 (RSA rsa, byte[] s) { // m = s^e mod n return rsa.EncryptValue (s); } // PKCS #1 v.2.1, Section 7.1.1 // RSAES-OAEP-ENCRYPT ((n, e), M, L) public static byte[] Encrypt_OAEP (RSA rsa, HashAlgorithm hash, RandomNumberGenerator rng, byte[] M) { int size = rsa.KeySize / 8; int hLen = hash.HashSize / 8; if (M.Length > size - 2 * hLen - 2) throw new CryptographicException ("message too long"); // empty label L SHA1 hash byte[] lHash = GetEmptyHash (hash); int PSLength = (size - M.Length - 2 * hLen - 2); // DB = lHash || PS || 0x01 || M byte[] DB = new byte [lHash.Length + PSLength + 1 + M.Length]; Buffer.BlockCopy (lHash, 0, DB, 0, lHash.Length); DB [(lHash.Length + PSLength)] = 0x01; Buffer.BlockCopy (M, 0, DB, (DB.Length - M.Length), M.Length); byte[] seed = new byte [hLen]; rng.GetBytes (seed); byte[] dbMask = MGF1 (hash, seed, size - hLen - 1); byte[] maskedDB = xor (DB, dbMask); byte[] seedMask = MGF1 (hash, maskedDB, hLen); byte[] maskedSeed = xor (seed, seedMask); // EM = 0x00 || maskedSeed || maskedDB byte[] EM = new byte [maskedSeed.Length + maskedDB.Length + 1]; Buffer.BlockCopy (maskedSeed, 0, EM, 1, maskedSeed.Length); Buffer.BlockCopy (maskedDB, 0, EM, maskedSeed.Length + 1, maskedDB.Length); byte[] m = OS2IP (EM); byte[] c = RSAEP (rsa, m); return I2OSP (c, size); } // PKCS #1 v.2.1, Section 7.1.2 // RSAES-OAEP-DECRYPT (K, C, L) public static byte[] Decrypt_OAEP (RSA rsa, HashAlgorithm hash, byte[] C) { int size = rsa.KeySize / 8; int hLen = hash.HashSize / 8; if ((size < (2 * hLen + 2)) || (C.Length != size)) throw new CryptographicException ("decryption error"); byte[] c = OS2IP (C); byte[] m = RSADP (rsa, c); byte[] EM = I2OSP (m, size); // split EM = Y || maskedSeed || maskedDB byte[] maskedSeed = new byte [hLen]; Buffer.BlockCopy (EM, 1, maskedSeed, 0, maskedSeed.Length); byte[] maskedDB = new byte [size - hLen - 1]; Buffer.BlockCopy (EM, (EM.Length - maskedDB.Length), maskedDB, 0, maskedDB.Length); byte[] seedMask = MGF1 (hash, maskedDB, hLen); byte[] seed = xor (maskedSeed, seedMask); byte[] dbMask = MGF1 (hash, seed, size - hLen - 1); byte[] DB = xor (maskedDB, dbMask); byte[] lHash = GetEmptyHash (hash); // split DB = lHash' || PS || 0x01 || M byte[] dbHash = new byte [lHash.Length]; Buffer.BlockCopy (DB, 0, dbHash, 0, dbHash.Length); bool h = Compare (lHash, dbHash); // find separator 0x01 int nPos = lHash.Length; while (DB[nPos] == 0) nPos++; int Msize = DB.Length - nPos - 1; byte[] M = new byte [Msize]; Buffer.BlockCopy (DB, (nPos + 1), M, 0, Msize); // we could have returned EM[0] sooner but would be helping a timing attack if ((EM[0] != 0) || (!h) || (DB[nPos] != 0x01)) return null; return M; } // PKCS #1 v.2.1, Section 7.2.1 // RSAES-PKCS1-V1_5-ENCRYPT ((n, e), M) public static byte[] Encrypt_v15 (RSA rsa, RandomNumberGenerator rng, byte[] M) { int size = rsa.KeySize / 8; if (M.Length > size - 11) throw new CryptographicException ("message too long"); int PSLength = System.Math.Max (8, (size - M.Length - 3)); byte[] PS = new byte [PSLength]; rng.GetNonZeroBytes (PS); byte[] EM = new byte [size]; EM [1] = 0x02; Buffer.BlockCopy (PS, 0, EM, 2, PSLength); Buffer.BlockCopy (M, 0, EM, (size - M.Length), M.Length); byte[] m = OS2IP (EM); byte[] c = RSAEP (rsa, m); byte[] C = I2OSP (c, size); return C; } // PKCS #1 v.2.1, Section 7.2.2 // RSAES-PKCS1-V1_5-DECRYPT (K, C) public static byte[] Decrypt_v15 (RSA rsa, byte[] C) { int size = rsa.KeySize >> 3; // div by 8 if ((size < 11) || (C.Length > size)) throw new CryptographicException ("decryption error"); byte[] c = OS2IP (C); byte[] m = RSADP (rsa, c); byte[] EM = I2OSP (m, size); if ((EM [0] != 0x00) || (EM [1] != 0x02)) return null; int mPos = 10; // PS is a minimum of 8 bytes + 2 bytes for header while ((EM [mPos] != 0x00) && (mPos < EM.Length)) mPos++; if (EM [mPos] != 0x00) return null; mPos++; byte[] M = new byte [EM.Length - mPos]; Buffer.BlockCopy (EM, mPos, M, 0, M.Length); return M; } // PKCS #1 v.2.1, Section 8.2.1 // RSASSA-PKCS1-V1_5-SIGN (K, M) public static byte[] Sign_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue) { int size = (rsa.KeySize >> 3); // div 8 byte[] EM = Encode_v15 (hash, hashValue, size); byte[] m = OS2IP (EM); byte[] s = RSASP1 (rsa, m); byte[] S = I2OSP (s, size); return S; } // PKCS #1 v.2.1, Section 8.2.2 // RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue, byte[] signature) { return Verify_v15 (rsa, hash, hashValue, signature, false); } // DO NOT USE WITHOUT A VERY GOOD REASON public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte [] hashValue, byte [] signature, bool tryNonStandardEncoding) { int size = (rsa.KeySize >> 3); // div 8 byte[] s = OS2IP (signature); byte[] m = RSAVP1 (rsa, s); byte[] EM2 = I2OSP (m, size); byte[] EM = Encode_v15 (hash, hashValue, size); bool result = Compare (EM, EM2); if (result || !tryNonStandardEncoding) return result; // NOTE: some signatures don't include the hash OID (pretty lame but real) // and compatible with MS implementation. E.g. Verisign Authenticode Timestamps // we're making this "as safe as possible" if ((EM2 [0] != 0x00) || (EM2 [1] != 0x01)) return false; int i; for (i = 2; i < EM2.Length - hashValue.Length - 1; i++) { if (EM2 [i] != 0xFF) return false; } if (EM2 [i++] != 0x00) return false; byte [] decryptedHash = new byte [hashValue.Length]; Buffer.BlockCopy (EM2, i, decryptedHash, 0, decryptedHash.Length); return Compare (decryptedHash, hashValue); } // PKCS #1 v.2.1, Section 9.2 // EMSA-PKCS1-v1_5-Encode public static byte[] Encode_v15 (HashAlgorithm hash, byte[] hashValue, int emLength) { if (hashValue.Length != (hash.HashSize >> 3)) throw new CryptographicException ("bad hash length for " + hash.ToString ()); // DigestInfo ::= SEQUENCE { // digestAlgorithm AlgorithmIdentifier, // digest OCTET STRING // } byte[] t = null; string oid = CryptoConfig.MapNameToOID (hash.ToString ()); if (oid != null) { ASN1 digestAlgorithm = new ASN1 (0x30); digestAlgorithm.Add (new ASN1 (CryptoConfig.EncodeOID (oid))); digestAlgorithm.Add (new ASN1 (0x05)); // NULL ASN1 digest = new ASN1 (0x04, hashValue); ASN1 digestInfo = new ASN1 (0x30); digestInfo.Add (digestAlgorithm); digestInfo.Add (digest); t = digestInfo.GetBytes (); } else { // There are no valid OID, in this case t = hashValue // This is the case of the MD5SHA hash algorithm t = hashValue; } Buffer.BlockCopy (hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length); int PSLength = System.Math.Max (8, emLength - t.Length - 3); // PS = PSLength of 0xff // EM = 0x00 | 0x01 | PS | 0x00 | T byte[] EM = new byte [PSLength + t.Length + 3]; EM [1] = 0x01; for (int i=2; i < PSLength + 2; i++) EM[i] = 0xff; Buffer.BlockCopy (t, 0, EM, PSLength + 3, t.Length); return EM; } // PKCS #1 v.2.1, Section B.2.1 public static byte[] MGF1 (HashAlgorithm hash, byte[] mgfSeed, int maskLen) { // 1. If maskLen > 2^32 hLen, output "mask too long" and stop. // easy - this is impossible by using a int (31bits) as parameter ;-) // BUT with a signed int we do have to check for negative values! if (maskLen < 0) throw new OverflowException(); int mgfSeedLength = mgfSeed.Length; int hLen = (hash.HashSize >> 3); // from bits to bytes int iterations = (maskLen / hLen); if (maskLen % hLen != 0) iterations++; // 2. Let T be the empty octet string. byte[] T = new byte [iterations * hLen]; byte[] toBeHashed = new byte [mgfSeedLength + 4]; int pos = 0; // 3. For counter from 0 to \ceil (maskLen / hLen) - 1, do the following: for (int counter = 0; counter < iterations; counter++) { // a. Convert counter to an octet string C of length 4 octets byte[] C = I2OSP (counter, 4); // b. Concatenate the hash of the seed mgfSeed and C to the octet string T: // T = T || Hash (mgfSeed || C) Buffer.BlockCopy (mgfSeed, 0, toBeHashed, 0, mgfSeedLength); Buffer.BlockCopy (C, 0, toBeHashed, mgfSeedLength, 4); byte[] output = hash.ComputeHash (toBeHashed); Buffer.BlockCopy (output, 0, T, pos, hLen); pos += mgfSeedLength; } // 4. Output the leading maskLen octets of T as the octet string mask. byte[] mask = new byte [maskLen]; Buffer.BlockCopy (T, 0, mask, 0, maskLen); return mask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.Tests.Common; using Xunit; public static class Int32Tests { [Fact] public static void TestCtorEmpty() { int i = new int(); Assert.Equal(0, i); } [Fact] public static void TestCtorValue() { int i = 41; Assert.Equal(41, i); } [Fact] public static void TestMaxValue() { Assert.Equal(0x7FFFFFFF, int.MaxValue); } [Fact] public static void TestMinValue() { Assert.Equal(unchecked((int)0x80000000), int.MinValue); } [Theory] [InlineData(234, 0)] [InlineData(int.MinValue, 1)] [InlineData(-123, 1)] [InlineData(0, 1)] [InlineData(45, 1)] [InlineData(123, 1)] [InlineData(456, -1)] [InlineData(int.MaxValue, -1)] public static void TestCompareTo(int value, int expected) { int i = 234; int result = CompareHelper.NormalizeCompare(i.CompareTo(value)); Assert.Equal(expected, result); } [Theory] [InlineData(null, 1)] [InlineData(234, 0)] [InlineData(int.MinValue, 1)] [InlineData(-123, 1)] [InlineData(0, 1)] [InlineData(45, 1)] [InlineData(123, 1)] [InlineData(456, -1)] [InlineData(int.MaxValue, -1)] public static void TestCompareToObject(object obj, int expected) { IComparable comparable = 234; int i = CompareHelper.NormalizeCompare(comparable.CompareTo(obj)); Assert.Equal(expected, i); } [Fact] public static void TestCompareToObjectInvalid() { IComparable comparable = 234; Assert.Throws<ArgumentException>(null, () => comparable.CompareTo("a")); //Obj is not a int } [Theory] [InlineData(789, true)] [InlineData(-789, false)] [InlineData(0, false)] public static void TestEqualsObject(object obj, bool expected) { int i = 789; Assert.Equal(expected, i.Equals(obj)); } [Theory] [InlineData(789, true)] [InlineData(-789, false)] [InlineData(0, false)] public static void TestEquals(int i2, bool expected) { int i = 789; Assert.Equal(expected, i.Equals(i2)); } [Fact] public static void TestGetHashCode() { int i1 = 123; int i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { int i1 = 6310; Assert.Equal("6310", i1.ToString()); int i2 = -8249; Assert.Equal("-8249", i2.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new NumberFormatInfo(); int i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); int i2 = -8249; Assert.Equal("-8249", i2.ToString(numberFormat)); int i3 = -2468; // Changing the negative pattern doesn't do anything without also passing in a format string numberFormat.NumberNegativePattern = 0; Assert.Equal("-2468", i3.ToString(numberFormat)); } [Fact] public static void TestToStringFormat() { int i1 = 6310; Assert.Equal("6310", i1.ToString("G")); int i2 = -8249; Assert.Equal("-8249", i2.ToString("g")); int i3 = -2468; Assert.Equal(string.Format("{0:N}", -2468.00), i3.ToString("N")); int i4 = 0x248; Assert.Equal("248", i4.ToString("x")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new NumberFormatInfo(); int i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); int i2 = -8249; Assert.Equal("-8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; int i3 = -2468; Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat)); } public static IEnumerable<object[]> ParseValidData() { NumberFormatInfo defaultFormat = null; NumberStyles defaultStyle = NumberStyles.Integer; var emptyNfi = new NumberFormatInfo(); var testNfi = new NumberFormatInfo(); testNfi.CurrencySymbol = "$"; yield return new object[] { "-2147483648", defaultStyle, defaultFormat, -2147483648 }; yield return new object[] { "0", defaultStyle, defaultFormat, 0 }; yield return new object[] { "123", defaultStyle, defaultFormat, 123 }; yield return new object[] { " 123 ", defaultStyle, defaultFormat, 123 }; yield return new object[] { "2147483647", defaultStyle, defaultFormat, 2147483647 }; yield return new object[] { "123", NumberStyles.HexNumber, defaultFormat, 0x123 }; yield return new object[] { "abc", NumberStyles.HexNumber, defaultFormat, 0xabc }; yield return new object[] { "1000", NumberStyles.AllowThousands, defaultFormat, 1000 }; yield return new object[] { "(123)", NumberStyles.AllowParentheses, defaultFormat, -123 }; // Parentheses = negative yield return new object[] { "123", defaultStyle, emptyNfi, 123 }; yield return new object[] { "123", NumberStyles.Any, emptyNfi, 123 }; yield return new object[] { "12", NumberStyles.HexNumber, emptyNfi, 0x12 }; yield return new object[] { "$1,000", NumberStyles.Currency, testNfi, 1000 }; } public static IEnumerable<object[]> ParseInvalidData() { NumberFormatInfo defaultFormat = null; NumberStyles defaultStyle = NumberStyles.Integer; var emptyNfi = new NumberFormatInfo(); var testNfi = new NumberFormatInfo(); testNfi.CurrencySymbol = "$"; testNfi.NumberDecimalSeparator = "."; yield return new object[] { null, defaultStyle, defaultFormat, typeof(ArgumentNullException) }; yield return new object[] { "", defaultStyle, defaultFormat, typeof(FormatException) }; yield return new object[] { " ", defaultStyle, defaultFormat, typeof(FormatException) }; yield return new object[] { "Garbage", defaultStyle, defaultFormat, typeof(FormatException) }; yield return new object[] { "abc", defaultStyle, defaultFormat, typeof(FormatException) }; // Hex value yield return new object[] { "1E23", defaultStyle, defaultFormat, typeof(FormatException) }; // Exponent yield return new object[] { "(123)", defaultStyle, defaultFormat, typeof(FormatException) }; // Parentheses yield return new object[] { 1000.ToString("C0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Currency yield return new object[] { 1000.ToString("N0"), defaultStyle, defaultFormat, typeof(FormatException) }; //Thousands yield return new object[] { 678.90.ToString("F2"), defaultStyle, defaultFormat, typeof(FormatException) }; //Decimal yield return new object[] { "abc", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Negative hex value yield return new object[] { " 123 ", NumberStyles.None, defaultFormat, typeof(FormatException) }; // Trailing and leading whitespace yield return new object[] { "67.90", defaultStyle, testNfi, typeof(FormatException) }; // Decimal yield return new object[] { "-2147483649", defaultStyle, defaultFormat, typeof(OverflowException) }; // > max value yield return new object[] { "2147483648", defaultStyle, defaultFormat, typeof(OverflowException) }; // < min value } [Theory, MemberData(nameof(ParseValidData))] public static void TestParse(string value, NumberStyles style, NumberFormatInfo nfi, int expected) { int i; //If no style is specified, use the (String) or (String, IFormatProvider) overload if (style == NumberStyles.Integer) { Assert.Equal(true, int.TryParse(value, out i)); Assert.Equal(expected, i); Assert.Equal(expected, int.Parse(value)); //If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload if (nfi != null) { Assert.Equal(expected, int.Parse(value, nfi)); } } // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo Assert.Equal(true, int.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i)); Assert.Equal(expected, i); //If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload if (nfi == null) { Assert.Equal(expected, int.Parse(value, style)); } Assert.Equal(expected, int.Parse(value, style, nfi ?? new NumberFormatInfo())); } [Theory, MemberData(nameof(ParseInvalidData))] public static void TestParseInvalid(string value, NumberStyles style, NumberFormatInfo nfi, Type exceptionType) { int i; //If no style is specified, use the (String) or (String, IFormatProvider) overload if (style == NumberStyles.Integer) { Assert.Equal(false, int.TryParse(value, out i)); Assert.Equal(default(int), i); Assert.Throws(exceptionType, () => int.Parse(value)); //If a format provider is specified, but the style is the default, use the (String, IFormatProvider) overload if (nfi != null) { Assert.Throws(exceptionType, () => int.Parse(value, nfi)); } } // If a format provider isn't specified, test the default one, using a new instance of NumberFormatInfo Assert.Equal(false, int.TryParse(value, style, nfi ?? new NumberFormatInfo(), out i)); Assert.Equal(default(int), i); //If a format provider isn't specified, test the default one, using the (String, NumberStyles) overload if (nfi == null) { Assert.Throws(exceptionType, () => int.Parse(value, style)); } Assert.Throws(exceptionType, () => int.Parse(value, style, nfi ?? new NumberFormatInfo())); } }
#region File Description //----------------------------------------------------------------------------- // GraphicsDeviceControl.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Drawing; using System.Windows.Forms; using Microsoft.Xna.Framework.Graphics; #endregion namespace LTreeDemo { // System.Drawing and the XNA Framework both define Color and Rectangle // types. To avoid conflicts, we specify exactly which ones to use. using Color = System.Drawing.Color; using Rectangle = Microsoft.Xna.Framework.Rectangle; /// <summary> /// Custom control uses the XNA Framework GraphicsDevice to render onto /// a Windows Form. Derived classes can override the Initialize and Draw /// methods to add their own drawing code. /// </summary> abstract public class GraphicsDeviceControl : Control { #region Fields // However many GraphicsDeviceControl instances you have, they all share // the same underlying GraphicsDevice, managed by this helper service. GraphicsDeviceService graphicsDeviceService; #endregion #region Properties /// <summary> /// Gets a GraphicsDevice that can be used to draw onto this control. /// </summary> public GraphicsDevice GraphicsDevice { get { return graphicsDeviceService.GraphicsDevice; } } /// <summary> /// Gets an IServiceProvider containing our IGraphicsDeviceService. /// This can be used with components such as the ContentManager, /// which use this service to look up the GraphicsDevice. /// </summary> public ServiceContainer Services { get { return services; } } ServiceContainer services = new ServiceContainer(); #endregion #region Initialization /// <summary> /// Initializes the control. /// </summary> protected override void OnCreateControl() { // Don't initialize the graphics device if we are running in the designer. if (!DesignMode) { graphicsDeviceService = GraphicsDeviceService.AddRef(Handle, ClientSize.Width, ClientSize.Height); // Register the service, so components like ContentManager can find it. services.AddService<IGraphicsDeviceService>(graphicsDeviceService); // Give derived classes a chance to initialize themselves. Initialize(); } base.OnCreateControl(); } /// <summary> /// Disposes the control. /// </summary> protected override void Dispose(bool disposing) { if (graphicsDeviceService != null) { graphicsDeviceService.Release(disposing); graphicsDeviceService = null; } base.Dispose(disposing); } #endregion #region Paint /// <summary> /// Redraws the control in response to a WinForms paint message. /// </summary> protected override void OnPaint(PaintEventArgs e) { string beginDrawError = BeginDraw(); if (string.IsNullOrEmpty(beginDrawError)) { // Draw the control using the GraphicsDevice. // Not exactly sure why, but in XNA 4.0 if we Present() without // actually clearing or drawing anything, a solid blue colour // comes up. if (Draw()) EndDraw(); } else { // If BeginDraw failed, show an error message using System.Drawing. PaintUsingSystemDrawing(e.Graphics, beginDrawError); } } /// <summary> /// Attempts to begin drawing the control. Returns an error message string /// if this was not possible, which can happen if the graphics device is /// lost, or if we are running inside the Form designer. /// </summary> string BeginDraw() { // If we have no graphics device, we must be running in the designer. if (graphicsDeviceService == null) { return Text + "\n\n" + GetType(); } // Make sure the graphics device is big enough, and is not lost. string deviceResetError = HandleDeviceReset(); if (!string.IsNullOrEmpty(deviceResetError)) { return deviceResetError; } // Many GraphicsDeviceControl instances can be sharing the same // GraphicsDevice. The device backbuffer will be resized to fit the // largest of these controls. But what if we are currently drawing // a smaller control? To avoid unwanted stretching, we set the // viewport to only use the top left portion of the full backbuffer. Viewport viewport = new Viewport(); viewport.X = 0; viewport.Y = 0; viewport.Width = ClientSize.Width; viewport.Height = ClientSize.Height; viewport.MinDepth = 0; viewport.MaxDepth = 1; GraphicsDevice.Viewport = viewport; return null; } /// <summary> /// Ends drawing the control. This is called after derived classes /// have finished their Draw method, and is responsible for presenting /// the finished image onto the screen, using the appropriate WinForms /// control handle to make sure it shows up in the right place. /// </summary> void EndDraw() { try { Rectangle sourceRectangle = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height); // TODO: Can't call Present with parameters in MonoGame v3.2. //GraphicsDevice.Present(sourceRectangle, null, this.Handle); GraphicsDevice.Present(); } catch { // Present might throw if the device became lost while we were // drawing. The lost device will be handled by the next BeginDraw, // so we just swallow the exception. } } /// <summary> /// Helper used by BeginDraw. This checks the graphics device status, /// making sure it is big enough for drawing the current control, and /// that the device is not lost. Returns an error string if the device /// could not be reset. /// </summary> string HandleDeviceReset() { bool deviceNeedsReset = false; switch (GraphicsDevice.GraphicsDeviceStatus) { case GraphicsDeviceStatus.Lost: // If the graphics device is lost, we cannot use it at all. return "Graphics device lost"; case GraphicsDeviceStatus.NotReset: // If device is in the not-reset state, we should try to reset it. deviceNeedsReset = true; break; default: // If the device state is ok, check whether it is big enough. PresentationParameters pp = GraphicsDevice.PresentationParameters; deviceNeedsReset = (ClientSize.Width > pp.BackBufferWidth) || (ClientSize.Height > pp.BackBufferHeight); break; } // Do we need to reset the device? if (deviceNeedsReset) { try { graphicsDeviceService.ResetDevice(ClientSize.Width, ClientSize.Height); } catch (Exception e) { return "Graphics device reset failed\n\n" + e; } } return null; } /// <summary> /// If we do not have a valid graphics device (for instance if the device /// is lost, or if we are running inside the Form designer), we must use /// regular System.Drawing method to display a status message. /// </summary> protected virtual void PaintUsingSystemDrawing(Graphics graphics, string text) { graphics.Clear(Color.CornflowerBlue); using (Brush brush = new SolidBrush(Color.Black)) { using (StringFormat format = new StringFormat()) { format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; graphics.DrawString(text, Font, brush, ClientRectangle, format); } } } /// <summary> /// Ignores WinForms paint-background messages. The default implementation /// would clear the control to the current background color, causing /// flickering when our OnPaint implementation then immediately draws some /// other color over the top using the XNA Framework GraphicsDevice. /// </summary> protected override void OnPaintBackground(PaintEventArgs pevent) { } #endregion #region Abstract Methods /// <summary> /// Derived classes override this to initialize their drawing code. /// </summary> protected abstract void Initialize(); /// <summary> /// Derived classes override this to draw themselves using the GraphicsDevice. /// </summary> protected abstract bool Draw(); #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.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.DeriveBytesTests { public class Rfc2898Tests { // 8 bytes is the minimum accepted value, by using it we've already assured that the minimum is acceptable. private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 }; private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 }; private const string TestPassword = "PasswordGoesHere"; private const string TestPasswordB = "FakePasswordsAreHard"; private const int DefaultIterationCount = 1000; [Fact] public static void Ctor_NullPasswordBytes() { Assert.Throws<NullReferenceException>(() => new Rfc2898DeriveBytes((byte[])null, s_testSalt, DefaultIterationCount)); } [Fact] public static void Ctor_NullPasswordString() { Assert.Throws<ArgumentNullException>(() => new Rfc2898DeriveBytes((string)null, s_testSalt, DefaultIterationCount)); } [Fact] public static void Ctor_NullSalt() { Assert.Throws<ArgumentNullException>(() => new Rfc2898DeriveBytes(TestPassword, null, DefaultIterationCount)); } [Fact] public static void Ctor_EmptySalt() { AssertExtensions.Throws<ArgumentException>("salt", null, () => new Rfc2898DeriveBytes(TestPassword, Array.Empty<byte>(), DefaultIterationCount)); } [Fact] public static void Ctor_DiminishedSalt() { AssertExtensions.Throws<ArgumentException>("salt", null, () => new Rfc2898DeriveBytes(TestPassword, new byte[7], DefaultIterationCount)); } [Fact] public static void Ctor_GenerateZeroSalt() { AssertExtensions.Throws<ArgumentException>("saltSize", null, () => new Rfc2898DeriveBytes(TestPassword, 0)); } [Fact] public static void Ctor_GenerateNegativeSalt() { Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, int.MinValue / 2)); } [Fact] public static void Ctor_GenerateDiminishedSalt() { AssertExtensions.Throws<ArgumentException>("saltSize", null, () => new Rfc2898DeriveBytes(TestPassword, 7)); } [Fact] public static void Ctor_TooFewIterations() { Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, 0)); } [Fact] public static void Ctor_NegativeIterations() { Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, int.MinValue / 2)); } #if netcoreapp [Fact] public static void Ctor_EmptyAlgorithm() { HashAlgorithmName alg = default(HashAlgorithmName); // (byte[], byte[], int, HashAlgorithmName) Assert.Throws<CryptographicException>(() => new Rfc2898DeriveBytes(s_testSalt, s_testSalt, DefaultIterationCount, alg)); // (string, byte[], int, HashAlgorithmName) Assert.Throws<CryptographicException>(() => new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, alg)); // (string, int, int, HashAlgorithmName) Assert.Throws<CryptographicException>(() => new Rfc2898DeriveBytes(TestPassword, 8, DefaultIterationCount, alg)); } [Fact] public static void Ctor_MD5NotSupported() { Assert.Throws<CryptographicException>( () => new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, HashAlgorithmName.MD5)); } [Fact] public static void Ctor_UnknownAlgorithm() { Assert.Throws<CryptographicException>( () => new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, new HashAlgorithmName("PotatoLemming"))); } #endif [Fact] public static void Ctor_SaltCopied() { byte[] saltIn = (byte[])s_testSalt.Clone(); using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, saltIn, DefaultIterationCount)) { byte[] saltOut = deriveBytes.Salt; Assert.NotSame(saltIn, saltOut); Assert.Equal(saltIn, saltOut); // Right now we know that at least one of the constructor and get_Salt made a copy, if it was // only get_Salt then this next part would fail. saltIn[0] = unchecked((byte)~saltIn[0]); // Have to read the property again to prove it's detached. Assert.NotEqual(saltIn, deriveBytes.Salt); } } [Fact] public static void Ctor_DefaultIterations() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount); } } [Fact] public static void Ctor_IterationsRespected() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt, 1)) { Assert.Equal(1, deriveBytes.IterationCount); } } [Fact] public static void GetSaltCopies() { byte[] first; byte[] second; using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount)) { first = deriveBytes.Salt; second = deriveBytes.Salt; } Assert.NotSame(first, second); Assert.Equal(first, second); } [Fact] public static void MinimumAcceptableInputs() { byte[] output; using (var deriveBytes = new Rfc2898DeriveBytes("", new byte[8], 1)) { output = deriveBytes.GetBytes(1); } Assert.Equal(1, output.Length); Assert.Equal(0xA6, output[0]); } [Fact] public static void GetBytes_ZeroLength() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(0)); } } [Fact] public static void GetBytes_NegativeLength() { Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt); Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(int.MinValue)); Assert.Throws<ArgumentOutOfRangeException>(() => deriveBytes.GetBytes(int.MinValue / 2)); } [Fact] public static void GetBytes_NotIdempotent() { byte[] first; byte[] second; using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { first = deriveBytes.GetBytes(32); second = deriveBytes.GetBytes(32); } Assert.NotEqual(first, second); } [Fact] public static void GetBytes_StreamLike() { byte[] first; using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { first = deriveBytes.GetBytes(32); } byte[] second = new byte[first.Length]; // Reset using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2); byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length); Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length); Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length); } Assert.Equal(first, second); } [Fact] public static void GetBytes_KnownValues_1() { TestKnownValue( TestPassword, s_testSalt, DefaultIterationCount, new byte[] { 0x6C, 0x3C, 0x55, 0xA4, 0x2E, 0xE9, 0xD6, 0xAE, 0x7D, 0x28, 0x6C, 0x83, 0xE4, 0xD7, 0xA3, 0xC8, 0xB5, 0x93, 0x9F, 0x45, 0x2F, 0x2B, 0xF3, 0x68, 0xFA, 0xE8, 0xB2, 0x74, 0x55, 0x3A, 0x36, 0x8A, }); } [Fact] public static void GetBytes_KnownValues_2() { TestKnownValue( TestPassword, s_testSalt, DefaultIterationCount + 1, new byte[] { 0x8E, 0x9B, 0xF7, 0xC1, 0x83, 0xD4, 0xD1, 0x20, 0x87, 0xA8, 0x2C, 0xD7, 0xCD, 0x84, 0xBC, 0x1A, 0xC6, 0x7A, 0x7A, 0xDD, 0x46, 0xFA, 0x40, 0xAA, 0x60, 0x3A, 0x2B, 0x8B, 0x79, 0x2C, 0x8A, 0x6D, }); } [Fact] public static void GetBytes_KnownValues_3() { TestKnownValue( TestPassword, s_testSaltB, DefaultIterationCount, new byte[] { 0x4E, 0xF5, 0xA5, 0x85, 0x92, 0x9D, 0x8B, 0xC5, 0x57, 0x0C, 0x83, 0xB5, 0x19, 0x69, 0x4B, 0xC2, 0x4B, 0xAA, 0x09, 0xE9, 0xE7, 0x9C, 0x29, 0x94, 0x14, 0x19, 0xE3, 0x61, 0xDA, 0x36, 0x5B, 0xB3, }); } [Fact] public static void GetBytes_KnownValues_4() { TestKnownValue( TestPasswordB, s_testSalt, DefaultIterationCount, new byte[] { 0x86, 0xBB, 0xB3, 0xD7, 0x99, 0x0C, 0xAC, 0x4D, 0x1D, 0xB2, 0x78, 0x9D, 0x57, 0x5C, 0x06, 0x93, 0x97, 0x50, 0x72, 0xFF, 0x56, 0x57, 0xAC, 0x7F, 0x9B, 0xD2, 0x14, 0x9D, 0xE9, 0x95, 0xA2, 0x6D, }); } #if netcoreapp [Theory] [MemberData(nameof(KnownValuesTestCases))] public static void GetBytes_KnownValues_WithAlgorithm(KnownValuesTestCase testCase) { byte[] output; var pbkdf2 = new Rfc2898DeriveBytes( testCase.Password, testCase.Salt, testCase.IterationCount, new HashAlgorithmName(testCase.HashAlgorithmName)); using (pbkdf2) { output = pbkdf2.GetBytes(testCase.AnswerHex.Length / 2); } Assert.Equal(testCase.AnswerHex, output.ByteArrayToHex()); } [Theory] [InlineData("SHA1")] [InlineData("SHA256")] [InlineData("SHA384")] [InlineData("SHA512")] public static void CheckHashAlgorithmValue(string hashAlgorithmName) { HashAlgorithmName hashAlgorithm = new HashAlgorithmName(hashAlgorithmName); using (var pbkdf2 = new Rfc2898DeriveBytes(TestPassword, s_testSalt, DefaultIterationCount, hashAlgorithm)) { Assert.Equal(hashAlgorithm, pbkdf2.HashAlgorithm); } } #endif public static void CryptDeriveKey_NotSupported() { using (var deriveBytes = new Rfc2898DeriveBytes(TestPassword, s_testSalt)) { Assert.Throws<PlatformNotSupportedException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[8])); } } private static void TestKnownValue(string password, byte[] salt, int iterationCount, byte[] expected) { byte[] output; using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, iterationCount)) { output = deriveBytes.GetBytes(expected.Length); } Assert.Equal(expected, output); } public static IEnumerable<object[]> KnownValuesTestCases() { HashSet<string> testCaseNames = new HashSet<string>(); // Wrap the class in the MemberData-required-object[]. foreach (KnownValuesTestCase testCase in GetKnownValuesTestCases()) { if (!testCaseNames.Add(testCase.CaseName)) { throw new InvalidOperationException($"Duplicate test case name: {testCase.CaseName}"); } yield return new object[] { testCase }; } } private static IEnumerable<KnownValuesTestCase> GetKnownValuesTestCases() { Encoding ascii = Encoding.ASCII; yield return new KnownValuesTestCase { CaseName = "RFC 3211 Section 3 #1", HashAlgorithmName = "SHA1", Password = "password", Salt = "1234567878563412".HexToByteArray(), IterationCount = 5, AnswerHex = "D1DAA78615F287E6", }; yield return new KnownValuesTestCase { CaseName = "RFC 3211 Section 3 #2", HashAlgorithmName = "SHA1", Password = "All n-entities must communicate with other n-entities via n-1 entiteeheehees", Salt = "1234567878563412".HexToByteArray(), IterationCount = 500, AnswerHex = "6A8970BF68C92CAEA84A8DF28510858607126380CC47AB2D", }; yield return new KnownValuesTestCase { CaseName = "RFC 6070 Case 5", HashAlgorithmName = "SHA1", Password = "passwordPASSWORDpassword", Salt = ascii.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"), IterationCount = 4096, AnswerHex = "3D2EEC4FE41C849B80C8D83662C0E44A8B291A964CF2F07038", }; // From OpenSSL. // https://github.com/openssl/openssl/blob/6f0ac0e2f27d9240516edb9a23b7863e7ad02898/test/evptests.txt // Corroborated on http://stackoverflow.com/questions/5130513/pbkdf2-hmac-sha2-test-vectors, // though the SO answer stopped at 25 bytes. yield return new KnownValuesTestCase { CaseName = "RFC 6070#5 SHA256", HashAlgorithmName = "SHA256", Password = "passwordPASSWORDpassword", Salt = ascii.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"), IterationCount = 4096, AnswerHex = "348C89DBCBD32B2F32D814B8116E84CF2B17347EBC1800181C4E2A1FB8DD53E1C635518C7DAC47E9", }; // From OpenSSL. yield return new KnownValuesTestCase { CaseName = "RFC 6070#5 SHA512", HashAlgorithmName = "SHA512", Password = "passwordPASSWORDpassword", Salt = ascii.GetBytes("saltSALTsaltSALTsaltSALTsaltSALTsalt"), IterationCount = 4096, AnswerHex = ( "8C0511F4C6E597C6AC6315D8F0362E225F3C501495BA23B868C005174DC4EE71" + "115B59F9E60CD9532FA33E0F75AEFE30225C583A186CD82BD4DAEA9724A3D3B8"), }; // Verified against BCryptDeriveKeyPBKDF2, as an independent implementation. yield return new KnownValuesTestCase { CaseName = "RFC 3962 Appendix B#1 SHA384-24000", HashAlgorithmName = "SHA384", Password = "password", Salt = ascii.GetBytes("ATHENA.MIT.EDUraeburn"), IterationCount = 24000, AnswerHex = ( "4B138897F289129C6E80965F96B940F76BBC0363CD22190E0BD94ADBA79BE33E" + "02C9D8E0AF0D19B295B02828770587F672E0ED182A9A59BA5E07120CA936E6BF" + "F5D425688253C2A8336ED30DA898C67FD9DDFD8EF3F8C708392E2E2458716DF8" + "6799372DEF27AB36AF239D7D654A56A51395086A322B9322977F62A98662B57E"), }; // These "alternate" tests are made up, due to a lack of test corpus diversity yield return new KnownValuesTestCase { CaseName = "SHA256 alternate", HashAlgorithmName = "SHA256", Password = "abcdefghij", Salt = ascii.GetBytes("abcdefghij"), IterationCount = 1, AnswerHex = ( // T-Block 1 "9545B9CCBF915299F09BC4E8922B34B042F32689C072539FAEA739FCA4E782" + // T-Block 2 "27B792394D6C13DB121CD16683CD738CB1717C69B34EF2B29E32306D24FCDF"), }; yield return new KnownValuesTestCase { CaseName = "SHA384 alternate", HashAlgorithmName = "SHA384", Password = "abcdefghij", Salt = ascii.GetBytes("abcdefghij"), IterationCount = 1, AnswerHex = ( // T-Block 1 "BB8CCC844224775A66E038E59B74B232232AE27C4BF9625BBF3E50317EDD9217BE7B7E07AA5697AF7D2617" + // T-Block 2 "AC02F63AA2B0EC9697B1801E70BD10A6B58CE5DE83DD18F4FFD2E8D9289716510AA0A170EF1D145F4B3247"), }; yield return new KnownValuesTestCase { CaseName = "SHA512 alternate", HashAlgorithmName = "SHA512", Password = "abcdefghij", Salt = ascii.GetBytes("abcdefghij"), IterationCount = 1, AnswerHex = ( // T-Block 1 "9D6E96B14A53207C759DBB456B2F038170AF03389096E6EEB2161B3868D3E5" + "1265A25EF7D7433BF8718DB14F934B6054ACCEA283528AD11A669C7C85196F" + // T-Block 2 "B5DFAA2185446D6218EBC2D4030A83A4353B302E698C8521B6B69F7D5612EF" + "AF060798DF40183FE6B71F2D35C60FBE27DFE963EFEE52A5756323BA1A41F6"), }; } public class KnownValuesTestCase { public string CaseName { get; set; } public string HashAlgorithmName { get; set; } public string Password { get; set; } public byte[] Salt { get; set; } public int IterationCount { get; set; } public string AnswerHex { get; set; } public override string ToString() { return CaseName; } } } }
/* * 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.Diagnostics; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using log4net; using log4net.Appender; using log4net.Core; using log4net.Repository; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Statistics; using Timer=System.Timers.Timer; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework.Servers { /// <summary> /// Common base for the main OpenSimServers (user, grid, inventory, region, etc) /// </summary> public abstract class BaseOpenSimServer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This will control a periodic log printout of the current 'show stats' (if they are active) for this /// server. /// </summary> private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000); protected CommandConsole m_console; protected OpenSimAppender m_consoleAppender; protected IAppender m_logFileAppender = null; /// <summary> /// Time at which this server was started /// </summary> protected DateTime m_startuptime; /// <summary> /// Record the initial startup directory for info purposes /// </summary> protected string m_startupDirectory = Environment.CurrentDirectory; /// <summary> /// Server version information. Usually VersionInfo + information about git commit, operating system, etc. /// </summary> protected string m_version; protected string m_pidFile = String.Empty; /// <summary> /// Random uuid for private data /// </summary> protected string m_osSecret = String.Empty; protected BaseHttpServer m_httpServer; public BaseHttpServer HttpServer { get { return m_httpServer; } } /// <summary> /// Holds the non-viewer statistics collection object for this service/server /// </summary> protected IStatsCollector m_stats; public BaseOpenSimServer() { m_startuptime = DateTime.Now; m_version = VersionInfo.Version; // Random uuid for private data m_osSecret = UUID.Random().ToString(); m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics); m_periodicDiagnosticsTimer.Enabled = true; // This thread will go on to become the console listening thread Thread.CurrentThread.Name = "ConsoleThread"; ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "LogFileAppender") { m_logFileAppender = appender; } } } /// <summary> /// Must be overriden by child classes for their own server specific startup behaviour. /// </summary> protected virtual void StartupSpecific() { if (m_console != null) { ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "Console") { m_consoleAppender = (OpenSimAppender)appender; break; } } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); } else { m_consoleAppender.Console = m_console; // If there is no threshold set then the threshold is effectively everything. if (null == m_consoleAppender.Threshold) m_consoleAppender.Threshold = Level.All; Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } m_console.Commands.AddCommand("base", false, "quit", "quit", "Quit the application", HandleQuit); m_console.Commands.AddCommand("base", false, "shutdown", "shutdown", "Quit the application", HandleQuit); m_console.Commands.AddCommand("base", false, "set log level", "set log level <level>", "Set the console logging level", HandleLogLevel); m_console.Commands.AddCommand("base", false, "show info", "show info", "Show general information", HandleShow); m_console.Commands.AddCommand("base", false, "show stats", "show stats", "Show statistics", HandleShow); m_console.Commands.AddCommand("base", false, "show threads", "show threads", "Show thread status", HandleShow); m_console.Commands.AddCommand("base", false, "show uptime", "show uptime", "Show server uptime", HandleShow); m_console.Commands.AddCommand("base", false, "show version", "show version", "Show server version", HandleShow); } } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> public virtual void ShutdownSpecific() {} /// <summary> /// Provides a list of help topics that are available. Overriding classes should append their topics to the /// information returned when the base method is called. /// </summary> /// /// <returns> /// A list of strings that represent different help topics on which more information is available /// </returns> protected virtual List<string> GetHelpTopics() { return new List<string>(); } /// <summary> /// Print statistics to the logfile, if they are active /// </summary> protected void LogDiagnostics(object source, ElapsedEventArgs e) { StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n"); sb.Append(GetUptimeReport()); if (m_stats != null) { sb.Append(m_stats.Report()); } sb.Append(Environment.NewLine); sb.Append(GetThreadsReport()); m_log.Debug(sb); } /// <summary> /// Get a report about the registered threads in this server. /// </summary> protected string GetThreadsReport() { StringBuilder sb = new StringBuilder(); ProcessThreadCollection threads = ThreadTracker.GetThreads(); if (threads == null) { sb.Append("OpenSim thread tracking is only enabled in DEBUG mode."); } else { sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine); foreach (ProcessThread t in threads) { sb.Append("ID: " + t.Id + ", TotalProcessorTime: " + t.TotalProcessorTime + ", TimeRunning: " + (DateTime.Now - t.StartTime) + ", Pri: " + t.CurrentPriority + ", State: " + t.ThreadState); if (t.ThreadState == System.Diagnostics.ThreadState.Wait) sb.Append(", Reason: " + t.WaitReason + Environment.NewLine); else sb.Append(Environment.NewLine); } } int workers = 0, ports = 0, maxWorkers = 0, maxPorts = 0; ThreadPool.GetAvailableThreads(out workers, out ports); ThreadPool.GetMaxThreads(out maxWorkers, out maxPorts); sb.Append(Environment.NewLine + "*** ThreadPool threads ***" + Environment.NewLine); sb.Append("workers: " + (maxWorkers - workers) + " (" + maxWorkers + "); ports: " + (maxPorts - ports) + " (" + maxPorts + ")" + Environment.NewLine); return sb.ToString(); } /// <summary> /// Return a report about the uptime of this server /// </summary> /// <returns></returns> protected string GetUptimeReport() { StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now)); sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime)); sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime)); return sb.ToString(); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> public virtual void Startup() { m_log.Info("[STARTUP]: Beginning startup processing"); EnhanceVersionInformation(); m_log.Info("[STARTUP]: OpenSimulator version: " + m_version + Environment.NewLine); // clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and // the clr version number doesn't match the project version number under Mono. //m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine); m_log.Info("[STARTUP]: Operating system version: " + Environment.OSVersion + Environment.NewLine); StartupSpecific(); TimeSpan timeTaken = DateTime.Now - m_startuptime; m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds); } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> public virtual void Shutdown() { ShutdownSpecific(); m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting..."); RemovePIDFile(); Environment.Exit(0); } private void HandleQuit(string module, string[] args) { Shutdown(); } private void HandleLogLevel(string module, string[] cmd) { if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); return; } string rawLevel = cmd[3]; ILoggerRepository repository = LogManager.GetRepository(); Level consoleLevel = repository.LevelMap[rawLevel]; if (consoleLevel != null) m_consoleAppender.Threshold = consoleLevel; else Notice( String.Format( "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", rawLevel)); Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } /// <summary> /// Show help information /// </summary> /// <param name="helpArgs"></param> protected virtual void ShowHelp(string[] helpArgs) { Notice(""); if (helpArgs.Length == 0) { Notice("set log level [level] - change the console logging level only. For example, off or debug."); Notice("show info - show server information (e.g. startup path)."); if (m_stats != null) Notice("show stats - show statistical information for this server"); Notice("show threads - list tracked threads"); Notice("show uptime - show server startup time and uptime."); Notice("show version - show server version."); Notice(""); return; } } public virtual void HandleShow(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "info": Notice("Version: " + m_version); Notice("Startup directory: " + m_startupDirectory); break; case "stats": if (m_stats != null) Notice(m_stats.Report()); break; case "threads": Notice(GetThreadsReport()); break; case "uptime": Notice(GetUptimeReport()); break; case "version": Notice( String.Format( "Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion)); break; } } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> protected void Notice(string msg) { if (m_console != null) { m_console.Output(msg); } } /// <summary> /// Enhance the version string with extra information if it's available. /// </summary> protected void EnhanceVersionInformation() { string buildVersion = string.Empty; // Add commit hash and date information if available // The commit hash and date are stored in a file bin/.version // This file can automatically created by a post // commit script in the opensim git master repository or // by issuing the follwoing command from the top level // directory of the opensim repository // git log -n 1 --pretty="format:%h: %ci" >bin/.version // For the full git commit hash use %H instead of %h // // The subversion information is deprecated and will be removed at a later date // Add subversion revision information if available // Try file "svn_revision" in the current directory first, then the .svn info. // This allows to make the revision available in simulators not running from the source tree. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place // elsewhere as well string svnRevisionFileName = "svn_revision"; string svnFileName = ".svn/entries"; string gitCommitFileName = ".version"; string inputLine; int strcmp; if (File.Exists(gitCommitFileName)) { StreamReader CommitFile = File.OpenText(gitCommitFileName); buildVersion = CommitFile.ReadLine(); CommitFile.Close(); m_version += buildVersion ?? ""; } // Remove the else logic when subversion mirror is no longer used else { if (File.Exists(svnRevisionFileName)) { StreamReader RevisionFile = File.OpenText(svnRevisionFileName); buildVersion = RevisionFile.ReadLine(); buildVersion.Trim(); RevisionFile.Close(); } if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName)) { StreamReader EntriesFile = File.OpenText(svnFileName); inputLine = EntriesFile.ReadLine(); while (inputLine != null) { // using the dir svn revision at the top of entries file strcmp = String.Compare(inputLine, "dir"); if (strcmp == 0) { buildVersion = EntriesFile.ReadLine(); break; } else { inputLine = EntriesFile.ReadLine(); } } EntriesFile.Close(); } m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6); } } protected void CreatePIDFile(string path) { try { string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); FileStream fs = File.Create(path); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(pidstring); fs.Write(buf, 0, buf.Length); fs.Close(); m_pidFile = path; } catch (Exception) { } } public string osSecret { // Secret uuid for the simulator get { return m_osSecret; } } public string StatReport(OSHttpRequest httpRequest) { // If we catch a request for "callback", wrap the response in the value for jsonp if (httpRequest.Query.ContainsKey("callback")) { return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");"; } else { return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version); } } protected void RemovePIDFile() { if (m_pidFile != String.Empty) { try { File.Delete(m_pidFile); m_pidFile = String.Empty; } catch (Exception) { } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Azure.Core.Pipeline; #pragma warning disable SA1402 // File may only contain a single type // branching logic on wrapping seekable vs unseekable streams has been handled via inheritance namespace Azure.Storage.Shared { /// <summary> /// Exposes a predetermined slice of a larger stream using the same Stream interface. /// There should not be access to the base stream while this facade is in use. /// </summary> internal abstract class WindowStream : StreamSlice { private Stream InnerStream { get; } public override long AbsolutePosition { get; } public override bool CanRead => true; public override bool CanWrite => false; /// <summary> /// Constructs a window of an underlying stream. /// </summary> /// <param name="stream"> /// Potentialy unseekable stream to expose a window of. /// </param> /// <param name="absolutePosition"> /// The offset of this stream from the start of the wrapped stream. /// </param> private WindowStream(Stream stream, long absolutePosition) { InnerStream = stream; AbsolutePosition = absolutePosition; } public static WindowStream GetWindow(Stream stream, long maxWindowLength, long absolutePosition = default) { if (stream.CanSeek) { return new SeekableWindowStream(stream, maxWindowLength); } else { return new UnseekableWindowStream(stream, maxWindowLength, absolutePosition); } } public override void Flush() { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); public override void WriteByte(byte value) => throw new NotSupportedException(); /// <inheritdoc/> /// <remarks> /// Implementing this method takes advantage of any optimizations in the wrapped stream's implementation. /// </remarks> public override int ReadByte() { if (AdjustCount(1) <= 0) { return -1; } int val = InnerStream.ReadByte(); if (val != -1) { ReportInnerStreamRead(1); } return val; } public override int Read(byte[] buffer, int offset, int count) => ReadInternal(buffer, offset, count, async: false, cancellationToken: default).EnsureCompleted(); public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => await ReadInternal(buffer, offset, count, async: true, cancellationToken).ConfigureAwait(false); private async Task<int> ReadInternal(byte[] buffer, int offset, int count, bool async, CancellationToken cancellationToken) { count = AdjustCount(count); if (count <= 0) { return 0; } int result = async ? await InnerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false) : InnerStream.Read(buffer, offset, count); ReportInnerStreamRead(result); return result; } protected abstract int AdjustCount(int count); protected abstract void ReportInnerStreamRead(int resultRead); /// <summary> /// Exposes a predetermined slice of a larger, unseekable stream using the same Stream /// interface. There should not be access to the base stream while this facade is in use. /// This stream wrapper is unseekable. To wrap a partition of an unseekable stream where /// the partition is seekable, see <see cref="PooledMemoryStream"/>. /// </summary> private class UnseekableWindowStream : WindowStream { private long _position = 0; private long MaxLength { get; } public UnseekableWindowStream(Stream stream, long maxWindowLength, long absolutePosition) : base(stream, absolutePosition) { MaxLength = maxWindowLength; } public override bool CanSeek => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); protected override int AdjustCount(int count) => (int)Math.Min(count, MaxLength - _position); protected override void ReportInnerStreamRead(int resultRead) => _position += resultRead; } /// <summary> /// Exposes a predetermined slice of a larger, seekable stream using the same Stream /// interface. There should not be access to the base stream while this facade is in use. /// This stream wrapper is sseekable. To wrap a partition of an unseekable stream where /// the partition is seekable, see <see cref="PooledMemoryStream"/>. /// </summary> private class SeekableWindowStream : WindowStream { public SeekableWindowStream(Stream stream, long maxWindowLength) : base(stream, stream.Position) { // accessing the stream's Position in the constructor acts as our validator that we're wrapping a seekable stream Length = Math.Min( stream.Length - stream.Position, maxWindowLength); } public override bool CanSeek => true; public override long Length { get; } public override long Position { get => InnerStream.Position - AbsolutePosition; set => InnerStream.Position = AbsolutePosition + value; } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: InnerStream.Seek(AbsolutePosition + offset, SeekOrigin.Begin); break; case SeekOrigin.Current: InnerStream.Seek(InnerStream.Position + offset, SeekOrigin.Current); break; case SeekOrigin.End: InnerStream.Seek((AbsolutePosition + this.Length) - InnerStream.Length + offset, SeekOrigin.End); break; } return Position; } public override void SetLength(long value) => throw new NotSupportedException(); protected override int AdjustCount(int count) => (int)Math.Min(count, Length - Position); protected override void ReportInnerStreamRead(int resultRead) { // no-op, inner stream took care of position adjustment } } } internal static partial class StreamExtensions { /// <summary> /// Some streams will throw if you try to access their length so we wrap /// the check in a TryGet helper. /// </summary> public static long? GetPositionOrDefault(this Stream content) { if (content == null) { /* Returning 0 instead of default puts us on the quick and clean one-shot upload, * which produces more consistent fail state with how a 1-1 method on the convenience * layer would fail. */ return 0; } try { if (content.CanSeek) { return content.Position; } } catch (NotSupportedException) { } return default; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using Microsoft.VisualBasic.CompilerServices; using System; using System.Diagnostics.Contracts; namespace Microsoft.VisualBasic { // Summary: // The Interaction module contains procedures used to interact with objects, // applications, and systems. //[StandardModule] public static class Interaction { #if !SILVERLIGHT // Summary: // Activates an application that is already running. // // Parameters: // ProcessId: // Integer specifying the Win32 process ID number assigned to this process. // You can use the ID returned by the Shell Function, provided it is not zero. [Pure] extern public static void AppActivate(int ProcessId); // // Summary: // Activates an application that is already running. // // Parameters: // Title: // String expression specifying the title in the title bar of the application // you want to activate. You can use the title assigned to the application when // it was launched. [Pure] extern public static void AppActivate(string Title); // // Summary: // Sounds a tone through the computer's speaker. [Pure] extern public static void Beep(); #endif // // Summary: // Executes a method on an object, or sets or returns a property on an object. // // Parameters: // ObjectRef: // Required. Object. A pointer to the object exposing the property or method. // // ProcName: // Required. String. A string expression containing the name of the property // or method on the object. // // UseCallType: // Required. An enumeration member of type CallType Enumeration representing // the type of procedure being called. The value of CallType can be Method, // Get, or Set. // // Args: // Optional. ParamArray. A parameter array containing the arguments to be passed // to the property or method being called. // // Returns: // Executes a method on an object, or sets or returns a property on an object. // public static object CallByName(object ObjectRef, string ProcName, CallType UseCallType, params object[] Args); // // Summary: // Selects and returns a value from a list of arguments. // // Parameters: // Index: // Required. Double. Numeric expression that results in a value between 1 and // the number of elements passed in the Choice argument. // // Choice: // Required. Object parameter array. You can supply either a single variable // or an expression that evaluates to the Object data type, to a list of Object // variables or expressions separated by commas, or to a single-dimensional // array of Object elements. // // Returns: // Selects and returns a value from a list of arguments. [Pure] public static object Choose(double Index, params object[] Choice) { Contract.Requires(Choice.Rank == 1); Contract.Requires(Index >= 0); Contract.Requires(Index < Choice.Length); return default(object); } #if !SILVERLIGHT // // Summary: // Returns the argument portion of the command line used to start Visual Basic // or an executable program developed with Visual Basic. The My feature provides // greater productivity and performance than the Command function. For more // information, see My.Application.CommandLineArgs Property. // // Returns: // Returns the argument portion of the command line used to start Visual Basic // or an executable program developed with Visual Basic.The My feature provides // greater productivity and performance than the Command function. For more // information, see My.Application.CommandLineArgs Property. [Pure] public static string Command() { Contract.Ensures(Contract.Result<string>() != null); return default(string); } #endif // // Summary: // Creates and returns a reference to a COM object. CreateObject cannot be used // to create instances of classes in Visual Basic unless those classes are explicitly // exposed as COM components. // // Parameters: // ProgId: // Required. String. The program ID of the object to create. // // ServerName: // Optional. String. The name of the network server where the object will be // created. If ServerName is an empty string (""), the local computer is used. // // Returns: // Creates and returns a reference to a COM object. CreateObject cannot be used // to create instances of classes in Visual Basic unless those classes are explicitly // exposed as COM components. //public static object CreateObject(string ProgId, string ServerName); // // Summary: // Deletes a section or key setting from an application's entry in the Windows // registry. The My feature gives you greater productivity and performance in // registry operations than the DeleteSetting function. For more information, // see My.Computer.Registry Object. // // Parameters: // AppName: // Required. String expression containing the name of the application or project // to which the section or key setting applies. // // Section: // Required. String expression containing the name of the section from which // the key setting is being deleted. If only AppName and Section are provided, // the specified section is deleted along with all related key settings. // // Key: // Optional. String expression containing the name of the key setting being // deleted. //public static void DeleteSetting(string AppName, string Section, string Key); #if !SILVERLIGHT // Summary: // Returns the string associated with an operating-system environment variable. // // Parameters: // Expression: // Required. Expression that evaluates either a string containing the name of // an environment variable, or an integer corresponding to the numeric order // of an environment string in the environment-string table. // // Returns: // Returns the string associated with an operating-system environment variable. [Pure] public static string Environ(int Expression) { Contract.Requires(Expression > 0); Contract.Requires(Expression <= 0xff); Contract.Ensures(Contract.Result<string>() != null); return default(string); } #endif // // Summary: // Returns the string associated with an operating-system environment variable. // // Parameters: // Expression: // Required. Expression that evaluates either a string containing the name of // an environment variable, or an integer corresponding to the numeric order // of an environment string in the environment-string table. // // Returns: // Returns the string associated with an operating-system environment variable. //public static string Environ(string Expression); // // Summary: // Returns a list of key settings and their respective values (originally created // with SaveSetting) from an application's entry in the Windows registry. Using // the My feature gives you greater productivity and performance in registry // operations than GetAllSettings. For more information, see My.Computer.Registry // Object. // // Parameters: // AppName: // Required. String expression containing the name of the application or project // whose key settings are requested. // // Section: // Required. String expression containing the name of the section whose key // settings are requested. GetAllSettings returns an object that contains a // two-dimensional array of strings. The strings contain all the key settings // in the specified section, plus their corresponding values. // // Returns: // Returns a list of key settings and their respective values (originally created // with SaveSetting) from an application's entry in the Windows registry.Using // the My feature gives you greater productivity and performance in registry // operations than GetAllSettings. For more information, see My.Computer.Registry // Object. //public static string[,] GetAllSettings(string AppName, string Section); // // Summary: // Returns a reference to an object provided by a COM component. // // Parameters: // PathName: // Optional. String. The full path and name of the file containing the object // to retrieve. If PathName is omitted, Class is required. // // Class: // Required if PathName is not supplied. String. A string representing the class // of the object. The Class argument has the following syntax and parts:appname.objecttypeParameterDescriptionappnameRequired. // String. The name of the application providing the object.objecttypeRequired. // String. The type or class of object to create. // // Returns: // Returns a reference to an object provided by a COM component. //public static object GetObject(string PathName, string Class); // // Summary: // Returns a key setting value from an application's entry in the Windows registry. // The My feature gives you greater productivity and performance in registry // operations than GetAllSettings. For more information, see My.Computer.Registry // Object. // // Parameters: // AppName: // Required. String expression containing the name of the application or project // whose key setting is requested. // // Section: // Required. String expression containing the name of the section in which the // key setting is found. // // Key: // Required. String expression containing the name of the key setting to return. // // Default: // Optional. Expression containing the value to return if no value is set in // the Key setting. If omitted, Default is assumed to be a zero-length string // (""). // // Returns: // Returns a key setting value from an application's entry in the Windows registry.The // My feature gives you greater productivity and performance in registry operations // than GetAllSettings. For more information, see My.Computer.Registry Object. //public static string GetSetting(string AppName, string Section, string Key, string Default); // // Summary: // Returns one of two objects, depending on the evaluation of an expression. // // Parameters: // Expression: // Required. Boolean. The expression you want to evaluate. // // TruePart: // Required. Object. Returned if Expression evaluates to True. // // FalsePart: // Required. Object. Returned if Expression evaluates to False. // // Returns: // Returns one of two objects, depending on the evaluation of an expression. [Pure] public static object IIf(bool Expression, object TruePart, object FalsePart) { Contract.Ensures(Contract.Result<object>() == (Expression? TruePart : FalsePart)); return default(object); } // // Summary: // Displays a prompt in a dialog box, waits for the user to input text or click // a button, and then returns a string containing the contents of the text box. // // Parameters: // Prompt: // Required String expression displayed as the message in the dialog box. The // maximum length of Prompt is approximately 1024 characters, depending on the // width of the characters used. If Prompt consists of more than one line, you // can separate the lines using a carriage return character (Chr(13)), a line // feed character (Chr(10)), or a carriage return/line feed combination (Chr(13) // & Chr(10)) between each line. // // Title: // Optional. String expression displayed in the title bar of the dialog box. // If you omit Title, the application name is placed in the title bar. // // DefaultResponse: // Optional. String expression displayed in the text box as the default response // if no other input is provided. If you omit DefaultResponse, the displayed // text box is empty. // // XPos: // Optional. Numeric expression that specifies, in twips, the distance of the // left edge of the dialog box from the left edge of the screen. If you omit // XPos, the dialog box is centered horizontally. // // YPos: // Optional. Numeric expression that specifies, in twips, the distance of the // upper edge of the dialog box from the top of the screen. If you omit YPos, // the dialog box is positioned vertically approximately one-third of the way // down the screen. // // Returns: // Displays a prompt in a dialog box, waits for the user to input text or click // a button, and then returns a string containing the contents of the text box. //public static string InputBox(string Prompt, string Title, string DefaultResponse, int XPos, int YPos); // // Summary: // Displays a message in a dialog box, waits for the user to click a button, // and then returns an integer indicating which button the user clicked. // // Parameters: // Prompt: // Required. String expression displayed as the message in the dialog box. The // maximum length of Prompt is approximately 1024 characters, depending on the // width of the characters used. If Prompt consists of more than one line, you // can separate the lines using a carriage return character (Chr(13)), a line // feed character (Chr(10)), or a carriage return/linefeed character combination // (Chr(13) & Chr(10)) between each line. // // Buttons: // Optional. Numeric expression that is the sum of values specifying the number // and type of buttons to display, the icon style to use, the identity of the // default button, and the modality of the message box. If you omit Buttons, // the default value is zero. // // Title: // Optional. String expression displayed in the title bar of the dialog box. // If you omit Title, the application name is placed in the title bar. // // Returns: // Constant OK, Value 1. Constant Cancel, Value 2. Constant Abort, Value 3. // Constant Retry, Value 4. Constant Ignore, Value 5. Constant Yes, Value 6. // Constant No, Value 7. //public static MsgBoxResult MsgBox(object Prompt, MsgBoxStyle Buttons, object Title); // // Summary: // Returns a string representing the calculated range that contains a number. // // Parameters: // Number: // Required. Long. Whole number that you want to locate within one of the calculated // ranges. // // Start: // Required. Long. Whole number that indicates the start of the set of calculated // ranges. Start cannot be less than 0. // // Stop: // Required. Long. Whole number that indicates the end of the set of calculated // ranges. Stop cannot be less than or equal to Start. // // Interval: // Required. Long. Whole number that indicates the size of each range calculated // between Start and Stop. Interval cannot be less than 1. // // Returns: // Returns a string representing the calculated range that contains a number. [Pure] public static string Partition(long Number, long Start, long Stop, long Interval) { Contract.Requires(Start >= 0); Contract.Requires(Interval >= 1); Contract.Requires(Stop > Start); Contract.Ensures(Contract.Result<string>() != null); return default(string); } #if !SILVERLIGHT // // Summary: // Saves or creates an application entry in the Windows registry. The My feature // gives you greater productivity and performance in registry operations than // SaveSetting. For more information, see My.Computer.Registry Object. // // Parameters: // AppName: // Required. String expression containing the name of the application or project // to which the setting applies. // // Section: // Required. String expression containing the name of the section in which the // key setting is being saved. // // Key: // Required. String expression containing the name of the key setting being // saved. // // Setting: // Required. Expression containing the value to which Key is being set. [Pure] public static void SaveSetting(string AppName, string Section, string Key, string Setting) { Contract.Requires(Key != null); } #endif // // Summary: // Runs an executable program and returns an integer containing the program's // process ID if it is still running. // // Parameters: // PathName: // Required. String. Name of the program to execute, together with any required // arguments and command-line switches. PathName can also include the drive // and the directory path or folder.If you do not know the path to the program, // you can use the My.Computer.FileSystem.GetFiles Method to locate it. For // example, you can call My.Computer.FileSystem.GetFiles("C:\", True, "testFile.txt"), // which returns the full path of every file named testFile.txt anywhere on // drive C:\. // // Style: // Optional. AppWinStyle. A value chosen from the AppWinStyle Enumeration specifying // the style of the window in which the program is to run. If Style is omitted, // Shell uses AppWinStyle.MinimizedFocus, which starts the program minimized // and with focus. // // Wait: // Optional. Boolean. A value indicating whether the Shell function should wait // for completion of the program. If Wait is omitted, Shell uses False. // // Timeout: // Optional. Integer. The number of milliseconds to wait for completion if Wait // is True. If Timeout is omitted, Shell uses -1, which means there is no timeout // and Shell does not return until the program finishes. Therefore, if you omit // Timeout or set it to -1, it is possible that Shell might never return control // to your program. // // Returns: // Runs an executable program and returns an integer containing the program's // process ID if it is still running. //public static int Shell(string PathName, AppWinStyle Style, bool Wait, int Timeout) // // Summary: // Evaluates a list of expressions and returns an Object value corresponding // to the first expression in the list that is True. // // Parameters: // VarExpr: // Required. Object parameter array. Must have an even number of elements. You // can supply a list of Object variables or expressions separated by commas, // or a single-dimensional array of Object elements. // // Returns: // Evaluates a list of expressions and returns an Object value corresponding // to the first expression in the list that is True. public static object Switch(params object[] VarExpr) { Contract.Requires(VarExpr == null || VarExpr.Length % 2 == 0); // F: can return null return default(object); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the ConTurnoAuditorium class. /// </summary> [Serializable] public partial class ConTurnoAuditoriumCollection : ActiveList<ConTurnoAuditorium, ConTurnoAuditoriumCollection> { public ConTurnoAuditoriumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ConTurnoAuditoriumCollection</returns> public ConTurnoAuditoriumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { ConTurnoAuditorium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the CON_TurnoAuditoria table. /// </summary> [Serializable] public partial class ConTurnoAuditorium : ActiveRecord<ConTurnoAuditorium>, IActiveRecord { #region .ctors and Default Settings public ConTurnoAuditorium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public ConTurnoAuditorium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public ConTurnoAuditorium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public ConTurnoAuditorium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_TurnoAuditoria", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTurnoAuditoria = new TableSchema.TableColumn(schema); colvarIdTurnoAuditoria.ColumnName = "idTurnoAuditoria"; colvarIdTurnoAuditoria.DataType = DbType.Int32; colvarIdTurnoAuditoria.MaxLength = 0; colvarIdTurnoAuditoria.AutoIncrement = true; colvarIdTurnoAuditoria.IsNullable = false; colvarIdTurnoAuditoria.IsPrimaryKey = true; colvarIdTurnoAuditoria.IsForeignKey = false; colvarIdTurnoAuditoria.IsReadOnly = false; colvarIdTurnoAuditoria.DefaultSetting = @""; colvarIdTurnoAuditoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTurnoAuditoria); TableSchema.TableColumn colvarIdTurno = new TableSchema.TableColumn(schema); colvarIdTurno.ColumnName = "idTurno"; colvarIdTurno.DataType = DbType.Int32; colvarIdTurno.MaxLength = 0; colvarIdTurno.AutoIncrement = false; colvarIdTurno.IsNullable = false; colvarIdTurno.IsPrimaryKey = false; colvarIdTurno.IsForeignKey = true; colvarIdTurno.IsReadOnly = false; colvarIdTurno.DefaultSetting = @""; colvarIdTurno.ForeignKeyTableName = "CON_Turno"; schema.Columns.Add(colvarIdTurno); TableSchema.TableColumn colvarIdTurnoEstado = new TableSchema.TableColumn(schema); colvarIdTurnoEstado.ColumnName = "idTurnoEstado"; colvarIdTurnoEstado.DataType = DbType.Int32; colvarIdTurnoEstado.MaxLength = 0; colvarIdTurnoEstado.AutoIncrement = false; colvarIdTurnoEstado.IsNullable = false; colvarIdTurnoEstado.IsPrimaryKey = false; colvarIdTurnoEstado.IsForeignKey = true; colvarIdTurnoEstado.IsReadOnly = false; colvarIdTurnoEstado.DefaultSetting = @""; colvarIdTurnoEstado.ForeignKeyTableName = "CON_TurnoEstado"; schema.Columns.Add(colvarIdTurnoEstado); TableSchema.TableColumn colvarIdUsuario = new TableSchema.TableColumn(schema); colvarIdUsuario.ColumnName = "idUsuario"; colvarIdUsuario.DataType = DbType.Int32; colvarIdUsuario.MaxLength = 0; colvarIdUsuario.AutoIncrement = false; colvarIdUsuario.IsNullable = false; colvarIdUsuario.IsPrimaryKey = false; colvarIdUsuario.IsForeignKey = false; colvarIdUsuario.IsReadOnly = false; colvarIdUsuario.DefaultSetting = @""; colvarIdUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuario); TableSchema.TableColumn colvarIdServicio = new TableSchema.TableColumn(schema); colvarIdServicio.ColumnName = "idServicio"; colvarIdServicio.DataType = DbType.Int32; colvarIdServicio.MaxLength = 0; colvarIdServicio.AutoIncrement = false; colvarIdServicio.IsNullable = false; colvarIdServicio.IsPrimaryKey = false; colvarIdServicio.IsForeignKey = false; colvarIdServicio.IsReadOnly = false; colvarIdServicio.DefaultSetting = @"((0))"; colvarIdServicio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdServicio); TableSchema.TableColumn colvarIdProfesional = new TableSchema.TableColumn(schema); colvarIdProfesional.ColumnName = "idProfesional"; colvarIdProfesional.DataType = DbType.Int32; colvarIdProfesional.MaxLength = 0; colvarIdProfesional.AutoIncrement = false; colvarIdProfesional.IsNullable = false; colvarIdProfesional.IsPrimaryKey = false; colvarIdProfesional.IsForeignKey = false; colvarIdProfesional.IsReadOnly = false; colvarIdProfesional.DefaultSetting = @"((0))"; colvarIdProfesional.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdProfesional); TableSchema.TableColumn colvarIdEspecialidad = new TableSchema.TableColumn(schema); colvarIdEspecialidad.ColumnName = "idEspecialidad"; colvarIdEspecialidad.DataType = DbType.Int32; colvarIdEspecialidad.MaxLength = 0; colvarIdEspecialidad.AutoIncrement = false; colvarIdEspecialidad.IsNullable = false; colvarIdEspecialidad.IsPrimaryKey = false; colvarIdEspecialidad.IsForeignKey = false; colvarIdEspecialidad.IsReadOnly = false; colvarIdEspecialidad.DefaultSetting = @"((0))"; colvarIdEspecialidad.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEspecialidad); TableSchema.TableColumn colvarIdConsultorio = new TableSchema.TableColumn(schema); colvarIdConsultorio.ColumnName = "idConsultorio"; colvarIdConsultorio.DataType = DbType.Int32; colvarIdConsultorio.MaxLength = 0; colvarIdConsultorio.AutoIncrement = false; colvarIdConsultorio.IsNullable = false; colvarIdConsultorio.IsPrimaryKey = false; colvarIdConsultorio.IsForeignKey = false; colvarIdConsultorio.IsReadOnly = false; colvarIdConsultorio.DefaultSetting = @"((0))"; colvarIdConsultorio.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdConsultorio); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = false; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; colvarFecha.DefaultSetting = @""; colvarFecha.ForeignKeyTableName = ""; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarHora = new TableSchema.TableColumn(schema); colvarHora.ColumnName = "hora"; colvarHora.DataType = DbType.AnsiStringFixedLength; colvarHora.MaxLength = 8; colvarHora.AutoIncrement = false; colvarHora.IsNullable = false; colvarHora.IsPrimaryKey = false; colvarHora.IsForeignKey = false; colvarHora.IsReadOnly = false; colvarHora.DefaultSetting = @""; colvarHora.ForeignKeyTableName = ""; schema.Columns.Add(colvarHora); TableSchema.TableColumn colvarFechaModificacion = new TableSchema.TableColumn(schema); colvarFechaModificacion.ColumnName = "fechaModificacion"; colvarFechaModificacion.DataType = DbType.DateTime; colvarFechaModificacion.MaxLength = 0; colvarFechaModificacion.AutoIncrement = false; colvarFechaModificacion.IsNullable = false; colvarFechaModificacion.IsPrimaryKey = false; colvarFechaModificacion.IsForeignKey = false; colvarFechaModificacion.IsReadOnly = false; colvarFechaModificacion.DefaultSetting = @""; colvarFechaModificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaModificacion); TableSchema.TableColumn colvarHoraModificacion = new TableSchema.TableColumn(schema); colvarHoraModificacion.ColumnName = "horaModificacion"; colvarHoraModificacion.DataType = DbType.AnsiStringFixedLength; colvarHoraModificacion.MaxLength = 5; colvarHoraModificacion.AutoIncrement = false; colvarHoraModificacion.IsNullable = false; colvarHoraModificacion.IsPrimaryKey = false; colvarHoraModificacion.IsForeignKey = false; colvarHoraModificacion.IsReadOnly = false; colvarHoraModificacion.DefaultSetting = @""; colvarHoraModificacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarHoraModificacion); TableSchema.TableColumn colvarIdPaciente = new TableSchema.TableColumn(schema); colvarIdPaciente.ColumnName = "idPaciente"; colvarIdPaciente.DataType = DbType.Int32; colvarIdPaciente.MaxLength = 0; colvarIdPaciente.AutoIncrement = false; colvarIdPaciente.IsNullable = false; colvarIdPaciente.IsPrimaryKey = false; colvarIdPaciente.IsForeignKey = false; colvarIdPaciente.IsReadOnly = false; colvarIdPaciente.DefaultSetting = @"((0))"; colvarIdPaciente.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdPaciente); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_TurnoAuditoria",schema); } } #endregion #region Props [XmlAttribute("IdTurnoAuditoria")] [Bindable(true)] public int IdTurnoAuditoria { get { return GetColumnValue<int>(Columns.IdTurnoAuditoria); } set { SetColumnValue(Columns.IdTurnoAuditoria, value); } } [XmlAttribute("IdTurno")] [Bindable(true)] public int IdTurno { get { return GetColumnValue<int>(Columns.IdTurno); } set { SetColumnValue(Columns.IdTurno, value); } } [XmlAttribute("IdTurnoEstado")] [Bindable(true)] public int IdTurnoEstado { get { return GetColumnValue<int>(Columns.IdTurnoEstado); } set { SetColumnValue(Columns.IdTurnoEstado, value); } } [XmlAttribute("IdUsuario")] [Bindable(true)] public int IdUsuario { get { return GetColumnValue<int>(Columns.IdUsuario); } set { SetColumnValue(Columns.IdUsuario, value); } } [XmlAttribute("IdServicio")] [Bindable(true)] public int IdServicio { get { return GetColumnValue<int>(Columns.IdServicio); } set { SetColumnValue(Columns.IdServicio, value); } } [XmlAttribute("IdProfesional")] [Bindable(true)] public int IdProfesional { get { return GetColumnValue<int>(Columns.IdProfesional); } set { SetColumnValue(Columns.IdProfesional, value); } } [XmlAttribute("IdEspecialidad")] [Bindable(true)] public int IdEspecialidad { get { return GetColumnValue<int>(Columns.IdEspecialidad); } set { SetColumnValue(Columns.IdEspecialidad, value); } } [XmlAttribute("IdConsultorio")] [Bindable(true)] public int IdConsultorio { get { return GetColumnValue<int>(Columns.IdConsultorio); } set { SetColumnValue(Columns.IdConsultorio, value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime Fecha { get { return GetColumnValue<DateTime>(Columns.Fecha); } set { SetColumnValue(Columns.Fecha, value); } } [XmlAttribute("Hora")] [Bindable(true)] public string Hora { get { return GetColumnValue<string>(Columns.Hora); } set { SetColumnValue(Columns.Hora, value); } } [XmlAttribute("FechaModificacion")] [Bindable(true)] public DateTime FechaModificacion { get { return GetColumnValue<DateTime>(Columns.FechaModificacion); } set { SetColumnValue(Columns.FechaModificacion, value); } } [XmlAttribute("HoraModificacion")] [Bindable(true)] public string HoraModificacion { get { return GetColumnValue<string>(Columns.HoraModificacion); } set { SetColumnValue(Columns.HoraModificacion, value); } } [XmlAttribute("IdPaciente")] [Bindable(true)] public int IdPaciente { get { return GetColumnValue<int>(Columns.IdPaciente); } set { SetColumnValue(Columns.IdPaciente, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a ConTurno ActiveRecord object related to this ConTurnoAuditorium /// /// </summary> public DalSic.ConTurno ConTurno { get { return DalSic.ConTurno.FetchByID(this.IdTurno); } set { SetColumnValue("idTurno", value.IdTurno); } } /// <summary> /// Returns a ConTurnoEstado ActiveRecord object related to this ConTurnoAuditorium /// /// </summary> public DalSic.ConTurnoEstado ConTurnoEstado { get { return DalSic.ConTurnoEstado.FetchByID(this.IdTurnoEstado); } set { SetColumnValue("idTurnoEstado", value.IdTurnoEstado); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdTurno,int varIdTurnoEstado,int varIdUsuario,int varIdServicio,int varIdProfesional,int varIdEspecialidad,int varIdConsultorio,DateTime varFecha,string varHora,DateTime varFechaModificacion,string varHoraModificacion,int varIdPaciente) { ConTurnoAuditorium item = new ConTurnoAuditorium(); item.IdTurno = varIdTurno; item.IdTurnoEstado = varIdTurnoEstado; item.IdUsuario = varIdUsuario; item.IdServicio = varIdServicio; item.IdProfesional = varIdProfesional; item.IdEspecialidad = varIdEspecialidad; item.IdConsultorio = varIdConsultorio; item.Fecha = varFecha; item.Hora = varHora; item.FechaModificacion = varFechaModificacion; item.HoraModificacion = varHoraModificacion; item.IdPaciente = varIdPaciente; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdTurnoAuditoria,int varIdTurno,int varIdTurnoEstado,int varIdUsuario,int varIdServicio,int varIdProfesional,int varIdEspecialidad,int varIdConsultorio,DateTime varFecha,string varHora,DateTime varFechaModificacion,string varHoraModificacion,int varIdPaciente) { ConTurnoAuditorium item = new ConTurnoAuditorium(); item.IdTurnoAuditoria = varIdTurnoAuditoria; item.IdTurno = varIdTurno; item.IdTurnoEstado = varIdTurnoEstado; item.IdUsuario = varIdUsuario; item.IdServicio = varIdServicio; item.IdProfesional = varIdProfesional; item.IdEspecialidad = varIdEspecialidad; item.IdConsultorio = varIdConsultorio; item.Fecha = varFecha; item.Hora = varHora; item.FechaModificacion = varFechaModificacion; item.HoraModificacion = varHoraModificacion; item.IdPaciente = varIdPaciente; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdTurnoAuditoriaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdTurnoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdTurnoEstadoColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdUsuarioColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn IdServicioColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn IdProfesionalColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn IdEspecialidadColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn IdConsultorioColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn HoraColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn FechaModificacionColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn HoraModificacionColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn IdPacienteColumn { get { return Schema.Columns[12]; } } #endregion #region Columns Struct public struct Columns { public static string IdTurnoAuditoria = @"idTurnoAuditoria"; public static string IdTurno = @"idTurno"; public static string IdTurnoEstado = @"idTurnoEstado"; public static string IdUsuario = @"idUsuario"; public static string IdServicio = @"idServicio"; public static string IdProfesional = @"idProfesional"; public static string IdEspecialidad = @"idEspecialidad"; public static string IdConsultorio = @"idConsultorio"; public static string Fecha = @"fecha"; public static string Hora = @"hora"; public static string FechaModificacion = @"fechaModificacion"; public static string HoraModificacion = @"horaModificacion"; public static string IdPaciente = @"idPaciente"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using NUnit.Framework; using NUnit.Core.Builders; using NUnit.Util; using NUnit.Tests.Assemblies; using System.Collections; using NUnit.Core.Filters; using NUnit.TestUtilities; using NUnit.TestData; namespace NUnit.Core.Tests { [TestFixture] public class TestSuiteTest { TestSuite mockTestFixture; TestSuite noTestSuite; [SetUp] public void SetUp() { mockTestFixture = TestBuilder.MakeFixture( typeof( MockTestFixture ) ); TestSuite noTestFixture = TestBuilder.MakeFixture( typeof( EmptyFixture ) ); noTestSuite = new TestSuite("No Tests"); noTestSuite.Add( noTestFixture); } [Test] public void RunTestsInFixture() { TestResult result = mockTestFixture.Run(NullListener.NULL, TestFilter.Empty); ResultSummarizer summarizer = new ResultSummarizer( result ); Assert.AreEqual( MockTestFixture.TestsRun, summarizer.TestsRun, "TestsRun" ); Assert.AreEqual( MockTestFixture.NotRunnable, summarizer.NotRunnable, "NotRunnable"); Assert.AreEqual(MockTestFixture.Ignored, summarizer.Ignored, "Ignored"); Assert.AreEqual(MockTestFixture.Errors, summarizer.Errors, "Errors"); Assert.AreEqual(MockTestFixture.Failures, summarizer.Failures, "Failures"); result = TestFinder.Find( "ExplicitlyRunTest", result, true ); Assert.IsNull( result, "ExplicitlyRunTest should not be in results" ); // TODO: Decide if we want to include Explicit tests that are not run in results // Assert.IsNotNull( result, "Cannot find ExplicitlyRunTest result" ); // Assert.IsFalse( result.Executed, "ExplicitlyRunTest should not be executed" ); // Assert.AreEqual( "Explicit selection required", result.Message ); } [Test] public void RunExplicitTestDirectly() { Test test = TestFinder.Find( "ExplicitlyRunTest", mockTestFixture, true ); Assert.IsNotNull( test, "Cannot find ExplicitlyRunTest" ); Assert.AreEqual( RunState.Explicit, test.RunState ); TestResult result = test.Run(NullListener.NULL, TestFilter.Empty); ResultSummarizer summarizer = new ResultSummarizer( result ); Assert.AreEqual( 1, summarizer.TestsRun ); } [Test] public void RunExplicitTestByName() { Test test = TestFinder.Find( "ExplicitlyRunTest", mockTestFixture, true ); Assert.IsNotNull( test, "Cannot find ExplicitlyRunTest" ); Assert.AreEqual( RunState.Explicit, test.RunState ); NameFilter filter = new NameFilter( test.TestName ); TestResult result = mockTestFixture.Run( NullListener.NULL, filter ); ResultSummarizer summarizer = new ResultSummarizer( result ); Assert.AreEqual( 1, summarizer.TestsRun ); } [Test] public void RunExplicitTestByCategory() { CategoryFilter filter = new CategoryFilter( "Special" ); TestResult result = mockTestFixture.Run( NullListener.NULL, filter ); ResultSummarizer summarizer = new ResultSummarizer( result ); Assert.AreEqual( 1, summarizer.TestsRun ); } [Test] public void ExcludingCategoryDoesNotRunExplicitTestCases() { NotFilter filter = new NotFilter( new CategoryFilter( "MockCategory" ) ); filter.TopLevel = true; TestResult result = mockTestFixture.Run( NullListener.NULL, filter ); ResultSummarizer summarizer = new ResultSummarizer( result ); Assert.AreEqual( MockTestFixture.TestsRun - MockTestFixture.MockCategoryTests, summarizer.TestsRun ); } [Test] public void ExcludingCategoryDoesNotRunExplicitTestFixtures() { NotFilter filter = new NotFilter( new CategoryFilter( "MockCategory" ) ); filter.TopLevel = true; TestAssemblyBuilder builder = new TestAssemblyBuilder(); TestSuite suite = builder.Build( MockAssembly.AssemblyPath, true ); TestResult result = suite.Run( NullListener.NULL, filter ); ResultSummarizer summarizer = new ResultSummarizer( result ); Assert.AreEqual( MockAssembly.TestsRun - 2, summarizer.TestsRun ); } [Test] public void InheritedTestCount() { TestSuite suite = TestBuilder.MakeFixture( typeof( InheritedTestFixture ) ); Assert.AreEqual(InheritedTestFixture.Tests, suite.TestCount); } [Test] public void SuiteRunInitialized() { Assert.AreEqual( RunState.Runnable, mockTestFixture.RunState ); } [Test] public void SuiteWithNoTests() { IList tests = noTestSuite.Tests; Assert.AreEqual(1, tests.Count); TestSuite testSuite = (TestSuite)tests[0]; // NOTE: Beginning with NUnit 2.5.3, a suite with no tests is now runnable Assert.AreEqual( RunState.Runnable, testSuite.RunState ); //Assert.AreEqual(testSuite.TestName.Name + " does not have any tests", testSuite.IgnoreReason); } [Test] public void RunNoTestSuite() { Assert.AreEqual(0, noTestSuite.TestCount); TestResult result = noTestSuite.Run(NullListener.NULL, TestFilter.Empty); ResultSummarizer summarizer = new ResultSummarizer(result); Assert.AreEqual(0, summarizer.TestsRun); Assert.AreEqual(0, summarizer.TestsNotRun); } [Test] public void RunTestByName() { TestSuite testSuite = new TestSuite("Mock Test Suite"); testSuite.Add(mockTestFixture); Assert.IsNull(testSuite.Parent); Test firstTest = (Test)testSuite.Tests[0]; Assert.AreEqual(testSuite, firstTest.Parent); Test bottom = (Test)firstTest.Tests[2]; RecordingListener listener = new RecordingListener(); NameFilter filter = new NameFilter(bottom.TestName); testSuite.Run(listener, filter); Assert.AreEqual(1, listener.testStarted.Count); Assert.AreEqual("MockTest3", (string)listener.testStarted[0]); } [Test] public void RunSuiteByName() { TestSuite testSuite = new TestSuite("Mock Test Suite"); testSuite.Add(mockTestFixture); RecordingListener listener = new RecordingListener(); testSuite.Run(listener, TestFilter.Empty); Assert.AreEqual(MockTestFixture.ResultCount, listener.testStarted.Count); Assert.AreEqual(2, listener.suiteStarted.Count); } [Test] public void CountTestCasesFilteredByName() { TestSuite testSuite = new TestSuite("Mock Test Suite"); testSuite.Add(mockTestFixture); Assert.AreEqual(MockTestFixture.Tests, testSuite.TestCount); Test mock3 = TestFinder.Find("MockTest3", testSuite, true); Test mock1 = TestFinder.Find("MockTest1", testSuite, true); NameFilter filter = new NameFilter(mock3.TestName); Assert.AreEqual(1, testSuite.CountTestCases(filter)); filter = new NameFilter(); filter.Add(mock3.TestName); filter.Add(mock1.TestName); Assert.AreEqual(2, testSuite.CountTestCases(filter)); filter = new NameFilter(testSuite.TestName); Assert.AreEqual(MockTestFixture.ResultCount, testSuite.CountTestCases(filter)); } [Test] public void RunTestByCategory() { TestSuite testSuite = new TestSuite("Mock Test Suite"); testSuite.Add(mockTestFixture); CategoryFilter filter = new CategoryFilter(); filter.AddCategory("MockCategory"); RecordingListener listener = new RecordingListener(); testSuite.Run(listener, filter); CollectionAssert.AreEquivalent( new string[] { "MockTest2", "MockTest3" }, listener.testStarted ); } [Test] public void RunTestExcludingCategory() { TestSuite testSuite = new TestSuite("Mock Test Suite"); testSuite.Add(mockTestFixture); CategoryFilter filter = new CategoryFilter(); filter.AddCategory("MockCategory"); RecordingListener listener = new RecordingListener(); NotFilter notFilter = new NotFilter(filter); notFilter.TopLevel = true; testSuite.Run(listener, notFilter); CollectionAssert.AreEquivalent( new string[] { "MockTest1", "MockTest4", "MockTest5", "TestWithManyProperties", "NotRunnableTest", "FailingTest", "TestWithException", "InconclusiveTest" }, listener.testStarted ); } [Test] public void RunSuiteByCategory() { TestSuite testSuite = new TestSuite("Mock Test Suite"); testSuite.Add(mockTestFixture); CategoryFilter filter = new CategoryFilter(); filter.AddCategory("FixtureCategory"); RecordingListener listener = new RecordingListener(); testSuite.Run(listener, filter); Assert.AreEqual(MockTestFixture.ResultCount, listener.testStarted.Count); } [Test] public void RunSingleTest() { TestSuite fixture = TestBuilder.MakeFixture( typeof( NUnit.Tests.Assemblies.MockTestFixture ) ); Test test = (Test) fixture.Tests[0]; RecordingListener listener = new RecordingListener(); test.Run(listener, null); Assert.IsFalse(listener.lastResult.IsFailure); } [Test] public void DefaultSortIsByName() { mockTestFixture.Sort(); Assert.AreEqual( "ExplicitlyRunTest", ((Test)mockTestFixture.Tests[0]).TestName.Name ); } [Test] public void CanSortUsingExternalComparer() { IComparer comparer = new ReverseSortComparer(); mockTestFixture.Sort(comparer); Assert.AreEqual( "TestWithManyProperties", ((Test)mockTestFixture.Tests[0]).TestName.Name ); } private class ReverseSortComparer : IComparer { public int Compare(object t1, object t2) { int result = Comparer.Default.Compare( t1, t2 ); return -result; } } } [Serializable] public class RecordingListener : EventListener { public ArrayList testStarted = new ArrayList(); public ArrayList testFinished = new ArrayList(); public ArrayList suiteStarted = new ArrayList(); public ArrayList suiteFinished = new ArrayList(); public TestResult lastResult = null; public void RunStarted(string name, int testCount) { } public void RunFinished(NUnit.Core.TestResult result) { } public void RunFinished(Exception exception) { } public void TestStarted(TestName testName) { testStarted.Add(testName.Name); } public void TestFinished(TestResult result) { testFinished.Add(result.Name); lastResult = result; } public void SuiteStarted(TestName suiteName) { suiteStarted.Add(suiteName.Name); } public void SuiteFinished(TestResult result) { suiteFinished.Add(result.Name); } public void UnhandledException(Exception exception ) { } public void TestOutput(TestOutput testOutput) { } } }
using System; using System.Text; namespace LiteNetLib.Utils { public class NetDataReader { protected byte[] _data; protected int _position; protected int _dataSize; public byte[] Data { get { return _data; } } public int Position { get { return _position; } } public bool EndOfData { get { return _position == _dataSize; } } public int AvailableBytes { get { return _dataSize - _position; } } public void SetSource(NetDataWriter dataWriter) { _data = dataWriter.Data; _position = 0; _dataSize = dataWriter.Length; } public void SetSource(byte[] source) { _data = source; _position = 0; _dataSize = source.Length; } public void SetSource(byte[] source, int offset) { _data = source; _position = offset; _dataSize = source.Length; } public void SetSource(byte[] source, int offset, int dataSize) { _data = source; _position = offset; _dataSize = dataSize; } public NetDataReader() { } public NetDataReader(byte[] source) { SetSource(source); } public NetDataReader(byte[] source, int offset) { SetSource(source, offset); } public NetDataReader(byte[] source, int offset, int maxSize) { SetSource(source, offset, maxSize); } #region GetMethods public NetEndPoint GetNetEndPoint() { string host = GetString(1000); int port = GetInt(); return new NetEndPoint(host, port); } public byte GetByte() { byte res = _data[_position]; _position += 1; return res; } public sbyte GetSByte() { var b = (sbyte)_data[_position]; _position++; return b; } public bool[] GetBoolArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new bool[size]; for (int i = 0; i < size; i++) { arr[i] = GetBool(); } return arr; } public ushort[] GetUShortArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new ushort[size]; for (int i = 0; i < size; i++) { arr[i] = GetUShort(); } return arr; } public short[] GetShortArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new short[size]; for (int i = 0; i < size; i++) { arr[i] = GetShort(); } return arr; } public long[] GetLongArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new long[size]; for (int i = 0; i < size; i++) { arr[i] = GetLong(); } return arr; } public ulong[] GetULongArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new ulong[size]; for (int i = 0; i < size; i++) { arr[i] = GetULong(); } return arr; } public int[] GetIntArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = GetInt(); } return arr; } public uint[] GetUIntArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new uint[size]; for (int i = 0; i < size; i++) { arr[i] = GetUInt(); } return arr; } public float[] GetFloatArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new float[size]; for (int i = 0; i < size; i++) { arr[i] = GetFloat(); } return arr; } public double[] GetDoubleArray() { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new double[size]; for (int i = 0; i < size; i++) { arr[i] = GetDouble(); } return arr; } public string[] GetStringArray(int maxLength) { ushort size = BitConverter.ToUInt16(_data, _position); _position += 2; var arr = new string[size]; for (int i = 0; i < size; i++) { arr[i] = GetString(maxLength); } return arr; } public bool GetBool() { bool res = _data[_position] > 0; _position += 1; return res; } public ushort GetUShort() { ushort result = BitConverter.ToUInt16(_data, _position); _position += 2; return result; } public short GetShort() { short result = BitConverter.ToInt16(_data, _position); _position += 2; return result; } public long GetLong() { long result = BitConverter.ToInt64(_data, _position); _position += 8; return result; } public ulong GetULong() { ulong result = BitConverter.ToUInt64(_data, _position); _position += 8; return result; } public int GetInt() { int result = BitConverter.ToInt32(_data, _position); _position += 4; return result; } public uint GetUInt() { uint result = BitConverter.ToUInt32(_data, _position); _position += 4; return result; } public float GetFloat() { float result = BitConverter.ToSingle(_data, _position); _position += 4; return result; } public double GetDouble() { double result = BitConverter.ToDouble(_data, _position); _position += 8; return result; } public string GetString(int maxLength) { int bytesCount = GetInt(); if (bytesCount <= 0 || bytesCount > maxLength*2) { return string.Empty; } int charCount = Encoding.UTF8.GetCharCount(_data, _position, bytesCount); if (charCount > maxLength) { return string.Empty; } string result = Encoding.UTF8.GetString(_data, _position, bytesCount); _position += bytesCount; return result; } public string GetString() { int bytesCount = GetInt(); if (bytesCount <= 0) { return string.Empty; } string result = Encoding.UTF8.GetString(_data, _position, bytesCount); _position += bytesCount; return result; } public byte[] GetRemainingBytes() { byte[] outgoingData = new byte[AvailableBytes]; Buffer.BlockCopy(_data, _position, outgoingData, 0, AvailableBytes); _position = _data.Length; return outgoingData; } public void GetRemainingBytes(byte[] destination) { Buffer.BlockCopy(_data, _position, destination, 0, AvailableBytes); _position = _data.Length; } public void GetBytes(byte[] destination, int lenght) { Buffer.BlockCopy(_data, _position, destination, 0, lenght); _position += lenght; } public byte[] GetBytesWithLength() { int length = GetInt(); byte[] outgoingData = new byte[length]; Buffer.BlockCopy(_data, _position, outgoingData, 0, length); _position += length; return outgoingData; } #endregion #region PeekMethods public byte PeekByte() { return _data[_position]; } public sbyte PeekSByte() { return (sbyte)_data[_position]; } public bool PeekBool() { return _data[_position] > 0; } public ushort PeekUShort() { return BitConverter.ToUInt16(_data, _position); } public short PeekShort() { return BitConverter.ToInt16(_data, _position); } public long PeekLong() { return BitConverter.ToInt64(_data, _position); } public ulong PeekULong() { return BitConverter.ToUInt64(_data, _position); } public int PeekInt() { return BitConverter.ToInt32(_data, _position); } public uint PeekUInt() { return BitConverter.ToUInt32(_data, _position); } public float PeekFloat() { return BitConverter.ToSingle(_data, _position); } public double PeekDouble() { return BitConverter.ToDouble(_data, _position); } public string PeekString(int maxLength) { int bytesCount = BitConverter.ToInt32(_data, _position); if (bytesCount <= 0 || bytesCount > maxLength * 2) { return string.Empty; } int charCount = Encoding.UTF8.GetCharCount(_data, _position + 4, bytesCount); if (charCount > maxLength) { return string.Empty; } string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); return result; } public string PeekString() { int bytesCount = BitConverter.ToInt32(_data, _position); if (bytesCount <= 0) { return string.Empty; } string result = Encoding.UTF8.GetString(_data, _position + 4, bytesCount); return result; } #endregion public void Clear() { _position = 0; _dataSize = 0; _data = null; } } }
// 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.Collections.Generic; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class HttpHeadersTests { [Theory] [InlineData("", (int)(ConnectionOptions.None))] [InlineData(",", (int)(ConnectionOptions.None))] [InlineData(" ,", (int)(ConnectionOptions.None))] [InlineData(" , ", (int)(ConnectionOptions.None))] [InlineData(",,", (int)(ConnectionOptions.None))] [InlineData(" ,,", (int)(ConnectionOptions.None))] [InlineData(",, ", (int)(ConnectionOptions.None))] [InlineData(" , ,", (int)(ConnectionOptions.None))] [InlineData(" , , ", (int)(ConnectionOptions.None))] [InlineData("KEEP-ALIVE", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive, upgrade", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("keep-alive,upgrade", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("upgrade, keep-alive", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("upgrade,keep-alive", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("upgrade,,keep-alive", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("keep-alive,", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive,,", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive, ", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive, ,", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive, , ", (int)(ConnectionOptions.KeepAlive))] [InlineData("keep-alive ,", (int)(ConnectionOptions.KeepAlive))] [InlineData(",keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData(", keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData(",,keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData(", ,keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData(",, keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData(", , keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData("UPGRADE", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade,", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade,,", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade, ", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade, ,", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade, , ", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade ,", (int)(ConnectionOptions.Upgrade))] [InlineData(",upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData(", upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData(",,upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData(", ,upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData(",, upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData(", , upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData("close,", (int)(ConnectionOptions.Close))] [InlineData("close,,", (int)(ConnectionOptions.Close))] [InlineData("close, ", (int)(ConnectionOptions.Close))] [InlineData("close, ,", (int)(ConnectionOptions.Close))] [InlineData("close, , ", (int)(ConnectionOptions.Close))] [InlineData("close ,", (int)(ConnectionOptions.Close))] [InlineData(",close", (int)(ConnectionOptions.Close))] [InlineData(", close", (int)(ConnectionOptions.Close))] [InlineData(",,close", (int)(ConnectionOptions.Close))] [InlineData(", ,close", (int)(ConnectionOptions.Close))] [InlineData(",, close", (int)(ConnectionOptions.Close))] [InlineData(", , close", (int)(ConnectionOptions.Close))] [InlineData("kupgrade", (int)(ConnectionOptions.None))] [InlineData("keupgrade", (int)(ConnectionOptions.None))] [InlineData("ukeep-alive", (int)(ConnectionOptions.None))] [InlineData("upkeep-alive", (int)(ConnectionOptions.None))] [InlineData("k,upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData("u,keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData("ke,upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData("up,keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData("CLOSE", (int)(ConnectionOptions.Close))] [InlineData("close", (int)(ConnectionOptions.Close))] [InlineData("upgrade,close", (int)(ConnectionOptions.Close | ConnectionOptions.Upgrade))] [InlineData("close,upgrade", (int)(ConnectionOptions.Close | ConnectionOptions.Upgrade))] [InlineData("keep-alive2", (int)(ConnectionOptions.None))] [InlineData("keep-alive2 ", (int)(ConnectionOptions.None))] [InlineData("keep-alive2 ,", (int)(ConnectionOptions.None))] [InlineData("keep-alive2,", (int)(ConnectionOptions.None))] [InlineData("upgrade2", (int)(ConnectionOptions.None))] [InlineData("upgrade2 ", (int)(ConnectionOptions.None))] [InlineData("upgrade2 ,", (int)(ConnectionOptions.None))] [InlineData("upgrade2,", (int)(ConnectionOptions.None))] [InlineData("close2", (int)(ConnectionOptions.None))] [InlineData("close2 ", (int)(ConnectionOptions.None))] [InlineData("close2 ,", (int)(ConnectionOptions.None))] [InlineData("close2,", (int)(ConnectionOptions.None))] [InlineData("close close", (int)(ConnectionOptions.None))] [InlineData("close dclose", (int)(ConnectionOptions.None))] [InlineData("keep-alivekeep-alive", (int)(ConnectionOptions.None))] [InlineData("keep-aliveupgrade", (int)(ConnectionOptions.None))] [InlineData("upgradeupgrade", (int)(ConnectionOptions.None))] [InlineData("upgradekeep-alive", (int)(ConnectionOptions.None))] [InlineData("closeclose", (int)(ConnectionOptions.None))] [InlineData("closeupgrade", (int)(ConnectionOptions.None))] [InlineData("upgradeclose", (int)(ConnectionOptions.None))] [InlineData("keep-alive 2", (int)(ConnectionOptions.None))] [InlineData("upgrade 2", (int)(ConnectionOptions.None))] [InlineData("keep-alive 2, close", (int)(ConnectionOptions.Close))] [InlineData("upgrade 2, close", (int)(ConnectionOptions.Close))] [InlineData("close, keep-alive 2", (int)(ConnectionOptions.Close))] [InlineData("close, upgrade 2", (int)(ConnectionOptions.Close))] [InlineData("close 2, upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData("upgrade, close 2", (int)(ConnectionOptions.Upgrade))] [InlineData("k2ep-alive", (int)(ConnectionOptions.None))] [InlineData("ke2p-alive", (int)(ConnectionOptions.None))] [InlineData("u2grade", (int)(ConnectionOptions.None))] [InlineData("up2rade", (int)(ConnectionOptions.None))] [InlineData("c2ose", (int)(ConnectionOptions.None))] [InlineData("cl2se", (int)(ConnectionOptions.None))] [InlineData("k2ep-alive,", (int)(ConnectionOptions.None))] [InlineData("ke2p-alive,", (int)(ConnectionOptions.None))] [InlineData("u2grade,", (int)(ConnectionOptions.None))] [InlineData("up2rade,", (int)(ConnectionOptions.None))] [InlineData("c2ose,", (int)(ConnectionOptions.None))] [InlineData("cl2se,", (int)(ConnectionOptions.None))] [InlineData("k2ep-alive ", (int)(ConnectionOptions.None))] [InlineData("ke2p-alive ", (int)(ConnectionOptions.None))] [InlineData("u2grade ", (int)(ConnectionOptions.None))] [InlineData("up2rade ", (int)(ConnectionOptions.None))] [InlineData("c2ose ", (int)(ConnectionOptions.None))] [InlineData("cl2se ", (int)(ConnectionOptions.None))] [InlineData("k2ep-alive ,", (int)(ConnectionOptions.None))] [InlineData("ke2p-alive ,", (int)(ConnectionOptions.None))] [InlineData("u2grade ,", (int)(ConnectionOptions.None))] [InlineData("up2rade ,", (int)(ConnectionOptions.None))] [InlineData("c2ose ,", (int)(ConnectionOptions.None))] [InlineData("cl2se ,", (int)(ConnectionOptions.None))] public void TestParseConnection(string connection, int intExpectedConnectionOptions) { var expectedConnectionOptions = (ConnectionOptions)intExpectedConnectionOptions; var requestHeaders = new HttpRequestHeaders(); requestHeaders.HeaderConnection = connection; var connectionOptions = HttpHeaders.ParseConnection(requestHeaders); Assert.Equal(expectedConnectionOptions, connectionOptions); } [Theory] [InlineData("keep-alive", "upgrade", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("upgrade", "keep-alive", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("keep-alive", "", (int)(ConnectionOptions.KeepAlive))] [InlineData("", "keep-alive", (int)(ConnectionOptions.KeepAlive))] [InlineData("upgrade", "", (int)(ConnectionOptions.Upgrade))] [InlineData("", "upgrade", (int)(ConnectionOptions.Upgrade))] [InlineData("keep-alive, upgrade", "", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("upgrade, keep-alive", "", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("", "keep-alive, upgrade", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("", "upgrade, keep-alive", (int)(ConnectionOptions.KeepAlive | ConnectionOptions.Upgrade))] [InlineData("", "", (int)(ConnectionOptions.None))] [InlineData("close", "", (int)(ConnectionOptions.Close))] [InlineData("", "close", (int)(ConnectionOptions.Close))] [InlineData("close", "upgrade", (int)(ConnectionOptions.Close | ConnectionOptions.Upgrade))] [InlineData("upgrade", "close", (int)(ConnectionOptions.Close | ConnectionOptions.Upgrade))] public void TestParseConnectionMultipleValues(string value1, string value2, int intExpectedConnectionOptions) { var expectedConnectionOptions = (ConnectionOptions)intExpectedConnectionOptions; var connection = new StringValues(new[] { value1, value2 }); var requestHeaders = new HttpRequestHeaders(); requestHeaders.HeaderConnection = connection; var connectionOptions = HttpHeaders.ParseConnection(requestHeaders); Assert.Equal(expectedConnectionOptions, connectionOptions); } [Theory] [InlineData("", (int)(TransferCoding.None))] [InlineData(",,", (int)(TransferCoding.None))] [InlineData(" ,,", (int)(TransferCoding.None))] [InlineData(",, ", (int)(TransferCoding.None))] [InlineData(" , ,", (int)(TransferCoding.None))] [InlineData(" , , ", (int)(TransferCoding.None))] [InlineData("chunked,", (int)(TransferCoding.Chunked))] [InlineData("chunked,,", (int)(TransferCoding.Chunked))] [InlineData("chunked, ", (int)(TransferCoding.Chunked))] [InlineData("chunked, ,", (int)(TransferCoding.Chunked))] [InlineData("chunked, , ", (int)(TransferCoding.Chunked))] [InlineData("chunked ,", (int)(TransferCoding.Chunked))] [InlineData(",chunked", (int)(TransferCoding.Chunked))] [InlineData(", chunked", (int)(TransferCoding.Chunked))] [InlineData(",,chunked", (int)(TransferCoding.Chunked))] [InlineData(", ,chunked", (int)(TransferCoding.Chunked))] [InlineData(",, chunked", (int)(TransferCoding.Chunked))] [InlineData(", , chunked", (int)(TransferCoding.Chunked))] [InlineData("chunked, gzip", (int)(TransferCoding.Other))] [InlineData("chunked,compress", (int)(TransferCoding.Other))] [InlineData("deflate, chunked", (int)(TransferCoding.Chunked))] [InlineData("gzip,chunked", (int)(TransferCoding.Chunked))] [InlineData("compress,,chunked", (int)(TransferCoding.Chunked))] [InlineData("chunkedchunked", (int)(TransferCoding.Other))] [InlineData("chunked2", (int)(TransferCoding.Other))] [InlineData("chunked 2", (int)(TransferCoding.Other))] [InlineData("2chunked", (int)(TransferCoding.Other))] [InlineData("c2unked", (int)(TransferCoding.Other))] [InlineData("ch2nked", (int)(TransferCoding.Other))] [InlineData("chunked 2, gzip", (int)(TransferCoding.Other))] [InlineData("chunked2, gzip", (int)(TransferCoding.Other))] [InlineData("gzip, chunked 2", (int)(TransferCoding.Other))] [InlineData("gzip, chunked2", (int)(TransferCoding.Other))] public void TestParseTransferEncoding(string transferEncoding, int intExpectedTransferEncodingOptions) { var expectedTransferEncodingOptions = (TransferCoding)intExpectedTransferEncodingOptions; var transferEncodingOptions = HttpHeaders.GetFinalTransferCoding(transferEncoding); Assert.Equal(expectedTransferEncodingOptions, transferEncodingOptions); } [Theory] [InlineData("chunked", "gzip", (int)(TransferCoding.Other))] [InlineData("compress", "chunked", (int)(TransferCoding.Chunked))] [InlineData("chunked", "", (int)(TransferCoding.Chunked))] [InlineData("", "chunked", (int)(TransferCoding.Chunked))] [InlineData("chunked, deflate", "", (int)(TransferCoding.Other))] [InlineData("gzip, chunked", "", (int)(TransferCoding.Chunked))] [InlineData("", "chunked, compress", (int)(TransferCoding.Other))] [InlineData("", "compress, chunked", (int)(TransferCoding.Chunked))] [InlineData("", "", (int)(TransferCoding.None))] [InlineData("deflate", "", (int)(TransferCoding.Other))] [InlineData("", "gzip", (int)(TransferCoding.Other))] public void TestParseTransferEncodingMultipleValues(string value1, string value2, int intExpectedTransferEncodingOptions) { var expectedTransferEncodingOptions = (TransferCoding)intExpectedTransferEncodingOptions; var transferEncoding = new StringValues(new[] { value1, value2 }); var transferEncodingOptions = HttpHeaders.GetFinalTransferCoding(transferEncoding); Assert.Equal(expectedTransferEncodingOptions, transferEncodingOptions); } [Fact] public void ValidContentLengthsAccepted() { ValidContentLengthsAcceptedImpl(new HttpRequestHeaders()); ValidContentLengthsAcceptedImpl(new HttpResponseHeaders()); } private static void ValidContentLengthsAcceptedImpl(HttpHeaders httpHeaders) { IDictionary<string, StringValues> headers = httpHeaders; Assert.False(headers.TryGetValue("Content-Length", out var value)); Assert.Null(httpHeaders.ContentLength); Assert.False(httpHeaders.ContentLength.HasValue); httpHeaders.ContentLength = 1; Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.Equal("1", value[0]); Assert.Equal(1, httpHeaders.ContentLength); Assert.True(httpHeaders.ContentLength.HasValue); httpHeaders.ContentLength = long.MaxValue; Assert.True(headers.TryGetValue("Content-Length", out value)); Assert.Equal(HeaderUtilities.FormatNonNegativeInt64(long.MaxValue), value[0]); Assert.Equal(long.MaxValue, httpHeaders.ContentLength); Assert.True(httpHeaders.ContentLength.HasValue); httpHeaders.ContentLength = null; Assert.False(headers.TryGetValue("Content-Length", out value)); Assert.Null(httpHeaders.ContentLength); Assert.False(httpHeaders.ContentLength.HasValue); } [Fact] public void InvalidContentLengthsRejected() { InvalidContentLengthsRejectedImpl(new HttpRequestHeaders()); InvalidContentLengthsRejectedImpl(new HttpResponseHeaders()); } private static void InvalidContentLengthsRejectedImpl(HttpHeaders httpHeaders) { IDictionary<string, StringValues> headers = httpHeaders; StringValues value; Assert.False(headers.TryGetValue("Content-Length", out value)); Assert.Null(httpHeaders.ContentLength); Assert.False(httpHeaders.ContentLength.HasValue); Assert.Throws<ArgumentOutOfRangeException>(() => httpHeaders.ContentLength = -1); Assert.Throws<ArgumentOutOfRangeException>(() => httpHeaders.ContentLength = long.MinValue); Assert.False(headers.TryGetValue("Content-Length", out value)); Assert.Null(httpHeaders.ContentLength); Assert.False(httpHeaders.ContentLength.HasValue); } } }
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 QuestGame.WebApi.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; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace Southwind { /// <summary> /// Strongly-typed collection for the Shipper class. /// </summary> [Serializable] public partial class ShipperCollection : ActiveList<Shipper, ShipperCollection> { public ShipperCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>ShipperCollection</returns> public ShipperCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Shipper o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the shippers table. /// </summary> [Serializable] public partial class Shipper : ActiveRecord<Shipper>, IActiveRecord { #region .ctors and Default Settings public Shipper() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Shipper(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Shipper(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Shipper(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("shippers", TableType.Table, DataService.GetInstance("Southwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarShipperID = new TableSchema.TableColumn(schema); colvarShipperID.ColumnName = "ShipperID"; colvarShipperID.DataType = DbType.Int32; colvarShipperID.MaxLength = 10; colvarShipperID.AutoIncrement = true; colvarShipperID.IsNullable = false; colvarShipperID.IsPrimaryKey = true; colvarShipperID.IsForeignKey = false; colvarShipperID.IsReadOnly = false; colvarShipperID.DefaultSetting = @""; colvarShipperID.ForeignKeyTableName = ""; schema.Columns.Add(colvarShipperID); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = false; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = false; colvarCompanyName.IsReadOnly = false; colvarCompanyName.DefaultSetting = @""; colvarCompanyName.ForeignKeyTableName = ""; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarPhone = new TableSchema.TableColumn(schema); colvarPhone.ColumnName = "Phone"; colvarPhone.DataType = DbType.String; colvarPhone.MaxLength = 24; colvarPhone.AutoIncrement = false; colvarPhone.IsNullable = true; colvarPhone.IsPrimaryKey = false; colvarPhone.IsForeignKey = false; colvarPhone.IsReadOnly = false; colvarPhone.DefaultSetting = @""; colvarPhone.ForeignKeyTableName = ""; schema.Columns.Add(colvarPhone); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Southwind"].AddSchema("shippers",schema); } } #endregion #region Props [XmlAttribute("ShipperID")] [Bindable(true)] public int ShipperID { get { return GetColumnValue<int>(Columns.ShipperID); } set { SetColumnValue(Columns.ShipperID, value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>(Columns.CompanyName); } set { SetColumnValue(Columns.CompanyName, value); } } [XmlAttribute("Phone")] [Bindable(true)] public string Phone { get { return GetColumnValue<string>(Columns.Phone); } set { SetColumnValue(Columns.Phone, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCompanyName,string varPhone) { Shipper item = new Shipper(); item.CompanyName = varCompanyName; item.Phone = varPhone; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varShipperID,string varCompanyName,string varPhone) { Shipper item = new Shipper(); item.ShipperID = varShipperID; item.CompanyName = varCompanyName; item.Phone = varPhone; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn ShipperIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CompanyNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn PhoneColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string ShipperID = @"ShipperID"; public static string CompanyName = @"CompanyName"; public static string Phone = @"Phone"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using WindowsInstaller; namespace WixSharp.UI { /// <summary> /// Utility class for simplifying MSI interpreting tasks DB querying, message data parsing /// </summary> public class MsiParser { string msiFile; IntPtr db; /// <summary> /// Opens the specified MSI file and returns the database handle. /// </summary> /// <param name="msiFile">The msi file.</param> /// <returns>Handle to the MSI database.</returns> public static IntPtr Open(string msiFile) { IntPtr db = IntPtr.Zero; MsiExtensions.Invoke(() => MsiInterop.MsiOpenDatabase(msiFile, MsiDbPersistMode.ReadOnly, out db)); return db; } /// <summary> /// Initializes a new instance of the <see cref="MsiParser" /> class. /// </summary> /// <param name="msiFile">The msi file.</param> public MsiParser(string msiFile) { this.msiFile = msiFile; this.db = MsiParser.Open(msiFile); } /// <summary> /// Queries the name of the product from the encapsulated MSI database. /// <para> /// <remarks>The DB view is not closed after the call</remarks> /// </para> /// </summary> /// <returns>Product name.</returns> public string GetProductName() { return this.db.View("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductName'") .NextRecord() .GetString(1); } /// <summary> /// Queries the version of the product from the encapsulated MSI database. /// <para> /// <remarks>The DB view is not closed after the call</remarks> /// </para> /// </summary> /// <returns>Product version.</returns> public string GetProductVersion() { return this.db.View("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductVersion'") .NextRecord() .GetString(1); } /// <summary> /// Queries the code of the product from the encapsulated MSI database. /// <para> /// <remarks>The DB view is not closed after the call</remarks> /// </para> /// </summary> /// <returns>Product code.</returns> public string GetProductCode() { return this.db.View("SELECT `Value` FROM `Property` WHERE `Property` = 'ProductCode'") .NextRecord() .GetString(1); } /// <summary> /// Determines whether the specified product code is installed. /// </summary> /// <param name="productCode">The product code.</param> /// <returns>Returns <c>true</c> if the product is installed. Otherwise returns <c>false</c>.</returns> public static bool IsInstalled(string productCode) { StringBuilder sb = new StringBuilder(2048); uint size = 2048; MsiError err = MsiInterop.MsiGetProductInfo(productCode, MsiInstallerProperty.InstallDate, sb, ref size); if (err == MsiError.UnknownProduct) return false; else if (err == MsiError.NoError) return true; else throw new Exception(err.ToString()); } /// <summary> /// Determines whether the product from the encapsulated msi file is installed. /// </summary> /// <returns>Returns <c>true</c> if the product is installed. Otherwise returns <c>false</c>.</returns> public bool IsInstalled() { return IsInstalled(this.GetProductCode()); } ///// <summary> ///// Extracts the root components of the top-level install directory from the encapsulated MSI database. ///// Typically it is a first child of the 'TARGETDIR' MSI directory. ///// <para><remarks>The DB view is not closed after the call</remarks></para> ///// </summary> ///// <returns> ///// Root component of install directory. If the 'TARGETDIR' cannot be located then the return value is the ///// expanded value of 'ProgramFilesFolder' WiX constant. ///// </returns> //public string GetInstallDirectoryRoot() //{ // while (IntPtr.Zero != (rec = view.NextRecord())) // { // var row = view.GetFieldValues(rec); // data.Add(row); // rec.Close(); // } // view.Close(); // // Should be 3 if msi has expected content. // //if ((int)qr == 3) // //{ // // string rootDirId = qr.GetString(1); // // return rootDirId.AsWixVarToPath(); // //} // //else // return "ProgramFilesFolder".AsWixVarToPath(); // Always default to Program Files folder. //} /// <summary> /// Returns the full path of the directory entry from the Directory MSI table /// </summary> /// <param name="name">The name (e.g. INSTALLDIR).</param> /// <returns></returns> public string GetDirectoryPath(string name) { string[] subDirs = GetDirectoryPathParts(name).Select(x => x.AsWixVarToPath()).ToArray(); return string.Join(@"\", subDirs); } string[] GetDirectoryPathParts(string name) { var path = new List<string>(); var names = new Queue<string>(new[] { name }); while (names.Any()) { var item = names.Dequeue(); var data = this.db.View("select * from Directory where Directory = '" + item + "'").GetData(); if (data.Any()) { var row = data.FirstOrDefault(); var subDir = row["DefaultDir"].ToString().Split('|').Last(); path.Add(subDir); var parent = (string)row["Directory_Parent"]; if (parent != null && parent != "TARGETDIR") names.Enqueue(parent.ToString()); } } path.Reverse(); return path.ToArray(); } /// <summary> /// Parses the <c>MsiInstallMessage.CommonData</c> data. /// </summary> /// <param name="s">Message data.</param> /// <returns>Collection of parsed tokens (fields).</returns> public static string[] ParseCommonData(string s) { //Example: 1: 0 2: 1033 3: 1252 var res = new string[3]; var regex = new Regex(@"\d:\s?\w+\s"); int i = 0; foreach (Match m in regex.Matches(s)) { if (i > 3) return null; res[i++] = m.Value.Substring(m.Value.IndexOf(":") + 1).Trim(); } return res; } /// <summary> /// Parses the <c>MsiInstallMessage.Progress</c> string. /// </summary> /// <param name="s">Message data.</param> /// <returns>Collection of parsed tokens (fields).</returns> public static string[] ParseProgressString(string s) { //1: 0 2: 86 3: 0 4: 1 var res = new string[4]; var regex = new Regex(@"\d:\s\d+\s"); int i = 0; foreach (Match m in regex.Matches(s)) { if (i > 4) return null; res[i++] = m.Value.Substring(m.Value.IndexOf(":") + 2).Trim(); } return res; } } }
using System; using System.Diagnostics.Contracts; abstract class A0 { public object this[string index] { g{off}et { return new object(); } } } abstract class A { public object this[string inde{on}x] { get { return new object(); } } } abstract class B { public object this[string inde{on}x] { set { return new object(); } } } abstract class B2 { public object this[string inde{on}x] { get { return new object(); } set {} } } abstract class B3 { public object this[string inde{on}x] { get { Contract.Requires(index != null); return new object(); } set {} } } abstract class B3 { public object this[string inde{on}x] { get { return new object(); } set { Contract.Requires(index != null); } } } abstract class B4 { public object this[string inde{off}x] { get { Contract.Requires(index != null); return new object(); } set { Contract.Requires(index != null); } } } abstract class C { public object this[int inde{off}x] { get { return new object(); } set {} } } abstract class C2 { public object this[int inde{off}x] { get { return new object(); } } } abstract class C3 { public object this[int inde{off}x] { set { return new object(); } } } abstract class D1 { public int this[int index] { s{off}et { return 42; } } } abstract class D11 { public object this[string index] { g{off}et { Contract.Requires(index != null); return new object(); } set { Contract.Requires(index != null); Contract.Requires<ArgumentNullException>(value != null); } } } abstract class D12 { public object this[string index] { get { return new object(); } s{off}et { Contract.Requires(index != null); Contract.Requires<ArgumentNullException>(value != null); } } } abstract class D2 { public string this[int index] { s{off}et { Contract.Requires(value != null); return "42"; } } } abstract class D3 { public string this[int index] { s{on}et { return "42"; } } } abstract class D4 { public string this[string index] { s{on}et { Contract.Requires(index != null); return "42"; } } }
// // ContextPane.cs // // Authors: // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2009 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Collections.Generic; using Mono.Unix; using Gtk; using Hyena.Gui; using Hyena.Widgets; using Banshee.Base; using Banshee.Configuration; using Banshee.Collection; using Banshee.ServiceStack; using Banshee.MediaEngine; using Banshee.Gui; namespace Banshee.ContextPane { public class ContextPane : Gtk.HBox { private object tooltip_host = TooltipSetter.CreateHost (); private Gtk.Notebook notebook; private VBox vbox; private bool large = false; private bool initialized = false; private RoundedFrame no_active; private RoundedFrame loading; private RadioButton radio_group = new RadioButton (null, ""); private Dictionary<BaseContextPage, RadioButton> pane_tabs = new Dictionary<BaseContextPage, RadioButton> (); private Dictionary<BaseContextPage, Widget> pane_pages = new Dictionary<BaseContextPage, Widget> (); private List<BaseContextPage> pages = new List<BaseContextPage> (); private BaseContextPage active_page; private Action<bool> expand_handler; public Action<bool> ExpandHandler { set { expand_handler = value; } } public bool Large { get { return large; } } public ContextPane () { HeightRequest = 200; CreateContextNotebook (); CreateTabButtonBox (); new ContextPageManager (this); initialized = true; RestoreLastActivePage (); Enabled = ShowSchema.Get (); ShowAction.Activated += OnShowContextPane; ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.StartOfStream | PlayerEvent.TrackInfoUpdated); } private void RestoreLastActivePage () { // TODO restore the last page string last_id = LastContextPageSchema.Get (); if (!String.IsNullOrEmpty (last_id)) { var page = pages.FirstOrDefault (p => p.Id == last_id); if (page != null) { SetActivePage (page); pane_tabs[page].Active = true; } } if (active_page == null) { ActivateFirstPage (); } } private void CreateTabButtonBox () { vbox = new VBox (); HBox hbox = new HBox (); var max = new Button (new Image (IconThemeUtils.LoadIcon ("context-pane-maximize", 7))); max.Clicked += (o, a) => { large = !large; expand_handler (large); }; TooltipSetter.Set (tooltip_host, max, Catalog.GetString ("Make the context pane larger or smaller")); var close = new Button (new Image (IconThemeUtils.LoadIcon ("context-pane-close", 7))); close.Clicked += (o, a) => ShowAction.Activate (); TooltipSetter.Set (tooltip_host, close, Catalog.GetString ("Hide context pane")); max.Relief = close.Relief = ReliefStyle.None; hbox.PackStart (max, false, false, 0); hbox.PackStart (close, false, false, 0); vbox.PackStart (hbox, false, false, 0); PackStart (vbox, false, false, 6); vbox.ShowAll (); } private void CreateContextNotebook () { notebook = new Notebook () { ShowBorder = false, ShowTabs = false }; // 'No active track' and 'Loading' widgets no_active = new RoundedFrame (); no_active.Add (new Label () { Markup = String.Format ("<b>{0}</b>", Catalog.GetString ("Waiting for playback to begin...")) }); no_active.ShowAll (); notebook.Add (no_active); loading = new RoundedFrame (); loading.Add (new Label () { Markup = String.Format ("<b>{0}</b>", Catalog.GetString ("Loading...")) }); loading.ShowAll (); notebook.Add (loading); PackStart (notebook, true, true, 0); notebook.Show (); } private void OnPlayerEvent (PlayerEventArgs args) { if (Enabled) { SetCurrentTrackForActivePage (); } } private void SetCurrentTrackForActivePage () { TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; if (track != null && active_page != null) { active_page.SetTrack (track); } } private void OnActivePageStateChanged (ContextState state) { if (active_page == null || !pane_pages.ContainsKey (active_page)) { return; } if (state == ContextState.NotLoaded) notebook.CurrentPage = notebook.PageNum (no_active); else if (state == ContextState.Loading) notebook.CurrentPage = notebook.PageNum (loading); else if (state == ContextState.Loaded) notebook.CurrentPage = notebook.PageNum (pane_pages[active_page]); } private Gtk.ToggleAction ShowAction { get { return ServiceManager.Get<InterfaceActionService> ().ViewActions["ShowContextPaneAction"] as ToggleAction; } } private void OnShowContextPane (object o, EventArgs args) { Enabled = ShowAction.Active; } private bool Enabled { get { return ShowSchema.Get (); } set { ShowSchema.Set (value); SetCurrentTrackForActivePage (); UpdateVisibility (); } } private void UpdateVisibility () { int npages = pages.Count; bool enabled = Enabled; ShowAction.Sensitive = npages > 0; if (enabled && npages > 0) { Show (); } else { if (expand_handler != null) { expand_handler (false); } large = false; Hide (); } vbox.Visible = true;//enabled && npages > 1; } private void SetActivePage (BaseContextPage page) { if (page == null || page == active_page) return; if (active_page != null) active_page.StateChanged -= OnActivePageStateChanged; active_page = page; active_page.StateChanged += OnActivePageStateChanged; LastContextPageSchema.Set (page.Id); OnActivePageStateChanged (active_page.State); SetCurrentTrackForActivePage (); } public void AddPage (BaseContextPage page) { Hyena.Log.DebugFormat ("Adding context page {0}", page.Id); // TODO delay adding the page.Widget until the page is first activated, // that way we don't even create those objects unless used var frame = new Hyena.Widgets.RoundedFrame (); frame.Add (page.Widget); frame.Show (); // TODO implement DnD? /*if (page is ITrackContextPage) { Gtk.Drag.DestSet (frame, DestDefaults.Highlight | DestDefaults.Motion, new TargetEntry [] { Banshee.Gui.DragDrop.DragDropTarget.UriList }, Gdk.DragAction.Default); frame.DragDataReceived += delegate(object o, DragDataReceivedArgs args) { }; }*/ page.Widget.Show (); notebook.AppendPage (frame, null); pane_pages[page] = frame; // Setup the tab-like button that switches the notebook to this page var tab_image = new Image (IconThemeUtils.LoadIcon (22, page.IconNames)); var toggle_button = new RadioButton (radio_group) { Child = tab_image, DrawIndicator = false, Relief = ReliefStyle.None }; TooltipSetter.Set (tooltip_host, toggle_button, page.Name); toggle_button.Clicked += (s, e) => { if (pane_pages.ContainsKey (page)) { if (page.State == ContextState.Loaded) { notebook.CurrentPage = notebook.PageNum (pane_pages[page]); } SetActivePage (page); } }; toggle_button.ShowAll (); vbox.PackStart (toggle_button, false, false, 0); pane_tabs[page] = toggle_button; pages.Add (page); if (initialized && pages.Count == 1) { SetActivePage (page); toggle_button.Active = true; } UpdateVisibility (); } public void RemovePage (BaseContextPage page) { Hyena.Log.DebugFormat ("Removing context page {0}", page.Id); // Remove the notebook page notebook.RemovePage (notebook.PageNum (pane_pages[page])); pane_pages.Remove (page); // Remove the tab button bool was_active = pane_tabs[page].Active; vbox.Remove (pane_tabs[page]); pane_tabs.Remove (page); pages.Remove (page); // Set a new page as the default if (was_active) { ActivateFirstPage (); } UpdateVisibility (); } private void ActivateFirstPage () { if (pages.Count > 0) { SetActivePage (pages[0]); pane_tabs[active_page].Active = true; } } internal static readonly SchemaEntry<bool> ShowSchema = new SchemaEntry<bool>( "interface", "show_context_pane", true, "Show context pane", "Show context pane for the currently playing track" ); private static readonly SchemaEntry<string> LastContextPageSchema = new SchemaEntry<string>( "interface", "last_context_page", null, "The id of the last context page", "The string id of the last context page, which will be defaulted to when Banshee starts" ); } }
#if WITH_XML namespace Volante.Impl { using System; using System.Collections; using System.Reflection; using Volante; public class XmlImporter { public XmlImporter(DatabaseImpl db, System.IO.StreamReader reader) { this.db = db; scanner = new XMLScanner(reader); classMap = new Hashtable(); } public virtual void importDatabase() { if (scanner.scan() != XMLScanner.Token.LT || scanner.scan() != XMLScanner.Token.IDENT || !scanner.Identifier.Equals("database")) { throwException("No root element"); } if (scanner.scan() != XMLScanner.Token.IDENT || !scanner.Identifier.Equals("root") || scanner.scan() != XMLScanner.Token.EQ || scanner.scan() != XMLScanner.Token.SCONST || scanner.scan() != XMLScanner.Token.GT) { throwException("Database element should have \"root\" attribute"); } int rootId = 0; try { rootId = System.Int32.Parse(scanner.String); } catch (System.FormatException) { throwException("Incorrect root object specification"); } idMap = new int[rootId * 2]; idMap[rootId] = db.allocateId(); db.header.root[1 - db.currIndex].rootObject = idMap[rootId]; XMLScanner.Token tkn; while ((tkn = scanner.scan()) == XMLScanner.Token.LT) { if (scanner.scan() != XMLScanner.Token.IDENT) { throwException("Element name expected"); } System.String elemName = scanner.Identifier; if (elemName.StartsWith("Volante.Impl.OldBtree") || elemName.StartsWith("Volante.Impl.OldBitIndexImpl") || elemName.StartsWith("Volante.Impl.OldPersistentSet") || elemName.StartsWith("Volante.Impl.OldBtreeFieldIndex") || elemName.StartsWith("Volante.Impl.OldBtreeMultiFieldIndex")) { createIndex(elemName); } else { createObject(readElement(elemName)); } } if (tkn != XMLScanner.Token.LTS || scanner.scan() != XMLScanner.Token.IDENT || !scanner.Identifier.Equals("database") || scanner.scan() != XMLScanner.Token.GT) { throwException("Root element is not closed"); } } internal class XMLElement { internal XMLElement NextSibling { get { return next; } } internal int Counter { get { return counter; } } internal long IntValue { get { return ivalue; } set { ivalue = value; valueType = XMLValueType.INT_VALUE; } } internal double RealValue { get { return rvalue; } set { rvalue = value; valueType = XMLValueType.REAL_VALUE; } } internal String StringValue { get { return svalue; } set { svalue = value; valueType = XMLValueType.STRING_VALUE; } } internal String Name { get { return name; } } private XMLElement next; private XMLElement prev; private String name; private Hashtable siblings; private Hashtable attributes; private String svalue; private long ivalue; private double rvalue; private XMLValueType valueType; private int counter; enum XMLValueType { NO_VALUE, STRING_VALUE, INT_VALUE, REAL_VALUE, NULL_VALUE } internal XMLElement(System.String name) { this.name = name; valueType = XMLValueType.NO_VALUE; } internal void addSibling(XMLElement elem) { if (siblings == null) { siblings = new Hashtable(); } XMLElement head = (XMLElement)siblings[elem.name]; if (head != null) { elem.next = null; elem.prev = head.prev; head.prev.next = elem; head.prev = elem; head.counter += 1; } else { elem.prev = elem; siblings[elem.name] = elem; elem.counter = 1; } } internal void addAttribute(System.String name, System.String val) { if (attributes == null) { attributes = new Hashtable(); } attributes[name] = val; } internal XMLElement getSibling(System.String name) { if (siblings != null) { return (XMLElement)siblings[name]; } return null; } internal System.String getAttribute(System.String name) { return attributes != null ? (System.String)attributes[name] : null; } internal void setNullValue() { valueType = XMLValueType.NULL_VALUE; } internal bool isIntValue() { return valueType == XMLValueType.INT_VALUE; } internal bool isRealValue() { return valueType == XMLValueType.REAL_VALUE; } internal bool isStringValue() { return valueType == XMLValueType.STRING_VALUE; } internal bool isNullValue() { return valueType == XMLValueType.NULL_VALUE; } } internal System.String getAttribute(XMLElement elem, String name) { System.String val = elem.getAttribute(name); if (val == null) { throwException("Attribute " + name + " is not set"); } return val; } internal int getIntAttribute(XMLElement elem, String name) { System.String val = elem.getAttribute(name); if (val == null) { throwException("Attribute " + name + " is not set"); } try { return System.Int32.Parse(val); } catch (System.FormatException) { throwException("Attribute " + name + " should has integer value"); } return -1; } internal int mapId(int id) { int oid = 0; if (id != 0) { if (id >= idMap.Length) { int[] newMap = new int[id * 2]; Array.Copy(idMap, 0, newMap, 0, idMap.Length); idMap = newMap; idMap[id] = oid = db.allocateId(); } else { oid = idMap[id]; if (oid == 0) { idMap[id] = oid = db.allocateId(); } } } return oid; } internal ClassDescriptor.FieldType mapType(System.String signature) { try { #if CF return (ClassDescriptor.FieldType)ClassDescriptor.parseEnum(typeof(ClassDescriptor.FieldType), signature); #else return (ClassDescriptor.FieldType)Enum.Parse(typeof(ClassDescriptor.FieldType), signature); #endif } catch (ArgumentException) { throwException("Bad type"); return ClassDescriptor.FieldType.tpObject; } } Key createCompoundKey(ClassDescriptor.FieldType[] types, String[] values) { ByteBuffer buf = new ByteBuffer(); int dst = 0; for (int i = 0; i < types.Length; i++) { String val = values[i]; switch (types[i]) { case ClassDescriptor.FieldType.tpBoolean: dst = buf.packBool(dst, Int32.Parse(val) != 0); break; case ClassDescriptor.FieldType.tpByte: case ClassDescriptor.FieldType.tpSByte: dst = buf.packI1(dst, Int32.Parse(val)); break; case ClassDescriptor.FieldType.tpChar: case ClassDescriptor.FieldType.tpShort: case ClassDescriptor.FieldType.tpUShort: dst = buf.packI2(dst, Int32.Parse(val)); break; case ClassDescriptor.FieldType.tpInt: dst = buf.packI4(dst, Int32.Parse(val)); break; case ClassDescriptor.FieldType.tpEnum: case ClassDescriptor.FieldType.tpUInt: dst = buf.packI4(dst, (int)UInt32.Parse(val)); break; case ClassDescriptor.FieldType.tpObject: case ClassDescriptor.FieldType.tpOid: dst = buf.packI4(dst, mapId((int)UInt32.Parse(val))); break; case ClassDescriptor.FieldType.tpLong: dst = buf.packI8(dst, Int64.Parse(val)); break; case ClassDescriptor.FieldType.tpULong: dst = buf.packI8(dst, (long)UInt64.Parse(val)); break; case ClassDescriptor.FieldType.tpDate: dst = buf.packDate(dst, DateTime.Parse(val)); break; case ClassDescriptor.FieldType.tpFloat: dst = buf.packF4(dst, Single.Parse(val)); break; case ClassDescriptor.FieldType.tpDouble: dst = buf.packF8(dst, Double.Parse(val)); break; case ClassDescriptor.FieldType.tpDecimal: dst = buf.packDecimal(dst, Decimal.Parse(val)); break; case ClassDescriptor.FieldType.tpGuid: dst = buf.packGuid(dst, new Guid(val)); break; case ClassDescriptor.FieldType.tpString: dst = buf.packString(dst, val); break; case ClassDescriptor.FieldType.tpArrayOfByte: buf.extend(dst + 4 + (val.Length >> 1)); Bytes.pack4(buf.arr, dst, val.Length >> 1); dst += 4; for (int j = 0, n = val.Length; j < n; j += 2) { buf.arr[dst++] = (byte)((getHexValue(val[j]) << 4) | getHexValue(val[j + 1])); } break; default: throwException("Bad key type"); break; } } return new Key(buf.toArray()); } Key createKey(ClassDescriptor.FieldType type, String val) { switch (type) { case ClassDescriptor.FieldType.tpBoolean: return new Key(Int32.Parse(val) != 0); case ClassDescriptor.FieldType.tpByte: return new Key(Byte.Parse(val)); case ClassDescriptor.FieldType.tpSByte: return new Key(SByte.Parse(val)); case ClassDescriptor.FieldType.tpChar: return new Key((char)Int32.Parse(val)); case ClassDescriptor.FieldType.tpShort: return new Key(Int16.Parse(val)); case ClassDescriptor.FieldType.tpUShort: return new Key(UInt16.Parse(val)); case ClassDescriptor.FieldType.tpInt: return new Key(Int32.Parse(val)); case ClassDescriptor.FieldType.tpUInt: case ClassDescriptor.FieldType.tpEnum: return new Key(UInt32.Parse(val)); case ClassDescriptor.FieldType.tpOid: return new Key(ClassDescriptor.FieldType.tpOid, mapId((int)UInt32.Parse(val))); case ClassDescriptor.FieldType.tpObject: return new Key(new PersistentStub(db, mapId((int)UInt32.Parse(val)))); case ClassDescriptor.FieldType.tpLong: return new Key(Int64.Parse(val)); case ClassDescriptor.FieldType.tpULong: return new Key(UInt64.Parse(val)); case ClassDescriptor.FieldType.tpFloat: return new Key(Single.Parse(val)); case ClassDescriptor.FieldType.tpDouble: return new Key(Double.Parse(val)); case ClassDescriptor.FieldType.tpDecimal: return new Key(Decimal.Parse(val)); case ClassDescriptor.FieldType.tpGuid: return new Key(new Guid(val)); case ClassDescriptor.FieldType.tpString: return new Key(val); case ClassDescriptor.FieldType.tpArrayOfByte: { byte[] buf = new byte[val.Length >> 1]; for (int i = 0; i < buf.Length; i++) { buf[i] = (byte)((getHexValue(val[i * 2]) << 4) | getHexValue(val[i * 2 + 1])); } return new Key(buf); } case ClassDescriptor.FieldType.tpDate: return new Key(DateTime.Parse(val)); default: throwException("Bad key type"); break; } return null; } internal int parseInt(String str) { return Int32.Parse(str); } internal Type findClassByName(String className) { Type type = (Type)classMap[className]; if (type == null) { type = ClassDescriptor.lookup(db, className); classMap[className] = type; } return type; } internal void createIndex(String indexType) { XMLScanner.Token tkn; int oid = 0; bool unique = false; String className = null; String fieldName = null; String[] fieldNames = null; long autoinc = 0; String type = null; while ((tkn = scanner.scan()) == XMLScanner.Token.IDENT) { System.String attrName = scanner.Identifier; if (scanner.scan() != XMLScanner.Token.EQ || scanner.scan() != XMLScanner.Token.SCONST) { throwException("Attribute value expected"); } System.String attrValue = scanner.String; if (attrName.Equals("id")) { oid = mapId(parseInt(attrValue)); } else if (attrName.Equals("unique")) { unique = parseInt(attrValue) != 0; } else if (attrName.Equals("class")) { className = attrValue; } else if (attrName.Equals("type")) { type = attrValue; } else if (attrName.Equals("autoinc")) { autoinc = parseInt(attrValue); } else if (attrName.StartsWith("field")) { int len = attrName.Length; if (len == 5) { fieldName = attrValue; } else { int fieldNo = Int32.Parse(attrName.Substring(5)); if (fieldNames == null || fieldNames.Length <= fieldNo) { String[] newFieldNames = new String[fieldNo + 1]; if (fieldNames != null) { Array.Copy(fieldNames, 0, newFieldNames, 0, fieldNames.Length); } fieldNames = newFieldNames; } fieldNames[fieldNo] = attrValue; } } } if (tkn != XMLScanner.Token.GT) { throwException("Unclosed element tag"); } if (oid == 0) { throwException("ID is not specified or index"); } ClassDescriptor desc = db.getClassDescriptor(findClassByName(indexType)); #if WITH_OLD_BTREE OldBtree btree = (OldBtree)desc.newInstance(); if (className != null) { Type cls = findClassByName(className); if (fieldName != null) { btree.init(cls, ClassDescriptor.FieldType.tpLast, new string[] { fieldName }, unique, autoinc); } else if (fieldNames != null) { btree.init(cls, ClassDescriptor.FieldType.tpLast, fieldNames, unique, autoinc); } else { throwException("Field name is not specified for field index"); } } else { if (type == null) { if (indexType.StartsWith("Volante.Impl.PersistentSet")) { } else { throwException("Key type is not specified for index"); } } else { if (indexType.StartsWith("Volante.impl.BitIndexImpl")) { } else { btree.init(null, mapType(type), null, unique, autoinc); } } } db.assignOid(btree, oid); #endif while ((tkn = scanner.scan()) == XMLScanner.Token.LT) { if (scanner.scan() != XMLScanner.Token.IDENT || !scanner.Identifier.Equals("ref")) { throwException("<ref> element expected"); } #if WITH_OLD_BTREE XMLElement refElem = readElement("ref"); Key key; if (fieldNames != null) { String[] values = new String[fieldNames.Length]; ClassDescriptor.FieldType[] types = btree.FieldTypes; for (int i = 0; i < values.Length; i++) { values[i] = getAttribute(refElem, "key" + i); } key = createCompoundKey(types, values); } else { key = createKey(btree.FieldType, getAttribute(refElem, "key")); } IPersistent obj = new PersistentStub(db, mapId(getIntAttribute(refElem, "id"))); btree.insert(key, obj, false); #endif } if (tkn != XMLScanner.Token.LTS || scanner.scan() != XMLScanner.Token.IDENT || !scanner.Identifier.Equals(indexType) || scanner.scan() != XMLScanner.Token.GT) { throwException("Element is not closed"); } #if WITH_OLD_BTREE ByteBuffer buf = new ByteBuffer(); buf.extend(ObjectHeader.Sizeof); int size = db.packObject(btree, desc, ObjectHeader.Sizeof, buf, null); byte[] data = buf.arr; ObjectHeader.setSize(data, 0, size); ObjectHeader.setType(data, 0, desc.Oid); long pos = db.allocate(size, 0); db.setPos(oid, pos | DatabaseImpl.dbModifiedFlag); db.pool.put(pos & ~DatabaseImpl.dbFlagsMask, data, size); #endif } internal void createObject(XMLElement elem) { ClassDescriptor desc = db.getClassDescriptor(findClassByName(elem.Name)); int oid = mapId(getIntAttribute(elem, "id")); ByteBuffer buf = new ByteBuffer(); int offs = ObjectHeader.Sizeof; buf.extend(offs); offs = packObject(elem, desc, offs, buf); ObjectHeader.setSize(buf.arr, 0, offs); ObjectHeader.setType(buf.arr, 0, desc.Oid); long pos = db.allocate(offs, 0); db.setPos(oid, pos | DatabaseImpl.dbModifiedFlag); db.pool.put(pos, buf.arr, offs); } internal int getHexValue(char ch) { if (ch >= '0' && ch <= '9') { return ch - '0'; } else if (ch >= 'A' && ch <= 'F') { return ch - 'A' + 10; } else if (ch >= 'a' && ch <= 'f') { return ch - 'a' + 10; } else { throwException("Bad hexadecimal constant"); } return -1; } internal int importBinary(XMLElement elem, int offs, ByteBuffer buf, String fieldName) { if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else if (elem.isStringValue()) { String hexStr = elem.StringValue; int len = hexStr.Length; if (hexStr.StartsWith("#")) { buf.extend(offs + 4 + len / 2 - 1); Bytes.pack4(buf.arr, offs, -2 - getHexValue(hexStr[1])); offs += 4; for (int j = 2; j < len; j += 2) { buf.arr[offs++] = (byte)((getHexValue(hexStr[j]) << 4) | getHexValue(hexStr[j + 1])); } } else { buf.extend(offs + 4 + len / 2); Bytes.pack4(buf.arr, offs, len / 2); offs += 4; for (int j = 0; j < len; j += 2) { buf.arr[offs++] = (byte)((getHexValue(hexStr[j]) << 4) | getHexValue(hexStr[j + 1])); } } } else { XMLElement refElem = elem.getSibling("ref"); if (refElem != null) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, mapId(getIntAttribute(refElem, "id"))); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { buf.arr[offs] = (byte)item.IntValue; } else if (item.isRealValue()) { buf.arr[offs] = (byte)item.RealValue; } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 1; } } } return offs; } internal int packObject(XMLElement objElem, ClassDescriptor desc, int offs, ByteBuffer buf) { ClassDescriptor.FieldDescriptor[] flds = desc.allFields; for (int i = 0, n = flds.Length; i < n; i++) { ClassDescriptor.FieldDescriptor fd = flds[i]; FieldInfo f = fd.field; String fieldName = fd.fieldName; XMLElement elem = (objElem != null) ? objElem.getSibling(fieldName) : null; switch (fd.type) { case ClassDescriptor.FieldType.tpByte: case ClassDescriptor.FieldType.tpSByte: buf.extend(offs + 1); if (elem != null) { if (elem.isIntValue()) { buf.arr[offs] = (byte)elem.IntValue; } else if (elem.isRealValue()) { buf.arr[offs] = (byte)elem.RealValue; } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 1; continue; case ClassDescriptor.FieldType.tpBoolean: buf.extend(offs + 1); if (elem != null) { if (elem.isIntValue()) { buf.arr[offs] = (byte)(elem.IntValue != 0 ? 1 : 0); } else if (elem.isRealValue()) { buf.arr[offs] = (byte)(elem.RealValue != 0.0 ? 1 : 0); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 1; continue; case ClassDescriptor.FieldType.tpShort: case ClassDescriptor.FieldType.tpUShort: case ClassDescriptor.FieldType.tpChar: buf.extend(offs + 2); if (elem != null) { if (elem.isIntValue()) { Bytes.pack2(buf.arr, offs, (short)elem.IntValue); } else if (elem.isRealValue()) { Bytes.pack2(buf.arr, offs, (short)elem.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 2; continue; case ClassDescriptor.FieldType.tpEnum: buf.extend(offs + 4); if (elem != null) { if (elem.isIntValue()) { Bytes.pack4(buf.arr, offs, (int)elem.IntValue); } else if (elem.isRealValue()) { Bytes.pack4(buf.arr, offs, (int)elem.RealValue); } else if (elem.isStringValue()) { try { #if CF Bytes.pack4(buf.arr, offs, (int)ClassDescriptor.parseEnum(f.FieldType, elem.StringValue)); #else Bytes.pack4(buf.arr, offs, (int)Enum.Parse(f.FieldType, elem.StringValue)); #endif } catch (ArgumentException) { throwException("Invalid enum value"); } } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 4; continue; case ClassDescriptor.FieldType.tpInt: case ClassDescriptor.FieldType.tpUInt: buf.extend(offs + 4); if (elem != null) { if (elem.isIntValue()) { Bytes.pack4(buf.arr, offs, (int)elem.IntValue); } else if (elem.isRealValue()) { Bytes.pack4(buf.arr, offs, (int)elem.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 4; continue; case ClassDescriptor.FieldType.tpLong: case ClassDescriptor.FieldType.tpULong: buf.extend(offs + 8); if (elem != null) { if (elem.isIntValue()) { Bytes.pack8(buf.arr, offs, elem.IntValue); } else if (elem.isRealValue()) { Bytes.pack8(buf.arr, offs, (long)elem.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 8; continue; case ClassDescriptor.FieldType.tpFloat: buf.extend(offs + 4); if (elem != null) { if (elem.isIntValue()) { Bytes.packF4(buf.arr, offs, (float)elem.IntValue); } else if (elem.isRealValue()) { Bytes.packF4(buf.arr, offs, (float)elem.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 4; continue; case ClassDescriptor.FieldType.tpDouble: buf.extend(offs + 8); if (elem != null) { if (elem.isIntValue()) { Bytes.packF8(buf.arr, offs, (double)elem.IntValue); } else if (elem.isRealValue()) { Bytes.packF8(buf.arr, offs, elem.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 8; continue; case ClassDescriptor.FieldType.tpDecimal: buf.extend(offs + 16); if (elem != null) { decimal d = 0; if (elem.isIntValue()) { d = elem.IntValue; } else if (elem.isRealValue()) { d = (decimal)elem.RealValue; } else if (elem.isStringValue()) { try { d = Decimal.Parse(elem.StringValue); } catch (FormatException) { throwException("Invalid date"); } } else { throwException("Conversion for field " + fieldName + " is not possible"); } Bytes.packDecimal(buf.arr, offs, d); } offs += 16; continue; case ClassDescriptor.FieldType.tpGuid: buf.extend(offs + 16); if (elem != null) { if (elem.isStringValue()) { Guid guid = new Guid(elem.StringValue); byte[] bits = guid.ToByteArray(); Array.Copy(bits, 0, buf.arr, offs, 16); } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 16; continue; case ClassDescriptor.FieldType.tpDate: buf.extend(offs + 8); if (elem != null) { if (elem.isIntValue()) { Bytes.pack8(buf.arr, offs, elem.IntValue); } else if (elem.isNullValue()) { Bytes.pack8(buf.arr, offs, -1); } else if (elem.isStringValue()) { try { Bytes.packDate(buf.arr, offs, DateTime.Parse(elem.StringValue)); } catch (FormatException) { throwException("Invalid date"); } } else { throwException("Conversion for field " + fieldName + " is not possible"); } } offs += 8; continue; case ClassDescriptor.FieldType.tpString: if (elem != null) { System.String val = null; if (elem.isIntValue()) { val = System.Convert.ToString(elem.IntValue); } else if (elem.isRealValue()) { val = elem.RealValue.ToString(); } else if (elem.isStringValue()) { val = elem.StringValue; } else if (elem.isNullValue()) { val = null; } else { throwException("Conversion for field " + fieldName + " is not possible"); } offs = buf.packString(offs, val); continue; } buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; continue; case ClassDescriptor.FieldType.tpOid: case ClassDescriptor.FieldType.tpObject: { int oid = 0; if (elem != null) { XMLElement refElem = elem.getSibling("ref"); if (refElem == null) { throwException("<ref> element expected"); } oid = mapId(getIntAttribute(refElem, "id")); } buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, oid); offs += 4; continue; } case ClassDescriptor.FieldType.tpValue: offs = packObject(elem, fd.valueDesc, offs, buf); continue; case ClassDescriptor.FieldType.tpRaw: case ClassDescriptor.FieldType.tpArrayOfByte: case ClassDescriptor.FieldType.tpArrayOfSByte: offs = importBinary(elem, offs, buf, fieldName); continue; case ClassDescriptor.FieldType.tpArrayOfBoolean: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { buf.arr[offs] = (byte)(item.IntValue != 0 ? 1 : 0); } else if (item.isRealValue()) { buf.arr[offs] = (byte)(item.RealValue != 0.0 ? 1 : 0); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 1; } } continue; case ClassDescriptor.FieldType.tpArrayOfChar: case ClassDescriptor.FieldType.tpArrayOfShort: case ClassDescriptor.FieldType.tpArrayOfUShort: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 2); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { Bytes.pack2(buf.arr, offs, (short)item.IntValue); } else if (item.isRealValue()) { Bytes.pack2(buf.arr, offs, (short)item.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 2; } } continue; case ClassDescriptor.FieldType.tpArrayOfEnum: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; Type elemType = f.FieldType.GetElementType(); buf.extend(offs + 4 + len * 4); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { Bytes.pack4(buf.arr, offs, (int)item.IntValue); } else if (item.isRealValue()) { Bytes.pack4(buf.arr, offs, (int)item.RealValue); } else if (item.isStringValue()) { try { #if CF Bytes.pack4(buf.arr, offs, (int)ClassDescriptor.parseEnum(elemType, item.StringValue)); #else Bytes.pack4(buf.arr, offs, (int)Enum.Parse(elemType, item.StringValue)); #endif } catch (ArgumentException) { throwException("Invalid enum value"); } } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 4; } } continue; case ClassDescriptor.FieldType.tpArrayOfInt: case ClassDescriptor.FieldType.tpArrayOfUInt: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 4); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { Bytes.pack4(buf.arr, offs, (int)item.IntValue); } else if (item.isRealValue()) { Bytes.pack4(buf.arr, offs, (int)item.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 4; } } continue; case ClassDescriptor.FieldType.tpArrayOfLong: case ClassDescriptor.FieldType.tpArrayOfULong: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 8); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { Bytes.pack8(buf.arr, offs, item.IntValue); } else if (item.isRealValue()) { Bytes.pack8(buf.arr, offs, (long)item.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 8; } } continue; case ClassDescriptor.FieldType.tpArrayOfFloat: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 4); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { Bytes.packF4(buf.arr, offs, (float)item.IntValue); } else if (item.isRealValue()) { Bytes.packF4(buf.arr, offs, (float)item.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 4; } } continue; case ClassDescriptor.FieldType.tpArrayOfDouble: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 8); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isIntValue()) { Bytes.packF8(buf.arr, offs, (double)item.IntValue); } else if (item.isRealValue()) { Bytes.packF8(buf.arr, offs, item.RealValue); } else { throwException("Conversion for field " + fieldName + " is not possible"); } item = item.NextSibling; offs += 8; } } continue; case ClassDescriptor.FieldType.tpArrayOfDate: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 8); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isNullValue()) { Bytes.pack8(buf.arr, offs, -1); } else if (item.isStringValue()) { try { Bytes.packDate(buf.arr, offs, DateTime.Parse(item.StringValue)); } catch (FormatException) { throwException("Conversion for field " + fieldName + " is not possible"); } } item = item.NextSibling; offs += 8; } } continue; case ClassDescriptor.FieldType.tpArrayOfDecimal: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 16); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isStringValue()) { try { Bytes.packDecimal(buf.arr, offs, Decimal.Parse(item.StringValue)); } catch (FormatException) { throwException("Conversion for field " + fieldName + " is not possible"); } } item = item.NextSibling; offs += 16; } } continue; case ClassDescriptor.FieldType.tpArrayOfGuid: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 16); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { if (item.isStringValue()) { try { Bytes.packGuid(buf.arr, offs, new Guid(item.StringValue)); } catch (FormatException) { throwException("Conversion for field " + fieldName + " is not possible"); } } item = item.NextSibling; offs += 16; } } continue; case ClassDescriptor.FieldType.tpArrayOfString: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { System.String val = null; if (item.isIntValue()) { val = System.Convert.ToString(item.IntValue); } else if (item.isRealValue()) { val = item.RealValue.ToString(); } else if (item.isStringValue()) { val = item.StringValue; } else if (item.isNullValue()) { val = null; } else { throwException("Conversion for field " + fieldName + " is not possible"); } offs = buf.packString(offs, val); item = item.NextSibling; } } continue; case ClassDescriptor.FieldType.tpArrayOfObject: case ClassDescriptor.FieldType.tpArrayOfOid: case ClassDescriptor.FieldType.tpLink: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; buf.extend(offs + 4 + len * 4); Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { XMLElement href = item.getSibling("ref"); if (href == null) { throwException("<ref> element expected"); } int oid = mapId(getIntAttribute(href, "id")); Bytes.pack4(buf.arr, offs, oid); item = item.NextSibling; offs += 4; } } continue; case ClassDescriptor.FieldType.tpArrayOfValue: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; Bytes.pack4(buf.arr, offs, len); offs += 4; ClassDescriptor elemDesc = fd.valueDesc; while (--len >= 0) { offs = packObject(item, elemDesc, offs, buf); item = item.NextSibling; } } continue; case ClassDescriptor.FieldType.tpArrayOfRaw: if (elem == null || elem.isNullValue()) { buf.extend(offs + 4); Bytes.pack4(buf.arr, offs, -1); offs += 4; } else { XMLElement item = elem.getSibling("element"); int len = (item == null) ? 0 : item.Counter; Bytes.pack4(buf.arr, offs, len); offs += 4; while (--len >= 0) { offs = importBinary(item, offs, buf, fieldName); item = item.NextSibling; } } continue; } } return offs; } internal XMLElement readElement(System.String name) { XMLElement elem = new XMLElement(name); System.String attribute; XMLScanner.Token tkn; while (true) { switch (scanner.scan()) { case XMLScanner.Token.GTS: return elem; case XMLScanner.Token.GT: while ((tkn = scanner.scan()) == XMLScanner.Token.LT) { if (scanner.scan() != XMLScanner.Token.IDENT) { throwException("Element name expected"); } System.String siblingName = scanner.Identifier; XMLElement sibling = readElement(siblingName); elem.addSibling(sibling); } switch (tkn) { case XMLScanner.Token.SCONST: elem.StringValue = scanner.String; tkn = scanner.scan(); break; case XMLScanner.Token.ICONST: elem.IntValue = scanner.Int; tkn = scanner.scan(); break; case XMLScanner.Token.FCONST: elem.RealValue = scanner.Real; tkn = scanner.scan(); break; case XMLScanner.Token.IDENT: if (scanner.Identifier.Equals("null")) { elem.setNullValue(); } else { elem.StringValue = scanner.Identifier; } tkn = scanner.scan(); break; } if (tkn != XMLScanner.Token.LTS || scanner.scan() != XMLScanner.Token.IDENT || !scanner.Identifier.Equals(name) || scanner.scan() != XMLScanner.Token.GT) { throwException("Element is not closed"); } return elem; case XMLScanner.Token.IDENT: attribute = scanner.Identifier; if (scanner.scan() != XMLScanner.Token.EQ || scanner.scan() != XMLScanner.Token.SCONST) { throwException("Attribute value expected"); } elem.addAttribute(attribute, scanner.String); continue; default: throwException("Unexpected token"); break; } } } internal void throwException(System.String message) { throw new XmlImportException(scanner.Line, scanner.Column, message); } internal DatabaseImpl db; internal XMLScanner scanner; internal Hashtable classMap; internal int[] idMap; internal class XMLScanner { internal virtual System.String Identifier { get { return ident; } } internal virtual System.String String { get { return new String(sconst, 0, slen); } } internal virtual long Int { get { return iconst; } } internal virtual double Real { get { return fconst; } } internal virtual int Line { get { return line; } } internal virtual int Column { get { return column; } } internal enum Token { IDENT, SCONST, ICONST, FCONST, LT, GT, LTS, GTS, EQ, EOF } internal System.IO.StreamReader reader; internal int line; internal int column; internal char[] sconst; internal long iconst; internal double fconst; internal int slen; internal String ident; internal int size; internal int ungetChar; internal bool hasUngetChar; internal XMLScanner(System.IO.StreamReader reader) { this.reader = reader; sconst = new char[size = 1024]; line = 1; column = 0; hasUngetChar = false; } internal int get() { if (hasUngetChar) { hasUngetChar = false; return ungetChar; } int ch = reader.Read(); if (ch == '\n') { line += 1; column = 0; } else if (ch == '\t') { column += (column + 8) & ~7; } else { column += 1; } return ch; } internal void unget(int ch) { if (ch == '\n') { line -= 1; } else { column -= 1; } ungetChar = ch; hasUngetChar = true; } internal Token scan() { int i, ch; bool floatingPoint; while (true) { do { if ((ch = get()) < 0) { return Token.EOF; } } while (ch <= ' '); switch (ch) { case '<': ch = get(); if (ch == '?') { while ((ch = get()) != '?') { if (ch < 0) { throw new XmlImportException(line, column, "Bad XML file format"); } } if ((ch = get()) != '>') { throw new XmlImportException(line, column, "Bad XML file format"); } continue; } if (ch != '/') { unget(ch); return Token.LT; } return Token.LTS; case '>': return Token.GT; case '/': ch = get(); if (ch != '>') { unget(ch); throw new XmlImportException(line, column, "Bad XML file format"); } return Token.GTS; case '=': return Token.EQ; case '"': i = 0; while (true) { ch = get(); if (ch < 0) { throw new XmlImportException(line, column, "Bad XML file format"); } else if (ch == '&') { switch (get()) { case 'a': if (get() != 'm' || get() != 'p' || get() != ';') { throw new XmlImportException(line, column, "Bad XML file format"); } ch = '&'; break; case 'l': if (get() != 't' || get() != ';') { throw new XmlImportException(line, column, "Bad XML file format"); } ch = '<'; break; case 'g': if (get() != 't' || get() != ';') { throw new XmlImportException(line, column, "Bad XML file format"); } ch = '>'; break; case 'q': if (get() != 'u' || get() != 'o' || get() != 't' || get() != ';') { throw new XmlImportException(line, column, "Bad XML file format"); } ch = '"'; break; default: throw new XmlImportException(line, column, "Bad XML file format"); } } else if (ch == '"') { slen = i; return Token.SCONST; } if (i == size) { char[] newBuf = new char[size *= 2]; Array.Copy(sconst, 0, newBuf, 0, i); sconst = newBuf; } sconst[i++] = (char)ch; } case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': i = 0; floatingPoint = false; while (true) { if (!System.Char.IsDigit((char)ch) && ch != '-' && ch != '+' && ch != '.' && ch != 'E') { unget(ch); try { if (floatingPoint) { fconst = System.Double.Parse(new String(sconst, 0, i)); return Token.FCONST; } else { iconst = sconst[0] == '-' ? System.Int64.Parse(new String(sconst, 0, i)) : (long)System.UInt64.Parse(new String(sconst, 0, i)); return Token.ICONST; } } catch (System.FormatException) { throw new XmlImportException(line, column, "Bad XML file format"); } } if (i == size) { throw new XmlImportException(line, column, "Bad XML file format"); } sconst[i++] = (char)ch; if (ch == '.') { floatingPoint = true; } ch = get(); } default: i = 0; while (System.Char.IsLetterOrDigit((char)ch) || ch == '-' || ch == ':' || ch == '_' || ch == '.') { if (i == size) { throw new XmlImportException(line, column, "Bad XML file format"); } if (ch == '-') { ch = '+'; } sconst[i++] = (char)ch; ch = get(); } unget(ch); if (i == 0) { throw new XmlImportException(line, column, "Bad XML file format"); } ident = new String(sconst, 0, i); ident = ident.Replace(".1", "`"); ident = ident.Replace(".2", ","); ident = ident.Replace(".3", "["); ident = ident.Replace(".4", "]"); ident = ident.Replace(".5", "="); return Token.IDENT; } } } } } } #endif
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class ImportTapeSpectraS3Request : Ds3Request { public string TapeId { get; private set; } private string _dataPolicyId; public string DataPolicyId { get { return _dataPolicyId; } set { WithDataPolicyId(value); } } private Priority? _priority; public Priority? Priority { get { return _priority; } set { WithPriority(value); } } private string _storageDomainId; public string StorageDomainId { get { return _storageDomainId; } set { WithStorageDomainId(value); } } private string _userId; public string UserId { get { return _userId; } set { WithUserId(value); } } private Priority? _verifyDataAfterImport; public Priority? VerifyDataAfterImport { get { return _verifyDataAfterImport; } set { WithVerifyDataAfterImport(value); } } private bool? _verifyDataPriorToImport; public bool? VerifyDataPriorToImport { get { return _verifyDataPriorToImport; } set { WithVerifyDataPriorToImport(value); } } public ImportTapeSpectraS3Request WithDataPolicyId(Guid? dataPolicyId) { this._dataPolicyId = dataPolicyId.ToString(); if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId.ToString()); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public ImportTapeSpectraS3Request WithDataPolicyId(string dataPolicyId) { this._dataPolicyId = dataPolicyId; if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public ImportTapeSpectraS3Request WithPriority(Priority? priority) { this._priority = priority; if (priority != null) { this.QueryParams.Add("priority", priority.ToString()); } else { this.QueryParams.Remove("priority"); } return this; } public ImportTapeSpectraS3Request WithStorageDomainId(Guid? storageDomainId) { this._storageDomainId = storageDomainId.ToString(); if (storageDomainId != null) { this.QueryParams.Add("storage_domain_id", storageDomainId.ToString()); } else { this.QueryParams.Remove("storage_domain_id"); } return this; } public ImportTapeSpectraS3Request WithStorageDomainId(string storageDomainId) { this._storageDomainId = storageDomainId; if (storageDomainId != null) { this.QueryParams.Add("storage_domain_id", storageDomainId); } else { this.QueryParams.Remove("storage_domain_id"); } return this; } public ImportTapeSpectraS3Request WithUserId(Guid? userId) { this._userId = userId.ToString(); if (userId != null) { this.QueryParams.Add("user_id", userId.ToString()); } else { this.QueryParams.Remove("user_id"); } return this; } public ImportTapeSpectraS3Request WithUserId(string userId) { this._userId = userId; if (userId != null) { this.QueryParams.Add("user_id", userId); } else { this.QueryParams.Remove("user_id"); } return this; } public ImportTapeSpectraS3Request WithVerifyDataAfterImport(Priority? verifyDataAfterImport) { this._verifyDataAfterImport = verifyDataAfterImport; if (verifyDataAfterImport != null) { this.QueryParams.Add("verify_data_after_import", verifyDataAfterImport.ToString()); } else { this.QueryParams.Remove("verify_data_after_import"); } return this; } public ImportTapeSpectraS3Request WithVerifyDataPriorToImport(bool? verifyDataPriorToImport) { this._verifyDataPriorToImport = verifyDataPriorToImport; if (verifyDataPriorToImport != null) { this.QueryParams.Add("verify_data_prior_to_import", verifyDataPriorToImport.ToString()); } else { this.QueryParams.Remove("verify_data_prior_to_import"); } return this; } public ImportTapeSpectraS3Request(Guid tapeId) { this.TapeId = tapeId.ToString(); this.QueryParams.Add("operation", "import"); } public ImportTapeSpectraS3Request(string tapeId) { this.TapeId = tapeId; this.QueryParams.Add("operation", "import"); } internal override HttpVerb Verb { get { return HttpVerb.PUT; } } internal override string Path { get { return "/_rest_/tape/" + TapeId; } } } }
// 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.Globalization; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { public partial class String { // // Search/Query methods // [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsHelper(string strA, string strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); Debug.Assert(strA.Length == strB.Length); return SpanHelpers.SequenceEqual( ref Unsafe.As<char, byte>(ref strA.GetRawStringData()), ref Unsafe.As<char, byte>(ref strB.GetRawStringData()), ((nuint)strA.Length) * 2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB) { Debug.Assert(strA != null); Debug.Assert(strB != null); Debug.Assert(indexA >= 0 && indexB >= 0); Debug.Assert(countA >= 0 && countB >= 0); Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length); return SpanHelpers.SequenceCompareTo(ref Unsafe.Add(ref strA.GetRawStringData(), indexA), countA, ref Unsafe.Add(ref strB.GetRawStringData(), indexB), countB); } private static bool EqualsOrdinalIgnoreCase(string strA, string strB) { Debug.Assert(strA.Length == strB.Length); return CompareInfo.EqualsOrdinalIgnoreCase(ref strA.GetRawStringData(), ref strB.GetRawStringData(), strB.Length); } private static unsafe int CompareOrdinalHelper(string strA, string strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); // NOTE: This may be subject to change if eliminating the check // in the callers makes them small enough to be inlined Debug.Assert(strA._firstChar == strB._firstChar, "For performance reasons, callers of this method should " + "check/short-circuit beforehand if the first char is the same."); int length = Math.Min(strA.Length, strB.Length); fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) { char* a = ap; char* b = bp; // Check if the second chars are different here // The reason we check if _firstChar is different is because // it's the most common case and allows us to avoid a method call // to here. // The reason we check if the second char is different is because // if the first two chars the same we can increment by 4 bytes, // leaving us word-aligned on both 32-bit (12 bytes into the string) // and 64-bit (16 bytes) platforms. // For empty strings, the second char will be null due to padding. // The start of the string is the type pointer + string length, which // takes up 8 bytes on 32-bit, 12 on x64. For empty strings the null // terminator immediately follows, leaving us with an object // 10/14 bytes in size. Since everything needs to be a multiple // of 4/8, this will get padded and zeroed out. // For one-char strings the second char will be the null terminator. // NOTE: If in the future there is a way to read the second char // without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe // is exposed to mscorlib, or a future version of C# allows inline IL), // then do that and short-circuit before the fixed. if (*(a + 1) != *(b + 1)) goto DiffOffset1; // Since we know that the first two chars are the same, // we can increment by 2 here and skip 4 bytes. // This leaves us 8-byte aligned, which results // on better perf for 64-bit platforms. length -= 2; a += 2; b += 2; // unroll the loop #if BIT64 while (length >= 12) { if (*(long*)a != *(long*)b) goto DiffOffset0; if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4; if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8; length -= 12; a += 12; b += 12; } #else // BIT64 while (length >= 10) { if (*(int*)a != *(int*)b) goto DiffOffset0; if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2; if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4; if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6; if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8; length -= 10; a += 10; b += 10; } #endif // BIT64 // Fallback loop: // go back to slower code path and do comparison on 4 bytes at a time. // This depends on the fact that the String objects are // always zero terminated and that the terminating zero is not included // in the length. For odd string sizes, the last compare will include // the zero terminator. while (length > 0) { if (*(int*)a != *(int*)b) goto DiffNextInt; length -= 2; a += 2; b += 2; } // At this point, we have compared all the characters in at least one string. // The longer string will be larger. return strA.Length - strB.Length; #if BIT64 DiffOffset8: a += 4; b += 4; DiffOffset4: a += 4; b += 4; #else // BIT64 // Use jumps instead of falling through, since // otherwise going to DiffOffset8 will involve // 8 add instructions before getting to DiffNextInt DiffOffset8: a += 8; b += 8; goto DiffOffset0; DiffOffset6: a += 6; b += 6; goto DiffOffset0; DiffOffset4: a += 2; b += 2; DiffOffset2: a += 2; b += 2; #endif // BIT64 DiffOffset0: // If we reached here, we already see a difference in the unrolled loop above #if BIT64 if (*(int*)a == *(int*)b) { a += 2; b += 2; } #endif // BIT64 DiffNextInt: if (*a != *b) return *a - *b; DiffOffset1: Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!"); return *(a + 1) - *(b + 1); } } // Provides a culture-correct string comparison. StrA is compared to StrB // to determine whether it is lexicographically less, equal, or greater, and then returns // either a negative integer, 0, or a positive integer; respectively. // public static int Compare(string? strA, string? strB) { return Compare(strA, strB, StringComparison.CurrentCulture); } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase // public static int Compare(string? strA, string? strB, bool ignoreCase) { var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; return Compare(strA, strB, comparisonType); } // Provides a more flexible function for string comparison. See StringComparison // for meaning of different comparisonType. public static int Compare(string? strA, string? strB, StringComparison comparisonType) { if (object.ReferenceEquals(strA, strB)) { CheckStringComparison(comparisonType); return 0; } // They can't both be null at this point. if (strA == null) { CheckStringComparison(comparisonType); return -1; } if (strB == null) { CheckStringComparison(comparisonType); return 1; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: // Most common case: first character is different. // Returns false for empty strings. if (strA._firstChar != strB._firstChar) { return strA._firstChar - strB._firstChar; } return CompareOrdinalHelper(strA, strB); case StringComparison.OrdinalIgnoreCase: return CompareInfo.CompareOrdinalIgnoreCase(strA, strB); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // public static int Compare(string? strA, string? strB, CultureInfo? culture, CompareOptions options) { CultureInfo compareCulture = culture ?? CultureInfo.CurrentCulture; return compareCulture.CompareInfo.Compare(strA, strB, options); } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase, and the culture is set // by culture // public static int Compare(string? strA, string? strB, bool ignoreCase, CultureInfo? culture) { var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return Compare(strA, strB, culture, options); } // Determines whether two string regions match. The substring of strA beginning // at indexA of given length is compared with the substring of strB // beginning at indexB of the same length. // public static int Compare(string? strA, int indexA, string? strB, int indexB, int length) { // NOTE: It's important we call the boolean overload, and not the StringComparison // one. The two have some subtly different behavior (see notes in the former). return Compare(strA, indexA, strB, indexB, length, ignoreCase: false); } // Determines whether two string regions match. The substring of strA beginning // at indexA of given length is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean. // public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase) { // Ideally we would just forward to the string.Compare overload that takes // a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase. // That function will return early if an optimization can be applied, e.g. if // (object)strA == strB && indexA == indexB then it will return 0 straightaway. // There are a couple of subtle behavior differences that prevent us from doing so // however: // - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works // since that method also returns early for nulls before validation. It shouldn't // for this overload. // - Since we originally forwarded to CompareInfo.Compare for all of the argument // validation logic, the ArgumentOutOfRangeExceptions thrown will contain different // parameter names. // Therefore, we have to duplicate some of the logic here. int lengthA = length; int lengthB = length; if (strA != null) { lengthA = Math.Min(lengthA, strA.Length - indexA); } if (strB != null) { lengthB = Math.Min(lengthB, strB.Length - indexB); } var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length length is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean, // and the culture is set by culture. // public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, CultureInfo? culture) { var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return Compare(strA, indexA, strB, indexB, length, culture, options); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length length is compared with the substring of strB // beginning at indexB of the same length. // public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, CultureInfo? culture, CompareOptions options) { CultureInfo compareCulture = culture ?? CultureInfo.CurrentCulture; int lengthA = length; int lengthB = length; if (strA != null) { lengthA = Math.Min(lengthA, strA.Length - indexA); } if (strB != null) { lengthB = Math.Min(lengthB, strB.Length - indexB); } return compareCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType) { CheckStringComparison(comparisonType); if (strA == null || strB == null) { if (object.ReferenceEquals(strA, strB)) { // They're both null return 0; } return strA == null ? -1 : 1; } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); } if (indexA < 0 || indexB < 0) { string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (strA.Length - indexA < 0 || strB.Length - indexB < 0) { string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB)) { return 0; } int lengthA = Math.Min(length, strA.Length - indexA); int lengthB = Math.Min(length, strB.Length - indexB); switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(strA, indexA, lengthA, strB, indexB, lengthB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB); default: Debug.Assert(comparisonType == StringComparison.OrdinalIgnoreCase); // CheckStringComparison validated these earlier return CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB); } } // Compares strA and strB using an ordinal (code-point) comparison. // public static int CompareOrdinal(string? strA, string? strB) { if (object.ReferenceEquals(strA, strB)) { return 0; } // They can't both be null at this point. if (strA == null) { return -1; } if (strB == null) { return 1; } // Most common case, first character is different. // This will return false for empty strings. if (strA._firstChar != strB._firstChar) { return strA._firstChar - strB._firstChar; } return CompareOrdinalHelper(strA, strB); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) => SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length); // Compares strA and strB using an ordinal (code-point) comparison. // public static int CompareOrdinal(string? strA, int indexA, string? strB, int indexB, int length) { if (strA == null || strB == null) { if (object.ReferenceEquals(strA, strB)) { // They're both null return 0; } return strA == null ? -1 : 1; } // COMPAT: Checking for nulls should become before the arguments are validated, // but other optimizations which allow us to return early should come after. if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount); } if (indexA < 0 || indexB < 0) { string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } int lengthA = Math.Min(length, strA.Length - indexA); int lengthB = Math.Min(length, strB.Length - indexB); if (lengthA < 0 || lengthB < 0) { string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB)) { return 0; } return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB); } // Compares this String to another String (cast as object), returning an integer that // indicates the relationship. This method returns a value less than 0 if this is less than value, 0 // if this is equal to value, or a value greater than 0 if this is greater than value. // public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is string other)) { throw new ArgumentException(SR.Arg_MustBeString); } return CompareTo(other); // will call the string-based overload } // Determines the sorting relation of StrB to the current instance. // public int CompareTo(string? strB) { return string.Compare(this, strB, StringComparison.CurrentCulture); } // Determines whether a specified string is a suffix of the current instance. // // The case-sensitive and culture-sensitive option is set by options, // and the default culture is used. // public bool EndsWith(string value) { return EndsWith(value, StringComparison.CurrentCulture); } public bool EndsWith(string value, StringComparison comparisonType) { if ((object)value == null) { throw new ArgumentNullException(nameof(value)); } if ((object)this == (object)value) { CheckStringComparison(comparisonType); return true; } if (value.Length == 0) { CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: int offset = this.Length - value.Length; return (uint)offset <= (uint)this.Length && this.AsSpan(offset).SequenceEqual(value); case StringComparison.OrdinalIgnoreCase: return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public bool EndsWith(string value, bool ignoreCase, CultureInfo? culture) { if (null == value) { throw new ArgumentNullException(nameof(value)); } if ((object)this == (object)value) { return true; } CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture; return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool EndsWith(char value) { int lastPos = Length - 1; return ((uint)lastPos < (uint)Length) && this[lastPos] == value; } // Determines whether two strings match. public override bool Equals(object? obj) { if (object.ReferenceEquals(this, obj)) return true; if (!(obj is string str)) return false; if (this.Length != str.Length) return false; return EqualsHelper(this, str); } // Determines whether two strings match. public bool Equals(string? value) { if (object.ReferenceEquals(this, value)) return true; // NOTE: No need to worry about casting to object here. // If either side of an == comparison between strings // is null, Roslyn generates a simple ceq instruction // instead of calling string.op_Equality. if (value == null) return false; if (this.Length != value.Length) return false; return EqualsHelper(this, value); } public bool Equals(string? value, StringComparison comparisonType) { if (object.ReferenceEquals(this, value)) { CheckStringComparison(comparisonType); return true; } if (value is null) { CheckStringComparison(comparisonType); return false; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return (CompareInfo.Invariant.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); case StringComparison.Ordinal: if (this.Length != value.Length) return false; return EqualsHelper(this, value); case StringComparison.OrdinalIgnoreCase: if (this.Length != value.Length) return false; return EqualsOrdinalIgnoreCase(this, value); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Determines whether two Strings match. public static bool Equals(string? a, string? b) { if (object.ReferenceEquals(a,b)) { return true; } if (a is null || b is null || a.Length != b.Length) { return false; } return EqualsHelper(a, b); } public static bool Equals(string? a, string? b, StringComparison comparisonType) { if (object.ReferenceEquals(a, b)) { CheckStringComparison(comparisonType); return true; } if (a is null || b is null) { CheckStringComparison(comparisonType); return false; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return (CompareInfo.Invariant.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0); case StringComparison.Ordinal: if (a.Length != b.Length) return false; return EqualsHelper(a, b); case StringComparison.OrdinalIgnoreCase: if (a.Length != b.Length) return false; return EqualsOrdinalIgnoreCase(a, b); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public static bool operator ==(string? a, string? b) { return string.Equals(a, b); } public static bool operator !=(string? a, string? b) { return !string.Equals(a, b); } // Gets a hash code for this string. If strings A and B are such that A.Equals(B), then // they will return the same hash code. [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { ulong seed = Marvin.DefaultSeed; // Multiplication below will not overflow since going from positive Int32 to UInt32. return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref _firstChar), (uint)_stringLength * 2 /* in bytes, not chars */, (uint)seed, (uint)(seed >> 32)); } // Gets a hash code for this string and this comparison. If strings A and B and comparison C are such // that string.Equals(A, B, C), then they will return the same hash code with this comparison C. public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int GetHashCodeOrdinalIgnoreCase() { ulong seed = Marvin.DefaultSeed; return Marvin.ComputeHash32OrdinalIgnoreCase(ref _firstChar, _stringLength /* in chars, not bytes */, (uint)seed, (uint)(seed >> 32)); } // A span-based equivalent of String.GetHashCode(). Computes an ordinal hash code. [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetHashCode(ReadOnlySpan<char> value) { ulong seed = Marvin.DefaultSeed; // Multiplication below will not overflow since going from positive Int32 to UInt32. return Marvin.ComputeHash32(ref Unsafe.As<char, byte>(ref MemoryMarshal.GetReference(value)), (uint)value.Length * 2 /* in bytes, not chars */, (uint)seed, (uint)(seed >> 32)); } // A span-based equivalent of String.GetHashCode(StringComparison). Uses the specified comparison type. public static int GetHashCode(ReadOnlySpan<char> value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return GetHashCode(value); case StringComparison.OrdinalIgnoreCase: return GetHashCodeOrdinalIgnoreCase(value); default: ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType); Debug.Fail("Should not reach this point."); return default; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetHashCodeOrdinalIgnoreCase(ReadOnlySpan<char> value) { ulong seed = Marvin.DefaultSeed; return Marvin.ComputeHash32OrdinalIgnoreCase(ref MemoryMarshal.GetReference(value), value.Length /* in chars, not bytes */, (uint)seed, (uint)(seed >> 32)); } // Use this if and only if 'Denial of Service' attacks are not a concern (i.e. never used for free-form user input), // or are otherwise mitigated internal unsafe int GetNonRandomizedHashCode() { fixed (char* src = &_firstChar) { Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'"); Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary"); uint hash1 = (5381 << 16) + 5381; uint hash2 = hash1; uint* ptr = (uint*)src; int length = this.Length; while (length > 2) { length -= 4; // Where length is 4n-1 (e.g. 3,7,11,15,19) this additionally consumes the null terminator hash1 = (BitOperations.RotateLeft(hash1, 5) + hash1) ^ ptr[0]; hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[1]; ptr += 2; } if (length > 0) { // Where length is 4n-3 (e.g. 1,5,9,13,17) this additionally consumes the null terminator hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[0]; } return (int)(hash1 + (hash2 * 1566083941)); } } // Determines whether a specified string is a prefix of the current instance // public bool StartsWith(string value) { if (value is null) { throw new ArgumentNullException(nameof(value)); } return StartsWith(value, StringComparison.CurrentCulture); } public bool StartsWith(string value, StringComparison comparisonType) { if (value is null) { throw new ArgumentNullException(nameof(value)); } if ((object)this == (object)value) { CheckStringComparison(comparisonType); return true; } if (value.Length == 0) { CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: if (this.Length < value.Length || _firstChar != value._firstChar) { return false; } return (value.Length == 1) ? true : // First char is the same and thats all there is to compare SpanHelpers.SequenceEqual( ref Unsafe.As<char, byte>(ref this.GetRawStringData()), ref Unsafe.As<char, byte>(ref value.GetRawStringData()), ((nuint)value.Length) * 2); case StringComparison.OrdinalIgnoreCase: if (this.Length < value.Length) { return false; } return CompareInfo.EqualsOrdinalIgnoreCase(ref this.GetRawStringData(), ref value.GetRawStringData(), value.Length); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture) { if (null == value) { throw new ArgumentNullException(nameof(value)); } if ((object)this == (object)value) { return true; } CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture; return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool StartsWith(char value) => Length != 0 && _firstChar == value; internal static void CheckStringComparison(StringComparison comparisonType) { // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase] if ((uint)comparisonType > (uint)StringComparison.OrdinalIgnoreCase) { ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType); } } internal static CompareOptions GetCaseCompareOfComparisonCulture(StringComparison comparisonType) { Debug.Assert((uint)comparisonType <= (uint)StringComparison.OrdinalIgnoreCase); // Culture enums can be & with CompareOptions.IgnoreCase 0x01 to extract if IgnoreCase or CompareOptions.None 0x00 // // CompareOptions.None 0x00 // CompareOptions.IgnoreCase 0x01 // // StringComparison.CurrentCulture: 0x00 // StringComparison.InvariantCulture: 0x02 // StringComparison.Ordinal 0x04 // // StringComparison.CurrentCultureIgnoreCase: 0x01 // StringComparison.InvariantCultureIgnoreCase: 0x03 // StringComparison.OrdinalIgnoreCase 0x05 return (CompareOptions)((int)comparisonType & (int)CompareOptions.IgnoreCase); } } }
using System; using Highcharts4Net.Library.Enums; using Highcharts4Net.Library.Helpers; namespace Highcharts4Net.Library.Options { /// <summary> /// <p>The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects.</p> <p>See <a class='internal' href='#axis.object'>the Axis object</a> for programmatic access to the axis.</p> /// </summary> public class YAxis { /// <summary> /// Whether to allow decimals in this axis' ticks. When counting integers, like persons or hits on a web page, decimals must be avoided in the axis tick labels. /// Default: true /// </summary> public bool? AllowDecimals { get; set; } /// <summary> /// When using an alternate grid color, a band is painted across the plot area between every other grid line. /// </summary> public string AlternateGridColor { get; set; } /// <summary> /// <p>If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, categories can also be extracted by giving each point a <a href='#series.data'>name</a> and setting axis <a href='#xAxis.type'>type</a> to <code>'category'</code>.</p><p>Example:<pre>categories: ['Apples', 'Bananas', 'Oranges']</pre> Defaults to <code>null</code></p> /// </summary> public AxisBreaks[] Breaks { get; set; } /// <summary> /// <p>If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highcharts 3.0, categories can also be extracted by giving each point a <a href='#series.data'>name</a> and setting axis <a href='#xAxis.type'>type</a> to <code>'category'</code>.</p><p>Example:<pre>categories: ['Apples', 'Bananas', 'Oranges']</pre> Defaults to <code>null</code></p> /// </summary> public string[] Categories { get; set; } /// <summary> /// The highest allowed value for automatically computed axis extremes. /// </summary> public HighchartsDataPoint? Ceiling { get; set; } /// <summary> /// Configure a crosshair that follows either the mouse pointer or the hovered point. /// </summary> public AxisCrosshair Crosshair { get; set; } /// <summary> /// For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default string representations used for each unit. For an overview of the replacement codes, see dateFormat. Defaults to:<pre>{ millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y'}</pre> /// </summary> public DateTimeLabel DateTimeLabelFormats { get; set; } /// <summary> /// Whether to force the axis to end on a tick. Use this option with the <code>maxPadding</code> option to control the axis end. /// Default: true /// </summary> public bool? EndOnTick { get; set; } public YAxisEvents Events { get; set; } /// <summary> /// The lowest allowed value for automatically computed axis extremes. /// Default: null /// </summary> public HighchartsDataPoint? Floor { get; set; } /// <summary> /// Color of the grid lines extending the ticks across the plot area. /// Default: #C0C0C0 /// </summary> public string GridLineColor { get; set; } /// <summary> /// The dash or dot style of the grid lines. For possible values, see <a href='http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/'>this demonstration</a>. /// Default: Solid /// </summary> public DashStyles? GridLineDashStyle { get; set; } /// <summary> /// Polar charts only. Whether the grid lines should draw as a polygon with straight lines between categories, or as circles. Can be either <code>circle</code> or <code>polygon</code>. /// Default: null /// </summary> public string GridLineInterpolation { get; set; } /// <summary> /// The width of the grid lines extending the ticks across the plot area. /// Default: 1 /// </summary> public HighchartsDataPoint? GridLineWidth { get; set; } /// <summary> /// The Z index of the grid lines. /// Default: 1 /// </summary> public HighchartsDataPoint? GridZIndex { get; set; } /// <summary> /// An id for the axis. This can be used after render time to get a pointer to the axis object through <code>chart.get()</code>. /// </summary> public string Id { get; set; } public YAxisLabels Labels { get; set; } /// <summary> /// The color of the line marking the axis itself. /// Default: #C0D0E0 /// </summary> public string LineColor { get; set; } /// <summary> /// The width of the line marking the axis itself. /// Default: 0 /// </summary> public HighchartsDataPoint? LineWidth { get; set; } /// <summary> /// Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, or to ease reading the chart by duplicating the scales. /// </summary> public HighchartsDataPoint? LinkedTo { get; set; } /// <summary> /// The maximum value of the axis. If <code>null</code>, the max value is automatically calculated. If the <code>endOnTick</code> option is true, the <code>max</code> value might be rounded up. The actual maximum value is also influenced by <a class='internal' href='#chart'>chart.alignTicks</a>. /// </summary> public HighchartsDataPoint? Max { get; set; } /// <summary> /// Solid gauge only. Unless <a href='#yAxis.stops'>stops</a> are set, the color to represent the maximum value of the Y axis. /// Default: #102D4C /// </summary> //public string MaxColor { get; set; } /// <summary> /// Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the highest data value to appear on the edge of the plot area. /// Default: 0.05 /// </summary> public HighchartsDataPoint? MaxPadding { get; set; } [Obsolete("Deprecated. Renamed to <code>minRange</code> as of Highcharts 2.2.")] public HighchartsDataPoint? MaxZoom { get; set; } /// <summary> /// The minimum value of the axis. If <code>null</code> the min value is automatically calculated. If the <code>startOnTick</code> option is true, the <code>min</code> value might be rounded down. /// </summary> public HighchartsDataPoint? Min { get; set; } /// <summary> /// Solid gauge only. Unless <a href='#yAxis.stops'>stops</a> are set, the color to represent the minimum value of the Y axis. /// Default: #EFEFFF /// </summary> //public string MinColor { get; set; } /// <summary> /// Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the lowest data value to appear on the edge of the plot area. /// Default: 0.05 /// </summary> public HighchartsDataPoint? MinPadding { get; set; } /// <summary> /// <p>The minimum range to display on this axis. The entire axis will not be allowed to span over a smaller interval than this. For example, for a datetime axis the main unit is milliseconds. If minRange is set to 3600000, you can't zoom in more than to one hour.</p> <p>The default minRange for the x axis is five times the smallest interval between any of the data points.</p> <p>On a logarithmic axis, the unit for the minimum range is the power. So a minRange of 1 means that the axis can be zoomed to 10-100, 100-1000, 1000-10000 etc.</p> /// </summary> public HighchartsDataPoint? MinRange { get; set; } /// <summary> /// The minimum tick interval allowed in axis values. For example on zooming in on an axis with daily data, this can be used to prevent the axis from showing hours. /// </summary> public HighchartsDataPoint? MinTickInterval { get; set; } /// <summary> /// Color of the minor, secondary grid lines. /// Default: #E0E0E0 /// </summary> public string MinorGridLineColor { get; set; } /// <summary> /// The dash or dot style of the minor grid lines. For possible values, see <a href='http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/series-dashstyle-all/'>this demonstration</a>. /// Default: Solid /// </summary> public DashStyles? MinorGridLineDashStyle { get; set; } /// <summary> /// Width of the minor, secondary grid lines. /// Default: 1 /// </summary> public HighchartsDataPoint? MinorGridLineWidth { get; set; } /// <summary> /// Color for the minor tick marks. /// Default: #A0A0A0 /// </summary> public string MinorTickColor { get; set; } /// <summary> /// <p>Tick interval in scale units for the minor ticks. On a linear axis, if <code>'auto'</code>, the minor tick interval is calculated as a fifth of the tickInterval. If <code>null</code>, minor ticks are not shown.</p> <p>On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter approximately 5 minor ticks between each major tick.</p><p>On axes using <a href='#xAxis.categories'>categories</a>, minor ticks are not supported.</p> /// </summary> public HighchartsDataPoint? MinorTickInterval { get; set; } /// <summary> /// The pixel length of the minor tick marks. /// Default: 2 /// </summary> public HighchartsDataPoint? MinorTickLength { get; set; } /// <summary> /// The position of the minor tick marks relative to the axis line. Can be one of <code>inside</code> and <code>outside</code>. /// Default: outside /// </summary> public TickPositions? MinorTickPosition { get; set; } /// <summary> /// The pixel width of the minor tick mark. /// Default: 0 /// </summary> public HighchartsDataPoint? MinorTickWidth { get; set; } /// <summary> /// The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same side of the plot. /// Default: 0 /// </summary> public HighchartsDataPoint? Offset { get; set; } /// <summary> /// Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with dual or multiple axes. /// Default: false /// </summary> public bool? Opposite { get; set; } public YAxisPlotBands[] PlotBands { get; set; } public YAxisPlotLines[] PlotLines { get; set; } /// <summary> /// Whether to reverse the axis so that the highest number is closest to the origin. If the chart is inverted, the x axis is reversed by default. /// Default: false /// </summary> public bool? Reversed { get; set; } /// <summary> /// If <code>true</code>, the first series in a stack will be drawn on top in a positive, non-reversed Y axis. If <code>false</code>, the first series is in the base of the stack. /// Default: true /// </summary> public bool? ReversedStacks { get; set; } /// <summary> /// Whether to show the axis line and title when the axis has no data. /// Default: true /// </summary> public bool? ShowEmpty { get; set; } /// <summary> /// Whether to show the first tick label. /// Default: true /// </summary> public bool? ShowFirstLabel { get; set; } /// <summary> /// Whether to show the last tick label. /// Default: true /// </summary> public bool? ShowLastLabel { get; set; } /// <summary> /// The stack labels show the total value for each bar in a stacked column or bar chart. The label will be placed on top of positive columns and below negative columns. In case of an inverted column chart or a bar chart the label is placed to the right of positive bars and to the left of negative bars. /// </summary> public YAxisStackLabels StackLabels { get; set; } /// <summary> /// For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday. /// Default: 1 /// </summary> public WeekDays? StartOfWeek { get; set; } /// <summary> /// Whether to force the axis to start on a tick. Use this option with the <code>maxPadding</code> option to control the axis start. /// Default: true /// </summary> public bool? StartOnTick { get; set; } /// <summary> /// <p>Solid gauge series only. Color stops for the solid gauge. Use this in cases where a linear gradient between a <code>minColor</code> and <code>maxColor</code> is not sufficient. The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color.</p><p>For solid gauges, the Y axis also inherits the concept of <a href='http://api.highcharts.com/highmaps#colorAxis.dataClasses'>data classes</a> from the Highmaps color axis.</p> /// </summary> // public Gradient Stops { get; set; } /// <summary> /// The amount of ticks to draw on the axis. This opens up for aligning the ticks of multiple charts or panes within a chart. This option overrides the <pre>tickPixelInterval</pre> option. /// This option only has an effect on linear axes. Datetime, logarithmic or category axes are not affected. /// </summary> public HighchartsDataPoint? TickAmount { get; set; } /// <summary> /// Color for the main tick marks. /// Default: #C0D0E0 /// </summary> public string TickColor { get; set; } /// <summary> /// <p>The interval of the tick marks in axis units. When <code>null</code>, the tick interval is computed to approximately follow the <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> on linear and datetime axes. On categorized axes, a <code>null</code> tickInterval will default to 1, one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is expressed as <code>24 * 3600 * 1000</code>.</p> <p>On logarithmic axes, the tickInterval is based on powers, so a tickInterval of 1 means one tick on each of 0.1, 1, 10, 100 etc. A tickInterval of 2 means a tick of 0.1, 10, 1000 etc. A tickInterval of 0.2 puts a tick on 0.1, 0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 10, 20, 40 etc.</p> /// </summary> public HighchartsDataPoint? TickInterval { get; set; } /// <summary> /// The pixel length of the main tick marks. /// Default: 10 /// </summary> public HighchartsDataPoint? TickLength { get; set; } /// <summary> /// If tickInterval is <code>null</code> this option sets the approximate pixel interval of the tick marks. Not applicable to categorized axis. Defaults to <code>72</code> for the Y axis and <code>100</code> forthe X axis. /// </summary> public HighchartsDataPoint? TickPixelInterval { get; set; } /// <summary> /// The position of the major tick marks relative to the axis line. Can be one of <code>inside</code> and <code>outside</code>. /// Default: outside /// </summary> public TickPositions? TickPosition { get; set; } /// <summary> /// A callback function returning array defining where the ticks are laid out on the axis. This overrides the default behaviour of <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> and <a href='#xAxis.tickInterval'>tickInterval</a>. /// </summary> public string TickPositioner { get; set; } /// <summary> /// An array defining where the ticks are laid out on the axis. This overrides the default behaviour of <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> and <a href='#xAxis.tickInterval'>tickInterval</a>. /// </summary> public HighchartsDataPoint?[] TickPositions { get; set; } /// <summary> /// The pixel width of the major tick marks. /// Default: 0 /// </summary> public HighchartsDataPoint? TickWidth { get; set; } /// <summary> /// For categorized axes only. If 'on' the tick mark is placed in the center of the category, if 'between' the tick mark is placed between categories. /// Default: between /// </summary> public Placement? TickmarkPlacement { get; set; } public YAxisTitle Title { get; set; } /// <summary> /// The type of axis. Can be one of <code>'linear'</code>, <code>'logarithmic'</code>, <code>'datetime'</code> or <code>'category'</code>. In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a category axis, the <a href='#series.data'>point names</a> of the chart's series are used for categories, if not a <a href='#xAxis.categories'>categories</a> array is defined. /// Default: linear /// </summary> public AxisTypes? Type { get; set; } /// <summary> /// Datetime axis only. An array determining what time intervals the ticks are allowed to fall on. Each array item is an array where the first value is the time unit and the second value another array of allowed multiples. /// </summary> //[JsonFormatter("[{0}, {1}]")] public AxisUnits Units { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata.Ecma335; #if SRM using System.Reflection.Internal; using BitArithmeticUtilities = System.Reflection.Internal.BitArithmetic; #else using Roslyn.Utilities; #endif #if SRM namespace System.Reflection.Metadata.Ecma335 #else namespace Roslyn.Reflection.Metadata.Ecma335 #endif { #if SRM public #endif sealed class MetadataSizes { private const int StreamAlignment = 4; public const ulong DebugMetadataTablesMask = 1UL << (int)TableIndex.Document | 1UL << (int)TableIndex.MethodDebugInformation | 1UL << (int)TableIndex.LocalScope | 1UL << (int)TableIndex.LocalVariable | 1UL << (int)TableIndex.LocalConstant | 1UL << (int)TableIndex.ImportScope | 1UL << (int)TableIndex.StateMachineMethod | 1UL << (int)TableIndex.CustomDebugInformation; public const ulong SortedDebugTables = 1UL << (int)TableIndex.LocalScope | 1UL << (int)TableIndex.StateMachineMethod | 1UL << (int)TableIndex.CustomDebugInformation; public readonly bool IsMinimalDelta; // EnC delta tables are stored as uncompressed metadata table stream public bool IsMetadataTableStreamCompressed => !IsMinimalDelta; public readonly byte BlobIndexSize; public readonly byte StringIndexSize; public readonly byte GuidIndexSize; public readonly byte CustomAttributeTypeCodedIndexSize; public readonly byte DeclSecurityCodedIndexSize; public readonly byte EventDefIndexSize; public readonly byte FieldDefIndexSize; public readonly byte GenericParamIndexSize; public readonly byte HasConstantCodedIndexSize; public readonly byte HasCustomAttributeCodedIndexSize; public readonly byte HasFieldMarshalCodedIndexSize; public readonly byte HasSemanticsCodedIndexSize; public readonly byte ImplementationCodedIndexSize; public readonly byte MemberForwardedCodedIndexSize; public readonly byte MemberRefParentCodedIndexSize; public readonly byte MethodDefIndexSize; public readonly byte MethodDefOrRefCodedIndexSize; public readonly byte ModuleRefIndexSize; public readonly byte ParameterIndexSize; public readonly byte PropertyDefIndexSize; public readonly byte ResolutionScopeCodedIndexSize; public readonly byte TypeDefIndexSize; public readonly byte TypeDefOrRefCodedIndexSize; public readonly byte TypeOrMethodDefCodedIndexSize; public readonly byte DocumentIndexSize; public readonly byte LocalVariableIndexSize; public readonly byte LocalConstantIndexSize; public readonly byte ImportScopeIndexSize; public readonly byte HasCustomDebugInformationSize; /// <summary> /// Table row counts. /// </summary> public readonly ImmutableArray<int> RowCounts; /// <summary> /// External table row counts. /// </summary> public readonly ImmutableArray<int> ExternalRowCounts; /// <summary> /// Non-empty tables that are emitted into the metadata table stream. /// </summary> public readonly ulong PresentTablesMask; /// <summary> /// Non-empty tables stored in an external metadata table stream that might be referenced from the metadata table stream being emitted. /// </summary> public readonly ulong ExternalTablesMask; /// <summary> /// Exact (unaligned) heap sizes. /// </summary> public readonly ImmutableArray<int> HeapSizes; /// <summary> /// Overall size of metadata stream storage (stream headers, table stream, heaps, additional streams). /// Aligned to <see cref="StreamAlignment"/>. /// </summary> public readonly int MetadataStreamStorageSize; /// <summary> /// The size of metadata stream (#- or #~). Aligned. /// Aligned to <see cref="StreamAlignment"/>. /// </summary> public readonly int MetadataTableStreamSize; /// <summary> /// The size of #Pdb stream. Aligned. /// </summary> public readonly int StandalonePdbStreamSize; public MetadataSizes( ImmutableArray<int> rowCounts, ImmutableArray<int> externalRowCounts, ImmutableArray<int> heapSizes, bool isMinimalDelta, bool isStandaloneDebugMetadata) { Debug.Assert(rowCounts.Length == MetadataTokens.TableCount); Debug.Assert(externalRowCounts.Length == MetadataTokens.TableCount); Debug.Assert(heapSizes.Length == MetadataTokens.HeapCount); const byte large = 4; const byte small = 2; this.RowCounts = rowCounts; this.ExternalRowCounts = externalRowCounts; this.HeapSizes = heapSizes; this.IsMinimalDelta = isMinimalDelta; this.BlobIndexSize = (isMinimalDelta || heapSizes[(int)HeapIndex.Blob] > ushort.MaxValue) ? large : small; this.StringIndexSize = (isMinimalDelta || heapSizes[(int)HeapIndex.String] > ushort.MaxValue) ? large : small; this.GuidIndexSize = (isMinimalDelta || heapSizes[(int)HeapIndex.Guid] > ushort.MaxValue) ? large : small; this.PresentTablesMask = ComputeNonEmptyTableMask(rowCounts); this.ExternalTablesMask = ComputeNonEmptyTableMask(externalRowCounts); // table can either be present or external, it can't be both: Debug.Assert((PresentTablesMask & ExternalTablesMask) == 0); this.CustomAttributeTypeCodedIndexSize = this.GetReferenceByteSize(3, TableIndex.MethodDef, TableIndex.MemberRef); this.DeclSecurityCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.MethodDef, TableIndex.TypeDef); this.EventDefIndexSize = this.GetReferenceByteSize(0, TableIndex.Event); this.FieldDefIndexSize = this.GetReferenceByteSize(0, TableIndex.Field); this.GenericParamIndexSize = this.GetReferenceByteSize(0, TableIndex.GenericParam); this.HasConstantCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.Field, TableIndex.Param, TableIndex.Property); this.HasCustomAttributeCodedIndexSize = this.GetReferenceByteSize(5, TableIndex.MethodDef, TableIndex.Field, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.Param, TableIndex.InterfaceImpl, TableIndex.MemberRef, TableIndex.Module, TableIndex.DeclSecurity, TableIndex.Property, TableIndex.Event, TableIndex.StandAloneSig, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.File, TableIndex.ExportedType, TableIndex.ManifestResource, TableIndex.GenericParam, TableIndex.GenericParamConstraint, TableIndex.MethodSpec); this.HasFieldMarshalCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.Field, TableIndex.Param); this.HasSemanticsCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.Event, TableIndex.Property); this.ImplementationCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.File, TableIndex.AssemblyRef, TableIndex.ExportedType); this.MemberForwardedCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.Field, TableIndex.MethodDef); this.MemberRefParentCodedIndexSize = this.GetReferenceByteSize(3, TableIndex.TypeDef, TableIndex.TypeRef, TableIndex.ModuleRef, TableIndex.MethodDef, TableIndex.TypeSpec); this.MethodDefIndexSize = this.GetReferenceByteSize(0, TableIndex.MethodDef); this.MethodDefOrRefCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.MethodDef, TableIndex.MemberRef); this.ModuleRefIndexSize = this.GetReferenceByteSize(0, TableIndex.ModuleRef); this.ParameterIndexSize = this.GetReferenceByteSize(0, TableIndex.Param); this.PropertyDefIndexSize = this.GetReferenceByteSize(0, TableIndex.Property); this.ResolutionScopeCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.Module, TableIndex.ModuleRef, TableIndex.AssemblyRef, TableIndex.TypeRef); this.TypeDefIndexSize = this.GetReferenceByteSize(0, TableIndex.TypeDef); this.TypeDefOrRefCodedIndexSize = this.GetReferenceByteSize(2, TableIndex.TypeDef, TableIndex.TypeRef, TableIndex.TypeSpec); this.TypeOrMethodDefCodedIndexSize = this.GetReferenceByteSize(1, TableIndex.TypeDef, TableIndex.MethodDef); this.DocumentIndexSize = this.GetReferenceByteSize(0, TableIndex.Document); this.LocalVariableIndexSize = this.GetReferenceByteSize(0, TableIndex.LocalVariable); this.LocalConstantIndexSize = this.GetReferenceByteSize(0, TableIndex.LocalConstant); this.ImportScopeIndexSize = this.GetReferenceByteSize(0, TableIndex.ImportScope); this.HasCustomDebugInformationSize = this.GetReferenceByteSize(5, TableIndex.MethodDef, TableIndex.Field, TableIndex.TypeRef, TableIndex.TypeDef, TableIndex.Param, TableIndex.InterfaceImpl, TableIndex.MemberRef, TableIndex.Module, TableIndex.DeclSecurity, TableIndex.Property, TableIndex.Event, TableIndex.StandAloneSig, TableIndex.ModuleRef, TableIndex.TypeSpec, TableIndex.Assembly, TableIndex.AssemblyRef, TableIndex.File, TableIndex.ExportedType, TableIndex.ManifestResource, TableIndex.GenericParam, TableIndex.GenericParamConstraint, TableIndex.MethodSpec, TableIndex.Document, TableIndex.LocalScope, TableIndex.LocalVariable, TableIndex.LocalConstant, TableIndex.ImportScope); int size = this.CalculateTableStreamHeaderSize(); size += GetTableSize(TableIndex.Module, 2 + 3 * this.GuidIndexSize + this.StringIndexSize); size += GetTableSize(TableIndex.TypeRef, this.ResolutionScopeCodedIndexSize + this.StringIndexSize + this.StringIndexSize); size += GetTableSize(TableIndex.TypeDef, 4 + this.StringIndexSize + this.StringIndexSize + this.TypeDefOrRefCodedIndexSize + this.FieldDefIndexSize + this.MethodDefIndexSize); Debug.Assert(rowCounts[(int)TableIndex.FieldPtr] == 0); size += GetTableSize(TableIndex.Field, 2 + this.StringIndexSize + this.BlobIndexSize); Debug.Assert(rowCounts[(int)TableIndex.MethodPtr] == 0); size += GetTableSize(TableIndex.MethodDef, 8 + this.StringIndexSize + this.BlobIndexSize + this.ParameterIndexSize); Debug.Assert(rowCounts[(int)TableIndex.ParamPtr] == 0); size += GetTableSize(TableIndex.Param, 4 + this.StringIndexSize); size += GetTableSize(TableIndex.InterfaceImpl, this.TypeDefIndexSize + this.TypeDefOrRefCodedIndexSize); size += GetTableSize(TableIndex.MemberRef, this.MemberRefParentCodedIndexSize + this.StringIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.Constant, 2 + this.HasConstantCodedIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.CustomAttribute, this.HasCustomAttributeCodedIndexSize + this.CustomAttributeTypeCodedIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.FieldMarshal, this.HasFieldMarshalCodedIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.DeclSecurity, 2 + this.DeclSecurityCodedIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.ClassLayout, 6 + this.TypeDefIndexSize); size += GetTableSize(TableIndex.FieldLayout, 4 + this.FieldDefIndexSize); size += GetTableSize(TableIndex.StandAloneSig, this.BlobIndexSize); size += GetTableSize(TableIndex.EventMap, this.TypeDefIndexSize + this.EventDefIndexSize); Debug.Assert(rowCounts[(int)TableIndex.EventPtr] == 0); size += GetTableSize(TableIndex.Event, 2 + this.StringIndexSize + this.TypeDefOrRefCodedIndexSize); size += GetTableSize(TableIndex.PropertyMap, this.TypeDefIndexSize + this.PropertyDefIndexSize); Debug.Assert(rowCounts[(int)TableIndex.PropertyPtr] == 0); size += GetTableSize(TableIndex.Property, 2 + this.StringIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.MethodSemantics, 2 + this.MethodDefIndexSize + this.HasSemanticsCodedIndexSize); size += GetTableSize(TableIndex.MethodImpl, 0 + this.TypeDefIndexSize + this.MethodDefOrRefCodedIndexSize + this.MethodDefOrRefCodedIndexSize); size += GetTableSize(TableIndex.ModuleRef, 0 + this.StringIndexSize); size += GetTableSize(TableIndex.TypeSpec, 0 + this.BlobIndexSize); size += GetTableSize(TableIndex.ImplMap, 2 + this.MemberForwardedCodedIndexSize + this.StringIndexSize + this.ModuleRefIndexSize); size += GetTableSize(TableIndex.FieldRva, 4 + this.FieldDefIndexSize); size += GetTableSize(TableIndex.EncLog, 8); size += GetTableSize(TableIndex.EncMap, 4); size += GetTableSize(TableIndex.Assembly, 16 + this.BlobIndexSize + this.StringIndexSize + this.StringIndexSize); Debug.Assert(rowCounts[(int)TableIndex.AssemblyProcessor] == 0); Debug.Assert(rowCounts[(int)TableIndex.AssemblyOS] == 0); size += GetTableSize(TableIndex.AssemblyRef, 12 + this.BlobIndexSize + this.StringIndexSize + this.StringIndexSize + this.BlobIndexSize); Debug.Assert(rowCounts[(int)TableIndex.AssemblyRefProcessor] == 0); Debug.Assert(rowCounts[(int)TableIndex.AssemblyRefOS] == 0); size += GetTableSize(TableIndex.File, 4 + this.StringIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.ExportedType, 8 + this.StringIndexSize + this.StringIndexSize + this.ImplementationCodedIndexSize); size += GetTableSize(TableIndex.ManifestResource, 8 + this.StringIndexSize + this.ImplementationCodedIndexSize); size += GetTableSize(TableIndex.NestedClass, this.TypeDefIndexSize + this.TypeDefIndexSize); size += GetTableSize(TableIndex.GenericParam, 4 + this.TypeOrMethodDefCodedIndexSize + this.StringIndexSize); size += GetTableSize(TableIndex.MethodSpec, this.MethodDefOrRefCodedIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.GenericParamConstraint, this.GenericParamIndexSize + this.TypeDefOrRefCodedIndexSize); size += GetTableSize(TableIndex.Document, this.BlobIndexSize + this.GuidIndexSize + this.BlobIndexSize + this.GuidIndexSize); size += GetTableSize(TableIndex.MethodDebugInformation, this.DocumentIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.LocalScope, this.MethodDefIndexSize + this.ImportScopeIndexSize + this.LocalVariableIndexSize + this.LocalConstantIndexSize + 4 + 4); size += GetTableSize(TableIndex.LocalVariable, 2 + 2 + this.StringIndexSize); size += GetTableSize(TableIndex.LocalConstant, this.StringIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.ImportScope, this.ImportScopeIndexSize + this.BlobIndexSize); size += GetTableSize(TableIndex.StateMachineMethod, this.MethodDefIndexSize + this.MethodDefIndexSize); size += GetTableSize(TableIndex.CustomDebugInformation, this.HasCustomDebugInformationSize + this.GuidIndexSize + this.BlobIndexSize); // +1 for terminating 0 byte size = BitArithmeticUtilities.Align(size + 1, StreamAlignment); this.MetadataTableStreamSize = size; size += GetAlignedHeapSize(HeapIndex.String); size += GetAlignedHeapSize(HeapIndex.UserString); size += GetAlignedHeapSize(HeapIndex.Guid); size += GetAlignedHeapSize(HeapIndex.Blob); this.StandalonePdbStreamSize = isStandaloneDebugMetadata ? CalculateStandalonePdbStreamSize() : 0; size += this.StandalonePdbStreamSize; this.MetadataStreamStorageSize = size; } public bool IsStandaloneDebugMetadata => StandalonePdbStreamSize > 0; public bool IsPresent(TableIndex table) => (PresentTablesMask & (1UL << (int)table)) != 0; /// <summary> /// Metadata header size. /// Includes: /// - metadata storage signature /// - storage header /// - stream headers /// </summary> public int MetadataHeaderSize { get { const int RegularStreamHeaderSizes = 76; const int MinimalDeltaMarkerStreamHeaderSize = 16; const int StandalonePdbStreamHeaderSize = 16; Debug.Assert(RegularStreamHeaderSizes == GetMetadataStreamHeaderSize("#~") + GetMetadataStreamHeaderSize("#Strings") + GetMetadataStreamHeaderSize("#US") + GetMetadataStreamHeaderSize("#GUID") + GetMetadataStreamHeaderSize("#Blob")); Debug.Assert(MinimalDeltaMarkerStreamHeaderSize == GetMetadataStreamHeaderSize("#JTD")); Debug.Assert(StandalonePdbStreamHeaderSize == GetMetadataStreamHeaderSize("#Pdb")); return sizeof(uint) + // signature sizeof(ushort) + // major version sizeof(ushort) + // minor version sizeof(uint) + // reserved sizeof(uint) + // padded metadata version length MetadataVersionPaddedLength + // metadata version sizeof(ushort) + // storage header: reserved sizeof(ushort) + // stream count (IsStandaloneDebugMetadata ? StandalonePdbStreamHeaderSize : 0) + RegularStreamHeaderSizes + (IsMinimalDelta ? MinimalDeltaMarkerStreamHeaderSize : 0); } } // version must be 12 chars long, this observation is not supported by the standard public const int MetadataVersionPaddedLength = 12; public static int GetMetadataStreamHeaderSize(string streamName) { return sizeof(int) + // offset sizeof(int) + // size BitArithmeticUtilities.Align(streamName.Length + 1, 4); // zero-terminated name, padding } /// <summary> /// Total size of metadata (header and all streams). /// </summary> public int MetadataSize => MetadataHeaderSize + MetadataStreamStorageSize; public int GetAlignedHeapSize(HeapIndex index) { return BitArithmeticUtilities.Align(HeapSizes[(int)index], StreamAlignment); } internal int CalculateTableStreamHeaderSize() { int result = sizeof(int) + // Reserved sizeof(short) + // Version (major, minor) sizeof(byte) + // Heap index sizes sizeof(byte) + // Bit width of RowId sizeof(long) + // Valid table mask sizeof(long); // Sorted table mask // present table row counts for (int i = 0; i < RowCounts.Length; i++) { if (((1UL << i) & PresentTablesMask) != 0) { result += sizeof(int); } } return result; } internal const int PdbIdSize = 20; internal int CalculateStandalonePdbStreamSize() { int result = PdbIdSize + // PDB ID sizeof(int) + // EntryPoint sizeof(long) + // ReferencedTypeSystemTables BitArithmeticUtilities.CountBits(ExternalTablesMask) * sizeof(int); // External row counts Debug.Assert(result % StreamAlignment == 0); return result; } private static ulong ComputeNonEmptyTableMask(ImmutableArray<int> rowCounts) { ulong mask = 0; for (int i = 0; i < rowCounts.Length; i++) { if (rowCounts[i] > 0) { mask |= (1UL << i); } } return mask; } private int GetTableSize(TableIndex index, int rowSize) { return RowCounts[(int)index] * rowSize; } private byte GetReferenceByteSize(int tagBitSize, params TableIndex[] tables) { const byte large = 4; const byte small = 2; const int smallBitCount = 16; return (!IsMetadataTableStreamCompressed || !ReferenceFits(smallBitCount - tagBitSize, tables)) ? large : small; } private bool ReferenceFits(int bitCount, TableIndex[] tables) { int maxIndex = (1 << bitCount) - 1; foreach (TableIndex table in tables) { // table can be either local or external, but not both: Debug.Assert(RowCounts[(int)table] == 0 || ExternalRowCounts[(int)table] == 0); if (RowCounts[(int)table] + ExternalRowCounts[(int)table] > maxIndex) { return false; } } return true; } } }
namespace zlib { using System; internal sealed class ZStream { static ZStream() { ZStream.DEF_WBITS = 15; } public ZStream() { this._adler = new Adler32(); } public int deflate(int flush) { if (this.dstate == null) { return -2; } return this.dstate.deflate(this, flush); } public int deflateEnd() { if (this.dstate == null) { return -2; } int num1 = this.dstate.deflateEnd(); this.dstate = null; return num1; } public int deflateInit(int level) { return this.deflateInit(level, 15); } public int deflateInit(int level, int bits) { this.dstate = new Deflate(); return this.dstate.deflateInit(this, level, bits); } public int deflateParams(int level, int strategy) { if (this.dstate == null) { return -2; } return this.dstate.deflateParams(this, level, strategy); } public int deflateSetDictionary(byte[] dictionary, int dictLength) { if (this.dstate == null) { return -2; } return this.dstate.deflateSetDictionary(this, dictionary, dictLength); } internal void flush_pending() { int num1 = this.dstate.pending; if (num1 > this.avail_out) { num1 = this.avail_out; } if (num1 != 0) { if (((this.dstate.pending_buf.Length <= this.dstate.pending_out) || (this.next_out.Length <= this.next_out_index)) || ((this.dstate.pending_buf.Length < (this.dstate.pending_out + num1)) || (this.next_out.Length < (this.next_out_index + num1)))) { Console.Out.WriteLine(string.Concat(new object[] { this.dstate.pending_buf.Length, ", ", this.dstate.pending_out, ", ", this.next_out.Length, ", ", this.next_out_index, ", ", num1 })); Console.Out.WriteLine("avail_out=" + this.avail_out); } Array.Copy(this.dstate.pending_buf, this.dstate.pending_out, this.next_out, this.next_out_index, num1); this.next_out_index += num1; this.dstate.pending_out += num1; this.total_out += num1; this.avail_out -= num1; this.dstate.pending -= num1; if (this.dstate.pending == 0) { this.dstate.pending_out = 0; } } } public void free() { this.next_in = null; this.next_out = null; this.msg = null; this._adler = null; } public int inflate(int f) { if (this.istate == null) { return -2; } return this.istate.inflate(this, f); } public int inflateEnd() { if (this.istate == null) { return -2; } int num1 = this.istate.inflateEnd(this); this.istate = null; return num1; } public int inflateInit() { return this.inflateInit(ZStream.DEF_WBITS); } public int inflateInit(int w) { this.istate = new Inflate(); return this.istate.inflateInit(this, w); } public int inflateSetDictionary(byte[] dictionary, int dictLength) { if (this.istate == null) { return -2; } return this.istate.inflateSetDictionary(this, dictionary, dictLength); } public int inflateSync() { if (this.istate == null) { return -2; } return this.istate.inflateSync(this); } internal int read_buf(byte[] buf, int start, int size) { int num1 = this.avail_in; if (num1 > size) { num1 = size; } if (num1 == 0) { return 0; } this.avail_in -= num1; if (this.dstate.noheader == 0) { this.adler = this._adler.adler32(this.adler, this.next_in, this.next_in_index, num1); } Array.Copy(this.next_in, this.next_in_index, buf, start, num1); this.next_in_index += num1; this.total_in += num1; return num1; } internal Adler32 _adler; public long adler; public int avail_in; public int avail_out; internal int data_type; private static readonly int DEF_WBITS; internal Deflate dstate; internal Inflate istate; private const int MAX_MEM_LEVEL = 9; private const int MAX_WBITS = 15; public string msg; public byte[] next_in; public int next_in_index; public byte[] next_out; public int next_out_index; public long total_in; public long total_out; private const int Z_BUF_ERROR = -5; private const int Z_DATA_ERROR = -3; private const int Z_ERRNO = -1; private const int Z_FINISH = 4; private const int Z_FULL_FLUSH = 3; private const int Z_MEM_ERROR = -4; private const int Z_NEED_DICT = 2; private const int Z_NO_FLUSH = 0; private const int Z_OK = 0; private const int Z_PARTIAL_FLUSH = 1; private const int Z_STREAM_END = 1; private const int Z_STREAM_ERROR = -2; private const int Z_SYNC_FLUSH = 2; private const int Z_VERSION_ERROR = -6; } }
/* ==================================================================== 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.Collections.ObjectModel; namespace TestCases.SS.Formula.Eval { using System; using System.IO; using NUnit.Framework; using NPOI.HSSF.UserModel; using NPOI.SS.Formula.Eval; using NPOI.SS.UserModel; using TestCases.HSSF; using TestCases.SS.Formula.Functions; using System.Diagnostics; /** * Tests formulas and operators as loaded from a Test data spreadsheet.<p/> * This class does not Test implementors of <c>Function</c> and <c>OperationEval</c> in * isolation. Much of the Evaluation engine (i.e. <c>HSSFFormulaEvaluator</c>, ...) Gets * exercised as well. Tests for bug fixes and specific/tricky behaviour can be found in the * corresponding Test class (<c>TestXxxx</c>) of the target (<c>Xxxx</c>) implementor, * where execution can be observed more easily. * * @author Amol S. Deshmukh &lt; amolweb at ya hoo dot com &gt; */ [TestFixture] public class TestFormulasFromSpreadsheet { private static class Result { public const int SOME_EVALUATIONS_FAILED = -1; public const int ALL_EVALUATIONS_SUCCEEDED = +1; public const int NO_EVALUATIONS_FOUND = 0; } /** * This class defines constants for navigating around the Test data spreadsheet used for these Tests. */ private static class SS { /** * Name of the Test spreadsheet (found in the standard Test data folder) */ public static String FILENAME = "FormulaEvalTestData.xls"; /** * Row (zero-based) in the Test spreadsheet where the operator examples start. */ public static int START_OPERATORS_ROW_INDEX = 22; // Row '23' /** * Row (zero-based) in the Test spreadsheet where the function examples start. */ public static int START_FUNCTIONS_ROW_INDEX = 95; // Row '96' /** * Index of the column that Contains the function names */ public static int COLUMN_INDEX_FUNCTION_NAME = 1; // Column 'B' /** * Used to indicate when there are no more functions left */ public static String FUNCTION_NAMES_END_SENTINEL = "<END-OF-FUNCTIONS>"; /** * Index of the column where the Test values start (for each function) */ public static short COLUMN_INDEX_FIRST_TEST_VALUE = 3; // Column 'D' /** * Each function takes 4 rows in the Test spreadsheet */ public static int NUMBER_OF_ROWS_PER_FUNCTION = 4; } private HSSFWorkbook workbook; private ISheet sheet; // Note - multiple failures are aggregated before ending. // If one or more functions fail, a single AssertionException is thrown at the end private int _functionFailureCount; private int _functionSuccessCount; private int _EvaluationFailureCount; private int _EvaluationSuccessCount; private static ICell GetExpectedValueCell(IRow row, int columnIndex) { if (row == null) { return null; } return row.GetCell(columnIndex); } private static void ConfirmExpectedResult(String msg, ICell expected, CellValue actual) { Assert.IsNotNull(expected, msg + " - Bad setup data expected value is null"); Assert.IsNotNull(actual, msg + " - actual value was null"); switch (expected.CellType) { case CellType.Blank: Assert.AreEqual(CellType.Blank, actual.CellType, msg); break; case CellType.Boolean: Assert.AreEqual(CellType.Boolean, actual.CellType, msg); Assert.AreEqual(expected.BooleanCellValue, actual.BooleanValue, msg); break; case CellType.Error: Assert.AreEqual(CellType.Error, actual.CellType, msg); Assert.AreEqual(ErrorEval.GetText(expected.ErrorCellValue), ErrorEval.GetText(actual.ErrorValue), msg); break; case CellType.Formula: // will never be used, since we will call method After formula Evaluation Assert.Fail("Cannot expect formula as result of formula Evaluation: " + msg); break; case CellType.Numeric: Assert.AreEqual(CellType.Numeric, actual.CellType, msg); AbstractNumericTestCase.AssertEquals(msg, expected.NumericCellValue, actual.NumberValue, AbstractNumericTestCase.POS_ZERO, AbstractNumericTestCase.DIFF_TOLERANCE_FACTOR); break; case CellType.String: Assert.AreEqual(CellType.String, actual.CellType, msg); Assert.AreEqual(expected.RichStringCellValue.String, actual.StringValue, msg); break; } } [SetUp] protected void SetUp() { if (workbook == null) { workbook = HSSFTestDataSamples.OpenSampleWorkbook(SS.FILENAME); sheet = workbook.GetSheetAt(0); } _functionFailureCount = 0; _functionSuccessCount = 0; _EvaluationFailureCount = 0; _EvaluationSuccessCount = 0; } [Test] public void TestFunctionsFromTestSpreadsheet() { ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, null); ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, null); // example for debugging individual functions/operators: // ProcessFunctionGroup(SS.START_OPERATORS_ROW_INDEX, "ConcatEval"); // ProcessFunctionGroup(SS.START_FUNCTIONS_ROW_INDEX, "AVERAGE"); // confirm results String successMsg = "There were " + _EvaluationSuccessCount + " successful Evaluation(s) and " + _functionSuccessCount + " function(s) without error"; String msg = _functionFailureCount + " function(s) failed in " + _EvaluationFailureCount + " Evaluation(s). " + successMsg; Assert.AreEqual(_functionFailureCount, 0, msg); Debug.WriteLine(this.GetType().Name + ": " + successMsg); } /** * @param startRowIndex row index in the spreadsheet where the first function/operator is found * @param TestFocusFunctionName name of a single function/operator to Test alone. * Typically pass <code>null</code> to Test all functions */ private void ProcessFunctionGroup(int startRowIndex, String testFocusFunctionName) { HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook); ReadOnlyCollection<String> funcs = FunctionEval.GetSupportedFunctionNames(); int rowIndex = startRowIndex; while (true) { IRow r = sheet.GetRow(rowIndex); String targetFunctionName = GetTargetFunctionName(r); Assert.IsNotNull(targetFunctionName, "Test spreadsheet cell empty on row (" + (rowIndex + 1) + "). Expected function name or '" + SS.FUNCTION_NAMES_END_SENTINEL + "'"); if (targetFunctionName.Equals(SS.FUNCTION_NAMES_END_SENTINEL)) { // found end of functions list break; } if (testFocusFunctionName == null || targetFunctionName.Equals(testFocusFunctionName, StringComparison.CurrentCultureIgnoreCase)) { // expected results are on the row below IRow expectedValuesRow = sheet.GetRow(rowIndex + 1); int missingRowNum = rowIndex + 2; //+1 for 1-based, +1 for next row Assert.IsNotNull(expectedValuesRow, "Missing expected values row for function '" + targetFunctionName + " (row " + missingRowNum + ")"); switch (ProcessFunctionRow(evaluator, targetFunctionName, r, expectedValuesRow)) { case Result.ALL_EVALUATIONS_SUCCEEDED: _functionSuccessCount++; break; case Result.SOME_EVALUATIONS_FAILED: _functionFailureCount++; break; default: throw new SystemException("unexpected result"); case Result.NO_EVALUATIONS_FOUND: // do nothing String uname = targetFunctionName.ToUpper(); if (startRowIndex >= SS.START_FUNCTIONS_ROW_INDEX && funcs.Contains(uname)) { Debug.WriteLine(uname + ": function is supported but missing test data", ""); } break; } } rowIndex += SS.NUMBER_OF_ROWS_PER_FUNCTION; } } /** * * @return a constant from the local Result class denoting whether there were any Evaluation * cases, and whether they all succeeded. */ private int ProcessFunctionRow(HSSFFormulaEvaluator Evaluator, String targetFunctionName, IRow formulasRow, IRow expectedValuesRow) { int result = Result.NO_EVALUATIONS_FOUND; // so far short endcolnum = (short)formulasRow.LastCellNum; // iterate across the row for all the Evaluation cases for (int colnum = SS.COLUMN_INDEX_FIRST_TEST_VALUE; colnum < endcolnum; colnum++) { ICell c = formulasRow.GetCell(colnum); if (c == null || c.CellType != CellType.Formula) { continue; } CellValue actualValue = Evaluator.Evaluate(c); ICell expectedValueCell = GetExpectedValueCell(expectedValuesRow, colnum); try { ConfirmExpectedResult("Function '" + targetFunctionName + "': Formula: " + c.CellFormula + " @ " + formulasRow.RowNum + ":" + colnum, expectedValueCell, actualValue); _EvaluationSuccessCount++; if (result != Result.SOME_EVALUATIONS_FAILED) { result = Result.ALL_EVALUATIONS_SUCCEEDED; } } catch (AssertionException e) { _EvaluationFailureCount++; printshortStackTrace(System.Console.Error, e); result = Result.SOME_EVALUATIONS_FAILED; } } return result; } /** * Useful to keep output concise when expecting many failures to be reported by this Test case */ private static void printshortStackTrace(TextWriter ps, AssertionException e) { ps.WriteLine(e.Message); ps.WriteLine(e.StackTrace); /*StackTraceElement[] stes = e.GetStackTrace(); int startIx = 0; // skip any top frames inside junit.framework.Assert while(startIx<stes.Length) { if(!stes[startIx].GetClassName().Equals(typeof(Assert).Name)) { break; } startIx++; } // skip bottom frames (part of junit framework) int endIx = startIx+1; while(endIx < stes.Length) { if (stes[endIx].GetClassName().Equals(typeof(Assert).Name)) { break; } endIx++; } if(startIx >= endIx) { // something went wrong. just print the whole stack trace e.printStackTrace(ps); } endIx -= 4; // skip 4 frames of reflection invocation ps.println(e.ToString()); for(int i=startIx; i<endIx; i++) { ps.println("\tat " + stes[i].ToString()); }*/ } /** * @return <code>null</code> if cell is missing, empty or blank */ private static String GetTargetFunctionName(IRow r) { if (r == null) { System.Console.Error.WriteLine("Warning - given null row, can't figure out function name"); return null; } ICell cell = r.GetCell(SS.COLUMN_INDEX_FUNCTION_NAME); if (cell == null) { System.Console.Error.WriteLine("Warning - Row " + r.RowNum + " has no cell " + SS.COLUMN_INDEX_FUNCTION_NAME + ", can't figure out function name"); return null; } if (cell.CellType == CellType.Blank) { return null; } if (cell.CellType == CellType.String) { return cell.RichStringCellValue.String; } throw new AssertionException("Bad cell type for 'function name' column: (" + cell.CellType + ") row (" + (r.RowNum + 1) + ")"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.Analysis; using Orleans.CodeGenerator.Analyzers; using Orleans.CodeGenerator.Compatibility; using Orleans.CodeGenerator.Generators; using Orleans.CodeGenerator.Model; using Orleans.CodeGenerator.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Orleans.CodeGenerator { public class CodeGenerator { public const string ToolName = "OrleansCodeGen"; public static readonly string Version = typeof(CodeGenerator).Assembly.GetName().Version.ToString(); private readonly IGeneratorExecutionContext context; private readonly Compilation compilation; private readonly WellKnownTypes wellKnownTypes; private readonly SemanticModel semanticModelForAccessibility; private readonly CompilationAnalyzer compilationAnalyzer; private readonly SerializerTypeAnalyzer serializerTypeAnalyzer; private readonly SerializerGenerator serializerGenerator; private readonly GrainMethodInvokerGenerator grainMethodInvokerGenerator; private readonly GrainReferenceGenerator grainReferenceGenerator; private readonly CodeGeneratorOptions options; public CodeGenerator(IGeneratorExecutionContext context, CodeGeneratorOptions options) { this.context = context; this.compilation = context.Compilation; this.options = options; this.wellKnownTypes = new WellKnownTypes(compilation); this.compilationAnalyzer = new CompilationAnalyzer(context, this.wellKnownTypes, compilation); var firstSyntaxTree = compilation.SyntaxTrees.FirstOrDefault() ?? throw new InvalidOperationException("Compilation has no syntax trees."); this.semanticModelForAccessibility = compilation.GetSemanticModel(firstSyntaxTree); this.serializerTypeAnalyzer = SerializerTypeAnalyzer.Create(this.wellKnownTypes); this.serializerGenerator = new SerializerGenerator(this.options, this.wellKnownTypes); this.grainMethodInvokerGenerator = new GrainMethodInvokerGenerator(this.options, this.wellKnownTypes); this.grainReferenceGenerator = new GrainReferenceGenerator(this.options, this.wellKnownTypes); } [MethodImpl(MethodImplOptions.NoInlining)] public CompilationUnitSyntax GenerateCode(CancellationToken cancellationToken) { // Create a model of the code to generate from the collection of types. var model = this.AnalyzeCompilation(cancellationToken); // Perform some validation against the generated model. this.ValidateModel(model, cancellationToken); // Finally, generate code for the model. return this.GenerateSyntax(model, cancellationToken); } private AggregatedModel AnalyzeCompilation(CancellationToken cancellationToken) { // Inspect the target assembly to discover known assemblies and known types. this.compilationAnalyzer.Analyze(cancellationToken); // Create a list of all distinct types from all known assemblies. var types = this.compilationAnalyzer .KnownAssemblies.SelectMany(a => a.GetDeclaredTypes()) .Concat(this.compilationAnalyzer.KnownTypes) .Distinct(SymbolEqualityComparer.Default) .Cast<INamedTypeSymbol>() .ToList(); var model = new AggregatedModel(); // Inspect all types foreach (var type in types) this.compilationAnalyzer.InspectType(type); // Get the types which need processing. var (grainClasses, grainInterfaces, serializationTypes) = this.compilationAnalyzer.GetTypesToProcess(); // Process each of the types into the model. foreach (var grainInterface in grainInterfaces) this.ProcessGrainInterface(model, grainInterface); foreach (var grainClass in grainClasses) { this.ProcessGrainClass(model, grainClass); this.ProcessSerializableType(model, grainClass); } foreach (var type in serializationTypes) this.ProcessSerializableType(model, type); foreach (var part in this.compilationAnalyzer.ApplicationParts) { model.ApplicationParts.Add(part); } this.AddAssemblyMetadata(model); return model; } private void AddAssemblyMetadata(AggregatedModel model) { var assembliesToScan = new List<IAssemblySymbol>(); foreach (var asm in this.compilationAnalyzer.ReferencedAssemblies) { // Known assemblies are already handled. if (this.compilationAnalyzer.KnownAssemblies.Contains(asm)) continue; if (this.compilationAnalyzer.AssembliesExcludedFromCodeGeneration.Contains(asm) || this.compilationAnalyzer.AssembliesExcludedFromMetadataGeneration.Contains(asm)) { continue; } assembliesToScan.Add(asm); } foreach (var asm in assembliesToScan) { foreach (var type in asm.GetDeclaredTypes()) { if (this.ValidForKnownTypes(type)) { AddKnownType(model, type); } } } } private void ValidateModel(AggregatedModel model, CancellationToken cancellationToken) { // Check that all types which the developer marked as requiring code generation have had code generation. foreach (var required in this.compilationAnalyzer.CodeGenerationRequiredTypes) { if (!model.Serializers.SerializerTypes.Any(t => SymbolEqualityComparer.Default.Equals(t.Target, required))) { throw new CodeGenerationException( $"Found {this.wellKnownTypes.ConsiderForCodeGenerationAttribute} with ThrowOnFailure set for type {required}, but a serializer" + " could not be generated. Ensure that the type is accessible."); } } } private CompilationUnitSyntax GenerateSyntax(AggregatedModel model, CancellationToken cancellationToken) { var namespaceGroupings = new Dictionary<INamespaceSymbol, List<MemberDeclarationSyntax>>(SymbolEqualityComparer.Default); // Pass the relevant elements of the model to each of the code generators. foreach (var grainInterface in model.GrainInterfaces) { var nsMembers = GetNamespace(namespaceGroupings, grainInterface.Type.ContainingNamespace); nsMembers.Add(grainMethodInvokerGenerator.GenerateClass(grainInterface)); nsMembers.Add(grainReferenceGenerator.GenerateClass(grainInterface)); } var serializersToGenerate = model.Serializers.SerializerTypes .Where(s => s.SerializerTypeSyntax == null) .Distinct(SerializerTypeDescription.TargetComparer); foreach (var serializerType in serializersToGenerate) { var nsMembers = GetNamespace(namespaceGroupings, serializerType.Target.ContainingNamespace); TypeDeclarationSyntax generated; (generated, serializerType.SerializerTypeSyntax) = this.serializerGenerator.GenerateClass(this.context, this.semanticModelForAccessibility, serializerType); nsMembers.Add(generated); } var compilationMembers = new List<MemberDeclarationSyntax>(); // Group the generated code by namespace since serialized types, such as the generated GrainReference classes must have a stable namespace. foreach (var group in namespaceGroupings) { var ns = group.Key; var members = group.Value; if (ns.IsGlobalNamespace) { compilationMembers.AddRange(members); } else { compilationMembers.Add(NamespaceDeclaration(ParseName(ns.ToDisplayString())).AddMembers(members.ToArray())); } } // Add and generate feature populators to tie everything together. var (attributes, featurePopulators) = FeaturePopulatorGenerator.GenerateSyntax(this.wellKnownTypes, model, this.compilation); compilationMembers.AddRange(featurePopulators); attributes.AddRange(ApplicationPartAttributeGenerator.GenerateSyntax(this.wellKnownTypes, model)); // Add some attributes detailing which assemblies this generated code targets. attributes.Add(AttributeList( AttributeTargetSpecifier(Token(SyntaxKind.AssemblyKeyword)), SeparatedList(GetCodeGenerationTargetAttribute().ToArray()))); return CompilationUnit() .AddUsings(UsingDirective(ParseName("global::Orleans"))) .WithAttributeLists(List(attributes)) .WithMembers(List(compilationMembers)); List<MemberDeclarationSyntax> GetNamespace(Dictionary<INamespaceSymbol, List<MemberDeclarationSyntax>> namespaces, INamespaceSymbol ns) { if (namespaces.TryGetValue(ns, out var result)) return result; return namespaces[ns] = new List<MemberDeclarationSyntax>(); } IEnumerable<AttributeSyntax> GetCodeGenerationTargetAttribute() { yield return GenerateAttribute(this.compilation.Assembly); foreach (var assembly in this.compilationAnalyzer.ReferencedAssemblies) { if (this.compilationAnalyzer.AssembliesExcludedFromCodeGeneration.Contains(assembly) || this.compilationAnalyzer.AssembliesExcludedFromMetadataGeneration.Contains(assembly)) { continue; } yield return GenerateAttribute(assembly); } AttributeSyntax GenerateAttribute(IAssemblySymbol assembly) { var assemblyName = assembly.Identity.GetDisplayName(fullKey: true); var nameSyntax = this.wellKnownTypes.OrleansCodeGenerationTargetAttribute.ToNameSyntax(); return Attribute(nameSyntax) .AddArgumentListArguments(AttributeArgument(assemblyName.ToLiteralExpression())); } } } private void ProcessGrainInterface(AggregatedModel model, INamedTypeSymbol type) { var accessible = this.semanticModelForAccessibility.IsAccessible(0, type); if (accessible) { var genericMethod = type.GetInstanceMembers<IMethodSymbol>().FirstOrDefault(m => m.IsGenericMethod); if (genericMethod != null && this.wellKnownTypes.GenericMethodInvoker is WellKnownTypes.None) { var declaration = genericMethod.GetDeclarationSyntax(); this.context.ReportDiagnostic(GenericMethodRequireOrleansCoreDiagnostic.CreateDiagnostic(declaration)); } var methods = GetGrainMethodDescriptions(type); model.GrainInterfaces.Add(new GrainInterfaceDescription( type, this.wellKnownTypes.GetTypeId(type), this.wellKnownTypes.GetVersion(type), methods)); } // Returns a list of all methods in all interfaces on the provided type. IEnumerable<GrainMethodDescription> GetGrainMethodDescriptions(INamedTypeSymbol initialType) { IEnumerable<INamedTypeSymbol> GetAllInterfaces(INamedTypeSymbol s) { if (s.TypeKind == TypeKind.Interface) yield return s; foreach (var i in s.AllInterfaces) yield return i; } foreach (var iface in GetAllInterfaces(initialType)) { foreach (var method in iface.GetDeclaredInstanceMembers<IMethodSymbol>()) { yield return new GrainMethodDescription(this.wellKnownTypes.GetMethodId(method), method); } } } } private void ProcessGrainClass(AggregatedModel model, INamedTypeSymbol type) { var accessible = this.semanticModelForAccessibility.IsAccessible(0, type); if (accessible) { model.GrainClasses.Add(new GrainClassDescription(type, this.wellKnownTypes.GetTypeId(type))); } else { var declaration = type.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as TypeDeclarationSyntax; this.context.ReportDiagnostic(InaccessibleGrainClassDiagnostic.CreateDiagnostic(declaration)); } } private void ProcessSerializableType(AggregatedModel model, INamedTypeSymbol type) { if (!ValidForKnownTypes(type)) { return; } AddKnownType(model, type); var serializerModel = model.Serializers; if (type.IsAbstract) { return; } // Ensure that the type is accessible from generated code. var accessible = this.semanticModelForAccessibility.IsAccessible(0, type); if (!accessible) { return; } if (type.HasBaseType(this.wellKnownTypes.Exception)) { return; } if (type.HasBaseType(this.wellKnownTypes.Delegate)) { return; } if (type.AllInterfaces.Contains(this.wellKnownTypes.IAddressable)) { return; } // Account for types that serialize themselves and/or are serializers for other types. var selfSerializing = false; if (this.serializerTypeAnalyzer.IsSerializer(type, out var serializerTargets)) { var typeSyntax = type.ToTypeSyntax(); foreach (var target in serializerTargets) { if (SymbolEqualityComparer.Default.Equals(target, type)) { selfSerializing = true; typeSyntax = type.WithoutTypeParameters().ToTypeSyntax(); } serializerModel.SerializerTypes.Add(new SerializerTypeDescription { Target = target, SerializerTypeSyntax = typeSyntax, OverrideExistingSerializer = true }); } } if (selfSerializing) { return; } if (type.HasAttribute(this.wellKnownTypes.GeneratedCodeAttribute)) { return; } if (type.IsStatic) { return; } if (type.TypeKind == TypeKind.Enum) { return; } if (type.TypeParameters.Any(p => p.ConstraintTypes.Any(c => SymbolEqualityComparer.Default.Equals(c, this.wellKnownTypes.Delegate)))) { return; } var isSerializable = this.compilationAnalyzer.IsSerializable(type); if (isSerializable && this.compilationAnalyzer.IsFromKnownAssembly(type)) { // Skip types which have fields whose types are inaccessible from generated code. foreach (var field in type.GetInstanceMembers<IFieldSymbol>()) { // Ignore fields which won't be serialized anyway. if (!this.serializerGenerator.ShouldSerializeField(field)) { continue; } // Check field type accessibility. var fieldAccessible = this.semanticModelForAccessibility.IsAccessible(0, field.Type); if (!fieldAccessible) { return; } } // Add the type that needs generation. // The serializer generator will fill in the missing SerializerTypeSyntax field with the // generated type. serializerModel.SerializerTypes.Add(new SerializerTypeDescription { Target = type }); } } private static void AddKnownType(AggregatedModel model, INamedTypeSymbol type) { // Many types which will never have a serializer generated are still added to known types so that they can be used to identify the type // in a serialized payload. For example, when serializing List<SomeAbstractType>, SomeAbstractType must be known. The same applies to // interfaces (which are encoded as abstract). var serializerModel = model.Serializers; var strippedType = type.WithoutTypeParameters(); serializerModel.KnownTypes.Add(new KnownTypeDescription(strippedType)); } private bool ValidForKnownTypes(INamedTypeSymbol type) { // Skip implicitly declared types like anonymous classes and closures. if (type.IsImplicitlyDeclared) { return false; } if (!type.CanBeReferencedByName) { return false; } if (type.SpecialType != SpecialType.None) { return false; } switch (type.TypeKind) { case TypeKind.Unknown: case TypeKind.Array: case TypeKind.Delegate: case TypeKind.Dynamic: case TypeKind.Error: case TypeKind.Module: case TypeKind.Pointer: case TypeKind.TypeParameter: case TypeKind.Submission: return false; } if (type.IsStatic) { return false; } if (type.HasUnsupportedMetadata) { return false; } return true; } } }
#if DISABLE_DBC || !DEBUG || PROFILE_SVELTO #define DISABLE_CHECKS using System.Diagnostics; #endif using System; namespace DBC.ECS { /// <summary> /// Design By Contract Checks. /// /// Each method generates an exception or /// a trace assertion statement if the contract is broken. /// </summary> /// <remarks> /// This example shows how to call the Require method. /// Assume DBC_CHECK_PRECONDITION is defined. /// <code> /// public void Test(int x) /// { /// try /// { /// Check.Require(x > 1, "x must be > 1"); /// } /// catch (System.Exception ex) /// { /// Console.WriteLine(ex.ToString()); /// } /// } /// </code> /// If you wish to use trace assertion statements, intended for Debug scenarios, /// rather than exception handling then set /// /// <code>Check.UseAssertions = true</code> /// /// You can specify this in your application entry point and maybe make it /// dependent on conditional compilation flags or configuration file settings, e.g., /// <code> /// #if DBC_USE_ASSERTIONS /// Check.UseAssertions = true; /// #endif /// </code> /// You can direct output to a Trace listener. For example, you could insert /// <code> /// Trace.Listeners.Clear(); /// Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); /// </code> /// /// or direct output to a file or the Event Log. /// /// (Note: For ASP.NET clients use the Listeners collection /// of the Debug, not the Trace, object and, for a Release build, only exception-handling /// is possible.) /// </remarks> /// static class Check { #region Interface /// <summary> /// Precondition check. /// </summary> #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Require(bool assertion, string message) { if (UseExceptions) { if (!assertion) throw new PreconditionException(message); } else { Trace.Assert(assertion, "Precondition: " + message); } } /// <summary> /// Precondition check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Require(bool assertion, string message, Exception inner) { if (UseExceptions) { if (!assertion) throw new PreconditionException(message, inner); } else { Trace.Assert(assertion, "Precondition: " + message); } } /// <summary> /// Precondition check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Require(bool assertion) { if (UseExceptions) { if (!assertion) throw new PreconditionException("Precondition failed."); } else { Trace.Assert(assertion, "Precondition failed."); } } /// <summary> /// Postcondition check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Ensure(bool assertion, string message) { if (UseExceptions) { if (!assertion) throw new PostconditionException(message); } else { Trace.Assert(assertion, "Postcondition: " + message); } } /// <summary> /// Postcondition check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Ensure(bool assertion, string message, Exception inner) { if (UseExceptions) { if (!assertion) throw new PostconditionException(message, inner); } else { Trace.Assert(assertion, "Postcondition: " + message); } } /// <summary> /// Postcondition check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Ensure(bool assertion) { if (UseExceptions) { if (!assertion) throw new PostconditionException("Postcondition failed."); } else { Trace.Assert(assertion, "Postcondition failed."); } } /// <summary> /// Invariant check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Invariant(bool assertion, string message) { if (UseExceptions) { if (!assertion) throw new InvariantException(message); } else { Trace.Assert(assertion, "Invariant: " + message); } } /// <summary> /// Invariant check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Invariant(bool assertion, string message, Exception inner) { if (UseExceptions) { if (!assertion) throw new InvariantException(message, inner); } else { Trace.Assert(assertion, "Invariant: " + message); } } /// <summary> /// Invariant check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Invariant(bool assertion) { if (UseExceptions) { if (!assertion) throw new InvariantException("Invariant failed."); } else { Trace.Assert(assertion, "Invariant failed."); } } /// <summary> /// Assertion check. /// </summary> #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Assert(bool assertion, string message) { if (UseExceptions) { if (!assertion) throw new AssertionException(message); } else { Trace.Assert(assertion, "Assertion: " + message); } } /// <summary> /// Assertion check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Assert(bool assertion, string message, Exception inner) { if (UseExceptions) { if (!assertion) throw new AssertionException(message, inner); } else { Trace.Assert(assertion, "Assertion: " + message); } } /// <summary> /// Assertion check. /// </summary> /// #if DISABLE_CHECKS [Conditional("__NEVER_DEFINED__")] #endif public static void Assert(bool assertion) { if (UseExceptions) { if (!assertion) throw new AssertionException("Assertion failed."); } else { Trace.Assert(assertion, "Assertion failed."); } } /// <summary> /// Set this if you wish to use Trace Assert statements /// instead of exception handling. /// (The Check class uses exception handling by default.) /// </summary> public static bool UseAssertions { get { return useAssertions; } set { useAssertions = value; } } #endregion // Interface #region Implementation // No creation /// <summary> /// Is exception handling being used? /// </summary> static bool UseExceptions { get { return !useAssertions; } } // Are trace assertion statements being used? // Default is to use exception handling. static bool useAssertions; #endregion // Implementation } // End Check internal class Trace { internal static void Assert(bool assertion, string v) { #if NETFX_CORE System.Diagnostics.Contracts.Contract.Assert(assertion, v); #else System.Diagnostics.Trace.Assert(assertion, v); #endif } } #region Exceptions /// <summary> /// Exception raised when a contract is broken. /// Catch this exception type if you wish to differentiate between /// any DesignByContract exception and other runtime exceptions. /// /// </summary> public class DesignByContractException : Exception { protected DesignByContractException() {} protected DesignByContractException(string message) : base(message) {} protected DesignByContractException(string message, Exception inner) : base(message, inner) {} } /// <summary> /// Exception raised when a precondition fails. /// </summary> public class PreconditionException : DesignByContractException { /// <summary> /// Precondition Exception. /// </summary> public PreconditionException() {} /// <summary> /// Precondition Exception. /// </summary> public PreconditionException(string message) : base(message) {} /// <summary> /// Precondition Exception. /// </summary> public PreconditionException(string message, Exception inner) : base(message, inner) {} } /// <summary> /// Exception raised when a postcondition fails. /// </summary> public class PostconditionException : DesignByContractException { /// <summary> /// Postcondition Exception. /// </summary> public PostconditionException() {} /// <summary> /// Postcondition Exception. /// </summary> public PostconditionException(string message) : base(message) {} /// <summary> /// Postcondition Exception. /// </summary> public PostconditionException(string message, Exception inner) : base(message, inner) {} } /// <summary> /// Exception raised when an invariant fails. /// </summary> public class InvariantException : DesignByContractException { /// <summary> /// Invariant Exception. /// </summary> public InvariantException() {} /// <summary> /// Invariant Exception. /// </summary> public InvariantException(string message) : base(message) {} /// <summary> /// Invariant Exception. /// </summary> public InvariantException(string message, Exception inner) : base(message, inner) {} } /// <summary> /// Exception raised when an assertion fails. /// </summary> public class AssertionException : DesignByContractException { /// <summary> /// Assertion Exception. /// </summary> public AssertionException() {} /// <summary> /// Assertion Exception. /// </summary> public AssertionException(string message) : base(message) {} /// <summary> /// Assertion Exception. /// </summary> public AssertionException(string message, Exception inner) : base(message, inner) {} } #endregion // Exception classes } // End Design By Contract
// <copyright file="StringExtensions.CurrentCulture.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System.Globalization; using JetBrains.Annotations; namespace IX.StandardExtensions.Globalization; /// <summary> /// Extensions to strings to help with globalization. /// </summary> [PublicAPI] public static partial class StringExtensions { #region Methods #region Static methods /// <summary> /// Compares the source string with a selected value in a case-sensitive manner using the comparison rules of the UI /// thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// The comparison of the two strings, with 0 meaning equality. /// </returns> public static int CurrentCultureCompareTo( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.Compare( source, value, CompareOptions.None); /// <summary> /// Compares the source string with a selected value in a case-insensitive manner using the comparison rules of the UI /// thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// The comparison of the two strings, with 0 meaning equality. /// </returns> public static int CurrentCultureCompareToInsensitive( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.Compare( source, value, CompareOptions.IgnoreCase); /// <summary> /// Determines whether a source string contains the specified value string in a case-sensitive manner using the /// comparison rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string contains the specified value string; otherwise, /// <see langword="false" />. /// </returns> public static bool CurrentCultureContains( this string source, string value) => source.CurrentCultureIndexOf(value) >= 0; /// <summary> /// Determines whether a source string contains the specified value string in a case-insensitive manner using the /// comparison rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string contains the specified value string; otherwise, /// <see langword="false" />. /// </returns> public static bool CurrentCultureContainsInsensitive( this string source, string value) => source.CurrentCultureIndexOfInsensitive(value) >= 0; /// <summary> /// Checks whether or not the source string ends with a selected value in a case-sensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />. /// </returns> public static bool CurrentCultureEndsWith( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.IsSuffix( source, value, CompareOptions.None); /// <summary> /// Checks whether or not the source string ends with a selected value in a case-insensitive manner using the /// comparison rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />. /// </returns> public static bool CurrentCultureEndsWithInsensitive( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.IsSuffix( source, value, CompareOptions.IgnoreCase); /// <summary> /// Equates the source string with a selected value in a case-sensitive manner using the comparison rules of the UI /// thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />. /// </returns> public static bool CurrentCultureEquals( this string source, string value) => source.CurrentCultureCompareTo(value) == 0; /// <summary> /// Equates the source string with a selected value in a case-insensitive manner using the comparison rules of the UI /// thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />. /// </returns> public static bool CurrentCultureEqualsInsensitive( this string source, string value) => source.CurrentCultureCompareToInsensitive(value) == 0; /// <summary> /// Finds the index of the specified value string in a source string in a case-sensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// The index where the string is found, otherwise -1. /// </returns> public static int CurrentCultureIndexOf( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.IndexOf( source, value, CompareOptions.None); /// <summary> /// Finds the index of the specified value string in a source string in a case-sensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <param name="startIndex">The index in the source string to start searching at.</param> /// <returns>The index where the string is found, otherwise -1.</returns> public static int CurrentCultureIndexOf( this string source, string value, int startIndex) => CultureInfo.CurrentCulture.CompareInfo.IndexOf( source, value, startIndex, CompareOptions.None); /// <summary> /// Finds the index of the specified value string in a source string in a case-sensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <param name="startIndex">The index in the source string to start searching at.</param> /// <param name="count">The number of characters to search.</param> /// <returns>The index where the string is found, otherwise -1.</returns> public static int CurrentCultureIndexOf( this string source, string value, int startIndex, int count) => CultureInfo.CurrentCulture.CompareInfo.IndexOf( source, value, startIndex, count, CompareOptions.None); /// <summary> /// Finds the index of the specified value string in a source string in a case-insensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// The index where the string is found, otherwise -1. /// </returns> public static int CurrentCultureIndexOfInsensitive( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.IndexOf( source, value, CompareOptions.IgnoreCase); /// <summary> /// Finds the index of the specified value string in a source string in a case-insensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <param name="startIndex">The index in the source string to start searching at.</param> /// <returns>The index where the string is found, otherwise -1.</returns> public static int CurrentCultureIndexOfInsensitive( this string source, string value, int startIndex) => CultureInfo.CurrentCulture.CompareInfo.IndexOf( source, value, startIndex, CompareOptions.IgnoreCase); /// <summary> /// Finds the index of the specified value string in a source string in a case-insensitive manner using the comparison /// rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <param name="startIndex">The index in the source string to start searching at.</param> /// <param name="count">The number of characters to search.</param> /// <returns>The index where the string is found, otherwise -1.</returns> public static int CurrentCultureIndexOfInsensitive( this string source, string value, int startIndex, int count) => CultureInfo.CurrentCulture.CompareInfo.IndexOf( source, value, startIndex, count, CompareOptions.IgnoreCase); /// <summary> /// Checks whether or not the source string starts with a selected value in a case-sensitive manner using the /// comparison rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />. /// </returns> public static bool CurrentCultureStartsWith( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.IsPrefix( source, value, CompareOptions.None); /// <summary> /// Checks whether or not the source string starts with a selected value in a case-insensitive manner using the /// comparison rules of the UI thread culture. /// </summary> /// <param name="source">The source to search in.</param> /// <param name="value">The string value to do the evaluation.</param> /// <returns> /// <see langword="true" /> if the source string is equal to the value; otherwise, <see langword="false" />. /// </returns> public static bool CurrentCultureStartsWithInsensitive( this string source, string value) => CultureInfo.CurrentCulture.CompareInfo.IsPrefix( source, value, CompareOptions.IgnoreCase); #endregion #endregion }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleHistoryTestingParallel.SampleHistoryTestingParallelPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleHistoryTestingParallel { using System; using System.IO; using System.Linq; using System.Windows; using System.Windows.Media; using System.Collections.Generic; using Ecng.Xaml; using Ecng.Common; using StockSharp.Algo; using StockSharp.Algo.Candles; using StockSharp.Algo.Storages; using StockSharp.Algo.Strategies.Testing; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Messages; using StockSharp.Xaml.Charting; using StockSharp.Localization; using StockSharp.Configuration; using StockSharp.Charting; public partial class MainWindow { private DateTime _startEmulationTime; private BatchEmulation _batchEmulation; public MainWindow() { InitializeComponent(); HistoryPath.Folder = Paths.HistoryDataPath; } private void StartBtnClick(object sender, RoutedEventArgs e) { if (_batchEmulation != null) { _batchEmulation.Resume(); return; } if (HistoryPath.Folder.IsEmpty() || !Directory.Exists(HistoryPath.Folder)) { MessageBox.Show(this, LocalizedStrings.Str3014); return; } TestingProcess.Value = 0; Curve.Clear(); Stat.Clear(); var logManager = new LogManager(); var fileLogListener = new FileLogListener("sample.log"); logManager.Listeners.Add(fileLogListener); // SMA periods var periods = new List<(int longMa, int shortMa, Color color)>(); for (var l = 100; l >= 50; l -= 10) { for (var s = 10; s >= 5; s -= 1) { periods.Add((l, s, Color.FromRgb((byte)RandomGen.GetInt(255), (byte)RandomGen.GetInt(255), (byte)RandomGen.GetInt(255)))); } } // storage to historical data var storageRegistry = new StorageRegistry { // set historical path DefaultDrive = new LocalMarketDataDrive(HistoryPath.Folder) }; var timeFrame = TimeSpan.FromMinutes(1); // create test security var security = new Security { Id = "SBER@TQBR", // sec id has the same name as folder with historical data Code = "SBER", Name = "SBER", Board = ExchangeBoard.Micex, }; var startTime = new DateTime(2020, 4, 1); var stopTime = new DateTime(2020, 4, 20); var level1Info = new Level1ChangeMessage { SecurityId = security.ToSecurityId(), ServerTime = startTime, } .TryAdd(Level1Fields.PriceStep, 0.01m) .TryAdd(Level1Fields.StepPrice, 0.01m) .TryAdd(Level1Fields.MinPrice, 0.01m) .TryAdd(Level1Fields.MaxPrice, 1000000m) .TryAdd(Level1Fields.MarginBuy, 10000m) .TryAdd(Level1Fields.MarginSell, 10000m); // test portfolio var portfolio = Portfolio.CreateSimulator(); // create backtesting connector _batchEmulation = new BatchEmulation(new[] { security }, new[] { portfolio }, storageRegistry) { EmulationSettings = { MarketTimeChangedInterval = timeFrame, StartTime = startTime, StopTime = stopTime, // count of parallel testing strategies // if not set, then CPU count * 2 //BatchSize = 3, } }; // handle historical time for update ProgressBar _batchEmulation.TotalProgressChanged += (currBatch, total) => this.GuiAsync(() => TestingProcess.Value = total); _batchEmulation.StateChanged += (oldState, newState) => { var isFinished = _batchEmulation.IsFinished; if (_batchEmulation.State == ChannelStates.Stopped) _batchEmulation = null; this.GuiAsync(() => { switch (newState) { case ChannelStates.Stopping: case ChannelStates.Starting: case ChannelStates.Suspending: SetIsEnabled(false, false, false); break; case ChannelStates.Stopped: SetIsEnabled(true, false, false); if (isFinished) { TestingProcess.Value = TestingProcess.Maximum; MessageBox.Show(this, LocalizedStrings.Str3024.Put(DateTime.Now - _startEmulationTime)); } else MessageBox.Show(this, LocalizedStrings.cancelled); break; case ChannelStates.Started: SetIsEnabled(false, true, true); break; case ChannelStates.Suspended: SetIsEnabled(true, false, true); break; default: throw new ArgumentOutOfRangeException(newState.ToString()); } }); }; _startEmulationTime = DateTime.Now; var strategies = periods .Select(period => { var series = new CandleSeries(typeof(TimeFrameCandle), security, timeFrame); // create strategy based SMA var strategy = new SampleHistoryTesting.SmaStrategy(series) { ShortSma = { Length = period.shortMa }, LongSma = { Length = period.longMa }, Volume = 1, Security = security, Portfolio = portfolio, //Connector = connector, // by default interval is 1 min, // it is excessively for time range with several months UnrealizedPnLInterval = ((stopTime - startTime).Ticks / 1000).To<TimeSpan>() }; this.GuiSync(() => { var curveElem = Curve.CreateCurve(LocalizedStrings.Str3026Params.Put(period.Item1, period.Item2), period.Item3, ChartIndicatorDrawStyles.Line); strategy.PnLChanged += () => { var data = new ChartDrawData(); data .Group(strategy.CurrentTime) .Add(curveElem, strategy.PnL); Curve.Draw(data); }; Stat.AddStrategies(new[] { strategy }); }); return strategy; }); // start emulation _batchEmulation.Start(strategies, periods.Count); } private void SetIsEnabled(bool canStart, bool canSuspend, bool canStop) { this.GuiAsync(() => { StopBtn.IsEnabled = canStop; StartBtn.IsEnabled = canStart; PauseBtn.IsEnabled = canSuspend; }); } private void StopBtnClick(object sender, RoutedEventArgs e) { _batchEmulation.Stop(); } private void PauseBtnClick(object sender, RoutedEventArgs e) { _batchEmulation.Suspend(); } } }
namespace Dbus.Sample { public static partial class DbusImplementations { private static void initRegistrations() { global::Dbus.Connection.AddPublishProxy<global::Dbus.IOrgFreedesktopDbusObjectManagerProvide>((global::System.Func<global::Dbus.Connection, global::Dbus.IOrgFreedesktopDbusObjectManagerProvide, global::Dbus.ObjectPath, global::Dbus.IProxy>)global::Dbus.OrgFreedesktopDbusObjectManager_Proxy.Factory); global::Dbus.Connection.AddConsumeImplementation<global::Dbus.IOrgFreedesktopDbusObjectManager>((global::System.Func<global::Dbus.Connection, global::Dbus.ObjectPath, string, global::System.Threading.CancellationToken, object>)IOrgFreedesktopDbusObjectManager_Implementation.Factory); global::Dbus.Connection.AddConsumeImplementation<global::Dbus.Sample.IOrgFreedesktopUpower>((global::System.Func<global::Dbus.Connection, global::Dbus.ObjectPath, string, global::System.Threading.CancellationToken, object>)IOrgFreedesktopUpower_Implementation.Factory); global::Dbus.Connection.AddConsumeImplementation<global::Dbus.Sample.IOrgMprisMediaPlayer2Player>((global::System.Func<global::Dbus.Connection, global::Dbus.ObjectPath, string, global::System.Threading.CancellationToken, object>)IOrgMprisMediaPlayer2Player_Implementation.Factory); global::Dbus.Connection.AddPublishProxy((global::System.Func<global::Dbus.Connection, global::Dbus.Sample.SampleObject, global::Dbus.ObjectPath, global::Dbus.IProxy>)SampleObject_Proxy.Factory); } static partial void DoInit() => initRegistrations(); } public sealed class IOrgFreedesktopDbusObjectManager_Implementation : global::Dbus.IOrgFreedesktopDbusObjectManager { private readonly global::Dbus.Connection connection; private readonly global::Dbus.ObjectPath path; private readonly string destination; private readonly global::System.Collections.Generic.List<global::System.IAsyncDisposable> eventSubscriptions = new global::System.Collections.Generic.List<global::System.IAsyncDisposable>(); public override string ToString() { return "org.freedesktop.DBus.ObjectManager@" + this.path; } public void Dispose() => global::System.Threading.Tasks.Task.Run((global::System.Func<global::System.Threading.Tasks.ValueTask>)DisposeAsync); public async global::System.Threading.Tasks.ValueTask DisposeAsync() { foreach (var eventSubscription in eventSubscriptions) await eventSubscription.DisposeAsync(); } private IOrgFreedesktopDbusObjectManager_Implementation(global::Dbus.Connection connection, global::Dbus.ObjectPath path, string destination, global::System.Threading.CancellationToken cancellationToken) { this.connection = connection; this.path = path ?? ""; this.destination = destination ?? ""; eventSubscriptions.Add(connection.RegisterSignalHandler( this.path, "org.freedesktop.DBus.ObjectManager", "InterfacesAdded", (global::Dbus.Connection.SignalHandler)this.handleInterfacesAdded )); eventSubscriptions.Add(connection.RegisterSignalHandler( this.path, "org.freedesktop.DBus.ObjectManager", "InterfacesRemoved", (global::Dbus.Connection.SignalHandler)this.handleInterfacesRemoved )); } public static IOrgFreedesktopDbusObjectManager_Implementation Factory(global::Dbus.Connection connection, global::Dbus.ObjectPath path, string destination, global::System.Threading.CancellationToken cancellationToken) { return new IOrgFreedesktopDbusObjectManager_Implementation(connection, path, destination, cancellationToken); } private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>> decode_result_GetManagedObjectsAsync_v_v = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetString, global::Dbus.Decoder.GetObject); private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.Dictionary<global::System.String, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>>> decode_result_GetManagedObjectsAsync_v = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetString, decode_result_GetManagedObjectsAsync_v_v); private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.Dictionary<global::Dbus.ObjectPath, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>>>> decode_result_GetManagedObjectsAsync = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetObjectPath, decode_result_GetManagedObjectsAsync_v); public async global::System.Threading.Tasks.Task<global::System.Collections.Generic.Dictionary<global::Dbus.ObjectPath, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>>>> GetManagedObjectsAsync(global::System.Threading.CancellationToken cancellationToken) { var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", this.destination, null, "", cancellationToken ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("a{oa{sa{sv}}}"); return decode_result_GetManagedObjectsAsync(decoder); } } public event global::System.Action<global::Dbus.ObjectPath, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>>> InterfacesAdded; private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>> decode_decoded1_InterfacesAdded_v = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetString, global::Dbus.Decoder.GetObject); private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.Dictionary<global::System.String, global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>>> decode_decoded1_InterfacesAdded = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetString, decode_decoded1_InterfacesAdded_v); private void handleInterfacesAdded(global::Dbus.Decoder decoder) { decoder.AssertSignature("oa{sa{sv}}"); var decoded0_InterfacesAdded = global::Dbus.Decoder.GetObjectPath(decoder); var decoded1_InterfacesAdded = decode_decoded1_InterfacesAdded(decoder); InterfacesAdded?.Invoke(decoded0_InterfacesAdded, decoded1_InterfacesAdded); } public event global::System.Action<global::Dbus.ObjectPath, global::System.Collections.Generic.List<global::System.String>> InterfacesRemoved; private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.List<global::System.String>> decode_decoded1_InterfacesRemoved = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetArray(decoder, global::Dbus.Decoder.GetString, false); private void handleInterfacesRemoved(global::Dbus.Decoder decoder) { decoder.AssertSignature("oas"); var decoded0_InterfacesRemoved = global::Dbus.Decoder.GetObjectPath(decoder); var decoded1_InterfacesRemoved = decode_decoded1_InterfacesRemoved(decoder); InterfacesRemoved?.Invoke(decoded0_InterfacesRemoved, decoded1_InterfacesRemoved); } } public sealed class IOrgFreedesktopUpower_Implementation : global::Dbus.Sample.IOrgFreedesktopUpower { private readonly global::Dbus.Connection connection; private readonly global::Dbus.ObjectPath path; private readonly string destination; private readonly global::System.Collections.Generic.List<global::System.IAsyncDisposable> eventSubscriptions = new global::System.Collections.Generic.List<global::System.IAsyncDisposable>(); public override string ToString() { return "org.freedesktop.UPower@" + this.path; } public void Dispose() => global::System.Threading.Tasks.Task.Run((global::System.Func<global::System.Threading.Tasks.ValueTask>)DisposeAsync); public async global::System.Threading.Tasks.ValueTask DisposeAsync() { foreach (var eventSubscription in eventSubscriptions) await eventSubscription.DisposeAsync(); } private IOrgFreedesktopUpower_Implementation(global::Dbus.Connection connection, global::Dbus.ObjectPath path, string destination, global::System.Threading.CancellationToken cancellationToken) { this.connection = connection; this.path = path ?? "/org/freedesktop/UPower"; this.destination = destination ?? "org.freedesktop.UPower"; } public static IOrgFreedesktopUpower_Implementation Factory(global::Dbus.Connection connection, global::Dbus.ObjectPath path, string destination, global::System.Threading.CancellationToken cancellationToken) { return new IOrgFreedesktopUpower_Implementation(connection, path, destination, cancellationToken); } private static void encode_GetAllAsync(global::Dbus.Encoder sendBody, global::System.String interfaceName) { sendBody.Add(interfaceName); } private static readonly global::Dbus.Decoder.ElementDecoder<global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>> decode_result_GetAllAsync = (global::Dbus.Decoder decoder) => global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetString, global::Dbus.Decoder.GetObject); public async global::System.Threading.Tasks.Task<global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object>> GetAllAsync(global::System.String interfaceName) { var sendBody = new global::Dbus.Encoder(); encode_GetAllAsync(sendBody, interfaceName); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.UPower", "GetAll", this.destination, sendBody, "s", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("a{sv}"); return decode_result_GetAllAsync(decoder); } } } public sealed class IOrgMprisMediaPlayer2Player_Implementation : global::Dbus.Sample.IOrgMprisMediaPlayer2Player { private readonly global::Dbus.Connection connection; private readonly global::Dbus.ObjectPath path; private readonly string destination; private readonly global::System.Collections.Generic.List<global::System.IAsyncDisposable> eventSubscriptions = new global::System.Collections.Generic.List<global::System.IAsyncDisposable>(); public override string ToString() { return "org.mpris.MediaPlayer2.Player@" + this.path; } public void Dispose() => global::System.Threading.Tasks.Task.Run((global::System.Func<global::System.Threading.Tasks.ValueTask>)DisposeAsync); public async global::System.Threading.Tasks.ValueTask DisposeAsync() { foreach (var eventSubscription in eventSubscriptions) await eventSubscription.DisposeAsync(); } private IOrgMprisMediaPlayer2Player_Implementation(global::Dbus.Connection connection, global::Dbus.ObjectPath path, string destination, global::System.Threading.CancellationToken cancellationToken) { this.connection = connection; this.path = path ?? ""; this.destination = destination ?? ""; eventSubscriptions.Add(connection.RegisterSignalHandler( this.path, "org.freedesktop.DBus.Properties", "PropertiesChanged", (global::Dbus.Connection.SignalHandler)this.handleProperties )); PropertyInitializationFinished = initProperties(cancellationToken); eventSubscriptions.Add(connection.RegisterSignalHandler( this.path, "org.mpris.MediaPlayer2.Player", "Seeked", (global::Dbus.Connection.SignalHandler)this.handleSeeked )); } public static IOrgMprisMediaPlayer2Player_Implementation Factory(global::Dbus.Connection connection, global::Dbus.ObjectPath path, string destination, global::System.Threading.CancellationToken cancellationToken) { return new IOrgMprisMediaPlayer2Player_Implementation(connection, path, destination, cancellationToken); } public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; public global::System.Threading.Tasks.Task PropertyInitializationFinished { get; } private void handleProperties(global::Dbus.Decoder decoder) { decoder.AssertSignature("sa{sv}as"); var interfaceName = global::Dbus.Decoder.GetString(decoder); if (interfaceName != "org.mpris.MediaPlayer2.Player") return; var changed = global::Dbus.Decoder.GetDictionary(decoder, global::Dbus.Decoder.GetString, global::Dbus.Decoder.GetObject); applyProperties(changed); } private async global::System.Threading.Tasks.Task initProperties(global::System.Threading.CancellationToken cancellationToken) { var sendBody = new global::Dbus.Encoder(); sendBody.Add("org.mpris.MediaPlayer2.Player"); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "GetAll", this.destination, sendBody, "s", cancellationToken ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("a{sv}"); var properties = global::Dbus.Decoder.GetDictionary( decoder, global::Dbus.Decoder.GetString, global::Dbus.Decoder.GetObject ); applyProperties(properties); } } private void applyProperties(global::System.Collections.Generic.Dictionary<string, object> changed) { foreach (var (name, value) in changed) { switch (name) { case "PlaybackStatus": PlaybackStatus = (global::System.String)value; break; case "LoopStatus": LoopStatus = (global::System.String)value; break; case "Rate": Rate = (global::System.Double)value; break; case "Shuffle": Shuffle = (global::System.Boolean)value; break; case "Metadata": Metadata = (global::System.Collections.Generic.IDictionary<global::System.String, global::System.Object>)value; break; case "Volume": Volume = (global::System.Double)value; break; case "MinimumRate": MinimumRate = (global::System.Double)value; break; case "MaximumRate": MaximumRate = (global::System.Double)value; break; case "CanGoNext": CanGoNext = (global::System.Boolean)value; break; case "CanGoPrevious": CanGoPrevious = (global::System.Boolean)value; break; case "CanPlay": CanPlay = (global::System.Boolean)value; break; case "CanPause": CanPause = (global::System.Boolean)value; break; case "CanSeek": CanSeek = (global::System.Boolean)value; break; } } foreach (var key in changed.Keys) PropertyChanged?.Invoke(this, new global::System.ComponentModel.PropertyChangedEventArgs(key)); } public global::System.String PlaybackStatus { get; private set; } public global::System.String LoopStatus { get; private set; } public global::System.Double Rate { get; private set; } public global::System.Boolean Shuffle { get; private set; } public global::System.Collections.Generic.IDictionary<global::System.String, global::System.Object> Metadata { get; private set; } public global::System.Double Volume { get; private set; } public global::System.Double MinimumRate { get; private set; } public global::System.Double MaximumRate { get; private set; } public global::System.Boolean CanGoNext { get; private set; } public global::System.Boolean CanGoPrevious { get; private set; } public global::System.Boolean CanPlay { get; private set; } public global::System.Boolean CanPause { get; private set; } public global::System.Boolean CanSeek { get; private set; } private static void encode_GetCanControlAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("CanControl"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetCanControlAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetCanControlAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetCanGoNextAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("CanGoNext"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetCanGoNextAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetCanGoNextAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetCanGoPreviousAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("CanGoPrevious"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetCanGoPreviousAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetCanGoPreviousAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetCanPauseAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("CanPause"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetCanPauseAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetCanPauseAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetCanPlayAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("CanPlay"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetCanPlayAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetCanPlayAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetCanSeekAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("CanSeek"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetCanSeekAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetCanSeekAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetLoopStatusAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("LoopStatus"); } public async global::System.Threading.Tasks.Task<global::System.String> GetLoopStatusAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetLoopStatusAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.String)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetMaximumRateAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("MaximumRate"); } public async global::System.Threading.Tasks.Task<global::System.Double> GetMaximumRateAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetMaximumRateAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Double)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetMetadataAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Metadata"); } public async global::System.Threading.Tasks.Task<global::System.Collections.Generic.IDictionary<global::System.String, global::System.Object>> GetMetadataAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetMetadataAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Collections.Generic.IDictionary<global::System.String, global::System.Object>)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetMinimumRateAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("MinimumRate"); } public async global::System.Threading.Tasks.Task<global::System.Double> GetMinimumRateAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetMinimumRateAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Double)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetPlaybackStatusAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("PlaybackStatus"); } public async global::System.Threading.Tasks.Task<global::System.String> GetPlaybackStatusAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetPlaybackStatusAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.String)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetPositionAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Position"); } public async global::System.Threading.Tasks.Task<global::System.Int64> GetPositionAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetPositionAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Int64)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetRateAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Rate"); } public async global::System.Threading.Tasks.Task<global::System.Double> GetRateAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetRateAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Double)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetShuffleAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Shuffle"); } public async global::System.Threading.Tasks.Task<global::System.Boolean> GetShuffleAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetShuffleAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Boolean)global::Dbus.Decoder.GetObject(decoder); } } private static void encode_GetVolumeAsync(global::Dbus.Encoder sendBody) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Volume"); } public async global::System.Threading.Tasks.Task<global::System.Double> GetVolumeAsync() { var sendBody = new global::Dbus.Encoder(); encode_GetVolumeAsync(sendBody); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Get", this.destination, sendBody, "ss", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature("v"); return (global::System.Double)global::Dbus.Decoder.GetObject(decoder); } } public async global::System.Threading.Tasks.Task NextAsync() { var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "Next", this.destination, null, "", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_OperUriAsync(global::Dbus.Encoder sendBody, global::System.String uri) { sendBody.Add(uri); } public async global::System.Threading.Tasks.Task OperUriAsync(global::System.String uri) { var sendBody = new global::Dbus.Encoder(); encode_OperUriAsync(sendBody, uri); var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "OperUri", this.destination, sendBody, "s", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } public async global::System.Threading.Tasks.Task PauseAsync() { var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "Pause", this.destination, null, "", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } public async global::System.Threading.Tasks.Task PlayAsync() { var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "Play", this.destination, null, "", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } public async global::System.Threading.Tasks.Task PlayPauseAsync() { var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "PlayPause", this.destination, null, "", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } public async global::System.Threading.Tasks.Task PreviousAsync() { var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "Previous", this.destination, null, "", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_SeekAsync(global::Dbus.Encoder sendBody, global::System.Int64 offsetInUsec) { sendBody.Add(offsetInUsec); } public async global::System.Threading.Tasks.Task SeekAsync(global::System.Int64 offsetInUsec) { var sendBody = new global::Dbus.Encoder(); encode_SeekAsync(sendBody, offsetInUsec); var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "Seek", this.destination, sendBody, "x", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_SetLoopStatusAsync(global::Dbus.Encoder sendBody, global::System.String status) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("LoopStatus"); sendBody.Add((global::Dbus.Signature)"s"); sendBody.Add(status); } public async global::System.Threading.Tasks.Task SetLoopStatusAsync(global::System.String status) { var sendBody = new global::Dbus.Encoder(); encode_SetLoopStatusAsync(sendBody, status); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Set", this.destination, sendBody, "ssv", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_SetPositionAsync(global::Dbus.Encoder sendBody, global::Dbus.ObjectPath track, global::System.Int64 startPosition) { sendBody.Add(track); sendBody.Add(startPosition); } public async global::System.Threading.Tasks.Task SetPositionAsync(global::Dbus.ObjectPath track, global::System.Int64 startPosition) { var sendBody = new global::Dbus.Encoder(); encode_SetPositionAsync(sendBody, track, startPosition); var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "SetPosition", this.destination, sendBody, "ox", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_SetRateAsync(global::Dbus.Encoder sendBody, global::System.Double rate) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Rate"); sendBody.Add((global::Dbus.Signature)"d"); sendBody.Add(rate); } public async global::System.Threading.Tasks.Task SetRateAsync(global::System.Double rate) { var sendBody = new global::Dbus.Encoder(); encode_SetRateAsync(sendBody, rate); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Set", this.destination, sendBody, "ssv", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_SetShuffleAsync(global::Dbus.Encoder sendBody, global::System.Boolean shuffle) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Shuffle"); sendBody.Add((global::Dbus.Signature)"b"); sendBody.Add(shuffle); } public async global::System.Threading.Tasks.Task SetShuffleAsync(global::System.Boolean shuffle) { var sendBody = new global::Dbus.Encoder(); encode_SetShuffleAsync(sendBody, shuffle); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Set", this.destination, sendBody, "ssv", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } private static void encode_SetVolumeAsync(global::Dbus.Encoder sendBody, global::System.Double volume) { sendBody.Add("org.mpris.MediaPlayer2.Player"); sendBody.Add("Volume"); sendBody.Add((global::Dbus.Signature)"d"); sendBody.Add(volume); } public async global::System.Threading.Tasks.Task SetVolumeAsync(global::System.Double volume) { var sendBody = new global::Dbus.Encoder(); encode_SetVolumeAsync(sendBody, volume); var decoder = await connection.SendMethodCall( this.path, "org.freedesktop.DBus.Properties", "Set", this.destination, sendBody, "ssv", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } public async global::System.Threading.Tasks.Task StopAsync() { var decoder = await connection.SendMethodCall( this.path, "org.mpris.MediaPlayer2.Player", "Stop", this.destination, null, "", default(global::System.Threading.CancellationToken) ).ConfigureAwait(false); using (decoder) { decoder.AssertSignature(""); return; } } public event global::System.Action<global::System.Int64> Seeked; private void handleSeeked(global::Dbus.Decoder decoder) { decoder.AssertSignature("x"); var decoded0_Seeked = global::Dbus.Decoder.GetInt64(decoder); Seeked?.Invoke(decoded0_Seeked); } } public sealed class SampleObject_Proxy : global::Dbus.IProxy { private readonly global::Dbus.Connection connection; private readonly global::Dbus.Sample.SampleObject target; private readonly global::Dbus.ObjectPath path; private readonly global::System.IDisposable registration; private SampleObject_Proxy(global::Dbus.Connection connection, global::Dbus.Sample.SampleObject target, global::Dbus.ObjectPath path) { this.connection = connection; this.target = target; this.path = path; InterfaceName = "org.dbuscore.sample.interface"; registration = connection.RegisterObjectProxy( path ?? "/org/dbuscore/sample", InterfaceName, this ); } public object Target => target; public string InterfaceName { get; } public override string ToString() { return this.InterfaceName + "@" + this.path; } public static SampleObject_Proxy Factory(global::Dbus.Connection connection, Dbus.Sample.SampleObject target, global::Dbus.ObjectPath path) { return new SampleObject_Proxy(connection, target, path); } public void Dispose() { registration.Dispose(); } public void EncodeProperties(global::Dbus.Encoder sendBody) { var state = sendBody.StartArray(storesCompoundValues: true); sendBody.FinishArray(state); } public void EncodeProperty(global::Dbus.Encoder sendBody, string propertyName) { switch (propertyName) { default: throw new global::Dbus.DbusException( global::Dbus.DbusException.CreateErrorName("UnknownProperty"), "No such Property: " + propertyName ); } } public void SetProperty(string propertyName, global::Dbus.Decoder decoder) { switch (propertyName) { default: throw new global::Dbus.DbusException( global::Dbus.DbusException.CreateErrorName("UnknownProperty"), "No such Property: " + propertyName ); } } private static void encode_MyComplexMethodAsync(global::Dbus.Encoder sendBody, global::System.Tuple<global::System.String, global::System.Int32> methodResult) { sendBody.StartCompoundValue(); sendBody.Add(methodResult.Item1); sendBody.Add(methodResult.Item2); } private async global::System.Threading.Tasks.Task handleMyComplexMethodAsync(global::Dbus.MethodCallOptions methodCallOptions, global::Dbus.Decoder decoder, global::System.Threading.CancellationToken cancellationToken) { decoder.AssertSignature("sii"); var p1 = global::Dbus.Decoder.GetString(decoder); var p2 = global::Dbus.Decoder.GetInt32(decoder); var p3 = global::Dbus.Decoder.GetInt32(decoder); var methodResult = await target.MyComplexMethodAsync(p1, p2, p3); if (methodCallOptions.NoReplyExpected) return; var sendBody = new global::Dbus.Encoder(); encode_MyComplexMethodAsync(sendBody, methodResult); await connection.SendMethodReturnAsync(methodCallOptions, sendBody, "(si)", cancellationToken).ConfigureAwait(false); } private static void encode_MyEchoAsync(global::Dbus.Encoder sendBody, global::System.String methodResult) { sendBody.Add(methodResult); } private async global::System.Threading.Tasks.Task handleMyEchoAsync(global::Dbus.MethodCallOptions methodCallOptions, global::Dbus.Decoder decoder, global::System.Threading.CancellationToken cancellationToken) { decoder.AssertSignature("s"); var message = global::Dbus.Decoder.GetString(decoder); var methodResult = await target.MyEchoAsync(message); if (methodCallOptions.NoReplyExpected) return; var sendBody = new global::Dbus.Encoder(); encode_MyEchoAsync(sendBody, methodResult); await connection.SendMethodReturnAsync(methodCallOptions, sendBody, "s", cancellationToken).ConfigureAwait(false); } private async global::System.Threading.Tasks.Task handleMyVoidAsync(global::Dbus.MethodCallOptions methodCallOptions, global::Dbus.Decoder decoder, global::System.Threading.CancellationToken cancellationToken) { decoder.AssertSignature(""); await target.MyVoidAsync(); if (methodCallOptions.NoReplyExpected) return; await connection.SendMethodReturnAsync(methodCallOptions, null, "", cancellationToken).ConfigureAwait(false); } public global::System.Threading.Tasks.Task HandleMethodCallAsync(global::Dbus.MethodCallOptions methodCallOptions, global::Dbus.Decoder decoder, global::System.Threading.CancellationToken cancellationToken) { switch (methodCallOptions.Member) { case "MyComplexMethod": return handleMyComplexMethodAsync(methodCallOptions, decoder, cancellationToken); case "MyEcho": return handleMyEchoAsync(methodCallOptions, decoder, cancellationToken); case "MyVoid": return handleMyVoidAsync(methodCallOptions, decoder, cancellationToken); default: throw new global::Dbus.DbusException( global::Dbus.DbusException.CreateErrorName("UnknownMethod"), "Method not supported" ); } } } }
using System; using System.Text; using System.Linq; using System.Xml; using System.Xml.Schema; using System.Xml.Xsl; using System.IO; using System.Xml.XPath; using System.Xml.Linq; using System.Text.RegularExpressions; using Saxon.Api; namespace Codes.October.Tools { public static class Xml { public static string RemoveDeclarations(string xml) { return Regex.Replace(xml, @"<\?.*\?>", "", RegexOptions.IgnoreCase); } public static string RemoveWhitespace(string xml) { Regex regex = null; try { regex = new Regex(@">\s*<"); return regex.Replace(xml, "><").Trim(); } finally { regex = null; } } public static XmlDocument RemoveAllNamespaces(XmlDocument doc) { XmlNodeReader xnr = null; XDocument xd = null; XmlDocument nDoc = null; XmlReader xr = null; try { xnr = new XmlNodeReader(doc); xd = XDocument.Load(xnr); xd.Root.Descendants().Attributes().Where(x => x.IsNamespaceDeclaration).Remove(); foreach (XElement elem in xd.Descendants()) { elem.Name = elem.Name.LocalName; } nDoc = new XmlDocument(); xr = xd.CreateReader(); nDoc.Load(xr); return nDoc; } finally { xnr = null; xd = null; nDoc = null; xr = null; } } public static XmlDocument RemoveAllNamespaces(String xml) { XmlDocument doc = null; try { doc = new XmlDocument(); doc.LoadXml(xml); return RemoveAllNamespaces(doc); } finally { doc = null; } } } public static class Xslt { public enum PROCESSOR { MICROSOFT = 1 , SAXON = 2 } public static string Transform(string xml, string xslt, PROCESSOR p) { switch (p) { case PROCESSOR.MICROSOFT: return Transform(xml, xslt); case PROCESSOR.SAXON: return SaxonTransform(xml, xslt); default: return String.Empty; } } public static string Transform(string xml, string xslt) { MemoryStream ms = null; XmlTextReader xtr = null; MemoryStream ms2 = null; XmlTextReader xtr2 = null; XslCompiledTransform xct = null; StringBuilder sb = null; try { ms = (MemoryStream)xml.ToStream(); ms.Position = 0; xtr = new XmlTextReader(ms); ms2 = (MemoryStream)xslt.ToStream(); ms2.Position = 0; xtr2 = new XmlTextReader(ms2); xct = new XslCompiledTransform(); xct.Load(xtr); sb = new StringBuilder(); using (TextWriter tw = new StringWriter(sb)) { xct.Transform(new XPathDocument(xtr2), null, tw); } return sb.ToString(); } catch { return null; } finally { ms = null; xtr = null; ms2 = null; xtr2 = null; xct = null; sb = null; } } public static string Transform(string xml, string xslt, bool hasEncoding) { if (!hasEncoding) { return Transform(xml, xslt); } else { Match m = null; Encoding encodingXml = null; Encoding encodingXslt = null; try { m = Regex.Match(xml, "encoding=\"([^\"]*)\"", RegexOptions.IgnoreCase | RegexOptions.Multiline); if (m.Success) { encodingXml = Encoding.GetEncoding(m.Groups[1].Value); } m = Regex.Match(xslt, "encoding=\"([^\"]*)\"", RegexOptions.IgnoreCase | RegexOptions.Multiline); if (m.Success) { encodingXslt = Encoding.GetEncoding(m.Groups[1].Value); } return Transform(xml, xslt, encodingXml, encodingXslt); } finally { m = null; encodingXml = null; encodingXslt = null; } } } public static string Transform(string xml, string xslt, Encoding encodingXml, Encoding encodingXslt) { if (String.IsNullOrEmpty(xml)) { throw new Exception("Error: No XML present for the transformation."); } if (String.IsNullOrEmpty(xslt)) { throw new Exception("Error: No XSLT present for the transformation."); } MemoryStream ms = null; MemoryStream ms2 = null; XmlTextReader tr = null; XmlTextReader tr2 = null; XPathDocument xpd = null; XmlUrlResolver xur = null; XsltSettings xs = null; XslCompiledTransform xct = null; StringBuilder sb = null; try { if (encodingXml == null) { encodingXml = new UTF8Encoding(false); } ms = new MemoryStream(); byte[] d = encodingXml.GetBytes(xml); ms.Write(d, 0, d.Length); ms.Seek(0, SeekOrigin.Begin); tr = new XmlTextReader(ms); xpd = new XPathDocument(tr); if (encodingXslt == null) { encodingXslt = new UTF8Encoding(false); } ms2 = new MemoryStream(); byte[] d2 = encodingXslt.GetBytes(xslt); ms2.Write(d2, 0, d2.Length); ms2.Seek(0, SeekOrigin.Begin); tr2 = new XmlTextReader(ms2); xs = new XsltSettings(); xs.EnableScript = true; xur = new XmlUrlResolver(); xct = new XslCompiledTransform(false); xct.Load(tr2, xs, xur); sb = new StringBuilder(); using (TextWriter tw = new StringWriter(sb)) { xct.Transform(xpd, null, tw); } return sb.ToString(); } finally { sb = null; xs = null; xur = null; xct = null; xpd = null; tr = null; tr2 = null; ms = null; ms2 = null; } } private static string SaxonTransform(string xml, string xslt) { Saxon.Api.Processor p = null; DocumentBuilder db = null; XdmNode xdm = null; MemoryStream xsl = null; XsltTransformer xt = null; XdmDestination xdmd = null; StringWriter sw = null; try { p = new Saxon.Api.Processor(); db = p.NewDocumentBuilder(); db.BaseUri = new Uri("file:///C:/"); xdm = db.Build(xml.ToStream()); xsl = (MemoryStream)xslt.ToStream(); xt = p.NewXsltCompiler().Compile(xsl).Load(); xt.InitialContextNode = xdm; xdmd = new XdmDestination(); xt.Run(xdmd); sw = new StringWriter(); xdmd.XdmNode.WriteTo(new XmlTextWriter(sw)); return sw.ToString(); } finally { p = null; db = null; xdm = null; xsl = null; xt = null; xdmd = null; sw = null; } } } public sealed class XmlSchema { private XmlReaderSettings _settings; private XmlDocument _doc; private string _xml; private string _validationErrors; public XmlSchema() { this._settings = new XmlReaderSettings(); } public XmlSchema(string xml) { this._xml = xml; this._settings = new XmlReaderSettings(); } public XmlSchema(string xml, string xsd) { this._xml = xml; this._settings.Schemas.Add((string)null, XmlReader.Create((MemoryStream)this.ConvertToStream(xsd))); } public void LoadXml(string xml) { this._xml = xml; } public void LoadXsd(string xsd) { this._settings.Schemas.Add((string)null, XmlReader.Create((MemoryStream)this.ConvertToStream(xsd))); } public void LoadXmlFromFile(string xmlPath) { this._xml = new StreamReader(xmlPath).ReadToEnd(); } public void LoadXsdFromFile(string xsdPath) { this._settings.Schemas.Add((string)null, XmlReader.Create(xsdPath)); } public void Validate() { this._settings.ValidationType = ValidationType.Schema; this._settings.ValidationEventHandler += new ValidationEventHandler(this.settings_ValidationEventHandler); XmlReader reader = XmlReader.Create((TextReader)new StringReader(this._xml), this._settings); while (reader.Read()); this._doc = new XmlDocument(); this._doc.Load(reader); } private MemoryStream ConvertToStream(string xml) { MemoryStream memoryStream; try { memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); memoryStream.Position = 0; return memoryStream; } catch { return (MemoryStream) null; } finally { memoryStream = null; } } private void settings_ValidationEventHandler(object sender, ValidationEventArgs e) { if (this._validationErrors == null) { this._validationErrors = string.Empty; } if (e.Severity == XmlSeverityType.Warning) { return; } this._validationErrors += e.Message; } public string ValidationErrors { get { return this._validationErrors; } set { this._validationErrors = value; } } public bool IsValid { get { return this._validationErrors == null || this._validationErrors == string.Empty; } } public XmlSchemaSet XmlSchemas { get { return this._settings.Schemas; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Threading; namespace SharpLua { /* * Structure to store a type and the return types of * its methods (the type of the returned value and out/ref * parameters). */ struct LuaClassType { public Type klass; public Type[][] returnTypes; } /* * Common interface for types generated from tables. The method * returns the table that overrides some or all of the type's methods. */ public interface ILuaGeneratedType { LuaTable __luaInterface_getLuaTable(); } /* * Class used for generating delegates that get a function from the Lua * stack as a delegate of a specific type. * * Author: Fabio Mascarenhas * Version: 1.0 */ class DelegateGenerator { private ObjectTranslator translator; private Type delegateType; public DelegateGenerator(ObjectTranslator translator, Type delegateType) { this.translator = translator; this.delegateType = delegateType; } public object extractGenerated(SharpLua.Lua.LuaState luaState, int stackPos) { return CodeGeneration.Instance.GetDelegate(delegateType, translator.getFunction(luaState, stackPos)); } } /* * Class used for generating delegates that get a table from the Lua * stack as a an object of a specific type. * * Author: Fabio Mascarenhas * Version: 1.0 */ class ClassGenerator { private ObjectTranslator translator; private Type klass; public ClassGenerator(ObjectTranslator translator, Type klass) { this.translator = translator; this.klass = klass; } public object extractGenerated(SharpLua.Lua.LuaState luaState, int stackPos) { return CodeGeneration.Instance.GetClassInstance(klass, translator.getTable(luaState, stackPos)); } } /* * Dynamically generates new types from existing types and * Lua function and table values. Generated types are event handlers, * delegates, interface implementations and subclasses. * * Author: Fabio Mascarenhas * Version: 1.0 */ class CodeGeneration { private Type eventHandlerParent = typeof(LuaEventHandler); private Dictionary<Type, Type> eventHandlerCollection = new Dictionary<Type, Type>(); private Type delegateParent = typeof(LuaDelegate); private Dictionary<Type, Type> delegateCollection = new Dictionary<Type, Type>(); private Type classHelper = typeof(LuaClassHelper); private Dictionary<Type, LuaClassType> classCollection = new Dictionary<Type, LuaClassType>(); private AssemblyName assemblyName; private AssemblyBuilder newAssembly; private ModuleBuilder newModule; private int luaClassNumber = 1; private static readonly CodeGeneration instance = new CodeGeneration(); static CodeGeneration() { } private CodeGeneration() { // Create an assembly name assemblyName = new AssemblyName(); assemblyName.Name = "LuaInterface_generatedcode"; // Create a new assembly with one module. newAssembly = Thread.GetDomain().DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run); newModule = newAssembly.DefineDynamicModule("LuaInterface_generatedcode"); } /* * Singleton instance of the class */ public static CodeGeneration Instance { get { return instance; } } /* * Generates an event handler that calls a Lua function */ private Type GenerateEvent(Type eventHandlerType) { string typeName; lock (this) { typeName = "LuaGeneratedClass" + luaClassNumber; luaClassNumber++; } // Define a public class in the assembly, called typeName TypeBuilder myType = newModule.DefineType(typeName, TypeAttributes.Public, eventHandlerParent); // Defines the handler method. Its signature is void(object,<subclassofEventArgs>) Type[] paramTypes = new Type[2]; paramTypes[0] = typeof(object); paramTypes[1] = eventHandlerType; Type returnType = typeof(void); MethodBuilder handleMethod = myType.DefineMethod("HandleEvent", MethodAttributes.Public | MethodAttributes.HideBySig, returnType, paramTypes); // Emits the IL for the method. It loads the arguments // and calls the handleEvent method of the base class ILGenerator generator = handleMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Ldarg_2); MethodInfo miGenericEventHandler; miGenericEventHandler = eventHandlerParent.GetMethod("handleEvent"); generator.Emit(OpCodes.Call, miGenericEventHandler); // returns generator.Emit(OpCodes.Ret); // creates the new type return myType.CreateType(); } /* * Generates a type that can be used for instantiating a delegate * of the provided type, given a Lua function. */ private Type GenerateDelegate(Type delegateType) { string typeName; lock (this) { typeName = "LuaGeneratedClass" + luaClassNumber; luaClassNumber++; } // Define a public class in the assembly, called typeName TypeBuilder myType = newModule.DefineType(typeName, TypeAttributes.Public, delegateParent); // Defines the delegate method with the same signature as the // Invoke method of delegateType MethodInfo invokeMethod = delegateType.GetMethod("Invoke"); ParameterInfo[] paramInfo = invokeMethod.GetParameters(); Type[] paramTypes = new Type[paramInfo.Length]; Type returnType = invokeMethod.ReturnType; // Counts out and ref params, for use later int nOutParams = 0; int nOutAndRefParams = 0; for (int i = 0; i < paramTypes.Length; i++) { paramTypes[i] = paramInfo[i].ParameterType; if ((!paramInfo[i].IsIn) && paramInfo[i].IsOut) nOutParams++; if (paramTypes[i].IsByRef) nOutAndRefParams++; } int[] refArgs = new int[nOutAndRefParams]; MethodBuilder delegateMethod = myType.DefineMethod("CallFunction", invokeMethod.Attributes, returnType, paramTypes); // Generates the IL for the method ILGenerator generator = delegateMethod.GetILGenerator(); generator.DeclareLocal(typeof(object[])); // original arguments generator.DeclareLocal(typeof(object[])); // with out-only arguments removed generator.DeclareLocal(typeof(int[])); // indexes of out and ref arguments if (!(returnType == typeof(void))) // return value generator.DeclareLocal(returnType); else generator.DeclareLocal(typeof(object)); // Initializes local variables generator.Emit(OpCodes.Ldc_I4, paramTypes.Length); generator.Emit(OpCodes.Newarr, typeof(object)); generator.Emit(OpCodes.Stloc_0); generator.Emit(OpCodes.Ldc_I4, paramTypes.Length - nOutParams); generator.Emit(OpCodes.Newarr, typeof(object)); generator.Emit(OpCodes.Stloc_1); generator.Emit(OpCodes.Ldc_I4, nOutAndRefParams); generator.Emit(OpCodes.Newarr, typeof(int)); generator.Emit(OpCodes.Stloc_2); // Stores the arguments in the local variables for (int iArgs = 0, iInArgs = 0, iOutArgs = 0; iArgs < paramTypes.Length; iArgs++) { generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldc_I4, iArgs); generator.Emit(OpCodes.Ldarg, iArgs + 1); if (paramTypes[iArgs].IsByRef) { if (paramTypes[iArgs].GetElementType().IsValueType) { generator.Emit(OpCodes.Ldobj, paramTypes[iArgs].GetElementType()); generator.Emit(OpCodes.Box, paramTypes[iArgs].GetElementType()); } else generator.Emit(OpCodes.Ldind_Ref); } else { if (paramTypes[iArgs].IsValueType) generator.Emit(OpCodes.Box, paramTypes[iArgs]); } generator.Emit(OpCodes.Stelem_Ref); if (paramTypes[iArgs].IsByRef) { generator.Emit(OpCodes.Ldloc_2); generator.Emit(OpCodes.Ldc_I4, iOutArgs); generator.Emit(OpCodes.Ldc_I4, iArgs); generator.Emit(OpCodes.Stelem_I4); refArgs[iOutArgs] = iArgs; iOutArgs++; } if (paramInfo[iArgs].IsIn || (!paramInfo[iArgs].IsOut)) { generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldc_I4, iInArgs); generator.Emit(OpCodes.Ldarg, iArgs + 1); if (paramTypes[iArgs].IsByRef) { if (paramTypes[iArgs].GetElementType().IsValueType) { generator.Emit(OpCodes.Ldobj, paramTypes[iArgs].GetElementType()); generator.Emit(OpCodes.Box, paramTypes[iArgs].GetElementType()); } else generator.Emit(OpCodes.Ldind_Ref); } else { if (paramTypes[iArgs].IsValueType) generator.Emit(OpCodes.Box, paramTypes[iArgs]); } generator.Emit(OpCodes.Stelem_Ref); iInArgs++; } } // Calls the callFunction method of the base class generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldloc_2); MethodInfo miGenericEventHandler; miGenericEventHandler = delegateParent.GetMethod("callFunction"); generator.Emit(OpCodes.Call, miGenericEventHandler); // Stores return value if (returnType == typeof(void)) { generator.Emit(OpCodes.Pop); generator.Emit(OpCodes.Ldnull); } else if (returnType.IsValueType) { generator.Emit(OpCodes.Unbox, returnType); generator.Emit(OpCodes.Ldobj, returnType); } else generator.Emit(OpCodes.Castclass, returnType); generator.Emit(OpCodes.Stloc_3); // Stores new value of out and ref params for (int i = 0; i < refArgs.Length; i++) { generator.Emit(OpCodes.Ldarg, refArgs[i] + 1); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldc_I4, refArgs[i]); generator.Emit(OpCodes.Ldelem_Ref); if (paramTypes[refArgs[i]].GetElementType().IsValueType) { generator.Emit(OpCodes.Unbox, paramTypes[refArgs[i]].GetElementType()); generator.Emit(OpCodes.Ldobj, paramTypes[refArgs[i]].GetElementType()); generator.Emit(OpCodes.Stobj, paramTypes[refArgs[i]].GetElementType()); } else { generator.Emit(OpCodes.Castclass, paramTypes[refArgs[i]].GetElementType()); generator.Emit(OpCodes.Stind_Ref); } } // Returns if (!(returnType == typeof(void))) generator.Emit(OpCodes.Ldloc_3); generator.Emit(OpCodes.Ret); // creates the new type return myType.CreateType(); } /* * Generates an implementation of klass, if it is an interface, or * a subclass of klass that delegates its virtual methods to a Lua table. */ public void GenerateClass(Type klass, out Type newType, out Type[][] returnTypes, LuaTable luaTable) { string typeName; lock (this) { typeName = "LuaGeneratedClass" + luaClassNumber; luaClassNumber++; } TypeBuilder myType; // Define a public class in the assembly, called typeName if (klass.IsInterface) myType = newModule.DefineType(typeName, TypeAttributes.Public, typeof(object), new Type[] { klass, typeof(ILuaGeneratedType) }); else myType = newModule.DefineType(typeName, TypeAttributes.Public, klass, new Type[] { typeof(ILuaGeneratedType) }); // Field that stores the Lua table FieldBuilder luaTableField = myType.DefineField("__luaInterface_luaTable", typeof(LuaTable), FieldAttributes.Public); // Field that stores the return types array FieldBuilder returnTypesField = myType.DefineField("__luaInterface_returnTypes", typeof(Type[][]), FieldAttributes.Public); // Generates the constructor for the new type, it takes a Lua table and an array // of return types and stores them in the respective fields ConstructorBuilder constructor = myType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(LuaTable), typeof(Type[][]) }); ILGenerator generator = constructor.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); if (klass.IsInterface) generator.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); else generator.Emit(OpCodes.Call, klass.GetConstructor(Type.EmptyTypes)); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Stfld, luaTableField); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldarg_2); generator.Emit(OpCodes.Stfld, returnTypesField); generator.Emit(OpCodes.Ret); // Generates overriden versions of the klass' public and protected virtual methods BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; MethodInfo[] classMethods = klass.GetMethods(flags); returnTypes = new Type[classMethods.Length][]; int i = 0; foreach (MethodInfo method in classMethods) { if (klass.IsInterface) { GenerateMethod(myType, method, MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot, i, luaTableField, returnTypesField, false, out returnTypes[i]); i++; } else { if (!method.IsPrivate && !method.IsFinal && method.IsVirtual && luaTable[method.Name] != null) { GenerateMethod(myType, method, (method.Attributes | MethodAttributes.NewSlot) ^ MethodAttributes.NewSlot, i, luaTableField, returnTypesField, true, out returnTypes[i]); i++; } } } // Generates an implementation of the __luaInterface_getLuaTable method MethodBuilder returnTableMethod = myType.DefineMethod("__luaInterface_getLuaTable", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.Virtual, typeof(LuaTable), new Type[0]); myType.DefineMethodOverride(returnTableMethod, typeof(ILuaGeneratedType).GetMethod("__luaInterface_getLuaTable")); generator = returnTableMethod.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, luaTableField); generator.Emit(OpCodes.Ret); // Creates the type newType = myType.CreateType(); } /* * Generates an overriden implementation of method inside myType that delegates * to a function in a Lua table with the same name, if the function exists. If it * doesn't the method calls the base method (or does nothing, in case of interface * implementations). */ private void GenerateMethod(TypeBuilder myType, MethodInfo method, MethodAttributes attributes, int methodIndex, FieldInfo luaTableField, FieldInfo returnTypesField, bool generateBase, out Type[] returnTypes) { ParameterInfo[] paramInfo = method.GetParameters(); Type[] paramTypes = new Type[paramInfo.Length]; List<Type> returnTypesList = new List<Type>(); // Counts out and ref parameters, for later use, // and creates the list of return types int nOutParams = 0; int nOutAndRefParams = 0; Type returnType = method.ReturnType; returnTypesList.Add(returnType); for (int i = 0; i < paramTypes.Length; i++) { paramTypes[i] = paramInfo[i].ParameterType; if ((!paramInfo[i].IsIn) && paramInfo[i].IsOut) nOutParams++; if (paramTypes[i].IsByRef) { returnTypesList.Add(paramTypes[i].GetElementType()); nOutAndRefParams++; } } int[] refArgs = new int[nOutAndRefParams]; returnTypes = returnTypesList.ToArray(); // Generates a version of the method that calls the base implementation // directly, for use by the base field of the table if (generateBase) { MethodBuilder baseMethod = myType.DefineMethod("__luaInterface_base_" + method.Name, MethodAttributes.Private | MethodAttributes.NewSlot | MethodAttributes.HideBySig, returnType, paramTypes); ILGenerator generatorBase = baseMethod.GetILGenerator(); generatorBase.Emit(OpCodes.Ldarg_0); for (int i = 0; i < paramTypes.Length; i++) generatorBase.Emit(OpCodes.Ldarg, i + 1); generatorBase.Emit(OpCodes.Call, method); // if(returnType == typeof(void)) // generatorBase.Emit(OpCodes.Pop); generatorBase.Emit(OpCodes.Ret); } // Defines the method MethodBuilder methodImpl = myType.DefineMethod(method.Name, attributes, returnType, paramTypes); // If it's an implementation of an interface tells what method it // is overriding if (myType.BaseType.Equals(typeof(object))) myType.DefineMethodOverride(methodImpl, method); ILGenerator generator = methodImpl.GetILGenerator(); generator.DeclareLocal(typeof(object[])); // original arguments generator.DeclareLocal(typeof(object[])); // with out-only arguments removed generator.DeclareLocal(typeof(int[])); // indexes of out and ref arguments if (!(returnType == typeof(void))) // return value generator.DeclareLocal(returnType); else generator.DeclareLocal(typeof(object)); // Initializes local variables generator.Emit(OpCodes.Ldc_I4, paramTypes.Length); generator.Emit(OpCodes.Newarr, typeof(object)); generator.Emit(OpCodes.Stloc_0); generator.Emit(OpCodes.Ldc_I4, paramTypes.Length - nOutParams + 1); generator.Emit(OpCodes.Newarr, typeof(object)); generator.Emit(OpCodes.Stloc_1); generator.Emit(OpCodes.Ldc_I4, nOutAndRefParams); generator.Emit(OpCodes.Newarr, typeof(int)); generator.Emit(OpCodes.Stloc_2); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldc_I4_0); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, luaTableField); generator.Emit(OpCodes.Stelem_Ref); // Stores the arguments into the local variables, as needed for (int iArgs = 0, iInArgs = 1, iOutArgs = 0; iArgs < paramTypes.Length; iArgs++) { generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldc_I4, iArgs); generator.Emit(OpCodes.Ldarg, iArgs + 1); if (paramTypes[iArgs].IsByRef) { if (paramTypes[iArgs].GetElementType().IsValueType) { generator.Emit(OpCodes.Ldobj, paramTypes[iArgs].GetElementType()); generator.Emit(OpCodes.Box, paramTypes[iArgs].GetElementType()); } else generator.Emit(OpCodes.Ldind_Ref); } else { if (paramTypes[iArgs].IsValueType) generator.Emit(OpCodes.Box, paramTypes[iArgs]); } generator.Emit(OpCodes.Stelem_Ref); if (paramTypes[iArgs].IsByRef) { generator.Emit(OpCodes.Ldloc_2); generator.Emit(OpCodes.Ldc_I4, iOutArgs); generator.Emit(OpCodes.Ldc_I4, iArgs); generator.Emit(OpCodes.Stelem_I4); refArgs[iOutArgs] = iArgs; iOutArgs++; } if (paramInfo[iArgs].IsIn || (!paramInfo[iArgs].IsOut)) { generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldc_I4, iInArgs); generator.Emit(OpCodes.Ldarg, iArgs + 1); if (paramTypes[iArgs].IsByRef) { if (paramTypes[iArgs].GetElementType().IsValueType) { generator.Emit(OpCodes.Ldobj, paramTypes[iArgs].GetElementType()); generator.Emit(OpCodes.Box, paramTypes[iArgs].GetElementType()); } else generator.Emit(OpCodes.Ldind_Ref); } else { if (paramTypes[iArgs].IsValueType) generator.Emit(OpCodes.Box, paramTypes[iArgs]); } generator.Emit(OpCodes.Stelem_Ref); iInArgs++; } } // Gets the function the method will delegate to by calling // the getTableFunction method of class LuaClassHelper generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, luaTableField); generator.Emit(OpCodes.Ldstr, method.Name); generator.Emit(OpCodes.Call, classHelper.GetMethod("getTableFunction")); Label lab1 = generator.DefineLabel(); generator.Emit(OpCodes.Dup); generator.Emit(OpCodes.Brtrue_S, lab1); // Function does not exist, call base method generator.Emit(OpCodes.Pop); if (!method.IsAbstract) { generator.Emit(OpCodes.Ldarg_0); for (int i = 0; i < paramTypes.Length; i++) generator.Emit(OpCodes.Ldarg, i + 1); generator.Emit(OpCodes.Call, method); if (returnType == typeof(void)) generator.Emit(OpCodes.Pop); generator.Emit(OpCodes.Ret); generator.Emit(OpCodes.Ldnull); } else generator.Emit(OpCodes.Ldnull); Label lab2 = generator.DefineLabel(); generator.Emit(OpCodes.Br_S, lab2); generator.MarkLabel(lab1); // Function exists, call using method callFunction of LuaClassHelper generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldfld, returnTypesField); generator.Emit(OpCodes.Ldc_I4, methodIndex); generator.Emit(OpCodes.Ldelem_Ref); generator.Emit(OpCodes.Ldloc_1); generator.Emit(OpCodes.Ldloc_2); generator.Emit(OpCodes.Call, classHelper.GetMethod("callFunction")); generator.MarkLabel(lab2); // Stores the function return value if (returnType == typeof(void)) { generator.Emit(OpCodes.Pop); generator.Emit(OpCodes.Ldnull); } else if (returnType.IsValueType) { generator.Emit(OpCodes.Unbox, returnType); generator.Emit(OpCodes.Ldobj, returnType); } else generator.Emit(OpCodes.Castclass, returnType); generator.Emit(OpCodes.Stloc_3); // Sets return values of out and ref parameters for (int i = 0; i < refArgs.Length; i++) { generator.Emit(OpCodes.Ldarg, refArgs[i] + 1); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Ldc_I4, refArgs[i]); generator.Emit(OpCodes.Ldelem_Ref); if (paramTypes[refArgs[i]].GetElementType().IsValueType) { generator.Emit(OpCodes.Unbox, paramTypes[refArgs[i]].GetElementType()); generator.Emit(OpCodes.Ldobj, paramTypes[refArgs[i]].GetElementType()); generator.Emit(OpCodes.Stobj, paramTypes[refArgs[i]].GetElementType()); } else { generator.Emit(OpCodes.Castclass, paramTypes[refArgs[i]].GetElementType()); generator.Emit(OpCodes.Stind_Ref); } } // Returns if (!(returnType == typeof(void))) generator.Emit(OpCodes.Ldloc_3); generator.Emit(OpCodes.Ret); } /* * Gets an event handler for the event type that delegates to the eventHandler Lua function. * Caches the generated type. */ public LuaEventHandler GetEvent(Type eventHandlerType, LuaFunction eventHandler) { Type eventConsumerType; if (eventHandlerCollection.ContainsKey(eventHandlerType)) { eventConsumerType = eventHandlerCollection[eventHandlerType]; } else { eventConsumerType = GenerateEvent(eventHandlerType); eventHandlerCollection[eventHandlerType] = eventConsumerType; } LuaEventHandler luaEventHandler = (LuaEventHandler)Activator.CreateInstance(eventConsumerType); luaEventHandler.handler = eventHandler; return luaEventHandler; } /* * Gets a delegate with delegateType that calls the luaFunc Lua function * Caches the generated type. */ public Delegate GetDelegate(Type delegateType, LuaFunction luaFunc) { List<Type> returnTypes = new List<Type>(); Type luaDelegateType; if (delegateCollection.ContainsKey(delegateType)) { luaDelegateType = delegateCollection[delegateType]; } else { luaDelegateType = GenerateDelegate(delegateType); delegateCollection[delegateType] = luaDelegateType; } MethodInfo methodInfo = delegateType.GetMethod("Invoke"); returnTypes.Add(methodInfo.ReturnType); foreach (ParameterInfo paramInfo in methodInfo.GetParameters()) if (paramInfo.ParameterType.IsByRef) returnTypes.Add(paramInfo.ParameterType); LuaDelegate luaDelegate = (LuaDelegate)Activator.CreateInstance(luaDelegateType); luaDelegate.function = luaFunc; luaDelegate.returnTypes = returnTypes.ToArray(); return Delegate.CreateDelegate(delegateType, luaDelegate, "CallFunction"); } /* * Gets an instance of an implementation of the klass interface or * subclass of klass that delegates public virtual methods to the * luaTable table. * Caches the generated type. */ public object GetClassInstance(Type klass, LuaTable luaTable) { LuaClassType luaClassType; if (classCollection.ContainsKey(klass)) { luaClassType = classCollection[klass]; } else { luaClassType = new LuaClassType(); GenerateClass(klass, out luaClassType.klass, out luaClassType.returnTypes, luaTable); classCollection[klass] = luaClassType; } return Activator.CreateInstance(luaClassType.klass, new object[] { luaTable, luaClassType.returnTypes }); } } }
// 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.AcceptanceTestsBodyByte { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// ByteModel operations. /// </summary> public partial class ByteModel : IServiceOperations<AutoRestSwaggerBATByteService>, IByteModel { /// <summary> /// Initializes a new instance of the ByteModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public ByteModel(AutoRestSwaggerBATByteService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestSwaggerBATByteService /// </summary> public AutoRestSwaggerBATByteService Client { get; private set; } /// <summary> /// Get null byte value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<byte[]>> GetNullWithHttpMessagesAsync(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, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.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, this.Client.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 HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.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; } /// <summary> /// Get empty byte value '' /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<byte[]>> GetEmptyWithHttpMessagesAsync(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, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/empty").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.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, this.Client.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 HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.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; } /// <summary> /// Get non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6) /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<byte[]>> GetNonAsciiWithHttpMessagesAsync(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, "GetNonAscii", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/nonAscii").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.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, this.Client.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 HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.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; } /// <summary> /// Put non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6) /// </summary> /// <param name='byteBody'> /// Base64-encoded non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6) /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutNonAsciiWithHttpMessagesAsync(byte[] byteBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (byteBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "byteBody"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("byteBody", byteBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutNonAscii", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/nonAscii").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; _requestContent = SafeJsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.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, this.Client.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 HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid byte value ':::SWAGGER::::' /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<byte[]>> GetInvalidWithHttpMessagesAsync(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, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "byte/invalid").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.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, this.Client.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 HttpOperationResponse<byte[]>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<byte[]>(_responseContent, this.Client.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; } } }
using System; using System.Collections; using System.Collections.Generic; namespace Algorithms.Strings { public interface IHashCoefficientTable { int[] Values { get; } } public sealed class SimpleHashCoefficientTable : IHashCoefficientTable { private readonly int[] _values; public int[] Values { get { return _values; } } public SimpleHashCoefficientTable() { _values = new int[1 << 16]; for (int i = 0; i < Values.Length; i++) { _values[i] = i; } } } public sealed class RandomizedHashCoefficientTable : IHashCoefficientTable { private readonly int[] _values; public int[] Values { get { return _values; } } public RandomizedHashCoefficientTable() { Random r = new Random(); _values = new int[1 << 16]; for (int i = 0; i < Values.Length; i++) { _values[i] = r.Next(); } } } public class RabinKarpHash { private sealed class RabinKarpHashEnumerable : IEnumerable<int> { private readonly string _input; private readonly int _blockSize; private readonly IHashCoefficientTable _hasher; public RabinKarpHashEnumerable(string s, int blockSize, IHashCoefficientTable hasher) { _input = s; _blockSize = blockSize; _hasher = hasher; } public IEnumerator<int> GetEnumerator() { return new RabinKarpHashEnumerator(_input, _blockSize, _hasher); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } private sealed class RabinKarpHashEnumerator : IEnumerator<int> { private readonly string _input; private readonly int _blockSize; private readonly IHashCoefficientTable _hasher; private RabinKarpHash _hash; private bool _wasReset; private int _offset; public int Current { get { return _hash.Value; } } object IEnumerator.Current { get { return this.Current; } } public RabinKarpHashEnumerator(string s, int blockSize, IHashCoefficientTable hasher) { _input = s; _blockSize = blockSize; _hasher = hasher; if (s.Length < _blockSize) { throw new ArgumentException("Block size cannot be smaller than input string length.", "blockSize"); } Reset(); } public bool MoveNext() { if (_wasReset) { _wasReset = false; return true; } else { _offset += 1; if (_offset >= (_input.Length - _blockSize + 1)) { return false; } else { _hash.Update(_input[_offset - 1], _input[_blockSize + _offset - 1]); return true; } } } bool IEnumerator.MoveNext() { return this.MoveNext(); } public void Reset() { _wasReset = true; _offset = 0; _hash = new RabinKarpHash(_blockSize, _hasher); for (int i = 0; i < _blockSize; i++) { _hash.Add(_input[i]); } } void IEnumerator.Reset() { this.Reset(); } public void Dispose() { } } private readonly int _n; private readonly int _b = 31; private readonly int _b2n; private readonly IHashCoefficientTable _hasher; private int _value = 0; public int Value { get { return _value; } } public int BlockSize { get { return _n; } } public RabinKarpHash(int blockSize) : this(blockSize, new SimpleHashCoefficientTable()) { } public RabinKarpHash(int blockSize, IHashCoefficientTable hasher) { int b2n = 1; _n = blockSize; _hasher = hasher; for (int i = 0; i < _n; i++) { b2n *= _b; } _b2n = b2n; } public int Add(char c) { _value = _b * _value + _hasher.Values[c]; return _value; } public int Update(char remove, char add) { _value = _b * _value +_hasher.Values[add] - _b2n * _hasher.Values[remove]; return _value; } public static IEnumerable<int> RollOver(string s, int blockSize) { return new RabinKarpHashEnumerable(s, blockSize, new SimpleHashCoefficientTable()); } } }
namespace SIL.Windows.Forms.WritingSystems { partial class WSSortControl { /// <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 Component 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.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this._testSortText = new System.Windows.Forms.TextBox(); this._testSortResult = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this._rulesValidationTimer = new System.Windows.Forms.Timer(this.components); this._testSortButton = new System.Windows.Forms.Button(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this._sortUsingComboBox = new System.Windows.Forms.ComboBox(); this.switcher_panel = new System.Windows.Forms.Panel(); this._sortrules_panel = new System.Windows.Forms.Panel(); this._languagecombo_panel = new System.Windows.Forms.TableLayoutPanel(); this.label2 = new System.Windows.Forms.Label(); this._languageComboBox = new System.Windows.Forms.ComboBox(); this._sortRulesTextBox = new System.Windows.Forms.TextBox(); this._helpLabel = new System.Windows.Forms.LinkLabel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel5 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel3.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); this.switcher_panel.SuspendLayout(); this._sortrules_panel.SuspendLayout(); this._languagecombo_panel.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tableLayoutPanel5.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(29, 13); this.label1.TabIndex = 0; this.label1.Text = "&Sort:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(3, 29); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(65, 13); this.label3.TabIndex = 0; this.label3.Text = "Te&xt to Sort:"; // // _testSortText // this._testSortText.AcceptsReturn = true; this._testSortText.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._testSortText.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._testSortText.Location = new System.Drawing.Point(3, 45); this._testSortText.Multiline = true; this._testSortText.Name = "_testSortText"; this._testSortText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._testSortText.Size = new System.Drawing.Size(426, 161); this._testSortText.TabIndex = 1; this._testSortText.Leave += new System.EventHandler(this.TextControl_Leave); this._testSortText.Enter += new System.EventHandler(this.TextControl_Enter); // // _testSortResult // this._testSortResult.BackColor = System.Drawing.SystemColors.Window; this._testSortResult.Dock = System.Windows.Forms.DockStyle.Fill; this._testSortResult.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._testSortResult.Location = new System.Drawing.Point(3, 225); this._testSortResult.Multiline = true; this._testSortResult.Name = "_testSortResult"; this._testSortResult.ReadOnly = true; this._testSortResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._testSortResult.Size = new System.Drawing.Size(426, 161); this._testSortResult.TabIndex = 1; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(3, 209); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(62, 13); this.label4.TabIndex = 0; this.label4.Text = "Sort Result:"; // // _rulesValidationTimer // this._rulesValidationTimer.Interval = 500; this._rulesValidationTimer.Tick += new System.EventHandler(this._rulesValidationTimer_Tick); // // _testSortButton // this._testSortButton.Anchor = System.Windows.Forms.AnchorStyles.Top; this._testSortButton.AutoSize = true; this._testSortButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._testSortButton.Location = new System.Drawing.Point(186, 3); this._testSortButton.Name = "_testSortButton"; this._testSortButton.Size = new System.Drawing.Size(60, 23); this._testSortButton.TabIndex = 0; this._testSortButton.Text = "&Test Sort"; this._testSortButton.UseVisualStyleBackColor = true; this._testSortButton.Click += new System.EventHandler(this._testSortButton_Click); // // tableLayoutPanel3 // this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel3.ColumnCount = 2; this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel4, 1, 0); this.tableLayoutPanel3.Controls.Add(this.switcher_panel, 1, 1); this.tableLayoutPanel3.Controls.Add(this._helpLabel, 1, 2); this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel3.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; this.tableLayoutPanel3.RowCount = 3; this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel3.Size = new System.Drawing.Size(187, 389); this.tableLayoutPanel3.TabIndex = 0; // // tableLayoutPanel4 // this.tableLayoutPanel4.AutoSize = true; this.tableLayoutPanel4.ColumnCount = 2; this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel4.Controls.Add(this.label1, 0, 1); this.tableLayoutPanel4.Controls.Add(this._sortUsingComboBox, 1, 1); this.tableLayoutPanel4.Location = new System.Drawing.Point(3, 3); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; this.tableLayoutPanel4.RowCount = 2; this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel4.Size = new System.Drawing.Size(181, 27); this.tableLayoutPanel4.TabIndex = 1; // // _sortUsingComboBox // this._sortUsingComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._sortUsingComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._sortUsingComboBox.FormattingEnabled = true; this._sortUsingComboBox.Location = new System.Drawing.Point(38, 3); this._sortUsingComboBox.Name = "_sortUsingComboBox"; this._sortUsingComboBox.Size = new System.Drawing.Size(140, 21); this._sortUsingComboBox.TabIndex = 2; this._sortUsingComboBox.SelectedIndexChanged += new System.EventHandler(this._sortUsingComboBox_SelectedIndexChanged); // // switcher_panel // this.switcher_panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.switcher_panel.Controls.Add(this._sortrules_panel); this.switcher_panel.Dock = System.Windows.Forms.DockStyle.Fill; this.switcher_panel.Location = new System.Drawing.Point(3, 36); this.switcher_panel.Name = "switcher_panel"; this.switcher_panel.Size = new System.Drawing.Size(181, 337); this.switcher_panel.TabIndex = 1; // // _sortrules_panel // this._sortrules_panel.Controls.Add(this._languagecombo_panel); this._sortrules_panel.Controls.Add(this._sortRulesTextBox); this._sortrules_panel.Dock = System.Windows.Forms.DockStyle.Fill; this._sortrules_panel.Location = new System.Drawing.Point(0, 0); this._sortrules_panel.Name = "_sortrules_panel"; this._sortrules_panel.Size = new System.Drawing.Size(181, 337); this._sortrules_panel.TabIndex = 4; // // _languagecombo_panel // this._languagecombo_panel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this._languagecombo_panel.ColumnCount = 1; this._languagecombo_panel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this._languagecombo_panel.Controls.Add(this.label2, 0, 0); this._languagecombo_panel.Controls.Add(this._languageComboBox, 0, 1); this._languagecombo_panel.Dock = System.Windows.Forms.DockStyle.Fill; this._languagecombo_panel.Location = new System.Drawing.Point(0, 0); this._languagecombo_panel.Name = "_languagecombo_panel"; this._languagecombo_panel.RowCount = 2; this._languagecombo_panel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._languagecombo_panel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this._languagecombo_panel.Size = new System.Drawing.Size(181, 337); this._languagecombo_panel.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(58, 13); this.label2.TabIndex = 0; this.label2.Text = "&Language:"; // // _languageComboBox // this._languageComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this._languageComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._languageComboBox.DropDownWidth = 156; this._languageComboBox.FormattingEnabled = true; this._languageComboBox.Location = new System.Drawing.Point(3, 16); this._languageComboBox.Name = "_languageComboBox"; this._languageComboBox.Size = new System.Drawing.Size(175, 21); this._languageComboBox.TabIndex = 1; this._languageComboBox.SelectedIndexChanged += new System.EventHandler(this._languageComboBox_SelectedIndexChanged); // // _sortRulesTextBox // this._sortRulesTextBox.AcceptsReturn = true; this._sortRulesTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this._sortRulesTextBox.Font = new System.Drawing.Font(System.Drawing.FontFamily.GenericSansSerif.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this._sortRulesTextBox.Location = new System.Drawing.Point(0, 0); this._sortRulesTextBox.Multiline = true; this._sortRulesTextBox.Name = "_sortRulesTextBox"; this._sortRulesTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this._sortRulesTextBox.Size = new System.Drawing.Size(181, 337); this._sortRulesTextBox.TabIndex = 0; this._sortRulesTextBox.Leave += new System.EventHandler(this._sortRulesTextBox_TextChanged); // // _helpLabel // this._helpLabel.AutoSize = true; this._helpLabel.Location = new System.Drawing.Point(3, 376); this._helpLabel.Name = "_helpLabel"; this._helpLabel.Size = new System.Drawing.Size(29, 13); this._helpLabel.TabIndex = 3; this._helpLabel.TabStop = true; this._helpLabel.Text = "Help"; this._helpLabel.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.OnHelpLabelClicked); // // tableLayoutPanel2 // this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel2.ColumnCount = 1; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.Controls.Add(this._testSortResult, 0, 4); this.tableLayoutPanel2.Controls.Add(this.label4, 0, 3); this.tableLayoutPanel2.Controls.Add(this.label3, 0, 1); this.tableLayoutPanel2.Controls.Add(this._testSortText, 0, 2); this.tableLayoutPanel2.Controls.Add(this._testSortButton, 0, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(196, 3); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 5; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(432, 389); this.tableLayoutPanel2.TabIndex = 0; // // tableLayoutPanel5 // this.tableLayoutPanel5.ColumnCount = 2; this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel5.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel3, 0, 0); this.tableLayoutPanel5.Controls.Add(this.tableLayoutPanel2, 1, 0); this.tableLayoutPanel5.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel5.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel5.Name = "tableLayoutPanel5"; this.tableLayoutPanel5.RowCount = 1; this.tableLayoutPanel5.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel5.Size = new System.Drawing.Size(631, 395); this.tableLayoutPanel5.TabIndex = 3; // // WSSortControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tableLayoutPanel5); this.Name = "WSSortControl"; this.Size = new System.Drawing.Size(631, 395); this.tableLayoutPanel3.ResumeLayout(false); this.tableLayoutPanel3.PerformLayout(); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); this.switcher_panel.ResumeLayout(false); this._sortrules_panel.ResumeLayout(false); this._sortrules_panel.PerformLayout(); this._languagecombo_panel.ResumeLayout(false); this._languagecombo_panel.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tableLayoutPanel5.ResumeLayout(false); this.tableLayoutPanel5.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox _testSortText; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox _testSortResult; private System.Windows.Forms.Label label4; private System.Windows.Forms.Timer _rulesValidationTimer; private System.Windows.Forms.Button _testSortButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.Panel switcher_panel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.TableLayoutPanel _languagecombo_panel; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox _languageComboBox; private System.Windows.Forms.TextBox _sortRulesTextBox; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.ComboBox _sortUsingComboBox; private System.Windows.Forms.LinkLabel _helpLabel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel5; private System.Windows.Forms.Panel _sortrules_panel; } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Reflection; using System.Text; using Gallio.Common.Concurrency; using Gallio.Common.Platform; using Gallio.Runtime.Logging; using Microsoft.Win32; namespace Gallio.NCoverIntegration.Tools { public abstract class NCoverTool { private readonly ProcessorArchitecture architecture; public static NCoverTool GetInstance(NCoverVersion version, ProcessorArchitecture architecture) { switch (version) { case NCoverVersion.V1: return new NCoverV1Tool(architecture); case NCoverVersion.V2: return new NCoverV2Tool(architecture); case NCoverVersion.V3: return new NCoverV3Tool(architecture); default: throw new NotSupportedException("Unrecognized NCover version."); } } public NCoverTool(ProcessorArchitecture architecture) { this.architecture = architecture; } public ProcessorArchitecture Architecture { get { return architecture; } } public string Name { get { if (architecture == ProcessorArchitecture.X86) return BaseName + " (x86)"; if (architecture == ProcessorArchitecture.Amd64) return BaseName + " (x64)"; return BaseName; } } protected abstract string BaseName { get; } public bool IsInstalled() { return GetInstallDir() != null; } public abstract string GetInstallDir(); public ProcessTask CreateNCoverConsoleTask(string executablePath, string arguments, string workingDirectory, string ncoverArguments, string ncoverCoverageFile, ILogger logger) { string ncoverConsolePath = Path.Combine(GetInstallDir(), "NCover.Console.exe"); StringBuilder ncoverArgumentsCombined = new StringBuilder(); BuildNCoverConsoleArguments(ncoverArgumentsCombined, executablePath, arguments, workingDirectory, ncoverArguments, ncoverCoverageFile); logger.Log(LogSeverity.Info, string.Format("Starting {0}: \"{1}\" {2}", Name, ncoverConsolePath, ncoverArgumentsCombined)); RegisterNCoverIfNecessary(); return new ProcessTask(ncoverConsolePath, ncoverArgumentsCombined.ToString(), workingDirectory); } public void Merge(IList<string> sources, string destination, ILogger logger) { if (File.Exists(destination)) File.Delete(destination); if (sources.Count == 0) return; if (sources.Count == 1) { File.Move(sources[0], destination); return; } ProcessTask mergeTask = CreateMergeTask(sources, destination); logger.Log(LogSeverity.Info, string.Format("Merging {0} coverage files to '{1}': \"{2}\" {3}", Name, destination, mergeTask.ExecutablePath, mergeTask.Arguments)); mergeTask.CaptureConsoleOutput = true; mergeTask.ConsoleOutputDataReceived += (sender, e) => { if (e.Data != null) logger.Log(LogSeverity.Info, e.Data); }; mergeTask.CaptureConsoleError = true; mergeTask.ConsoleErrorDataReceived += (sender, e) => { if (e.Data != null) logger.Log(LogSeverity.Error, e.Data); }; if (!mergeTask.Run(null)) throw new NCoverToolException(string.Format("Failed to merge {0} coverage files. The merge command failed with exit code {1}.", Name, mergeTask.ExitCode)); if (!File.Exists(destination)) throw new NCoverToolException(string.Format("Failed to merge {0} coverage files. The merge command did not produce the merged file as expected.", Name)); foreach (string source in sources) File.Delete(source); } public ProcessorArchitecture NegotiateProcessorArchitecture(ProcessorArchitecture requestedArchitecture) { if (requestedArchitecture == ProcessorArchitecture.IA64) throw new NCoverToolException(string.Format("NCover {0} does not support IA64.", Name)); if (!RequiresX86()) return requestedArchitecture; if (requestedArchitecture == ProcessorArchitecture.Amd64) throw new NCoverToolException(string.Format("NCover {0} must run code as a 32bit process but the requested architecture was 64bit. Please use a newer version of NCover.", Name)); return ProcessorArchitecture.X86; } public string NegotiateRuntimeVersion(string requestedRuntimeVersion) { if (!RequiresDotNet20()) return requestedRuntimeVersion; if (requestedRuntimeVersion == null) return DotNetRuntimeSupport.InstalledDotNet20RuntimeVersion; if (requestedRuntimeVersion.Contains("2.0.")) return requestedRuntimeVersion; throw new NCoverToolException(string.Format("{0} does not support .Net runtime {1} at this time. Please use a newer version of NCover.", Name, requestedRuntimeVersion)); } protected virtual bool RequiresX86() { return false; } protected virtual bool RequiresDotNet20() { return false; } protected virtual void BuildNCoverConsoleArguments(StringBuilder result, string executablePath, string arguments, string workingDirectory, string ncoverArguments, string ncoverCoverageFile) { result.Append('"').Append(executablePath).Append('"'); result.Append(' ').Append(arguments); result.Append(" //w \"").Append(RemoveTrailingBackslash(workingDirectory)).Append('"'); result.Append(" //x \"").Append(ncoverCoverageFile).Append('"'); if (ncoverArguments.Length != 0) result.Append(' ').Append(ncoverArguments); } protected abstract ProcessTask CreateMergeTask(IList<string> sources, string destination); protected virtual void RegisterNCoverIfNecessary() { } protected bool GetNCoverInstallInfoFromRegistry(string versionPrefix, out string version, out string installDir) { string resultVersion = null; string resultInstallDir = null; bool resultSuccess = RegistryUtils.TryActionOnOpenSubKeyWithBitness( architecture, RegistryHive.LocalMachine, @"Software\Gnoso\NCover", key => { string candidateVersion = key.GetValue("CurrentVersion") as string; if (candidateVersion != null && candidateVersion.StartsWith(versionPrefix)) { resultInstallDir = key.GetValue("InstallDir") as string; if (resultInstallDir != null) { resultVersion = candidateVersion; return true; } } return false; }); version = resultVersion; installDir = resultInstallDir; return resultSuccess; } protected static string RemoveTrailingBackslash(string path) { if (path.EndsWith(@"\")) return path.Substring(0, path.Length - 1); return path; } protected ProcessTask CreateNCoverReportingMergeTask(IList<string> sources, string destination) { string exeDir = GetInstallDir(); string exePath = Path.Combine(exeDir, "NCover.Reporting.exe"); var arguments = new StringBuilder(); arguments.Append("//q //s \"").Append(Path.GetFullPath(destination)).Append('"'); AppendSources(arguments, sources); return new ProcessTask(exePath, arguments.ToString(), exeDir); } protected ProcessTask CreateNCoverExplorerConsoleMergeTask(string relativeDirPath, IList<string> sources, string destination) { string exeDir = Path.GetFullPath(Path.Combine(GetInstallDir(), relativeDirPath)); string exePath = Path.Combine(exeDir, "NCoverExplorer.Console.exe"); var arguments = new StringBuilder(); arguments.Append("/q /s:\"").Append(Path.GetFullPath(destination)).Append('"'); AppendSources(arguments, sources); return new ProcessTask(exePath, arguments.ToString(), exeDir); } private static void AppendSources(StringBuilder arguments, IEnumerable<string> sources) { foreach (string source in sources) { arguments.Append(" \"").Append(Path.GetFullPath(source)).Append('"'); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcbcv = Google.Cloud.BigQuery.Connection.V1; using sys = System; namespace Google.Cloud.BigQuery.Connection.V1 { /// <summary>Resource name for the <c>Connection</c> resource.</summary> public sealed partial class ConnectionName : gax::IResourceName, sys::IEquatable<ConnectionName> { /// <summary>The possible contents of <see cref="ConnectionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/connections/{connection}</c>. /// </summary> ProjectLocationConnection = 1, } private static gax::PathTemplate s_projectLocationConnection = new gax::PathTemplate("projects/{project}/locations/{location}/connections/{connection}"); /// <summary>Creates a <see cref="ConnectionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ConnectionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ConnectionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ConnectionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ConnectionName"/> with the pattern /// <c>projects/{project}/locations/{location}/connections/{connection}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="connectionId">The <c>Connection</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ConnectionName"/> constructed from the provided ids.</returns> public static ConnectionName FromProjectLocationConnection(string projectId, string locationId, string connectionId) => new ConnectionName(ResourceNameType.ProjectLocationConnection, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), connectionId: gax::GaxPreconditions.CheckNotNullOrEmpty(connectionId, nameof(connectionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConnectionName"/> with pattern /// <c>projects/{project}/locations/{location}/connections/{connection}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="connectionId">The <c>Connection</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConnectionName"/> with pattern /// <c>projects/{project}/locations/{location}/connections/{connection}</c>. /// </returns> public static string Format(string projectId, string locationId, string connectionId) => FormatProjectLocationConnection(projectId, locationId, connectionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ConnectionName"/> with pattern /// <c>projects/{project}/locations/{location}/connections/{connection}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="connectionId">The <c>Connection</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ConnectionName"/> with pattern /// <c>projects/{project}/locations/{location}/connections/{connection}</c>. /// </returns> public static string FormatProjectLocationConnection(string projectId, string locationId, string connectionId) => s_projectLocationConnection.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(connectionId, nameof(connectionId))); /// <summary>Parses the given resource name string into a new <see cref="ConnectionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/connections/{connection}</c></description> /// </item> /// </list> /// </remarks> /// <param name="connectionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ConnectionName"/> if successful.</returns> public static ConnectionName Parse(string connectionName) => Parse(connectionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ConnectionName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/connections/{connection}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="connectionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ConnectionName"/> if successful.</returns> public static ConnectionName Parse(string connectionName, bool allowUnparsed) => TryParse(connectionName, allowUnparsed, out ConnectionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConnectionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/connections/{connection}</c></description> /// </item> /// </list> /// </remarks> /// <param name="connectionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConnectionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string connectionName, out ConnectionName result) => TryParse(connectionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ConnectionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/connections/{connection}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="connectionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ConnectionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string connectionName, bool allowUnparsed, out ConnectionName result) { gax::GaxPreconditions.CheckNotNull(connectionName, nameof(connectionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationConnection.TryParseName(connectionName, out resourceName)) { result = FromProjectLocationConnection(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(connectionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ConnectionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string connectionId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ConnectionId = connectionId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ConnectionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/connections/{connection}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="connectionId">The <c>Connection</c> ID. Must not be <c>null</c> or empty.</param> public ConnectionName(string projectId, string locationId, string connectionId) : this(ResourceNameType.ProjectLocationConnection, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), connectionId: gax::GaxPreconditions.CheckNotNullOrEmpty(connectionId, nameof(connectionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Connection</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ConnectionId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationConnection: return s_projectLocationConnection.Expand(ProjectId, LocationId, ConnectionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ConnectionName); /// <inheritdoc/> public bool Equals(ConnectionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ConnectionName a, ConnectionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ConnectionName a, ConnectionName b) => !(a == b); } public partial class CreateConnectionRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetConnectionRequest { /// <summary> /// <see cref="gcbcv::ConnectionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::ConnectionName ConnectionName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::ConnectionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListConnectionsRequest { /// <summary> /// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class UpdateConnectionRequest { /// <summary> /// <see cref="gcbcv::ConnectionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::ConnectionName ConnectionName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::ConnectionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteConnectionRequest { /// <summary> /// <see cref="gcbcv::ConnectionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::ConnectionName ConnectionName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::ConnectionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Connection { /// <summary> /// <see cref="gcbcv::ConnectionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcbcv::ConnectionName ConnectionName { get => string.IsNullOrEmpty(Name) ? null : gcbcv::ConnectionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Creates a <see cref="LambdaExpression"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> [DebuggerTypeProxy(typeof(LambdaExpressionProxy))] public abstract class LambdaExpression : Expression, IParameterProvider { private readonly Expression _body; internal LambdaExpression(Expression body) { _body = body; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type => TypeCore; internal abstract Type TypeCore { get; } internal abstract Type PublicType { get; } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Lambda; /// <summary> /// Gets the parameters of the lambda expression. /// </summary> public ReadOnlyCollection<ParameterExpression> Parameters => GetOrMakeParameters(); /// <summary> /// Gets the name of the lambda expression. /// </summary> /// <remarks>Used for debugging purposes.</remarks> public string Name => NameCore; internal virtual string NameCore => null; /// <summary> /// Gets the body of the lambda expression. /// </summary> public Expression Body => _body; /// <summary> /// Gets the return type of the lambda expression. /// </summary> public Type ReturnType => Type.GetInvokeMethod().ReturnType; /// <summary> /// Gets the value that indicates if the lambda expression will be compiled with /// tail call optimization. /// </summary> public bool TailCall => TailCallCore; internal virtual bool TailCallCore => false; [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable ParameterExpression IParameterProvider.GetParameter(int index) => GetParameter(index); [ExcludeFromCodeCoverage] // Unreachable internal virtual ParameterExpression GetParameter(int index) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable int IParameterProvider.ParameterCount => ParameterCount; [ExcludeFromCodeCoverage] // Unreachable internal virtual int ParameterCount { get { throw ContractUtils.Unreachable; } } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile() { return Compile(preferInterpretation: false); } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile(bool preferInterpretation) { #if FEATURE_COMPILE #if FEATURE_INTERPRET if (preferInterpretation) { return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); } #endif return Compiler.LambdaCompiler.Compile(this); #else return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Compiles the lambda into a method definition. /// </summary> /// <param name="method">A <see cref="Emit.MethodBuilder"/> which will be used to hold the lambda's IL.</param> public void CompileToMethod(System.Reflection.Emit.MethodBuilder method) { ContractUtils.RequiresNotNull(method, nameof(method)); ContractUtils.Requires(method.IsStatic, nameof(method)); var type = method.DeclaringType as System.Reflection.Emit.TypeBuilder; if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder(); Compiler.LambdaCompiler.Compile(this, method); } #endif #if FEATURE_COMPILE internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller); #endif /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile(DebugInfoGenerator debugInfoGenerator) { return Compile(); } } /// <summary> /// Defines a <see cref="Expression{TDelegate}"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <typeparam name="TDelegate">The type of the delegate.</typeparam> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> public class Expression<TDelegate> : LambdaExpression { internal Expression(Expression body) : base(body) { } internal sealed override Type TypeCore => typeof(TDelegate); internal override Type PublicType => typeof(Expression<TDelegate>); /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile() { return Compile(preferInterpretation: false); } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile(bool preferInterpretation) { #if FEATURE_COMPILE #if FEATURE_INTERPRET if (preferInterpretation) { return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); } #endif return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this); #else return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="LambdaExpression.Body" /> property of the result.</param> /// <param name="parameters">The <see cref="LambdaExpression.Parameters" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters) { if (body == Body) { // Ensure parameters is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection<ParameterExpression> pars; if (parameters == null) { pars = null; } else { pars = parameters as ICollection<ParameterExpression>; if (pars == null) { parameters = pars = parameters.ToReadOnly(); } } if (SameParameters(pars)) { return this; } } return Lambda<TDelegate>(body, Name, TailCall, parameters); } [ExcludeFromCodeCoverage] // Unreachable internal virtual bool SameParameters(ICollection<ParameterExpression> parameters) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { throw ContractUtils.Unreachable; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitLambda(this); } #if FEATURE_COMPILE internal override LambdaExpression Accept(Compiler.StackSpiller spiller) { return spiller.Rewrite(this); } internal static Expression<TDelegate> Create(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters) { if (name == null && !tailCall) { switch (parameters.Count) { case 0: return new Expression0<TDelegate>(body); case 1: return new Expression1<TDelegate>(body, parameters[0]); case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]); case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]); default: return new ExpressionN<TDelegate>(body, parameters); } } return new FullExpression<TDelegate>(body, name, tailCall, parameters); } #endif /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile(DebugInfoGenerator debugInfoGenerator) { return Compile(); } } #if !FEATURE_COMPILE // Separate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T> public class ExpressionCreator<TDelegate> { public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { if (name == null && !tailCall) { switch (parameters.Count) { case 0: return new Expression0<TDelegate>(body); case 1: return new Expression1<TDelegate>(body, parameters[0]); case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]); case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]); default: return new ExpressionN<TDelegate>(body, parameters); } } return new FullExpression<TDelegate>(body, name, tailCall, parameters); } } #endif internal sealed class Expression0<TDelegate> : Expression<TDelegate> { public Expression0(Expression body) : base(body) { } internal override int ParameterCount => 0; internal override bool SameParameters(ICollection<ParameterExpression> parameters) => parameters == null || parameters.Count == 0; internal override ParameterExpression GetParameter(int index) { throw Error.ArgumentOutOfRange(nameof(index)); } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => EmptyReadOnlyCollection<ParameterExpression>.Instance; internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 0); return Expression.Lambda<TDelegate>(body, parameters); } } internal sealed class Expression1<TDelegate> : Expression<TDelegate> { private object _par0; public Expression1(Expression body, ParameterExpression par0) : base(body) { _par0 = par0; } internal override int ParameterCount => 1; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 1) { using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); return en.Current == ExpressionUtils.ReturnObject<ParameterExpression>(_par0); } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 1); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0)); } } internal sealed class Expression2<TDelegate> : Expression<TDelegate> { private object _par0; private readonly ParameterExpression _par1; public Expression2(Expression body, ParameterExpression par0, ParameterExpression par1) : base(body) { _par0 = par0; _par1 = par1; } internal override int ParameterCount => 2; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); case 1: return _par1; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 2) { ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(parameters, alreadyCollection); } using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); if (en.Current == _par0) { en.MoveNext(); return en.Current == _par1; } } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 2); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1); } } internal sealed class Expression3<TDelegate> : Expression<TDelegate> { private object _par0; private readonly ParameterExpression _par1; private readonly ParameterExpression _par2; public Expression3(Expression body, ParameterExpression par0, ParameterExpression par1, ParameterExpression par2) : base(body) { _par0 = par0; _par1 = par1; _par2 = par2; } internal override int ParameterCount => 3; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); case 1: return _par1; case 2: return _par2; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 3) { ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(parameters, alreadyCollection); } using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); if (en.Current == _par0) { en.MoveNext(); if (en.Current == _par1) { en.MoveNext(); return en.Current == _par2; } } } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 3); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1, _par2); } } internal class ExpressionN<TDelegate> : Expression<TDelegate> { private IReadOnlyList<ParameterExpression> _parameters; public ExpressionN(Expression body, IReadOnlyList<ParameterExpression> parameters) : base(body) { _parameters = parameters; } internal override int ParameterCount => _parameters.Count; internal override ParameterExpression GetParameter(int index) => _parameters[index]; internal override bool SameParameters(ICollection<ParameterExpression> parameters) => ExpressionUtils.SameElements(parameters, _parameters); internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(ref _parameters); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == _parameters.Count); return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters ?? _parameters); } } internal sealed class FullExpression<TDelegate> : ExpressionN<TDelegate> { public FullExpression(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters) : base(body, parameters) { NameCore = name; TailCallCore = tailCall; } internal override string NameCore { get; } internal override bool TailCallCore { get; } } public partial class Expression { /// <summary> /// Creates an Expression{T} given the delegate type. Caches the /// factory method to speed up repeated creations for the same T. /// </summary> internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { // Get or create a delegate to the public Expression.Lambda<T> // method and call that will be used for creating instances of this // delegate type Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath; CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> factories = s_lambdaFactories; if (factories == null) { s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50); } if (!factories.TryGetValue(delegateType, out fastPath)) { #if FEATURE_COMPILE MethodInfo create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic); #else MethodInfo create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public); #endif if (delegateType.IsCollectible) { return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters }); } factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)); } return fastPath(body, name, tailCall, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, tailCall, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, name, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly(); ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList, nameof(TDelegate)); return (Expression<TDelegate>)CreateLambda(typeof(TDelegate), body, name, tailCall, parameterList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) { return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda(body, name, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(body, nameof(body)); ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly(); int paramCount = parameterList.Count; Type[] typeArgs = new Type[paramCount + 1]; if (paramCount > 0) { var set = new HashSet<ParameterExpression>(); for (int i = 0; i < paramCount; i++) { ParameterExpression param = parameterList[i]; ContractUtils.RequiresNotNull(param, "parameter"); typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type; if (!set.Add(param)) { throw Error.DuplicateVariable(param, nameof(parameters), i); } } } typeArgs[paramCount] = body.Type; Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs); return CreateLambda(delegateType, body, name, tailCall, parameterList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType)); return CreateLambda(delegateType, body, name, false, paramList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType)); return CreateLambda(delegateType, body, name, tailCall, paramList); } private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters, string paramName) { ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); ExpressionUtils.RequiresCanRead(body, nameof(body)); if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) { throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(paramName); } TypeUtils.ValidateType(delegateType, nameof(delegateType), allowByRef: true, allowPointer: true); CacheDict<Type, MethodInfo> ldc = s_lambdaDelegateCache; if (!ldc.TryGetValue(delegateType, out MethodInfo mi)) { mi = delegateType.GetInvokeMethod(); if (!delegateType.IsCollectible) { ldc[delegateType] = mi; } } ParameterInfo[] pis = mi.GetParametersCached(); if (pis.Length > 0) { if (pis.Length != parameters.Count) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } var set = new HashSet<ParameterExpression>(); for (int i = 0, n = pis.Length; i < n; i++) { ParameterExpression pex = parameters[i]; ParameterInfo pi = pis[i]; ExpressionUtils.RequiresCanRead(pex, nameof(parameters), i); Type pType = pi.ParameterType; if (pex.IsByRef) { if (!pType.IsByRef) { //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type. throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType); } pType = pType.GetElementType(); } if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) { throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType); } if (!set.Add(pex)) { throw Error.DuplicateVariable(pex, nameof(parameters), i); } } } else if (parameters.Count > 0) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) { if (!TryQuote(mi.ReturnType, ref body)) { throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType); } } } private enum TryGetFuncActionArgsResult { Valid, ArgumentNull, ByRef, PointerOrVoid } private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[] typeArgs) { if (typeArgs == null) { return TryGetFuncActionArgsResult.ArgumentNull; } for (int i = 0; i < typeArgs.Length; i++) { Type a = typeArgs[i]; if (a == null) { return TryGetFuncActionArgsResult.ArgumentNull; } if (a.IsByRef) { return TryGetFuncActionArgsResult.ByRef; } if (a == typeof(void) || a.IsPointer) { return TryGetFuncActionArgsResult.PointerOrVoid; } } return TryGetFuncActionArgsResult.Valid; } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param> /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns> public static Type GetFuncType(params Type[] typeArgs) { switch (ValidateTryGetFuncActionArgs(typeArgs)) { case TryGetFuncActionArgsResult.ArgumentNull: throw new ArgumentNullException(nameof(typeArgs)); case TryGetFuncActionArgsResult.ByRef: throw Error.TypeMustNotBeByRef(nameof(typeArgs)); default: // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs)); } return result; } } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param> /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null; } funcType = null; return false; } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param> /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns> public static Type GetActionType(params Type[] typeArgs) { switch (ValidateTryGetFuncActionArgs(typeArgs)) { case TryGetFuncActionArgsResult.ArgumentNull: throw new ArgumentNullException(nameof(typeArgs)); case TryGetFuncActionArgsResult.ByRef: throw Error.TypeMustNotBeByRef(nameof(typeArgs)); default: // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetActionType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs)); } return result; } } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param> /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetActionType(Type[] typeArgs, out Type actionType) { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null; } actionType = null; return false; } /// <summary> /// Gets a <see cref="System.Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments. /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom /// delegate type. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments of the delegate type.</param> /// <returns>The delegate type.</returns> /// <remarks> /// As with Func, the last argument is the return type. It can be set /// to <see cref="System.Void"/> to produce an Action.</remarks> public static Type GetDelegateType(params Type[] typeArgs) { ContractUtils.RequiresNotEmpty(typeArgs, nameof(typeArgs)); ContractUtils.RequiresNotNullItems(typeArgs, nameof(typeArgs)); return Compiler.DelegateHelpers.MakeDelegateType(typeArgs); } } }
// *********************************************************************** // Copyright (c) 2012-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal { /// <summary> /// The Test abstract class represents a test within the framework. /// </summary> public abstract class Test : ITest, IComparable { #region Fields /// <summary> /// Static value to seed ids. It's started at 1000 so any /// uninitialized ids will stand out. /// </summary> private static int _nextID = 1000; /// <summary> /// The SetUp methods. /// </summary> protected MethodInfo[] setUpMethods; /// <summary> /// The teardown methods /// </summary> protected MethodInfo[] tearDownMethods; /// <summary> /// Used to cache the declaring type for this MethodInfo /// </summary> protected ITypeInfo DeclaringTypeInfo; /// <summary> /// Method property backing field /// </summary> private IMethodInfo _method; #endregion #region Construction /// <summary> /// Constructs a test given its name /// </summary> /// <param name="name">The name of the test</param> protected Test( string name ) { Guard.ArgumentNotNullOrEmpty(name, "name"); Initialize(name); } /// <summary> /// Constructs a test given the path through the /// test hierarchy to its parent and a name. /// </summary> /// <param name="pathName">The parent tests full name</param> /// <param name="name">The name of the test</param> protected Test( string pathName, string name ) { Guard.ArgumentNotNullOrEmpty(pathName, "pathName"); Initialize(name); FullName = pathName + "." + name; } /// <summary> /// TODO: Documentation needed for constructor /// </summary> /// <param name="typeInfo"></param> protected Test(ITypeInfo typeInfo) { Initialize(typeInfo.GetDisplayName()); string nspace = typeInfo.Namespace; if (nspace != null && nspace != "") FullName = nspace + "." + Name; TypeInfo = typeInfo; } /// <summary> /// Construct a test from a MethodInfo /// </summary> /// <param name="method"></param> protected Test(IMethodInfo method) { Initialize(method.Name); Method = method; TypeInfo = method.TypeInfo; FullName = method.TypeInfo.FullName + "." + Name; } private void Initialize(string name) { FullName = Name = name; Id = GetNextId(); Properties = new PropertyBag(); RunState = RunState.Runnable; } private static string GetNextId() { return IdPrefix + unchecked(_nextID++); } #endregion #region ITest Members /// <summary> /// Gets or sets the id of the test /// </summary> /// <value></value> public string Id { get; set; } /// <summary> /// Gets or sets the name of the test /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the fully qualified name of the test /// </summary> /// <value></value> public string FullName { get; set; } /// <summary> /// Gets the name of the class where this test was declared. /// Returns null if the test is not associated with a class. /// </summary> public string ClassName { get { ITypeInfo typeInfo = TypeInfo; if (Method != null) { if (DeclaringTypeInfo == null) DeclaringTypeInfo = new TypeWrapper(Method.MethodInfo.DeclaringType); typeInfo = DeclaringTypeInfo; } if (typeInfo == null) return null; return typeInfo.IsGenericType ? typeInfo.GetGenericTypeDefinition().FullName : typeInfo.FullName; } } /// <summary> /// Gets the name of the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> public virtual string MethodName { get { return null; } } /// <summary> /// Gets the TypeInfo of the fixture used in running this test /// or null if no fixture type is associated with it. /// </summary> public ITypeInfo TypeInfo { get; private set; } /// <summary> /// Gets a MethodInfo for the method implementing this test. /// Returns null if the test is not implemented as a method. /// </summary> public IMethodInfo Method { get { return _method; } set { DeclaringTypeInfo = null; _method = value; } } // public setter needed by NUnitTestCaseBuilder /// <summary> /// Whether or not the test should be run /// </summary> public RunState RunState { get; set; } /// <summary> /// Gets the name used for the top-level element in the /// XML representation of this test /// </summary> public abstract string XmlElementName { get; } /// <summary> /// Gets a string representing the type of test. Used as an attribute /// value in the XML representation of a test and has no other /// function in the framework. /// </summary> public virtual string TestType { get { return this.GetType().Name; } } /// <summary> /// Gets a count of test cases represented by /// or contained under this test. /// </summary> public virtual int TestCaseCount { get { return 1; } } /// <summary> /// Gets the properties for this test /// </summary> public IPropertyBag Properties { get; private set; } /// <summary> /// Returns true if this is a TestSuite /// </summary> public bool IsSuite { get { return this is TestSuite; } } /// <summary> /// Gets a bool indicating whether the current test /// has any descendant tests. /// </summary> public abstract bool HasChildren { get; } /// <summary> /// Gets the parent as a Test object. /// Used by the core to set the parent. /// </summary> public ITest Parent { get; set; } /// <summary> /// Gets this test's child tests /// </summary> /// <value>A list of child tests</value> public abstract System.Collections.Generic.IList<ITest> Tests { get; } /// <summary> /// Gets or sets a fixture object for running this test. /// </summary> public virtual object Fixture { get; set; } #endregion #region Other Public Properties /// <summary> /// Static prefix used for ids in this AppDomain. /// Set by FrameworkController. /// </summary> public static string IdPrefix { get; set; } /// <summary> /// Gets or Sets the Int value representing the seed for the RandomGenerator /// </summary> /// <value></value> public int Seed { get; set; } #endregion #region Internal Properties internal bool RequiresThread { get; set; } #endregion #region Other Public Methods /// <summary> /// Creates a TestResult for this test. /// </summary> /// <returns>A TestResult suitable for this type of test.</returns> public abstract TestResult MakeTestResult(); #if PORTABLE /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object deriving from MemberInfo</param> public void ApplyAttributesToTest(MemberInfo provider) { foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>(true)) iApply.ApplyToTest(this); } /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object deriving from MemberInfo</param> public void ApplyAttributesToTest(Assembly provider) { foreach (IApplyToTest iApply in provider.GetAttributes<IApplyToTest>()) iApply.ApplyToTest(this); } #else /// <summary> /// Modify a newly constructed test by applying any of NUnit's common /// attributes, based on a supplied ICustomAttributeProvider, which is /// usually the reflection element from which the test was constructed, /// but may not be in some instances. The attributes retrieved are /// saved for use in subsequent operations. /// </summary> /// <param name="provider">An object implementing ICustomAttributeProvider</param> public void ApplyAttributesToTest(ICustomAttributeProvider provider) { foreach (IApplyToTest iApply in provider.GetCustomAttributes(typeof(IApplyToTest), true)) iApply.ApplyToTest(this); } #endif #endregion #region Protected Methods /// <summary> /// Add standard attributes and members to a test node. /// </summary> /// <param name="thisNode"></param> /// <param name="recursive"></param> protected void PopulateTestNode(TNode thisNode, bool recursive) { thisNode.AddAttribute("id", this.Id.ToString()); thisNode.AddAttribute("name", this.Name); thisNode.AddAttribute("fullname", this.FullName); if (this.MethodName != null) thisNode.AddAttribute("methodname", this.MethodName); if (this.ClassName != null) thisNode.AddAttribute("classname", this.ClassName); thisNode.AddAttribute("runstate", this.RunState.ToString()); if (Properties.Keys.Count > 0) Properties.AddToXml(thisNode, recursive); } #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the Xml representation of the test /// </summary> /// <param name="recursive">If true, include child tests recursively</param> /// <returns></returns> public TNode ToXml(bool recursive) { return AddToXml(new TNode("dummy"), recursive); } /// <summary> /// Returns an XmlNode representing the current result after /// adding it as a child of the supplied parent node. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public abstract TNode AddToXml(TNode parentNode, bool recursive); #endregion #region IComparable Members /// <summary> /// Compares this test to another test for sorting purposes /// </summary> /// <param name="obj">The other test</param> /// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns> public int CompareTo(object obj) { Test other = obj as Test; if (other == null) return -1; return this.FullName.CompareTo(other.FullName); } #endregion } }
#region License // Copyright (c) 2007 James Newton-King // // 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 using System; namespace Newtonsoft.Json { /// <summary> /// Instructs the <see cref="JsonSerializer"/> to always serialize the member with the specified name. /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)] public sealed class JsonPropertyAttribute : Attribute { // yuck. can't set nullable properties on an attribute in C# // have to use this approach to get an unset default state internal NullValueHandling? _nullValueHandling; internal DefaultValueHandling? _defaultValueHandling; internal ReferenceLoopHandling? _referenceLoopHandling; internal ObjectCreationHandling? _objectCreationHandling; internal TypeNameHandling? _typeNameHandling; internal bool? _isReference; internal int? _order; internal Required? _required; internal bool? _itemIsReference; internal ReferenceLoopHandling? _itemReferenceLoopHandling; internal TypeNameHandling? _itemTypeNameHandling; internal string _dollarTag; /// <summary> /// Gets or sets the converter used when serializing the property's collection items. /// </summary> /// <value>The collection's items converter.</value> public Type ItemConverterType { get; set; } /// <summary> /// The parameter list to use when constructing the JsonConverter described by ItemConverterType. /// If null, the default constructor is used. /// When non-null, there must be a constructor defined in the JsonConverter that exactly matches the number, /// order, and type of these parameters. /// </summary> /// <example> /// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })] /// </example> public object[] ItemConverterParameters { get; set; } /// <summary> /// Gets or sets the null value handling used when serializing this property. /// </summary> /// <value>The null value handling.</value> public NullValueHandling NullValueHandling { get { return _nullValueHandling ?? default(NullValueHandling); } set { _nullValueHandling = value; } } /// <summary> /// Gets or sets the default value handling used when serializing this property. /// </summary> /// <value>The default value handling.</value> public DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling ?? default(DefaultValueHandling); } set { _defaultValueHandling = value; } } /// <summary> /// Gets or sets the reference loop handling used when serializing this property. /// </summary> /// <value>The reference loop handling.</value> public ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling ?? default(ReferenceLoopHandling); } set { _referenceLoopHandling = value; } } /// <summary> /// Gets or sets the object creation handling used when deserializing this property. /// </summary> /// <value>The object creation handling.</value> public ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling ?? default(ObjectCreationHandling); } set { _objectCreationHandling = value; } } /// <summary> /// Gets or sets the type name handling used when serializing this property. /// </summary> /// <value>The type name handling.</value> public TypeNameHandling TypeNameHandling { get { return _typeNameHandling ?? default(TypeNameHandling); } set { _typeNameHandling = value; } } /// <summary> /// Gets or sets whether this property's value is serialized as a reference. /// </summary> /// <value>Whether this property's value is serialized as a reference.</value> public bool IsReference { get { return _isReference ?? default(bool); } set { _isReference = value; } } /// <summary> /// Gets or sets the order of serialization and deserialization of a member. /// </summary> /// <value>The numeric order of serialization or deserialization.</value> public int Order { get { return _order ?? default(int); } set { _order = value; } } /// <summary> /// Gets or sets a value indicating whether this property is required. /// </summary> /// <value> /// A value indicating whether this property is required. /// </value> public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } /// <summary> /// Gets or sets the name of the property. /// </summary> /// <value>The name of the property.</value> public string PropertyName { get; set; } /// <summary> /// Gets or sets the the reference loop handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items reference loop handling.</value> public ReferenceLoopHandling ItemReferenceLoopHandling { get { return _itemReferenceLoopHandling ?? default(ReferenceLoopHandling); } set { _itemReferenceLoopHandling = value; } } /// <summary> /// Gets or sets the the type name handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items type name handling.</value> public TypeNameHandling ItemTypeNameHandling { get { return _itemTypeNameHandling ?? default(TypeNameHandling); } set { _itemTypeNameHandling = value; } } /// <summary> /// Gets or sets whether this property's collection items are serialized as a reference. /// </summary> /// <value>Whether this property's collection items are serialized as a reference.</value> public bool ItemIsReference { get { return _itemIsReference ?? default(bool); } set { _itemIsReference = value; } } /// <summary> /// DollarTag /// </summary> public string DollarTag { get { return _dollarTag; } set { if (value.Contains("$")) throw new ArgumentException(@"Invalid DollarTag. Can't contain $."); _dollarTag = value; } } /// <summary> /// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class. /// </summary> public JsonPropertyAttribute() { } /// <summary> /// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class with the specified name. /// </summary> /// <param name="propertyName">Name of the property.</param> public JsonPropertyAttribute(string propertyName) { PropertyName = propertyName; } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Common; using Mosa.Compiler.Framework; using Mosa.Compiler.Framework.IR; using Mosa.Compiler.MosaTypeSystem; using System; using System.Diagnostics; namespace Mosa.Platform.x86.Stages { /// <summary> /// Transforms IR instructions into their appropriate X86. /// </summary> /// <remarks> /// This transformation stage transforms IR instructions into their equivalent X86 sequences. /// </remarks> public sealed class IRTransformationStage : BaseTransformationStage, IIRVisitor { private const int LargeAlignment = 16; #region IIRVisitor /// <summary> /// Visitation function for AddSigned. /// </summary> /// <param name="context">Initializeontext.</param> void IIRVisitor.AddSigned(Context context) { context.ReplaceInstructionOnly(X86.Add); } /// <summary> /// Visitation function for AddUnsigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.AddUnsigned(Context context) { context.ReplaceInstructionOnly(X86.Add); } /// <summary> /// Visitation function for AddFloat. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.AddFloat(Context context) { if (context.Result.IsR4) { context.ReplaceInstructionOnly(X86.Addss); context.Size = InstructionSize.Size32; } else { context.ReplaceInstructionOnly(X86.Addsd); context.Size = InstructionSize.Size64; } } /// <summary> /// Visitation function for DivFloat. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.DivFloat(Context context) { if (context.Result.IsR4) { context.ReplaceInstructionOnly(X86.Divss); context.Size = InstructionSize.Size32; } else { context.ReplaceInstructionOnly(X86.Divsd); context.Size = InstructionSize.Size64; } } /// <summary> /// Addresses the of instruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.AddressOf(Context context) { Operand result = context.Result; Operand register = AllocateVirtualRegister(result.Type); context.Result = register; context.ReplaceInstructionOnly(X86.Lea); context.AppendInstruction(X86.Mov, NativeInstructionSize, result, register); } /// <summary> /// Floating point compare instruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.FloatCompare(Context context) { Operand result = context.Result; Operand left = context.Operand1; Operand right = context.Operand2; ConditionCode condition = context.ConditionCode; // normalize condition switch (condition) { case ConditionCode.Equal: break; case ConditionCode.NotEqual: break; case ConditionCode.UnsignedGreaterOrEqual: condition = ConditionCode.GreaterOrEqual; break; case ConditionCode.UnsignedGreaterThan: condition = ConditionCode.GreaterThan; break; case ConditionCode.UnsignedLessOrEqual: condition = ConditionCode.LessOrEqual; break; case ConditionCode.UnsignedLessThan: condition = ConditionCode.LessThan; break; } // TODO - Move the following to its own pre-IR decomposition stage for this instruction // Swap, if necessary, the operands to place register operand first than memory operand // otherwise the memory operand will have to be loaded into a register if ((condition == ConditionCode.Equal || condition == ConditionCode.NotEqual) && left.IsMemoryAddress && !right.IsMemoryAddress) { // swap order of operands to move var t = left; left = right; right = t; } Context before = context.InsertBefore(); // Compare using the smallest precision if (left.IsR4 && right.IsR8) { Operand rop = AllocateVirtualRegister(TypeSystem.BuiltIn.R4); before.SetInstruction(X86.Cvtsd2ss, rop, right); right = rop; } if (left.IsR8 && right.IsR4) { Operand rop = AllocateVirtualRegister(TypeSystem.BuiltIn.R4); before.SetInstruction(X86.Cvtsd2ss, rop, left); left = rop; } X86Instruction instruction = null; InstructionSize size = InstructionSize.None; if (left.IsR4) { instruction = X86.Ucomiss; size = InstructionSize.Size32; } else { instruction = X86.Ucomisd; size = InstructionSize.Size64; } switch (condition) { case ConditionCode.Equal: { // a==b // mov eax, 1 // ucomisd xmm0, xmm1 // jp L3 // jne L3 // ret //L3: // mov eax, 0 var newBlocks = CreateNewBlockContexts(2); Context nextBlock = Split(context); context.SetInstruction(X86.Mov, result, Operand.CreateConstant(TypeSystem, 1)); context.AppendInstruction(instruction, size, null, left, right); context.AppendInstruction(X86.Branch, ConditionCode.Parity, newBlocks[1].Block); context.AppendInstruction(X86.Jmp, newBlocks[0].Block); newBlocks[0].AppendInstruction(X86.Branch, ConditionCode.NotEqual, newBlocks[1].Block); newBlocks[0].AppendInstruction(X86.Jmp, nextBlock.Block); newBlocks[1].AppendInstruction(X86.Mov, result, ConstantZero); newBlocks[1].AppendInstruction(X86.Jmp, nextBlock.Block); break; } case ConditionCode.NotEqual: { // a!=b // mov eax, 1 // ucomisd xmm0, xmm1 // jp L5 // setne al // movzx eax, al //L5: var newBlocks = CreateNewBlockContexts(1); Context nextBlock = Split(context); context.SetInstruction(X86.Mov, result, Operand.CreateConstant(TypeSystem, 1)); context.AppendInstruction(instruction, size, null, left, right); context.AppendInstruction(X86.Branch, ConditionCode.Parity, nextBlock.Block); context.AppendInstruction(X86.Jmp, newBlocks[0].Block); newBlocks[0].AppendInstruction(X86.Setcc, ConditionCode.NotEqual, result); newBlocks[0].AppendInstruction(X86.Movzx, result, result); newBlocks[0].AppendInstruction(X86.Jmp, nextBlock.Block); break; } case ConditionCode.LessThan: { // a<b // mov eax, 0 // ucomisd xmm1, xmm0 // seta al context.SetInstruction(X86.Mov, result, ConstantZero); context.AppendInstruction(instruction, size, null, right, left); context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterThan, result); break; } case ConditionCode.GreaterThan: { // a>b // mov eax, 0 // ucomisd xmm0, xmm1 // seta al context.SetInstruction(X86.Mov, result, ConstantZero); context.AppendInstruction(instruction, size, null, left, right); context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterThan, result); break; } case ConditionCode.LessOrEqual: { // a<=b // mov eax, 0 // ucomisd xmm1, xmm0 // setae al context.SetInstruction(X86.Mov, result, ConstantZero); context.AppendInstruction(instruction, size, null, right, left); context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterOrEqual, result); break; } case ConditionCode.GreaterOrEqual: { // a>=b // mov eax, 0 // ucomisd xmm0, xmm1 // setae al context.SetInstruction(X86.Mov, result, ConstantZero); context.AppendInstruction(instruction, size, null, left, right); context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterOrEqual, result); break; } } } /// <summary> /// Visitation function for IntegerCompareBranchInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.IntegerCompareBranch(Context context) { var target = context.BranchTargets[0]; var condition = context.ConditionCode; var operand1 = context.Operand1; var operand2 = context.Operand2; context.SetInstruction(X86.Cmp, null, operand1, operand2); context.AppendInstruction(X86.Branch, condition, target); } /// <summary> /// Visitation function for IntegerCompareInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.IntegerCompare(Context context) { var condition = context.ConditionCode; var resultOperand = context.Result; var operand1 = context.Operand1; var operand2 = context.Operand2; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); context.SetInstruction(X86.Mov, v1, ConstantZero); context.AppendInstruction(X86.Cmp, null, operand1, operand2); if (resultOperand.IsUnsigned || resultOperand.IsChar) context.AppendInstruction(X86.Setcc, condition.GetUnsigned(), v1); else context.AppendInstruction(X86.Setcc, condition, v1); context.AppendInstruction(X86.Mov, resultOperand, v1); } /// <summary> /// Visitation function for JmpInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Jmp(Context context) { context.ReplaceInstructionOnly(X86.Jmp); } /// <summary> /// Visitation function for LoadInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Load(Context context) { Operand result = context.Result; Operand baseOperand = context.Operand1; Operand offsetOperand = context.Operand2; var type = context.MosaType; var size = context.Size; if (offsetOperand.IsConstant) { Operand mem = Operand.CreateMemoryAddress(baseOperand.Type, baseOperand, offsetOperand.ConstantSignedLongInteger); var mov = GetMove(result, mem); if (result.IsR8 && type.IsR4) // size == InstructionSize.Size32) { mov = X86.Cvtss2sd; } context.SetInstruction(mov, size, result, mem); } else { Operand v1 = AllocateVirtualRegister(baseOperand.Type); Operand mem = Operand.CreateMemoryAddress(v1.Type, v1, 0); context.SetInstruction(X86.Mov, v1, baseOperand); context.AppendInstruction(X86.Add, v1, v1, offsetOperand); var mov = GetMove(result, mem); if (result.IsR8 && type.IsR4) // size == InstructionSize.Size32) { mov = X86.Cvtss2sd; } context.AppendInstruction(mov, size, result, mem); } } void IIRVisitor.CompoundLoad(Context context) { var type = context.Result.Type; int typeSize = TypeLayout.GetTypeSize(type); int alignedTypeSize = typeSize - (typeSize % NativeAlignment); int largeAlignedTypeSize = typeSize - (typeSize % LargeAlignment); Debug.Assert(typeSize > 0, context.Operand2.Name); int offset = 0; if (context.Operand2.IsConstant) { offset = (int)context.Operand2.ConstantSignedLongInteger; } var offsetop = context.Operand2; var src = context.Operand1; var dest = context.Result; Debug.Assert(dest.IsMemoryAddress, dest.Name); var srcReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var dstReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var tmp = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var tmpLarge = Operand.CreateCPURegister(MethodCompiler.TypeSystem.BuiltIn.Void, SSE2Register.XMM1); context.SetInstruction(X86.Nop); context.AppendInstruction(X86.Mov, srcReg, src); context.AppendInstruction(X86.Lea, dstReg, dest); if (!offsetop.IsConstant) { context.AppendInstruction(X86.Add, srcReg, srcReg, offsetop); } for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment) { // Large Aligned moves allow 128bits to be copied at a time var memSrc = Operand.CreateMemoryAddress(MethodCompiler.TypeSystem.BuiltIn.Void, srcReg, i + offset); var memDest = Operand.CreateMemoryAddress(MethodCompiler.TypeSystem.BuiltIn.Void, dstReg, i); context.AppendInstruction(X86.MovAPS, InstructionSize.Size128, tmpLarge, memSrc); context.AppendInstruction(X86.MovAPS, InstructionSize.Size128, memDest, tmpLarge); } for (int i = largeAlignedTypeSize; i < alignedTypeSize; i += NativeAlignment) { context.AppendInstruction(X86.Mov, InstructionSize.Size32, tmp, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, srcReg, i + offset)); context.AppendInstruction(X86.Mov, InstructionSize.Size32, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, dstReg, i), tmp); } for (int i = alignedTypeSize; i < typeSize; i++) { context.AppendInstruction(X86.Mov, InstructionSize.Size8, tmp, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, srcReg, i + offset)); context.AppendInstruction(X86.Mov, InstructionSize.Size8, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, dstReg, i), tmp); } } /// <summary> /// Visitation function for Load Sign Extended. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.LoadSignExtended(Context context) { var destination = context.Result; var source = context.Operand1; var type = context.MosaType; var offset = context.Operand2; var v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); long offsetPtr = 0; context.SetInstruction(X86.Mov, v1, source); if (offset.IsConstant) { offsetPtr = offset.ConstantSignedLongInteger; } else { context.AppendInstruction(X86.Add, v1, v1, offset); } context.AppendInstruction(X86.Movsx, destination, Operand.CreateMemoryAddress(type, v1, offsetPtr)); } /// <summary> /// Visitation function for Load Zero Extended. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.LoadZeroExtended(Context context) { var destination = context.Result; var source = context.Operand1; var offset = context.Operand2; var type = context.MosaType; Debug.Assert(offset != null); Operand v1 = AllocateVirtualRegister(source.Type); long offsetPtr = 0; context.SetInstruction(X86.Mov, v1, source); if (offset.IsConstant) { offsetPtr = offset.ConstantSignedLongInteger; } else { context.AppendInstruction(X86.Add, v1, v1, offset); } context.AppendInstruction(X86.Movzx, destination, Operand.CreateMemoryAddress(type, v1, offsetPtr)); } /// <summary> /// Visitation function for LogicalAndInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.LogicalAnd(Context context) { context.ReplaceInstructionOnly(X86.And); } /// <summary> /// Visitation function for LogicalOrInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.LogicalOr(Context context) { context.ReplaceInstructionOnly(X86.Or); } /// <summary> /// Visitation function for LogicalXorInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.LogicalXor(Context context) { context.ReplaceInstructionOnly(X86.Xor); } /// <summary> /// Visitation function for LogicalNotInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.LogicalNot(Context context) { Operand dest = context.Result; context.SetInstruction(X86.Mov, context.Result, context.Operand1); if (dest.IsByte) context.AppendInstruction(X86.Xor, dest, dest, Operand.CreateConstant(TypeSystem, 0xFF)); else if (dest.IsU2) context.AppendInstruction(X86.Xor, dest, dest, Operand.CreateConstant(TypeSystem, 0xFFFF)); else context.AppendInstruction(X86.Not, dest, dest); } /// <summary> /// Visitation function for MoveInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Move(Context context) { Operand result = context.Result; Operand operand = context.Operand1; X86Instruction instruction = X86.Mov; InstructionSize size = InstructionSize.None; if (result.IsR) { //Debug.Assert(operand.IsFloatingPoint, @"Move can't convert to floating point type."); if (result.Type == operand.Type) { if (result.IsR4) { instruction = X86.Movss; size = InstructionSize.Size32; } else if (result.IsR8) { instruction = X86.Movsd; size = InstructionSize.Size64; } } else if (result.IsR8) { instruction = X86.Cvtss2sd; } else if (result.IsR4) { instruction = X86.Cvtsd2ss; } } context.ReplaceInstructionOnly(instruction); context.Size = size; } void IIRVisitor.CompoundMove(Context context) { var type = context.Result.Type; int typeSize = TypeLayout.GetTypeSize(type); int alignedTypeSize = typeSize - (typeSize % NativeAlignment); int largeAlignedTypeSize = typeSize - (typeSize % LargeAlignment); Debug.Assert(typeSize > 0, MethodCompiler.Method.FullName); var src = context.Operand1; var dest = context.Result; Debug.Assert((src.IsMemoryAddress || src.IsSymbol) && dest.IsMemoryAddress, context.ToString()); var srcReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var dstReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var tmp = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var tmpLarge = Operand.CreateCPURegister(MethodCompiler.TypeSystem.BuiltIn.Void, SSE2Register.XMM1); context.SetInstruction(X86.Nop); if (src.IsSymbol) { context.AppendInstruction(X86.Mov, srcReg, src); } else { context.AppendInstruction(X86.Lea, srcReg, src); } context.AppendInstruction(X86.Lea, dstReg, dest); for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment) { // Large Aligned moves allow 128bits to be copied at a time var memSrc = Operand.CreateMemoryAddress(MethodCompiler.TypeSystem.BuiltIn.Void, srcReg, i); var memDest = Operand.CreateMemoryAddress(MethodCompiler.TypeSystem.BuiltIn.Void, dstReg, i); context.AppendInstruction(X86.MovAPS, InstructionSize.Size128, tmpLarge, memSrc); context.AppendInstruction(X86.MovAPS, InstructionSize.Size128, memDest, tmpLarge); } for (int i = largeAlignedTypeSize; i < alignedTypeSize; i += NativeAlignment) { context.AppendInstruction(X86.Mov, InstructionSize.Size32, tmp, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, srcReg, i)); context.AppendInstruction(X86.Mov, InstructionSize.Size32, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, dstReg, i), tmp); } for (int i = alignedTypeSize; i < typeSize; i++) { context.AppendInstruction(X86.Mov, InstructionSize.Size8, tmp, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, srcReg, i)); context.AppendInstruction(X86.Mov, InstructionSize.Size8, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, dstReg, i), tmp); } } /// <summary> /// Visitation function for Return. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Return(Context context) { //Debug.Assert(context.BranchTargets != null); if (context.Operand1 != null) { var returnOperand = context.Operand1; context.Empty(); CallingConvention.SetReturnValue(MethodCompiler, TypeLayout, context, returnOperand); context.AppendInstruction(X86.Jmp, BasicBlocks.EpilogueBlock); } else { context.SetInstruction(X86.Jmp, BasicBlocks.EpilogueBlock); } } /// <summary> /// Visitation function for InternalCall. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.InternalCall(Context context) { context.ReplaceInstructionOnly(X86.Call); } /// <summary> /// Visitation function for InternalReturn. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.InternalReturn(Context context) { Debug.Assert(context.BranchTargets == null); // To return from an internal method call (usually from within a finally or exception clause) context.SetInstruction(X86.Ret); } /// <summary> /// Arithmetic the shift right instruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.ArithmeticShiftRight(Context context) { context.ReplaceInstructionOnly(X86.Sar); } /// <summary> /// Visitation function for ShiftLeftInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.ShiftLeft(Context context) { context.ReplaceInstructionOnly(X86.Shl); } /// <summary> /// Visitation function for ShiftRightInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.ShiftRight(Context context) { context.ReplaceInstructionOnly(X86.Shr); } /// <summary> /// Visitation function for StoreInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Store(Context context) { Operand baseOperand = context.Operand1; Operand offsetOperand = context.Operand2; Operand value = context.Operand3; MosaType storeType = context.MosaType; var type = baseOperand.Type; var size = context.Size; if (value.IsR8 && type.IsR4) //&& size == InstructionSize.Size32) { Operand xmm1 = AllocateVirtualRegister(TypeSystem.BuiltIn.R4); context.InsertBefore().AppendInstruction(X86.Cvtsd2ss, size, xmm1, value); value = xmm1; } else if (value.IsMemoryAddress) { Operand v2 = AllocateVirtualRegister(value.Type); context.InsertBefore().AppendInstruction(X86.Mov, size, v2, value); value = v2; } if (offsetOperand.IsConstant) { if (baseOperand.IsField) { Debug.Assert(offsetOperand.IsConstantZero); Debug.Assert(baseOperand.Field.IsStatic); context.SetInstruction(GetMove(baseOperand, value), size, baseOperand, value); } else { var mem = Operand.CreateMemoryAddress(storeType, baseOperand, offsetOperand.ConstantSignedLongInteger); context.SetInstruction(GetMove(mem, value), size, mem, value); } } else { if (type.IsUnmanagedPointer) type = storeType.ToUnmanagedPointer(); else if (type.IsManagedPointer) type = storeType.ToManagedPointer(); Operand v1 = AllocateVirtualRegister(type); Operand mem = Operand.CreateMemoryAddress(storeType, v1, 0); context.SetInstruction(X86.Mov, v1, baseOperand); context.AppendInstruction(X86.Add, v1, v1, offsetOperand); context.AppendInstruction(GetMove(mem, value), size, mem, value); } } void IIRVisitor.CompoundStore(Context context) { var type = context.Operand3.Type; int typeSize = TypeLayout.GetTypeSize(type); int alignedTypeSize = typeSize - (typeSize % NativeAlignment); int largeAlignedTypeSize = typeSize - (typeSize % LargeAlignment); Debug.Assert(typeSize > 0, MethodCompiler.Method.FullName); int offset = 0; if (context.Operand2.IsConstant) { offset = (int)context.Operand2.ConstantSignedLongInteger; } var offsetop = context.Operand2; var src = context.Operand3; var dest = context.Operand1; Debug.Assert(src.IsMemoryAddress); var srcReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var dstReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var tmp = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4); var tmpLarge = Operand.CreateCPURegister(MethodCompiler.TypeSystem.BuiltIn.Void, SSE2Register.XMM1); context.SetInstruction(X86.Nop); context.AppendInstruction(X86.Lea, srcReg, src); context.AppendInstruction(X86.Mov, dstReg, dest); if (!offsetop.IsConstant) { context.AppendInstruction(X86.Add, dstReg, dstReg, offsetop); } for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment) { // Large Aligned moves allow 128bits to be copied at a time var memSrc = Operand.CreateMemoryAddress(MethodCompiler.TypeSystem.BuiltIn.Void, srcReg, i); var memDest = Operand.CreateMemoryAddress(MethodCompiler.TypeSystem.BuiltIn.Void, dstReg, i + offset); context.AppendInstruction(X86.MovAPS, InstructionSize.Size128, tmpLarge, memSrc); context.AppendInstruction(X86.MovAPS, InstructionSize.Size128, memDest, tmpLarge); } for (int i = largeAlignedTypeSize; i < alignedTypeSize; i += NativeAlignment) { context.AppendInstruction(X86.Mov, InstructionSize.Size32, tmp, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, srcReg, i)); context.AppendInstruction(X86.Mov, InstructionSize.Size32, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, dstReg, i + offset), tmp); } for (int i = alignedTypeSize; i < typeSize; i++) { context.AppendInstruction(X86.Mov, InstructionSize.Size8, tmp, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, srcReg, i)); context.AppendInstruction(X86.Mov, InstructionSize.Size8, Operand.CreateMemoryAddress(TypeSystem.BuiltIn.I4, dstReg, i + offset), tmp); } } /// <summary> /// Visitation function for MulFloat. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.MulFloat(Context context) { if (context.Result.IsR4) { context.ReplaceInstructionOnly(X86.Mulss); context.Size = InstructionSize.Size32; } else { context.ReplaceInstructionOnly(X86.Mulsd); context.Size = InstructionSize.Size64; } } /// <summary> /// Visitation function for SubFloat. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.SubFloat(Context context) { if (context.Result.IsR4) { context.ReplaceInstructionOnly(X86.Subss); context.Size = InstructionSize.Size32; } else { context.ReplaceInstructionOnly(X86.Subsd); context.Size = InstructionSize.Size64; } } /// <summary> /// Visitation function for SubSigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.SubSigned(Context context) { context.ReplaceInstructionOnly(X86.Sub); } /// <summary> /// Visitation function for SubUnsigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.SubUnsigned(Context context) { context.ReplaceInstructionOnly(X86.Sub); } /// <summary> /// Visitation function for MulSigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.MulSigned(Context context) { Operand result = context.Result; Operand operand1 = context.Operand1; Operand operand2 = context.Operand2; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); context.SetInstruction2(X86.Mul, v1, result, operand1, operand2); } /// <summary> /// Visitation function for MulUnsigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.MulUnsigned(Context context) { Operand result = context.Result; Operand operand1 = context.Operand1; Operand operand2 = context.Operand2; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); context.SetInstruction2(X86.Mul, v1, result, operand1, operand2); } /// <summary> /// Visitation function for DivSigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.DivSigned(Context context) { Operand operand1 = context.Operand1; Operand operand2 = context.Operand2; Operand result = context.Result; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); Operand v3 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); context.SetInstruction2(X86.Cdq, v1, v2, operand1); context.AppendInstruction2(X86.IDiv, v3, result, v1, v2, operand2); } /// <summary> /// Visitation function for DivUnsigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.DivUnsigned(Context context) { Operand operand1 = context.Operand1; Operand operand2 = context.Operand2; Operand result = context.Result; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); context.SetInstruction(X86.Mov, v1, ConstantZero); context.AppendInstruction2(X86.Div, v1, v2, v1, operand1, operand2); context.AppendInstruction(X86.Mov, result, v2); } /// <summary> /// Visitation function for RemSigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.RemSigned(Context context) { Operand result = context.Result; Operand operand1 = context.Operand1; Operand operand2 = context.Operand2; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); Operand v3 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4); context.SetInstruction2(X86.Cdq, v1, v2, operand1); context.AppendInstruction2(X86.IDiv, result, v3, v1, v2, operand2); } /// <summary> /// Visitation function for RemUnsigned. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.RemUnsigned(Context context) { Operand result = context.Result; Operand operand1 = context.Operand1; Operand operand2 = context.Operand2; Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4); context.SetInstruction(X86.Mov, v1, ConstantZero); context.AppendInstruction2(X86.Div, v1, v2, v1, operand1, operand2); context.AppendInstruction(X86.Mov, result, v1); } /// <summary> /// Visitation function for RemFloat. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.RemFloat(Context context) { var result = context.Result; var dividend = context.Operand1; var divisor = context.Operand2; var method = (result.IsR8) ? "RemR8" : "RemR4"; var type = TypeSystem.GetTypeByName("Mosa.Platform.Internal.x86", "Division"); Debug.Assert(type != null, "Cannot find type: Mosa.Platform.Internal.x86.Division type"); var mosaMethod = type.FindMethodByName(method); Debug.Assert(method != null, "Cannot find method: " + method); context.ReplaceInstructionOnly(IRInstruction.Call); context.SetOperand(0, Operand.CreateSymbolFromMethod(TypeSystem, mosaMethod)); context.Result = result; context.Operand2 = dividend; context.Operand3 = divisor; context.OperandCount = 3; context.ResultCount = 1; context.InvokeMethod = mosaMethod; // Since we are already in IR Transformation Stage we gotta call this now CallingConvention.MakeCall(MethodCompiler, TypeLayout, context); } /// <summary> /// Visitation function for SwitchInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Switch(Context context) { var targets = context.BranchTargets; Operand operand = context.Operand1; context.Empty(); for (int i = 0; i < targets.Count - 1; ++i) { context.AppendInstruction(X86.Cmp, null, operand, Operand.CreateConstant(TypeSystem, i)); context.AppendInstruction(X86.Branch, ConditionCode.Equal, targets[i]); } } /// <summary> /// Visitation function for BreakInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Break(Context context) { context.SetInstruction(X86.Break); } /// <summary> /// Visitation function for NopInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Nop(Context context) { context.SetInstruction(X86.Nop); } /// <summary> /// Visitation function for SignExtendedMoveInstruction instructions. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.SignExtendedMove(Context context) { context.ReplaceInstructionOnly(X86.Movsx); } /// <summary> /// Visitation function for Call. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Call(Context context) { if (context.OperandCount == 0 && context.BranchTargets != null) { // inter-method call; usually for exception processing context.ReplaceInstructionOnly(X86.Call); } else { CallingConvention.MakeCall(MethodCompiler, TypeLayout, context); } } /// <summary> /// Visitation function for ZeroExtendedMoveInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.ZeroExtendedMove(Context context) { context.ReplaceInstructionOnly(X86.Movzx); } /// <summary> /// Visitation function for FloatingPointToIntegerConversionInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.FloatToIntegerConversion(Context context) { Operand source = context.Operand1; Operand destination = context.Result; if (destination.Type.IsI1 || destination.Type.IsI2 || destination.Type.IsI4) { if (source.IsR8) context.ReplaceInstructionOnly(X86.Cvttsd2si); else context.ReplaceInstructionOnly(X86.Cvttss2si); } else { throw new NotImplementCompilerException(); } } /// <summary> /// Visitation function for ThrowInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Throw(Context context) { throw new InvalidCompilerException("Throw instruction should have been processed by ExceptionStage."); } /// <summary> /// Visitation function for IntegerToFloatingPointConversion. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.IntegerToFloatConversion(Context context) { if (context.Result.IsR4) context.ReplaceInstructionOnly(X86.Cvtsi2ss); else if (context.Result.IsR8) context.ReplaceInstructionOnly(X86.Cvtsi2sd); else throw new NotSupportedException(); } ///// <summary> ///// Visitation function for StackLoad. ///// </summary> ///// <param name="context">The context.</param> //void IIRVisitor.StackLoad(Context context) //{ //} ///// <summary> ///// Visitation function for StackStore. ///// </summary> ///// <param name="context">The context.</param> //void IIRVisitor.StackStore(Context context) //{ //} ///// <summary> ///// Visitation function for ParamLoad. ///// </summary> ///// <param name="context">The context.</param> //void IIRVisitor.ParamLoad(Context context) //{ //} ///// <summary> ///// Visitation function for ParamStore. ///// </summary> ///// <param name="context">The context.</param> //void IIRVisitor.ParamStore(Context context) //{ //} #endregion IIRVisitor #region IIRVisitor - Unused /// <summary> /// Visitation function for PrologueInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Prologue(Context context) { } /// <summary> /// Visitation function for EpilogueInstruction. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Epilogue(Context context) { } /// <summary> /// Visitation function for PhiInstruction"/> instructions. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Phi(Context context) { } /// <summary> /// Visitation function for intrinsic the method call. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.IntrinsicMethodCall(Context context) { } /// <summary> /// Visitation function for TryStart. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.TryStart(Context context) { } /// <summary> /// Visitation function for FinallyStart. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.FinallyStart(Context context) { } /// <summary> /// Visitation function for ExceptionStart. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.ExceptionStart(Context context) { } /// <summary> /// Visitation function for TryEnd. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.TryEnd(Context context) { } /// <summary> /// Visitation function for ExceptionEnd. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.ExceptionEnd(Context context) { } /// <summary> /// Visitation function for FinallyEnd. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.FinallyEnd(Context context) { } /// <summary> /// Visitation function for CallFinally. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.CallFinally(Context context) { } /// <summary> /// Visitation function for FinallyReturn. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.FinallyReturn(Context context) { } /// <summary> /// Visitation function for FinallyReturn. /// </summary> /// <param name="context">The context.</param> void IIRVisitor.Flow(Context context) { } #endregion IIRVisitor - Unused } }
using Signum.Entities.Workflow; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.Authorization; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Signum.Engine.Authorization; using Signum.Entities.Dynamic; using System.Text.RegularExpressions; using Signum.Entities.Reflection; using Signum.Engine.Basics; using Signum.Engine; using Signum.Engine.UserAssets; using Signum.Entities.Basics; namespace Signum.Engine.Workflow { public static class WorkflowLogic { public static Action<ICaseMainEntity, WorkflowTransitionContext>? OnTransition; public static ResetLazy<Dictionary<Lite<WorkflowEntity>, WorkflowEntity>> Workflows = null!; [AutoExpressionField] public static bool HasExpired(this WorkflowEntity w) => As.Expression(() => w.ExpirationDate.HasValue && w.ExpirationDate.Value < TimeZoneManager.Now); [AutoExpressionField] public static IQueryable<WorkflowPoolEntity> WorkflowPools(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowPoolEntity>().Where(a => a.Workflow == e)); [AutoExpressionField] public static IQueryable<WorkflowActivityEntity> WorkflowActivities(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowActivityEntity>().Where(a => a.Lane.Pool.Workflow == e)); public static IEnumerable<WorkflowActivityEntity> WorkflowActivitiesFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowActivityEntity>(); } [AutoExpressionField] public static IQueryable<WorkflowEventEntity> WorkflowEvents(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowEventEntity>().Where(a => a.Lane.Pool.Workflow == e)); [AutoExpressionField] public static WorkflowEventEntity? WorkflowStartEvent(this WorkflowEntity e) => As.Expression(() => e.WorkflowEvents().Where(we => we.Type == WorkflowEventType.Start).SingleOrDefault()); public static IEnumerable<WorkflowEventEntity> WorkflowEventsFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowEventEntity>(); } [AutoExpressionField] public static IQueryable<WorkflowGatewayEntity> WorkflowGateways(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowGatewayEntity>().Where(a => a.Lane.Pool.Workflow == e)); public static IEnumerable<WorkflowGatewayEntity> WorkflowGatewaysFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.OfType<WorkflowGatewayEntity>(); } [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> WorkflowConnections(this WorkflowEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool.Workflow == e && a.To.Lane.Pool.Workflow == e)); public static IEnumerable<WorkflowConnectionEntity> WorkflowConnectionsFromCache(this WorkflowEntity e) { return GetWorkflowNodeGraph(e.ToLite()).NextGraph.EdgesWithValue.SelectMany(edge => edge.Value); } [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> WorkflowMessageConnections(this WorkflowEntity e) => As.Expression(() => e.WorkflowConnections().Where(a => a.From.Lane.Pool != a.To.Lane.Pool)); [AutoExpressionField] public static IQueryable<WorkflowLaneEntity> WorkflowLanes(this WorkflowPoolEntity e) => As.Expression(() => Database.Query<WorkflowLaneEntity>().Where(a => a.Pool == e)); [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> WorkflowConnections(this WorkflowPoolEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From.Lane.Pool == e && a.To.Lane.Pool == e)); [AutoExpressionField] public static IQueryable<WorkflowGatewayEntity> WorkflowGateways(this WorkflowLaneEntity e) => As.Expression(() => Database.Query<WorkflowGatewayEntity>().Where(a => a.Lane == e)); [AutoExpressionField] public static IQueryable<WorkflowEventEntity> WorkflowEvents(this WorkflowLaneEntity e) => As.Expression(() => Database.Query<WorkflowEventEntity>().Where(a => a.Lane == e)); [AutoExpressionField] public static IQueryable<WorkflowActivityEntity> WorkflowActivities(this WorkflowLaneEntity e) => As.Expression(() => Database.Query<WorkflowActivityEntity>().Where(a => a.Lane == e)); [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> NextConnections(this IWorkflowNodeEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.From == e)); [AutoExpressionField] public static WorkflowEntity Workflow(this CaseActivityEntity ca) => As.Expression(() => ca.Case.Workflow); public static IEnumerable<WorkflowConnectionEntity> NextConnectionsFromCache(this IWorkflowNodeEntity e, ConnectionType? type) { var result = GetWorkflowNodeGraph(e.Lane.Pool.Workflow.ToLite()).NextConnections(e); if (type == null) return result; return result.Where(a => a.Type == type); } [AutoExpressionField] public static IQueryable<WorkflowConnectionEntity> PreviousConnections(this IWorkflowNodeEntity e) => As.Expression(() => Database.Query<WorkflowConnectionEntity>().Where(a => a.To == e)); public static IEnumerable<WorkflowConnectionEntity> PreviousConnectionsFromCache(this IWorkflowNodeEntity e) { return GetWorkflowNodeGraph(e.Lane.Pool.Workflow.ToLite()).PreviousConnections(e); } public static ResetLazy<Dictionary<Lite<WorkflowEntity>, WorkflowNodeGraph>> WorkflowGraphLazy = null!; public static List<Lite<IWorkflowNodeEntity>> AutocompleteNodes(Lite<WorkflowEntity> workflow, string subString, int count, List<Lite<IWorkflowNodeEntity>> excludes) { return WorkflowGraphLazy.Value.GetOrThrow(workflow).Autocomplete(subString, count, excludes); } public static WorkflowNodeGraph GetWorkflowNodeGraph(Lite<WorkflowEntity> workflow) { var graph = WorkflowGraphLazy.Value.GetOrThrow(workflow); if (graph.TrackId != null) return graph; lock (graph) { if (graph.TrackId != null) return graph; var issues = new List<WorkflowIssue>(); graph.Validate(issues, (g, newDirection) => { throw new InvalidOperationException($"Unexpected direction of gateway '{g}' (Should be '{newDirection.NiceToString()}'). Consider saving Workflow '{workflow}'."); }); var errors = issues.Where(a => a.Type == WorkflowIssueType.Error); if (errors.HasItems()) throw new ApplicationException("Errors in Workflow '" + workflow + "':\r\n" + errors.ToString("\r\n").Indent(4)); return graph; } } static Func<WorkflowConfigurationEmbedded> getConfiguration = null!; public static WorkflowConfigurationEmbedded Configuration { get { return getConfiguration(); } } static Regex CurrentIsRegex = new Regex($@"{nameof(WorkflowActivityInfo)}\s*\.\s*{nameof(WorkflowActivityInfo.Current)}\s*\.\s*{nameof(WorkflowActivityInfo.Is)}\s*\(\s*""(?<workflowName>[^""]*)""\s*,\s*""(?<activityName>[^""]*)""\s*\)"); internal static List<CustomCompilerError> GetCustomErrors(string code) { var matches = CurrentIsRegex.Matches(code).Cast<Match>().ToList(); return matches.Select(m => { var workflowName = m.Groups["workflowName"].Value; var wa = WorkflowLogic.WorkflowGraphLazy.Value.Values.SingleOrDefault(w => w.Workflow.Name == workflowName); if (wa == null) return CreateCompilerError(code, m, $"No workflow with Name '{workflowName}' found."); var activityName = m.Groups["activityName"].Value; if (!wa.Activities.Values.Any(a => a.Name == activityName)) return CreateCompilerError(code, m, $"No activity with Name '{activityName}' found in workflow '{workflowName}'."); return null; }).NotNull().ToList(); } private static CustomCompilerError CreateCompilerError(string code, Match m, string errorText) { int index = 0; int line = 1; while (true) { var newIndex = code.IndexOf('\n', index + 1); if (newIndex >= m.Index || newIndex == -1) return new CustomCompilerError { ErrorText = errorText, Line = line }; index = newIndex; line++; } } public static void Start(SchemaBuilder sb, Func<WorkflowConfigurationEmbedded> getConfiguration) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewWorkflowPanel); PermissionAuthLogic.RegisterPermissions(WorkflowPermission.ViewCaseFlow); WorkflowLogic.getConfiguration = getConfiguration; UserAssetsImporter.Register<WorkflowEntity>("Workflow", WorkflowOperation.Save); UserAssetsImporter.Register<WorkflowScriptEntity>("WorkflowScript", WorkflowScriptOperation.Save); UserAssetsImporter.Register<WorkflowTimerConditionEntity>("WorkflowTimerCondition", WorkflowTimerConditionOperation.Save); UserAssetsImporter.Register<WorkflowConditionEntity>("WorkflowCondition", WorkflowConditionOperation.Save); UserAssetsImporter.Register<WorkflowActionEntity>("WorkflowAction", WorkflowActionOperation.Save); sb.Include<WorkflowEntity>() .WithConstruct(WorkflowOperation.Create) .WithQuery(() => DynamicQueryCore.Auto( from e in Database.Query<WorkflowEntity>() select new { Entity = e, e.Id, e.Name, e.MainEntityType, HasExpired = e.HasExpired(), e.ExpirationDate, }) .ColumnDisplayName(a => a.HasExpired, () => WorkflowMessage.HasExpired.NiceToString())) .WithExpressionFrom((CaseActivityEntity ca) => ca.Workflow()); WorkflowGraph.Register(); QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.WorkflowStartEvent()); QueryLogic.Expressions.Register((WorkflowEntity wf) => wf.HasExpired(), () => WorkflowMessage.HasExpired.NiceToString()); sb.AddIndex((WorkflowEntity wf) => wf.ExpirationDate); DynamicCode.GetCustomErrors += GetCustomErrors; Workflows = sb.GlobalLazy(() => Database.Query<WorkflowEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowEntity))); sb.Include<WorkflowPoolEntity>() .WithUniqueIndex(wp => new { wp.Workflow, wp.Name }) .WithSave(WorkflowPoolOperation.Save) .WithDelete(WorkflowPoolOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowPools()) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.Workflow, }); sb.Include<WorkflowLaneEntity>() .WithUniqueIndex(wp => new { wp.Pool, wp.Name }) .WithSave(WorkflowLaneOperation.Save) .WithDelete(WorkflowLaneOperation.Delete) .WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowLanes()) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.Pool, e.Pool.Workflow, }); sb.Include<WorkflowActivityEntity>() .WithUniqueIndex(w => new { w.Lane, w.Name }) .WithSave(WorkflowActivityOperation.Save) .WithDelete(WorkflowActivityOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowActivities()) .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowActivities()) .WithVirtualMList(wa => wa.BoundaryTimers, e => e.BoundaryOf, WorkflowEventOperation.Save, WorkflowEventOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.Comments, e.Lane, e.Lane.Pool.Workflow, }); sb.Include<WorkflowEventEntity>() .WithExpressionFrom((WorkflowEntity p) => p.WorkflowEvents()) .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowEvents()) .WithQuery(() => e => new { Entity = e, e.Id, e.Type, e.Name, e.BpmnElementId, e.Lane, e.Lane.Pool.Workflow, }); new Graph<WorkflowEventEntity>.Execute(WorkflowEventOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (e.Timer == null && e.Type.IsTimer()) throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); if (e.Timer != null && !e.Type.IsTimer()) throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.Timer), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); if (e.BoundaryOf == null && e.Type.IsBoundaryTimer()) throw new InvalidOperationException(ValidationMessage._0IsMandatoryWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); if (e.BoundaryOf != null && !e.Type.IsBoundaryTimer()) throw new InvalidOperationException(ValidationMessage._0ShouldBeNullWhen1IsSetTo2.NiceToString(e.NicePropertyName(a => a.BoundaryOf), e.NicePropertyName(a => a.Type), e.Type.NiceToString())); e.Save(); }, }.Register(); new Graph<WorkflowEventEntity>.Delete(WorkflowEventOperation.Delete) { Delete = (e, _) => { if (e.Type.IsScheduledStart()) { var scheduled = e.ScheduledTask(); if (scheduled != null) WorkflowEventTaskLogic.DeleteWorkflowEventScheduledTask(scheduled); } e.Delete(); }, }.Register(); sb.Include<WorkflowGatewayEntity>() .WithSave(WorkflowGatewayOperation.Save) .WithDelete(WorkflowGatewayOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowGateways()) .WithExpressionFrom((WorkflowLaneEntity p) => p.WorkflowGateways()) .WithQuery(() => e => new { Entity = e, e.Id, e.Type, e.Name, e.BpmnElementId, e.Lane, e.Lane.Pool.Workflow, }); sb.Include<WorkflowConnectionEntity>() .WithSave(WorkflowConnectionOperation.Save) .WithDelete(WorkflowConnectionOperation.Delete) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowConnections()) .WithExpressionFrom((WorkflowEntity p) => p.WorkflowMessageConnections(), null!) .WithExpressionFrom((WorkflowPoolEntity p) => p.WorkflowConnections()) .WithExpressionFrom((IWorkflowNodeEntity p) => p.NextConnections(), null!) .WithExpressionFrom((IWorkflowNodeEntity p) => p.PreviousConnections(), null!) .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.BpmnElementId, e.From, e.To, }); WorkflowEventTaskEntity.GetWorkflowEntity = lite => WorkflowGraphLazy.Value.GetOrThrow(lite).Workflow; WorkflowGraphLazy = sb.GlobalLazy(() => { using (new EntityCache()) { var events = Database.RetrieveAll<WorkflowEventEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite()); var gateways = Database.RetrieveAll<WorkflowGatewayEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite()); var activities = Database.RetrieveAll<WorkflowActivityEntity>().GroupToDictionary(a => a.Lane.Pool.Workflow.ToLite()); var connections = Database.RetrieveAll<WorkflowConnectionEntity>().GroupToDictionary(a => a.From.Lane.Pool.Workflow.ToLite()); var result = Database.RetrieveAll<WorkflowEntity>().ToDictionary(workflow => workflow.ToLite(), workflow => { var w = workflow.ToLite(); var nodeGraph = new WorkflowNodeGraph { Workflow = workflow, Events = events.TryGetC(w).EmptyIfNull().ToDictionary(e => e.ToLite()), Gateways = gateways.TryGetC(w).EmptyIfNull().ToDictionary(g => g.ToLite()), Activities = activities.TryGetC(w).EmptyIfNull().ToDictionary(a => a.ToLite()), Connections = connections.TryGetC(w).EmptyIfNull().ToDictionary(c => c.ToLite()), }; nodeGraph.FillGraphs(); return nodeGraph; }); return result; } }, new InvalidateWith(typeof(WorkflowConnectionEntity))); WorkflowGraphLazy.OnReset += (e, args) => DynamicCode.OnInvalidated?.Invoke(); Validator.PropertyValidator((WorkflowConnectionEntity c) => c.Condition).StaticPropertyValidation = (e, pi) => { if (e.Condition != null && e.From != null) { var conditionType = (e.Condition.EntityOrNull ?? Conditions.Value.GetOrThrow(e.Condition)).MainEntityType; var workflowType = e.From.Lane.Pool.Workflow.MainEntityType; if (!conditionType.Is(workflowType)) return WorkflowMessage.Condition0IsDefinedFor1Not2.NiceToString(conditionType, workflowType); } return null; }; StartWorkflowConditions(sb); StartWorkflowTimerConditions(sb); StartWorkflowActions(sb); StartWorkflowScript(sb); } } public static ResetLazy<Dictionary<Lite<WorkflowTimerConditionEntity>, WorkflowTimerConditionEntity>> TimerConditions = null!; public static WorkflowTimerConditionEntity RetrieveFromCache(this Lite<WorkflowTimerConditionEntity> wc) => TimerConditions.Value.GetOrThrow(wc); private static void StartWorkflowTimerConditions(SchemaBuilder sb) { sb.Include<WorkflowTimerConditionEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainEntityType, e.Eval.Script }); new Graph<WorkflowTimerConditionEntity>.Execute(WorkflowTimerConditionOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowEventEntity>().Where(a => a.Timer!.Condition == e.ToLite()), e, WorkflowTimerConditionOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowTimerConditionEntity>.Delete(WorkflowTimerConditionOperation.Delete) { Delete = (e, _) => { ThrowConnectionError(Database.Query<WorkflowEventEntity>().Where(a => a.Timer!.Condition == e.ToLite()), e, WorkflowTimerConditionOperation.Delete); e.Delete(); }, }.Register(); new Graph<WorkflowTimerConditionEntity>.ConstructFrom<WorkflowTimerConditionEntity>(WorkflowTimerConditionOperation.Clone) { Construct = (e, args) => { return new WorkflowTimerConditionEntity { MainEntityType = e.MainEntityType, Eval = new WorkflowTimerConditionEval { Script = e.Eval.Script } }; }, }.Register(); TimerConditions = sb.GlobalLazy(() => Database.Query<WorkflowTimerConditionEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowTimerConditionEntity))); } public static ResetLazy<Dictionary<Lite<WorkflowActionEntity>, WorkflowActionEntity>> Actions = null!; public static WorkflowActionEntity RetrieveFromCache(this Lite<WorkflowActionEntity> wa) => Actions.Value.GetOrThrow(wa); private static void StartWorkflowActions(SchemaBuilder sb) { sb.Include<WorkflowActionEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainEntityType, e.Eval.Script }); new Graph<WorkflowActionEntity>.Execute(WorkflowActionOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Action == e.ToLite()), e, WorkflowActionOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowActionEntity>.Delete(WorkflowActionOperation.Delete) { Delete = (e, _) => { ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Action == e.ToLite()), e, WorkflowActionOperation.Delete); e.Delete(); }, }.Register(); new Graph<WorkflowActionEntity>.ConstructFrom<WorkflowActionEntity>(WorkflowActionOperation.Clone) { Construct = (e, args) => { return new WorkflowActionEntity { MainEntityType = e.MainEntityType, Eval = new WorkflowActionEval { Script = e.Eval.Script } }; }, }.Register(); Actions = sb.GlobalLazy(() => Database.Query<WorkflowActionEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowActionEntity))); } public static ResetLazy<Dictionary<Lite<WorkflowConditionEntity>, WorkflowConditionEntity>> Conditions = null!; public static WorkflowConditionEntity RetrieveFromCache(this Lite<WorkflowConditionEntity> wc) => Conditions.Value.GetOrThrow(wc); private static void StartWorkflowConditions(SchemaBuilder sb) { sb.Include<WorkflowConditionEntity>() .WithQuery(() => e => new { Entity = e, e.Id, e.Name, e.MainEntityType, e.Eval.Script }); new Graph<WorkflowConditionEntity>.Execute(WorkflowConditionOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Condition == e.ToLite()), e, WorkflowConditionOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowConditionEntity>.Delete(WorkflowConditionOperation.Delete) { Delete = (e, _) => { ThrowConnectionError(Database.Query<WorkflowConnectionEntity>().Where(a => a.Condition == e.ToLite()), e, WorkflowConditionOperation.Delete); e.Delete(); }, }.Register(); new Graph<WorkflowConditionEntity>.ConstructFrom<WorkflowConditionEntity>(WorkflowConditionOperation.Clone) { Construct = (e, args) => { return new WorkflowConditionEntity { MainEntityType = e.MainEntityType, Eval = new WorkflowConditionEval { Script = e.Eval.Script } }; }, }.Register(); Conditions = sb.GlobalLazy(() => Database.Query<WorkflowConditionEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowConditionEntity))); } public static ResetLazy<Dictionary<Lite<WorkflowScriptEntity>, WorkflowScriptEntity>> Scripts = null!; public static WorkflowScriptEntity RetrieveFromCache(this Lite<WorkflowScriptEntity> ws)=> Scripts.Value.GetOrThrow(ws); private static void StartWorkflowScript(SchemaBuilder sb) { sb.Include<WorkflowScriptEntity>() .WithQuery(() => s => new { Entity = s, s.Id, s.Name, s.MainEntityType, }); new Graph<WorkflowScriptEntity>.Execute(WorkflowScriptOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, _) => { if (!e.IsNew) { var oldMainEntityType = e.InDB(a => a.MainEntityType); if (!oldMainEntityType.Is(e.MainEntityType)) ThrowConnectionError(Database.Query<WorkflowActivityEntity>().Where(a => a.Script!.Script == e.ToLite()), e, WorkflowScriptOperation.Save); } e.Save(); }, }.Register(); new Graph<WorkflowScriptEntity>.ConstructFrom<WorkflowScriptEntity>(WorkflowScriptOperation.Clone) { Construct = (s, _) => new WorkflowScriptEntity() { MainEntityType = s.MainEntityType, Eval = new WorkflowScriptEval() { Script = s.Eval.Script } } }.Register(); new Graph<WorkflowScriptEntity>.Delete(WorkflowScriptOperation.Delete) { Delete = (s, _) => { ThrowConnectionError(Database.Query<WorkflowActivityEntity>().Where(a => a.Script!.Script == s.ToLite()), s, WorkflowScriptOperation.Delete); s.Delete(); }, }.Register(); Scripts = sb.GlobalLazy(() => Database.Query<WorkflowScriptEntity>().ToDictionary(a => a.ToLite()), new InvalidateWith(typeof(WorkflowScriptEntity))); sb.Include<WorkflowScriptRetryStrategyEntity>() .WithSave(WorkflowScriptRetryStrategyOperation.Save) .WithDelete(WorkflowScriptRetryStrategyOperation.Delete) .WithQuery(() => e => new { Entity = e, e.Id, e.Rule }); } private static void ThrowConnectionError(IQueryable<WorkflowConnectionEntity> queryable, Entity entity, IOperationSymbolContainer operation) { if (queryable.Count() == 0) return; var errors = queryable.Select(a => new { Connection = a.ToLite(), From = a.From.ToLite(), To = a.To.ToLite(), Workflow = a.From.Lane.Pool.Workflow.ToLite() }).ToList(); var formattedErrors = errors.GroupBy(a => a.Workflow).ToString(gr => $"Workflow '{gr.Key}':" + gr.ToString(a => $"Connection {a.Connection!.Id} ({a.Connection}): {a.From} -> {a.To}", "\r\n").Indent(4), "\r\n\r\n").Indent(4); throw new ApplicationException($"Impossible to {operation.Symbol.Key.After('.')} '{entity}' because is used in some connections: \r\n" + formattedErrors); } private static void ThrowConnectionError<T>(IQueryable<T> queryable, Entity entity, IOperationSymbolContainer operation) where T : Entity, IWorkflowNodeEntity { if (queryable.Count() == 0) return; var errors = queryable.Select(a => new { Entity = a.ToLite(), Workflow = a.Lane.Pool.Workflow.ToLite() }).ToList(); var formattedErrors = errors.GroupBy(a => a.Workflow).ToString(gr => $"Workflow '{gr.Key}':" + gr.ToString(a => $"{typeof(T).NiceName()} {a.Entity}", "\r\n").Indent(4), "\r\n\r\n").Indent(4); throw new ApplicationException($"Impossible to {operation.Symbol.Key.After('.')} '{entity}' because is used in some {typeof(T).NicePluralName()}: \r\n" + formattedErrors); } public class WorkflowGraph : Graph<WorkflowEntity> { public static void Register() { new Execute(WorkflowOperation.Save) { CanBeNew = true, CanBeModified = true, Execute = (e, args) => { if (e.MainEntityStrategies.Contains(WorkflowMainEntityStrategy.CreateNew)) { var type = e.MainEntityType.ToType(); if (CaseActivityLogic.Options.TryGetC(type)?.Constructor == null) throw new ApplicationException(WorkflowMessage._0NotAllowedFor1NoConstructorHasBeenDefinedInWithWorkflow.NiceToString(WorkflowMainEntityStrategy.CreateNew.NiceToString(), type.NiceName())); } WorkflowLogic.ApplyDocument(e, args.TryGetArgC<WorkflowModel>(), args.TryGetArgC<WorkflowReplacementModel>(), args.TryGetArgC<List<WorkflowIssue>>() ?? new List<WorkflowIssue>()); DynamicCode.OnInvalidated?.Invoke(); } }.Register(); new ConstructFrom<WorkflowEntity>(WorkflowOperation.Clone) { Construct = (w, args) => { WorkflowBuilder wb = new WorkflowBuilder(w); var result = wb.Clone(); return result; } }.Register(); new Delete(WorkflowOperation.Delete) { CanDelete = w => { var usedWorkflows = Database.Query<CaseEntity>() .Where(c => c.Workflow.Is(w) && c.ParentCase != null) .Select(c => c.ParentCase!.Workflow) .ToList(); if (usedWorkflows.Any()) return WorkflowMessage.WorkflowUsedIn0ForDecompositionOrCallWorkflow.NiceToString(usedWorkflows.ToString(", ")); return null; }, Delete = (w, _) => { var wb = new WorkflowBuilder(w); wb.Delete(); DynamicCode.OnInvalidated?.Invoke(); } }.Register(); new Execute(WorkflowOperation.Activate) { CanExecute = w => w.HasExpired() ? null : WorkflowMessage.Workflow0AlreadyActivated.NiceToString(w), Execute = (w, _) => { w.ExpirationDate = null; w.Save(); w.SuspendWorkflowScheduledTasks(suspended: false); } }.Register(); new Execute(WorkflowOperation.Deactivate) { CanExecute = w => w.HasExpired() ? WorkflowMessage.Workflow0HasExpiredOn1.NiceToString(w, w.ExpirationDate!.Value.ToString()) : w.Cases().SelectMany(c => c.CaseActivities()).Any(ca => ca.DoneDate == null) ? CaseActivityMessage.ThereAreInprogressActivities.NiceToString() : null, Execute = (w, args) => { w.ExpirationDate = args.GetArg<DateTime>(); w.Save(); w.SuspendWorkflowScheduledTasks(suspended: true); } }.Register(); } } public static void SuspendWorkflowScheduledTasks(this WorkflowEntity workflow, bool suspended) { workflow.WorkflowEvents() .Where(a => a.Type == WorkflowEventType.ScheduledStart) .Select(a => a.ScheduledTask()!) .UnsafeUpdate() .Set(a => a.Suspended, a => suspended) .Execute(); } public static Func<UserEntity, Lite<Entity>, bool> IsUserActor = (user, actor) => actor.Is(user) || (actor is Lite<RoleEntity> && AuthLogic.IndirectlyRelated(user.Role).Contains((Lite<RoleEntity>)actor)); public static Expression<Func<UserEntity, Lite<Entity>, bool>> IsUserActorForNotifications = (user, actorConstant) => actorConstant.Is(user) || (actorConstant is Lite<RoleEntity> && AuthLogic.InverseIndirectlyRelated((Lite<RoleEntity>)actorConstant).Contains(user.Role)); public static List<WorkflowEntity> GetAllowedStarts() { return WorkflowGraphLazy.Value.Values.Where(wg => wg.IsStartCurrentUser()).Select(wg => wg.Workflow).ToList(); } public static WorkflowModel GetWorkflowModel(WorkflowEntity workflow) { var wb = new WorkflowBuilder(workflow); return wb.GetWorkflowModel(); } public static WorkflowReplacementModel PreviewChanges(WorkflowEntity workflow, WorkflowModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); var document = WorkflowBuilder.ParseDocument(model.DiagramXml); var wb = new WorkflowBuilder(workflow); return wb.PreviewChanges(document, model); } public static void ApplyDocument(WorkflowEntity workflow, WorkflowModel? model, WorkflowReplacementModel? replacements, List<WorkflowIssue> issuesContainer) { if (issuesContainer.Any()) throw new InvalidOperationException("issuesContainer should be empty"); var wb = new WorkflowBuilder(workflow); if (workflow.IsNew) workflow.Save(); if (model != null) { wb.ApplyChanges(model, replacements); } wb.ValidateGraph(issuesContainer); if (issuesContainer.Any(a => a.Type == WorkflowIssueType.Error)) throw new IntegrityCheckException(new Dictionary<Guid, IntegrityCheck>()); workflow.FullDiagramXml = new WorkflowXmlEmbedded { DiagramXml = wb.GetXDocument().ToString() }; workflow.Save(); } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Reflection; using NLog.Common; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Factory for class-based items. /// </summary> /// <typeparam name="TBaseType">The base type of each item.</typeparam> /// <typeparam name="TAttributeType">The type of the attribute used to annotate items.</typeparam> internal class Factory<TBaseType, TAttributeType> : INamedItemFactory<TBaseType, Type>, IFactory where TBaseType : class where TAttributeType : NameBaseAttribute { private readonly Dictionary<string, GetTypeDelegate> _items = new Dictionary<string, GetTypeDelegate>(StringComparer.OrdinalIgnoreCase); private readonly ConfigurationItemFactory _parentFactory; private readonly Factory<TBaseType, TAttributeType> _globalDefaultFactory; internal Factory(ConfigurationItemFactory parentFactory, Factory<TBaseType, TAttributeType> globalDefaultFactory) { _parentFactory = parentFactory; _globalDefaultFactory = globalDefaultFactory; } private delegate Type GetTypeDelegate(); /// <summary> /// Scans the assembly. /// </summary> /// <param name="types">The types to scan.</param> /// <param name="assemblyName">The assembly name for the types.</param> /// <param name="itemNamePrefix">The prefix.</param> public void ScanTypes(Type[] types, string assemblyName, string itemNamePrefix) { foreach (Type t in types) { try { RegisterType(t, assemblyName, itemNamePrefix); } catch (Exception exception) { InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName); if (exception.MustBeRethrown()) { throw; } } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> public void RegisterType(Type type, string itemNamePrefix) { RegisterType(type, string.Empty, itemNamePrefix); } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="assemblyName">The assembly name for the type.</param> /// <param name="itemNamePrefix">The item name prefix.</param> public void RegisterType(Type type, string assemblyName, string itemNamePrefix) { if (typeof(TBaseType).IsAssignableFrom(type)) { IEnumerable<TAttributeType> attributes = type.GetCustomAttributes<TAttributeType>(false); if (attributes != null) { foreach (var attr in attributes) { RegisterDefinition(attr.Name, type, assemblyName, itemNamePrefix); } } } } /// <summary> /// Registers the item based on a type name. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="typeName">Name of the type.</param> public void RegisterNamedType(string itemName, string typeName) { itemName = NormalizeName(itemName); _items[itemName] = () => Type.GetType(typeName, false); } /// <summary> /// Clears the contents of the factory. /// </summary> public void Clear() { _items.Clear(); } /// <summary> /// Registers a single type definition. /// </summary> /// <param name="itemName">The item name.</param> /// <param name="itemDefinition">The type of the item.</param> public void RegisterDefinition(string itemName, Type itemDefinition) { RegisterDefinition(itemName, itemDefinition, string.Empty, string.Empty); } /// <summary> /// Registers a single type definition. /// </summary> /// <param name="itemName">The item name.</param> /// <param name="itemDefinition">The type of the item.</param> /// <param name="assemblyName">The assembly name for the types.</param> /// <param name="itemNamePrefix">The item name prefix.</param> private void RegisterDefinition(string itemName, Type itemDefinition, string assemblyName, string itemNamePrefix) { GetTypeDelegate typeLookup = () => itemDefinition; itemName = NormalizeName(itemName); _items[itemNamePrefix + itemName] = typeLookup; if (!string.IsNullOrEmpty(assemblyName)) { _items[itemName + ", " + assemblyName] = typeLookup; _items[itemDefinition.Name + ", " + assemblyName] = typeLookup; _items[itemDefinition.ToString() + ", " + assemblyName] = typeLookup; } } /// <summary> /// Tries to get registered item definition. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">Reference to a variable which will store the item definition.</param> /// <returns>Item definition.</returns> public bool TryGetDefinition(string itemName, out Type result) { GetTypeDelegate getTypeDelegate; itemName = NormalizeName(itemName); if (!_items.TryGetValue(itemName, out getTypeDelegate)) { if (_globalDefaultFactory != null && _globalDefaultFactory.TryGetDefinition(itemName, out result)) { return true; } result = null; return false; } try { result = getTypeDelegate(); return result != null; } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } // delegate invocation failed - type is not available result = null; return false; } } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public virtual bool TryCreateInstance(string itemName, out TBaseType result) { itemName = NormalizeName(itemName); if (!TryGetDefinition(itemName, out var itemType)) { result = null; return false; } result = (TBaseType)_parentFactory.CreateInstance(itemType); return true; } /// <summary> /// Creates an item instance. /// </summary> /// <param name="itemName">The name of the item.</param> /// <returns>Created item.</returns> public virtual TBaseType CreateInstance(string itemName) { itemName = NormalizeName(itemName); if (TryCreateInstance(itemName, out TBaseType result)) { return result; } var message = typeof(TBaseType).Name + " symbol-name is unknown: '" + itemName + "'"; if (itemName != null && (itemName.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) || itemName.StartsWith("iis", StringComparison.OrdinalIgnoreCase))) { #if NETSTANDARD message += ". Extension NLog.Web.AspNetCore not included?"; #else message += ". Extension NLog.Web not included?"; #endif } else if (itemName?.StartsWith("database", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.Database not included?"; } else if (itemName?.StartsWith("windows-identity", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.WindowsIdentity not included?"; } else if (itemName?.StartsWith("outputdebugstring", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.OutputDebugString not included?"; } else if (itemName?.StartsWith("performancecounter", StringComparison.OrdinalIgnoreCase) == true) { message += ". Extension NLog.PerformanceCounter not included?"; } throw new ArgumentException(message); } protected static string NormalizeName(string itemName) { if (itemName == null) { return string.Empty; } var delimitIndex = itemName.IndexOf('-'); if (delimitIndex < 0) { return itemName; } // Only for the first comma var commaIndex = itemName.IndexOf(','); if (commaIndex >= 0) { var left = itemName.Substring(0, commaIndex).Replace("-", string.Empty); var right = itemName.Substring(commaIndex); return left + right; } return itemName.Replace("-", string.Empty); } } /// <summary> /// Factory specialized for <see cref="LayoutRenderer"/>s. /// </summary> internal class LayoutRendererFactory : Factory<LayoutRenderer, LayoutRendererAttribute> { private Dictionary<string, FuncLayoutRenderer> _funcRenderers; private readonly LayoutRendererFactory _globalDefaultFactory; public LayoutRendererFactory(ConfigurationItemFactory parentFactory, LayoutRendererFactory globalDefaultFactory) : base(parentFactory, globalDefaultFactory) { _globalDefaultFactory = globalDefaultFactory; } /// <summary> /// Clear all func layouts /// </summary> public void ClearFuncLayouts() { _funcRenderers?.Clear(); } /// <summary> /// Register a layout renderer with a callback function. /// </summary> /// <param name="itemName">Name of the layoutrenderer, without ${}.</param> /// <param name="renderer">the renderer that renders the value.</param> public void RegisterFuncLayout(string itemName, FuncLayoutRenderer renderer) { itemName = NormalizeName(itemName); _funcRenderers = _funcRenderers ?? new Dictionary<string, FuncLayoutRenderer>(StringComparer.OrdinalIgnoreCase); //overwrite current if there is one _funcRenderers[itemName] = renderer; } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public override bool TryCreateInstance(string itemName, out LayoutRenderer result) { //first try func renderers, as they should have the possibility to overwrite a current one. FuncLayoutRenderer funcResult; itemName = NormalizeName(itemName); if (_funcRenderers != null) { var successAsFunc = _funcRenderers.TryGetValue(itemName, out funcResult); if (successAsFunc) { result = funcResult; return true; } } if (_globalDefaultFactory?._funcRenderers != null && _globalDefaultFactory._funcRenderers.TryGetValue(itemName, out funcResult)) { result = funcResult; return true; } return base.TryCreateInstance(itemName, out result); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; #pragma warning disable 0649 // Uninitialized field namespace System.Reflection.Tests { public static class TypeTests_GetMember { [Fact] public static void TestNull() { Type t = typeof(Mixed).Project(); Assert.Throws<ArgumentNullException>(() => t.GetMember(null, MemberTypes.All, BindingFlags.Public | BindingFlags.Instance)); } [Fact] public static void TestExtraBitsIgnored() { Type t = typeof(Mixed).Project(); MemberInfo[] expectedMembers = t.GetMember("*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance); MemberInfo[] actualMembers = t.GetMember("*", (MemberTypes)(-1), BindingFlags.Public | BindingFlags.Instance); Assert.Equal(expectedMembers.Length, actualMembers.Length); } [Fact] public static void TestTypeInfoIsSynonymForNestedInfo() { Type t = typeof(Mixed).Project(); MemberInfo[] expectedMembers = t.GetMember("*", MemberTypes.NestedType, BindingFlags.Public | BindingFlags.Instance); Assert.Equal(1, expectedMembers.Length); Assert.Equal(typeof(Mixed.MyType).Project(), expectedMembers[0]); MemberInfo[] actualMembers; actualMembers = t.GetMember("*", MemberTypes.TypeInfo, BindingFlags.Public | BindingFlags.Instance); Assert.Equal<MemberInfo>(expectedMembers, actualMembers); actualMembers = t.GetMember("*", MemberTypes.NestedType | MemberTypes.TypeInfo, BindingFlags.Public | BindingFlags.Instance); Assert.Equal<MemberInfo>(expectedMembers, actualMembers); } [Fact] public static void TestReturnType() { Type t = typeof(Mixed).Project(); // Desktop compat: Type.GetMember() returns the most specific array type possible given the MemberType combinations passed in. for (MemberTypes memberType = (MemberTypes)0; memberType <= MemberTypes.All; memberType++) { MemberInfo[] m = t.GetMember("*", memberType, BindingFlags.Public | BindingFlags.Instance); Type actualElementType = m.GetType().GetElementType(); switch (memberType) { case MemberTypes.Constructor: Assert.Equal(typeof(ConstructorInfo), actualElementType); break; case MemberTypes.Event: Assert.Equal(typeof(EventInfo), actualElementType); break; case MemberTypes.Field: Assert.Equal(typeof(FieldInfo), actualElementType); break; case MemberTypes.Method: Assert.Equal(typeof(MethodInfo), actualElementType); break; case MemberTypes.Constructor | MemberTypes.Method: Assert.Equal(typeof(MethodBase), actualElementType); break; case MemberTypes.Property: Assert.Equal(typeof(PropertyInfo), actualElementType); break; case MemberTypes.NestedType: case MemberTypes.TypeInfo: Assert.Equal(typeof(Type), actualElementType); break; default: Assert.Equal(typeof(MemberInfo), actualElementType); break; } } } [Fact] public static void TestMemberTypeCombos() { Type t = typeof(Mixed); for (MemberTypes memberType = (MemberTypes)0; memberType <= MemberTypes.All; memberType++) { MemberInfo[] members = t.GetMember("*", memberType, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); int constructors = 0; int events = 0; int fields = 0; int methods = 0; int nestedTypes = 0; int properties = 0; foreach (MemberInfo member in members) { switch (member.MemberType) { case MemberTypes.Constructor: constructors++; break; case MemberTypes.Event: events++; break; case MemberTypes.Field: fields++; break; case MemberTypes.Method: methods++; break; case MemberTypes.NestedType: nestedTypes++; break; case MemberTypes.Property: properties++; break; default: Assert.True(false, "Bad member type."); break; } } int expectedConstructors = ((memberType & MemberTypes.Constructor) == 0) ? 0 : 1; int expectedEvents = ((memberType & MemberTypes.Event) == 0) ? 0 : 1; int expectedFields = ((memberType & MemberTypes.Field) == 0) ? 0 : 1; int expectedMethods = ((memberType & MemberTypes.Method) == 0) ? 0 : 4; int expectedNestedTypes = ((memberType & (MemberTypes.NestedType | MemberTypes.TypeInfo)) == 0) ? 0 : 1; int expectedProperties = ((memberType & MemberTypes.Property) == 0) ? 0 : 1; Assert.Equal(expectedConstructors, constructors); Assert.Equal(expectedEvents, events); Assert.Equal(expectedFields, fields); Assert.Equal(expectedMethods, methods); Assert.Equal(expectedNestedTypes, nestedTypes); Assert.Equal(expectedProperties, properties); } } [Fact] public static void TestZeroMatch() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("NOSUCHMEMBER", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Assert.Equal(0, members.Length); } [Fact] public static void TestCaseSensitive1() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MyField", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Assert.Equal(1, members.Length); Assert.True(members[0] is FieldInfo); Assert.Equal("MyField", members[0].Name); } [Fact] public static void TestCaseSensitive2() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MYFIELD", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Assert.Equal(0, members.Length); } [Fact] public static void TestCaseInsensitive1() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MyField", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase); Assert.Equal(1, members.Length); Assert.True(members[0] is FieldInfo); Assert.Equal("MyField", members[0].Name); } [Fact] public static void TestCaseInsensitive2() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MYfiELD", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase); Assert.Equal(1, members.Length); Assert.True(members[0] is FieldInfo); Assert.Equal("MyField", members[0].Name); } [Fact] public static void TestPrefixCaseSensitive1() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MyFi*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Assert.Equal(1, members.Length); Assert.True(members[0] is FieldInfo); Assert.Equal("MyField", members[0].Name); } [Fact] public static void TestPrefixCaseSensitive2() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MYFI*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); Assert.Equal(0, members.Length); } [Fact] public static void TestPrefixCaseInsensitive1() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MyFi*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase); Assert.Equal(1, members.Length); Assert.True(members[0] is FieldInfo); Assert.Equal("MyField", members[0].Name); } [Fact] public static void TestPrefixCaseInsensitive2() { Type t = typeof(Mixed).Project(); MemberInfo[] members = t.GetMember("MYFI*", MemberTypes.All, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase); Assert.Equal(1, members.Length); Assert.True(members[0] is FieldInfo); Assert.Equal("MyField", members[0].Name); } private class Mixed { public Mixed() { } public event Action MyEvent { add { } remove { } } public int MyField; public void MyMethod() { } public class MyType { } public int MyProperty { get; } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Professional service: Attorney. /// </summary> public class Attorney_Core : TypeCore, IProfessionalService { public Attorney_Core() { this._TypeId = 21; this._Id = "Attorney"; this._Schema_Org_Url = "http://schema.org/Attorney"; string label = ""; GetLabel(out label, "Attorney", typeof(Attorney_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,216}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{216}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Runtime.CompilerServices; using System.Security; [assembly: InternalsVisibleTo("ClassFriend, PublicKey=00240000048000009400000006020000002400005253413100040000010001000fc5993e0f511ad5e16e8b226553493e09067afc41039f70daeb94a968d664f40e69a46b617d15d3d5328be7dbedd059eb98495a3b03cb4ea4ba127444671c3c84cbc1fdc393d7e10b5ee3f31f5a29f005e5eed7e3c9c8af74f413f0004f0c2cabb22f9dd4f75a6f599784e1bab70985ef8174ca6c684278be82ce055a03ebaf")] [assembly: InternalsVisibleTo("StaticClassFriend, PublicKey=00240000048000009400000006020000002400005253413100040000010001000fc5993e0f511ad5e16e8b226553493e09067afc41039f70daeb94a968d664f40e69a46b617d15d3d5328be7dbedd059eb98495a3b03cb4ea4ba127444671c3c84cbc1fdc393d7e10b5ee3f31f5a29f005e5eed7e3c9c8af74f413f0004f0c2cabb22f9dd4f75a6f599784e1bab70985ef8174ca6c684278be82ce055a03ebaf")] [assembly: InternalsVisibleTo("StructFriend, PublicKey=00240000048000009400000006020000002400005253413100040000010001000fc5993e0f511ad5e16e8b226553493e09067afc41039f70daeb94a968d664f40e69a46b617d15d3d5328be7dbedd059eb98495a3b03cb4ea4ba127444671c3c84cbc1fdc393d7e10b5ee3f31f5a29f005e5eed7e3c9c8af74f413f0004f0c2cabb22f9dd4f75a6f599784e1bab70985ef8174ca6c684278be82ce055a03ebaf")] // // This file can be compiled in two ways: ALL public (ALL_PUB), or Restricted. // The intention of the ALL public (ALL_PUB) is to allow a C# caller to build. // The restricted version is intended to be used at runtime, causing some // calls to fail. // // // Enum // #if ALL_PUB public #endif enum DefaultEnum { VALUE1, VALUE3 } public enum PublicEnum { VALUE1, VALUE3 } #if ALL_PUB public enum InternalEnum { VALUE1, VALUE3 } #else internal enum InternalEnum { VALUE1, VALUE3 } #endif // // Class // #if ALL_PUB public #endif class DefaultClass { } public class PublicClass { // // Ctors // public PublicClass() {} #if ALL_PUB public #endif PublicClass(int i1) {} public PublicClass(int i1, int i2) {} #if ALL_PUB public PublicClass(int i1, int i2, int i3) {} public PublicClass(int i1, int i2, int i3, int i4) {} public PublicClass(int i1, int i2, int i3, int i4, int i5) {} public PublicClass(int i1, int i2, int i3, int i4, int i5, int i6) {} #else protected PublicClass(int i1, int i2, int i3) {} internal PublicClass(int i1, int i2, int i3, int i4) {} protected internal PublicClass(int i1, int i2, int i3, int i4, int i5) {} private PublicClass(int i1, int i2, int i3, int i4, int i5, int i6) {} #endif // // static fields // #pragma warning disable 169 #if ALL_PUB public #endif static int defaultStaticField; public static int publicStaticField = 0; #if ALL_PUB public static int protectedStaticField = 0; public static int internalStaticField = 0; public static int protectedInternalStaticField = 0; public static int privateStaticField; #else protected static int protectedStaticField = 0; internal static int internalStaticField = 0; protected internal static int protectedInternalStaticField = 0; private static int privateStaticField; #endif // // instance fields // #if ALL_PUB public #endif int defaultField; public int publicField; #if ALL_PUB public int protectedField; public int internalField; public int protectedInternalField; public int privateField; #else protected int protectedField; internal int internalField; protected internal int protectedInternalField; private int privateField; #endif #pragma warning restore 169 // // static Properties // #if ALL_PUB public #endif static int DefaultStaticProperty { get { return 0; } set { ; } } public static int PublicStaticProperty { get { return 0; } set { ; } } #if ALL_PUB public static int ProtectedStaticProperty { get { return 0; } set { ; } } public static int InternalStaticProperty { get { return 0; } set { ; } } public static int ProtectedInternalStaticProperty { get { return 0; } set { ; } } public static int PrivateStaticProperty { get { return 0; } set { ; } } #else protected static int ProtectedStaticProperty { get { return 0; } set { ; } } internal static int InternalStaticProperty { get { return 0; } set { ; } } protected internal static int ProtectedInternalStaticProperty { get { return 0; } set { ; } } private static int PrivateStaticProperty { get { return 0; } set { ; } } #endif // // instance Properties // #if ALL_PUB public #endif int DefaultProperty { get { return 0; } set { ; } } public int PublicProperty { get { return 0; } set { ; } } #if ALL_PUB public int ProtectedProperty { get { return 0; } set { ; } } public int InternalProperty { get { return 0; } set { ; } } public int ProtectedInternalProperty { get { return 0; } set { ; } } public int PrivateProperty { get { return 0; } set { ; } } #else protected int ProtectedProperty { get { return 0; } set { ; } } internal int InternalProperty { get { return 0; } set { ; } } protected internal int ProtectedInternalProperty { get { return 0; } set { ; } } private int PrivateProperty { get { return 0; } set { ; } } #endif // // static Methods // #if ALL_PUB public #endif static int DefaultStaticMethod() { return 1; } public static int PublicStaticMethod() { return 1; } #if ALL_PUB public static int ProtectedStaticMethod() { return 1; } public static int InternalStaticMethod() { return 1; } public static int ProtectedInternalStaticMethod() { return 1; } public static int PrivateStaticMethod() { return 1; } #else protected static int ProtectedStaticMethod() { return 1; } internal static int InternalStaticMethod() { return 1; } protected internal static int ProtectedInternalStaticMethod() { return 1; } private static int PrivateStaticMethod() { return 1; } #endif // // instance Methods // #if ALL_PUB public #endif int DefaultMethod() { return 1; } public int PublicMethod() { return 1; } #if ALL_PUB public int ProtectedMethod() { return 1; } public int InternalMethod() { return 1; } public int ProtectedInternalMethod() { return 1; } public int PrivateMethod() { return 1; } #else protected int ProtectedMethod() { return 1; } internal int InternalMethod() { return 1; } protected internal int ProtectedInternalMethod() { return 1; } private int PrivateMethod() { return 1; } #endif } #if ALL_PUB public class InternalClass #else internal class InternalClass #endif { } // // Static Class // #if ALL_PUB public #endif static class DefaultStaticClass { public static int field = 0; } public static class PublicStaticClass { public static int field = 0; } #if ALL_PUB public static class InternalStaticClass #else internal static class InternalStaticClass #endif { public static int field = 0; } // // Interface // #if ALL_PUB public #endif interface DefaultInterface { bool Foo(); } public interface PublicInterface { bool Foo(); } #if ALL_PUB public interface InternalInterface #else internal interface InternalInterface #endif { bool Foo(); } // // Struct // #if ALL_PUB public #endif struct DefaultStruct {} public struct PublicStruct { // // Ctors // #if ALL_PUB public #endif PublicStruct(int i1) {defaultField=publicField=internalField=privateField=0;} public PublicStruct(int i1, int i2) {defaultField=publicField=internalField=privateField=0;} #if ALL_PUB public PublicStruct(int i1, int i2, int i3) {defaultField=publicField=internalField=privateField=0;} public PublicStruct(int i1, int i2, int i3, int i4) {defaultField=publicField=internalField=privateField=0;} #else internal PublicStruct(int i1, int i2, int i3) {defaultField=publicField=internalField=privateField=0;} private PublicStruct(int i1, int i2, int i3, int i4) {defaultField=publicField=internalField=privateField=0;} #endif #pragma warning disable 414 // // static fields // #if ALL_PUB public #endif static int defaultStaticField = 0; public static int publicStaticField = 0; #if ALL_PUB public static int internalStaticField = 0; public static int privateStaticField = 0; #else internal static int internalStaticField = 0; private static int privateStaticField = 0; #endif // // instance fields // #if ALL_PUB public #endif int defaultField; public int publicField; #if ALL_PUB public int internalField; public int privateField; #else internal int internalField; private int privateField; #endif #pragma warning restore 414 // // static Properties // #if ALL_PUB public #endif static int DefaultStaticProperty { get { return 0; } set { ; } } public static int PublicStaticProperty { get { return 0; } set { ; } } #if ALL_PUB public static int InternalStaticProperty { get { return 0; } set { ; } } public static int PrivateStaticProperty { get { return 0; } set { ; } } #else internal static int InternalStaticProperty { get { return 0; } set { ; } } private static int PrivateStaticProperty { get { return 0; } set { ; } } #endif // // instance Properties // #if ALL_PUB public #endif int DefaultProperty { get { return 0; } set { ; } } public int PublicProperty { get { return 0; } set { ; } } #if ALL_PUB public int InternalProperty { get { return 0; } set { ; } } public int PrivateProperty { get { return 0; } set { ; } } #else internal int InternalProperty { get { return 0; } set { ; } } private int PrivateProperty { get { return 0; } set { ; } } #endif // // static Methods // #if ALL_PUB public #endif static int DefaultStaticMethod() { return 1; } public static int PublicStaticMethod() { return 1; } #if ALL_PUB public static int InternalStaticMethod() { return 1; } public static int PrivateStaticMethod() { return 1; } #else internal static int InternalStaticMethod() { return 1; } private static int PrivateStaticMethod() { return 1; } #endif // // instance Methods // #if ALL_PUB public #endif int DefaultMethod() { return 1; } public int PublicMethod() { return 1; } #if ALL_PUB public int InternalMethod() { return 1; } public int PrivateMethod() { return 1; } #else internal int InternalMethod() { return 1; } private int PrivateMethod() { return 1; } #endif } #if ALL_PUB public struct InternalStruct {}; #else internal struct InternalStruct {}; #endif
using System.Collections.Generic; namespace Tibia.Objects { /// <summary> /// Represents a player, which is just an extended version of creature. /// </summary> public class Player : Creature { /// <summary> /// Default constructor, same as Objects.Creature. /// </summary> /// <param name="client">The client.</param> /// <param name="address">The address.</param> public Player(Client client, uint address) : base(client, address) { } #region Packet Methods /// <summary> /// Turn to the specified direction. /// </summary> /// <param name="direction"></param> /// <returns></returns> public bool Turn(Constants.Direction direction) { return client.Player.Turn(direction); } /// <summary> /// Walk in the specified direction /// </summary> /// <param name="direction"></param> /// <returns></returns> public bool Walk(Constants.Direction direction) { return client.Player.Walk(direction); } /// <summary> /// Walk in the specified list of directions. /// </summary> /// <param name="list"></param> /// <returns></returns> public bool Walk(List<Constants.Direction> list) { return client.Player.Walk(list); } /// <summary> /// Go to the specified location. /// </summary> /// <returns></returns> public Location GoTo { set { GoToX = (uint)value.X; GoToY = (uint)value.Y; GoToZ = (uint)value.Z; IsWalking = true; } get { return new Location((int)GoToX, (int)GoToY, (int)GoToZ); } } /// <summary> /// Stop all actions. /// </summary> /// <returns></returns> public bool Stop() { return client.Player.Stop(); } /// <summary> /// Set the player's outfit. Sends a packet. /// </summary> public bool SetOutfit(Outfit outfit) { return client.Player.SetOutfit(outfit); } #endregion /// <summary> /// Check if the specified flag is set. Wrapper for Flags. /// </summary> /// <param name="flag"></param> /// <returns></returns> public bool HasFlag(Constants.Flag flag) { return client.Player.HasFlag(flag); } #region Get/Set Properties public new uint Id { get { return client.Player.Id; } set { client.Player.Id = value; } } public ulong Experience { get { return client.Player.Experience; } set { client.Player.Experience = value; } } public uint Flags { get { return client.Player.Flags; } set { client.Player.Flags = value; } } public uint Level { get { return client.Player.Level; } set { client.Player.Level = value; } } public uint LevelPercent { get { return client.Player.LevelPercent; } set { client.Player.LevelPercent = value; } } public uint MagicLevel { get { return client.Player.MagicLevel; } set { client.Player.MagicLevel = value; } } public uint MagicLevelPercent { get { return client.Player.MagicLevelPercent; } set { client.Player.MagicLevelPercent = value; } } public uint Mana { get { return client.Player.Mana; } set { client.Player.Mana = value; } } public uint ManaMax { get { return client.Player.ManaMax; } set { client.Player.ManaMax = value; } } public uint Health { get { return client.Player.Health; } set { client.Player.Health = value; } } public uint HealthMax { get { return client.Player.HealthMax; } set { client.Player.HealthMax = value; } } public uint Soul { get { return client.Player.Soul; } set { client.Player.Soul = value; } } public uint Capacity { get { return client.Player.Capacity; } set { client.Player.Capacity = value; } } public uint Stamina { get { return client.Player.Stamina; } set { client.Player.Stamina = value; } } public uint Fist { get { return client.Player.Fist; } set { client.Player.Fist = value; } } public uint FistPercent { get { return client.Player.FistPercent; } set { client.Player.FistPercent = value; } } public uint Club { get { return client.Player.Club; } set { client.Player.Club = value; } } public uint ClubPercent { get { return client.Player.ClubPercent; } set { client.Player.ClubPercent = value; } } public uint Sword { get { return client.Player.Sword; } set { client.Player.Sword = value; } } public uint SwordPercent { get { return client.Player.SwordPercent; } set { client.Player.SwordPercent = value; } } public uint Axe { get { return client.Player.Axe; } set { client.Player.Axe = value; } } public uint AxePercent { get { return client.Player.AxePercent; } set { client.Player.AxePercent = value; } } public uint Distance { get { return client.Player.Distance; } set { client.Player.Distance = value; } } public uint DistancePercent { get { return client.Player.DistancePercent; } set { client.Player.DistancePercent = value; } } public uint Shielding { get { return client.Player.Shielding; } set { client.Player.Shielding = value; } } public uint ShieldingPercent { get { return client.Player.ShieldingPercent; } set { client.Player.ShieldingPercent = value; } } public uint Fishing { get { return client.Player.Fishing; } set { client.Player.Fishing = value; } } public uint FishingPercent { get { return client.Player.FishingPercent; } set { client.Player.FishingPercent = value; } } public uint GoToX { get { return client.Player.GoToX; } set { client.Player.GoToX = value; } } public uint GoToY { get { return client.Player.GoToY; } set { client.Player.GoToY = value; } } public uint GoToZ { get { return client.Player.GoToZ; } set { client.Player.GoToZ = value; } } public uint RedSquare { get { return client.Player.RedSquare; } set { client.Player.RedSquare = value; } } public uint GreenSquare { get { return client.Player.GreenSquare; } set { client.Player.GreenSquare = value; } } public uint WhiteSquare { get { return client.Player.WhiteSquare; } set { client.Player.WhiteSquare = value; } } public uint AccessN { get { return client.Player.AccessN; } set { client.Player.AccessN = value; } } public uint AccessS { get { return client.Player.AccessS; } set { client.Player.AccessS = value; } } public uint TargetId { get { return client.Player.TargetId; } set { client.Player.TargetId = value; } } public uint TargetType { get { return client.Player.TargetType; } set { client.Player.TargetType = value; } } public uint TargetBattlelistId { get { return client.Player.TargetBattlelistId; } set { client.Player.TargetBattlelistId = value; } } public uint TargetBattlelistType { get { return client.Player.TargetBattlelistType; } set { client.Player.TargetBattlelistType = value; } } public new uint Z { get { return client.Player.Z; } set { client.Player.Z = value; } } public new uint Y { get { return client.Player.Y; } set { client.Player.Y = value; } } public new uint X { get { return client.Player.X; } set { client.Player.X = value; } } public string WorldName { get { return client.Player.WorldName; } } #endregion } }
namespace Lex { /* * Class: Emit */ using System; using System.Text; using System.IO; using System.Collections; public class Emit { /* * Member Variables */ private Spec spec; private StreamWriter outstream; /* * Constants: Anchor Types */ private const int START = 1; private const int END = 2; private const int NONE = 4; /* * Constants */ private const bool EDBG = true; private const bool NOT_EDBG = false; /* * Function: Emit * Description: Constructor. */ public Emit() { reset(); } /* * Function: reset * Description: Clears member variables. */ private void reset() { spec = null; outstream = null; } /* * Function: set * Description: Initializes member variables. */ private void set(Spec s, StreamWriter o) { #if DEBUG Utility.assert(null != s); Utility.assert(null != o); #endif spec = s; outstream = o; } /* * Function: print_details * Description: Debugging output. */ private void print_details() { int i; int j; int next; int state; DTrans dtrans; Accept accept; bool tr; System.Console.WriteLine("---------------------- Transition Table ----------------------"); for (i = 0; i < spec.row_map.Length; ++i) { System.Console.Write("State " + i); accept = (Accept) spec.accept_list[i]; if (null == accept) { System.Console.WriteLine(" [nonaccepting]"); } else { System.Console.WriteLine(" [accepting, line " + accept.line_number + " <" + accept.action + ">]"); } dtrans = (DTrans) spec.dtrans_list[spec.row_map[i]]; tr = false; state = dtrans.GetDTrans(spec.col_map[0]); if (DTrans.F != state) { tr = true; System.Console.Write("\tgoto " + state.ToString() + " on ["); } for (j = 1; j < spec.dtrans_ncols; j++) { next = dtrans.GetDTrans(spec.col_map[j]); if (state == next) { if (DTrans.F != state) { System.Console.Write((char) j); } } else { state = next; if (tr) { System.Console.WriteLine("]"); tr = false; } if (DTrans.F != state) { tr = true; System.Console.Write("\tgoto " + state.ToString() + " on [" + Char.ToString((char) j)); } } } if (tr) { System.Console.WriteLine("]"); } } System.Console.WriteLine("---------------------- Transition Table ----------------------"); } /* * Function: Write * Description: High-level access function to module. */ public void Write(Spec spec, StreamWriter o) { set(spec, o); #if DEBUG Utility.assert(null != spec); Utility.assert(null != o); #endif #if OLD_DEBUG print_details(); #endif Header(); Construct(); Helpers(); Driver(); Footer(); reset(); } /* * Function: construct * Description: Emits constructor, member variables, * and constants. */ private void Construct() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif /* Constants */ outstream.Write( "private const int YY_BUFFER_SIZE = 512;\n" + "private const int YY_F = -1;\n" + "private const int YY_NO_STATE = -1;\n" + "private const int YY_NOT_ACCEPT = 0;\n" + "private const int YY_START = 1;\n" + "private const int YY_END = 2;\n" + "private const int YY_NO_ANCHOR = 4;\n" ); /* type declarations */ outstream.Write("delegate "+spec.type_name+" AcceptMethod();\n" + "AcceptMethod[] accept_dispatch;\n"); /* * write beg and end line chars */ outstream.Write("private const int YY_BOL = "); outstream.Write(spec.BOL); outstream.Write(";\n"); outstream.Write("private const int YY_EOF = "); outstream.Write(spec.EOF); outstream.Write(";\n"); if (spec.integer_type || true == spec.yyeof) outstream.Write("public const int YYEOF = -1;\n"); /* User specified class code */ if (null != spec.class_code) { outstream.Write(spec.class_code); } /* Member Variables */ outstream.Write( "private System.IO.TextReader yy_reader;\n" + "private int yy_buffer_index;\n" + "private int yy_buffer_read;\n" + "private int yy_buffer_start;\n" + "private int yy_buffer_end;\n" + "private char[] yy_buffer;\n"); if (spec.count_chars) outstream.Write("private int yychar;\n"); if (spec.count_lines) outstream.Write("private int yyline;\n"); outstream.Write("private bool yy_at_bol;\n"); outstream.Write("private int yy_lexical_state;\n\n"); /* Function: first constructor (Reader) */ string spec_access = "internal "; if (spec.lex_public) spec_access = "public "; outstream.Write( spec_access + spec.class_name + "(System.IO.TextReader reader) : this()\n" + " {\n" + " if (null == reader)\n" + " {\n" + " throw new System.ApplicationException(\"Error: Bad input stream initializer.\");\n" + " }\n" + " yy_reader = reader;\n" + " }\n\n"); /* Function: second constructor (InputStream) */ outstream.Write( spec_access + spec.class_name + "(System.IO.FileStream instream) : this()\n" + " {\n" + " if (null == instream)\n" + " {\n" + " throw new System.ApplicationException(\"Error: Bad input stream initializer.\");\n" + " }\n" + " yy_reader = new System.IO.StreamReader(instream);\n" + " }\n\n"); /* Function: third, private constructor - only for internal use */ outstream.Write( "private " + spec.class_name + "()\n" + " {\n" + " yy_buffer = new char[YY_BUFFER_SIZE];\n" + " yy_buffer_read = 0;\n" + " yy_buffer_index = 0;\n" + " yy_buffer_start = 0;\n" + " yy_buffer_end = 0;\n"); if (spec.count_chars) outstream.Write(" yychar = 0;\n"); if (spec.count_lines) outstream.Write(" yyline = 0;\n"); outstream.Write(" yy_at_bol = true;\n"); outstream.Write(" yy_lexical_state = YYINITIAL;\n"); string methinit = Action_Methods_Init(); outstream.Write(methinit); /* User specified constructor code. */ if (null != spec.init_code) outstream.Write(spec.init_code); outstream.Write(" }\n\n"); string methstr = Action_Methods_Body(); outstream.Write(methstr); } /* * Function: states * Description: Emits constants that serve as lexical states, * including YYINITIAL. */ private void States() { foreach (string state in spec.states.Keys) { #if DEBUG Utility.assert(null != state); #endif outstream.Write( "private const int " + state + " = " + spec.states[state] + ";\n"); } outstream.Write("private static int[] yy_state_dtrans = new int[] \n" + " { "); for (int index = 0; index < spec.state_dtrans.Length; ++index) { outstream.Write(" " + spec.state_dtrans[index]); if (index < spec.state_dtrans.Length - 1) outstream.Write(",\n"); else outstream.Write("\n"); } outstream.Write(" };\n"); } /* * Function: Helpers * Description: Emits helper functions, particularly * error handling and input buffering. */ private void Helpers() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif /* Function: yy_do_eof */ if (spec.eof_code != null) { outstream.Write("private bool yy_eof_done = false;\n" + "private void yy_do_eof ()\n" + " {\n" + " if (!yy_eof_done)\n" + " {\n" + " " + spec.eof_code + "\n" + " }\n" + " yy_eof_done = true;\n" + " }\n\n"); } States(); /* Function: yybegin */ outstream.Write( "private void yybegin (int state)\n" + " {\n" + " yy_lexical_state = state;\n" + " }\n\n"); /* Function: yy_advance */ outstream.Write( "private char yy_advance ()\n" + " {\n" + " int next_read;\n" + " int i;\n" + " int j;\n" + "\n" + " if (yy_buffer_index < yy_buffer_read)\n" + " {\n" + " return yy_buffer[yy_buffer_index++];\n" + " }\n" + "\n" + " if (0 != yy_buffer_start)\n" + " {\n" + " i = yy_buffer_start;\n" + " j = 0;\n" + " while (i < yy_buffer_read)\n" + " {\n" + " yy_buffer[j] = yy_buffer[i];\n" + " i++;\n" + " j++;\n" + " }\n" + " yy_buffer_end = yy_buffer_end - yy_buffer_start;\n" + " yy_buffer_start = 0;\n" + " yy_buffer_read = j;\n" + " yy_buffer_index = j;\n" + " next_read = yy_reader.Read(yy_buffer,yy_buffer_read,\n" + " yy_buffer.Length - yy_buffer_read);\n" // + " if (-1 == next_read)\n" + " if (next_read <= 0)\n" + " {\n" + " return (char) YY_EOF;\n" + " }\n" + " yy_buffer_read = yy_buffer_read + next_read;\n" + " }\n" + " while (yy_buffer_index >= yy_buffer_read)\n" + " {\n" + " if (yy_buffer_index >= yy_buffer.Length)\n" + " {\n" + " yy_buffer = yy_double(yy_buffer);\n" + " }\n" + " next_read = yy_reader.Read(yy_buffer,yy_buffer_read,\n" + " yy_buffer.Length - yy_buffer_read);\n" // + " if (-1 == next_read)\n" + " if (next_read <= 0)\n" + " {\n" + " return (char) YY_EOF;\n" + " }\n" + " yy_buffer_read = yy_buffer_read + next_read;\n" + " }\n" + " return yy_buffer[yy_buffer_index++];\n" + " }\n"); /* Function: yy_move_end */ outstream.Write( "private void yy_move_end ()\n" + " {\n" + " if (yy_buffer_end > yy_buffer_start && \n" + " '\\n' == yy_buffer[yy_buffer_end-1])\n" + " yy_buffer_end--;\n" + " if (yy_buffer_end > yy_buffer_start &&\n" + " '\\r' == yy_buffer[yy_buffer_end-1])\n" + " yy_buffer_end--;\n" + " }\n" ); /* Function: yy_mark_start */ outstream.Write("private bool yy_last_was_cr=false;\n" + "private void yy_mark_start ()\n" + " {\n"); if (spec.count_lines) { outstream.Write( " int i;\n" + " for (i = yy_buffer_start; i < yy_buffer_index; i++)\n" + " {\n" + " if (yy_buffer[i] == '\\n' && !yy_last_was_cr)\n" + " {\n" + " yyline++;\n" + " }\n" + " if (yy_buffer[i] == '\\r')\n" + " {\n" + " yyline++;\n" + " yy_last_was_cr=true;\n" + " }\n" + " else\n" + " {\n" + " yy_last_was_cr=false;\n" + " }\n" + " }\n" ); } if (spec.count_chars) { outstream.Write( " yychar = yychar + yy_buffer_index - yy_buffer_start;\n"); } outstream.Write( " yy_buffer_start = yy_buffer_index;\n" + " }\n"); /* Function: yy_mark_end */ outstream.Write( "private void yy_mark_end ()\n" + " {\n" + " yy_buffer_end = yy_buffer_index;\n" + " }\n"); /* Function: yy_to_mark */ outstream.Write( "private void yy_to_mark ()\n" + " {\n" + " yy_buffer_index = yy_buffer_end;\n" + " yy_at_bol = (yy_buffer_end > yy_buffer_start) &&\n" + " (yy_buffer[yy_buffer_end-1] == '\\r' ||\n" + " yy_buffer[yy_buffer_end-1] == '\\n');\n" + " }\n"); /* Function: yytext */ outstream.Write( "internal string yytext()\n" + " {\n" + " return (new string(yy_buffer,\n" + " yy_buffer_start,\n" + " yy_buffer_end - yy_buffer_start)\n" + " );\n" + " }\n"); /* Function: yylength */ outstream.Write( "private int yylength ()\n" + " {\n" + " return yy_buffer_end - yy_buffer_start;\n" + " }\n"); /* Function: yy_double */ outstream.Write( "private char[] yy_double (char[] buf)\n" + " {\n" + " int i;\n" + " char[] newbuf;\n" + " newbuf = new char[2*buf.Length];\n" + " for (i = 0; i < buf.Length; i++)\n" + " {\n" + " newbuf[i] = buf[i];\n" + " }\n" + " return newbuf;\n" + " }\n"); /* Function: yy_error */ outstream.Write( "private const int YY_E_INTERNAL = 0;\n" + "private const int YY_E_MATCH = 1;\n" + "private static string[] yy_error_string = new string[]\n" + " {\n" + " \"Error: Internal error.\\n\",\n" + " \"Error: Unmatched input.\\n\"\n" + " };\n"); outstream.Write( "private void yy_error (int code,bool fatal)\n" + " {\n" + " System.Console.Write(yy_error_string[code]);\n" + " if (fatal)\n" + " {\n" + " throw new System.ApplicationException(\"Fatal Error.\\n\");\n" + " }\n" + " }\n"); // /* Function: yy_next */ // outstream.Write("\tprivate int yy_next (int current,char lookahead) {\n" // + " return yy_nxt[yy_rmap[current],yy_cmap[lookahead]];\n" // + "\t}\n"); // /* Function: yy_accept */ // outstream.Write("\tprivate int yy_accept (int current) {\n"); // + " return yy_acpt[current];\n" // + "\t}\n"); } /* * Function: Header * Description: Emits class header. */ private void Header() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif outstream.Write("\n\n"); string spec_access = "internal "; if (spec.lex_public) spec_access = "public "; outstream.Write(spec_access + "class " + spec.class_name); if (spec.implements_name != null) { outstream.Write(" : "); outstream.Write(spec.implements_name); } outstream.Write("\n{\n"); } private void Accept_table() { int size = spec.accept_list.Count; int lastelem = size-1; StringBuilder sb = new StringBuilder(Lex.MAXSTR); sb.Append("private static int[] yy_acpt = new int[]\n {\n"); for (int elem = 0; elem < size; elem++) { sb.Append(" /* "); sb.Append(elem); sb.Append(" */ "); string s = " YY_NOT_ACCEPT"; // default to NOT Accept accept = (Accept) spec.accept_list[elem]; if (accept != null) { bool is_start = ((spec.anchor_array[elem] & Spec.START) != 0); bool is_end = ((spec.anchor_array[elem] & Spec.END) != 0); if (is_start && is_end) s = " YY_START | YY_END"; else if (is_start) s = " YY_START"; else if (is_end) s = " YY_END"; else s = " YY_NO_ANCHOR"; } sb.Append(s); if (elem < lastelem) sb.Append(","); sb.Append("\n"); } sb.Append(" };\n"); outstream.Write(sb.ToString()); } private void CMap_table() { // int size = spec.col_map.Length; int size = spec.ccls_map.Length; int lastelem = size-1; outstream.Write("private static int[] yy_cmap = new int[]\n {\n "); for (int i = 0; i < size; i++) { outstream.Write(spec.col_map[spec.ccls_map[i]]); if (i < lastelem) outstream.Write(","); if (((i + 1) % 8) == 0) outstream.Write("\n "); else outstream.Write(" "); } if (size%8 != 0) outstream.Write("\n "); outstream.Write("};\n"); } private void RMap_table() { int size = spec.row_map.Length; int lastelem = size-1; outstream.Write("private static int[] yy_rmap = new int[]\n {\n "); for (int i = 0; i < size; ++i) { outstream.Write(spec.row_map[i]); if (i < lastelem) outstream.Write(","); if (((i + 1) % 8) == 0) outstream.Write("\n "); else outstream.Write(" "); } if (size%8 != 0) outstream.Write("\n "); outstream.Write("};\n"); } private void YYNXT_table() { int size = spec.dtrans_list.Count; int lastelem = size-1; int lastcol = spec.dtrans_ncols-1; StringBuilder sb = new StringBuilder(Lex.MAXSTR); sb.Append("private static int[,] yy_nxt = new int[,]\n {\n"); for (int elem = 0; elem < size; elem++) { DTrans cdt_list = (DTrans) spec.dtrans_list[elem]; #if DEBUG Utility.assert( spec.dtrans_ncols <= cdt_list.GetDTransLength() ); #endif sb.Append(" { "); for (int i = 0; i < spec.dtrans_ncols; i++) { sb.Append(cdt_list.GetDTrans(i)); if (i < lastcol) { sb.Append(","); if (((i + 1) % 8) == 0) sb.Append("\n "); else sb.Append(" "); } } sb.Append(" }"); if (elem < lastelem) sb.Append(","); sb.Append("\n"); } sb.Append(" };\n"); outstream.Write(sb.ToString()); } /* * Function: Table * Description: Emits transition table. */ private void Table() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif Accept_table(); CMap_table(); RMap_table(); YYNXT_table(); } string EOF_Test() { StringBuilder sb = new StringBuilder(Lex.MAXSTR); if (spec.eof_code != null) sb.Append(" yy_do_eof();\n"); if (spec.integer_type) sb.Append(" return YYEOF;\n"); else if (null != spec.eof_value_code) sb.Append(spec.eof_value_code); else sb.Append(" return null;\n"); return sb.ToString(); } /* * Function: Driver * Description: */ private void Driver() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif Table(); string begin_str = ""; string state_str = ""; #if NOT_EDBG begin_str = " System.Console.WriteLine(\"Begin\");\n"; state_str = " System.Console.WriteLine(\"\\n\\nCurrent state: \" + yy_state);\n" + " System.Console.Write(\"Lookahead input: " + " (\" + yy_lookahead + \")\");\n" + " if (yy_lookahead < 32)\n" + " System.Console.WriteLine(" + " \"'^\" + System.Convert.ToChar(yy_lookahead+'A'-1).ToString() + \"'\");\n" + " else if (yy_lookahead > 127)\n" + " System.Console.WriteLine(" + " \"'^\" + yy_lookahead + \"'\");\n" + " else\n" + " System.Console.WriteLine(" + " \"'\" + yy_lookahead.ToString() + \"'\");\n" + " System.Console.WriteLine(\"State = \"+ yy_state);\n" + " System.Console.WriteLine(\"Accepting status = \"+ yy_this_accept);\n" + " System.Console.WriteLine(\"Last accepting state = \"+ yy_last_accept_state);\n" + " System.Console.WriteLine(\"Next state = \"+ yy_next_state);\n" ; #endif string hdr_str = ""; if (spec.integer_type) hdr_str = "public int " + spec.function_name + "()\n"; else if (spec.intwrap_type) hdr_str = "public Int32 " + spec.function_name + "()\n"; else hdr_str = "public " + spec.type_name + " " + spec.function_name + "()\n"; outstream.Write(hdr_str + " {\n" + " char yy_lookahead;\n" + " int yy_anchor = YY_NO_ANCHOR;\n" + " int yy_state = yy_state_dtrans[yy_lexical_state];\n" + " int yy_next_state = YY_NO_STATE;\n" + " int yy_last_accept_state = YY_NO_STATE;\n" + " bool yy_initial = true;\n" + " int yy_this_accept;\n" + "\n" + " yy_mark_start();\n" + " yy_this_accept = yy_acpt[yy_state];\n" + " if (YY_NOT_ACCEPT != yy_this_accept)\n" + " {\n" + " yy_last_accept_state = yy_state;\n" + " yy_mark_end();\n" + " }\n" + begin_str + " while (true)\n" + " {\n" + " if (yy_initial && yy_at_bol)\n" + " yy_lookahead = (char) YY_BOL;\n" + " else\n" + " {\n" + " yy_lookahead = yy_advance();\n" // + " yy_next_state = YY_F;\n" // + " if (YY_EOF != yy_lookahead)\n" + " }\n" + " yy_next_state = yy_nxt[yy_rmap[yy_state],yy_cmap[yy_lookahead]];\n" + state_str + " if (YY_EOF == yy_lookahead && yy_initial)\n" + " {\n" + EOF_Test() + " }\n" + " if (YY_F != yy_next_state)\n" + " {\n" + " yy_state = yy_next_state;\n" + " yy_initial = false;\n" + " yy_this_accept = yy_acpt[yy_state];\n" + " if (YY_NOT_ACCEPT != yy_this_accept)\n" + " {\n" + " yy_last_accept_state = yy_state;\n" + " yy_mark_end();\n" + " }\n" + " }\n" + " else\n" + " {\n" + " if (YY_NO_STATE == yy_last_accept_state)\n" + " {\n" + " throw new System.ApplicationException(\"Lexical Error: Unmatched Input.\");\n" + " }\n" + " else\n" + " {\n" + " yy_anchor = yy_acpt[yy_last_accept_state];\n" + " if (0 != (YY_END & yy_anchor))\n" + " {\n" + " yy_move_end();\n" + " }\n" + " yy_to_mark();\n" + " if (yy_last_accept_state < 0)\n" + " {\n" + " if (yy_last_accept_state < " + spec.accept_list.Count + ")\n" + " yy_error(YY_E_INTERNAL, false);\n" + " }\n" + " else\n" + " {\n" + " AcceptMethod m = accept_dispatch[yy_last_accept_state];\n" + " if (m != null)\n" + " {\n" + " "+spec.type_name+" tmp = m();\n" + " if (tmp != null)\n" + " return tmp;\n" + " }\n" + " }\n" + " yy_initial = true;\n" + " yy_state = yy_state_dtrans[yy_lexical_state];\n" + " yy_next_state = YY_NO_STATE;\n" + " yy_last_accept_state = YY_NO_STATE;\n" + " yy_mark_start();\n" + " yy_this_accept = yy_acpt[yy_state];\n" + " if (YY_NOT_ACCEPT != yy_this_accept)\n" + " {\n" + " yy_last_accept_state = yy_state;\n" + " yy_mark_end();\n" + " }\n" + " }\n" + " }\n" + " }\n" + " }\n"); } /* * Function: Actions * Description: */ private string Actions() { int size = spec.accept_list.Count; int bogus_index = -2; Accept accept; StringBuilder sb = new StringBuilder(Lex.MAXSTR); #if DEBUG Utility.assert(spec.accept_list.Count == spec.anchor_array.Length); #endif string prefix = ""; for (int elem = 0; elem < size; elem++) { accept = (Accept) spec.accept_list[elem]; if (accept != null) { sb.Append(" " + prefix + "if (yy_last_accept_state == "); sb.Append(elem); sb.Append(")\n"); sb.Append(" { // begin accept action #"); sb.Append(elem); sb.Append("\n"); sb.Append(accept.action); sb.Append("\n"); sb.Append(" } // end accept action #"); sb.Append(elem); sb.Append("\n"); sb.Append(" else if (yy_last_accept_state == "); sb.Append(bogus_index); sb.Append(")\n"); sb.Append(" { /* no work */ }\n"); prefix = "else "; bogus_index--; } } return sb.ToString(); } /* * Function: Action_Methods_Init */ private string Action_Methods_Init() { int size = spec.accept_list.Count; Accept accept; StringBuilder tbl = new StringBuilder(); #if DEBUG Utility.assert(spec.accept_list.Count == spec.anchor_array.Length); #endif tbl.Append("accept_dispatch = new AcceptMethod[] \n {\n"); for (int elem = 0; elem < size; elem++) { accept = (Accept) spec.accept_list[elem]; if (accept != null && accept.action != null) { tbl.Append(" new AcceptMethod(this.Accept_"); tbl.Append(elem); tbl.Append("),\n"); } else tbl.Append(" null,\n"); } tbl.Append(" };\n"); return tbl.ToString(); } /* * Function: Action_Methods_Body */ private string Action_Methods_Body() { int size = spec.accept_list.Count; Accept accept; StringBuilder sb = new StringBuilder(Lex.MAXSTR); #if DEBUG Utility.assert(spec.accept_list.Count == spec.anchor_array.Length); #endif for (int elem = 0; elem < size; elem++) { accept = (Accept) spec.accept_list[elem]; if (accept != null && accept.action != null) { sb.Append(spec.type_name+" Accept_"); sb.Append(elem); sb.Append("()\n"); sb.Append(" { // begin accept action #"); sb.Append(elem); sb.Append("\n"); sb.Append(accept.action); sb.Append("\n"); sb.Append(" } // end accept action #"); sb.Append(elem); sb.Append("\n\n"); } } return sb.ToString(); } /* * Function: Footer * Description: */ private void Footer() { #if DEBUG Utility.assert(null != spec); Utility.assert(null != outstream); #endif outstream.Write("}\n"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestCUInt16() { var test = new BooleanBinaryOpTest__TestCUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestCUInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int Op2ElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector128<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector128<UInt16> _fld1; private Vector128<UInt16> _fld2; private BooleanBinaryOpTest__DataTable<UInt16, UInt16> _dataTable; static BooleanBinaryOpTest__TestCUInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestCUInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<UInt16, UInt16>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestC( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestC( Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestC( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestC), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Sse41.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestCUInt16(); var result = Sse41.TestC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(UInt16[] left, UInt16[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((~left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestC)}<UInt16>(Vector128<UInt16>, Vector128<UInt16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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.AcceptanceTestsAzureParameterGrouping { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestParameterGroupingTestService : ServiceClient<AutoRestParameterGroupingTestService>, IAutoRestParameterGroupingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public 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> /// Gets the IParameterGroupingOperations. /// </summary> public virtual IParameterGroupingOperations ParameterGrouping { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestParameterGroupingTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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 AutoRestParameterGroupingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestParameterGroupingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestParameterGroupingTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestParameterGroupingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestParameterGroupingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestParameterGroupingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestParameterGroupingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestParameterGroupingTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.ParameterGrouping = new ParameterGroupingOperations(this); this.BaseUri = new Uri("https://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; namespace MGTK.Controls { public class TrackBar : Control { private TrackBarOrientation orientation; public int TickFrequency = 1; public TickStyle tickStyle = TickStyle.BottomRight; public int SmallChange = 1; public int LargeChange = 5; public int minimum = 0; public int maximum = 10; private int _value; private int sliderSize = 11; private int tickSize = 4; protected Button btnSlider; private bool mouseDown = false; private int sbPosWhenMouseDown = 0; private int mousePosWhenMouseDown = 0; private int valueWhenMouseDown = 0; private double TotalMilliseconds = 0; private int MsToNextIndex = 150; private double LastUpdateIndexChange; public int Value { get { return _value; } set { _value = value; CapValue(); SetSliderPosAccordingToValue(); if (ValueChanged != null) ValueChanged(this, new EventArgs()); } } public int Minimum { get { return minimum; } set { minimum = value; CapValue(); } } public int Maximum { get { return maximum; } set { maximum = value; CapValue(); } } public TrackBarOrientation Orientation { get { return orientation; } set { orientation = value; ConfigureSlider(); } } public TickStyle TickStyle { get { return tickStyle; } set { tickStyle = value; ConfigureSlider(); } } public int TickSize { get { return tickSize; } set { tickSize = value; ConfigureSlider(); } } public DrawTickRoutine AlternativeTickDraw; public event EventHandler ValueChanged; public TrackBar(Form formowner) : base(formowner) { btnSlider = new Button(formowner); btnSlider.Parent = this; btnSlider.MouseLeftPressed += new EventHandler(btnSlider_MouseLeftPressed); btnSlider.Frame = btnSlider.FramePressed = Theme.SliderButtonFrame; btnSlider.KeyDown += new ControlKeyEventHandler(TrackBar_KeyDown); Controls.Add(btnSlider); this.WidthChanged += new EventHandler(TrackBar_SizeChanged); this.HeightChanged += new EventHandler(TrackBar_SizeChanged); this.KeyDown += new ControlKeyEventHandler(TrackBar_KeyDown); this.MouseLeftDown += new EventHandler(TrackBar_MouseLeftDown); ConfigureSlider(); } int ChangeValueMouseDown; bool mouseDownLargeChange = false; void TrackBar_MouseLeftDown(object sender, EventArgs e) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { if (!mouseDownLargeChange) { if (Orientation == TrackBarOrientation.Horizontal) { if (WindowManager.MouseX < OwnerX + X + btnSlider.X) ChangeValueMouseDown = -LargeChange; else if (WindowManager.MouseX > OwnerX + X + btnSlider.X + btnSlider.Width) ChangeValueMouseDown = LargeChange; } else if (Orientation == TrackBarOrientation.Vertical) { if (WindowManager.MouseY < OwnerY + Y + btnSlider.Y) ChangeValueMouseDown = LargeChange; else if (WindowManager.MouseY > OwnerY + Y + btnSlider.Y + btnSlider.Height) ChangeValueMouseDown = -LargeChange; } mouseDownLargeChange = true; } if (Orientation == TrackBarOrientation.Horizontal) { if (WindowManager.MouseX < OwnerX + X + btnSlider.X && ChangeValueMouseDown < 0) Value += ChangeValueMouseDown; else if (WindowManager.MouseX > OwnerX + X + btnSlider.X + btnSlider.Width && ChangeValueMouseDown > 0) Value += ChangeValueMouseDown; } else if (Orientation == TrackBarOrientation.Vertical) { if (WindowManager.MouseY < OwnerY + Y + btnSlider.Y && ChangeValueMouseDown > 0) Value += ChangeValueMouseDown; else if (WindowManager.MouseY > OwnerY + Y + btnSlider.Y + btnSlider.Height && ChangeValueMouseDown < 0) Value += ChangeValueMouseDown; } LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } void TrackBar_KeyDown(object sender, ControlKeyEventArgs e) { if (gameTime.TotalGameTime.TotalMilliseconds - LastUpdateIndexChange > MsToNextIndex) { if ((e.Key == Keys.Down && Orientation == TrackBarOrientation.Vertical) || (e.Key == Keys.Up && Orientation == TrackBarOrientation.Horizontal) || e.Key == Keys.Left) Value--; else if ((e.Key == Keys.Up && Orientation == TrackBarOrientation.Vertical) || (e.Key == Keys.Down && Orientation == TrackBarOrientation.Horizontal) || e.Key == Keys.Right) Value++; else if (e.Key == Keys.PageDown && Orientation == TrackBarOrientation.Vertical) Value -= LargeChange; else if (e.Key == Keys.PageUp && Orientation == TrackBarOrientation.Vertical) Value += LargeChange; else if (e.Key == Keys.PageDown && Orientation == TrackBarOrientation.Horizontal) Value += LargeChange; else if (e.Key == Keys.PageUp && Orientation == TrackBarOrientation.Horizontal) Value -= LargeChange; LastUpdateIndexChange = gameTime.TotalGameTime.TotalMilliseconds; } } void TrackBar_SizeChanged(object sender, EventArgs e) { ConfigureSlider(); } private void CapValue() { if (Value < minimum) Value = minimum; if (Value > maximum) Value = maximum; } void btnSlider_MouseLeftPressed(object sender, EventArgs e) { if (!mouseDown) { sbPosWhenMouseDown = GetTickPos(Value - Minimum); mousePosWhenMouseDown = GetWindowManagerMousePos(); valueWhenMouseDown = Value; mouseDown = true; } } public override void Update() { TotalMilliseconds = gameTime.TotalGameTime.TotalMilliseconds; if (!WindowManager.MouseLeftPressed) { mouseDown = false; mouseDownLargeChange = false; } if (mouseDown) { int mSub; if (Orientation == TrackBarOrientation.Horizontal) mSub = GetWindowManagerMousePos() - mousePosWhenMouseDown; else mSub = mousePosWhenMouseDown - GetWindowManagerMousePos(); Value = (int)(valueWhenMouseDown + (mSub + sliderSize / 2) / GetTickIntervalSize()); } base.Update(); } public override void Draw() { btnSlider.Z = Z - 0.001f; if (TickStyle != TickStyle.None) { for (int i = 0; i < Maximum - Minimum + 1; i++) { DrawTick(i); } } if (Orientation == TrackBarOrientation.Horizontal) DrawingService.DrawFrame(SpriteBatchProvider, Theme.SliderBarFrame, OwnerX + X, OwnerY + Y + Height / 2 - 2, Width, 4, Z - 0.000001f); else DrawingService.DrawFrame(SpriteBatchProvider, Theme.SliderBarFrame, OwnerX + X + Width / 2 - 2, OwnerY + Y, 4, Height, Z - 0.000001f); base.Draw(); } protected void DrawTick(int i) { if (AlternativeTickDraw != null) { AlternativeTickDraw(i); return; } int tX = 0, tY = 0; int tW = 0, tH = 0; if (TickStyle == TickStyle.BottomRight || TickStyle == TickStyle.Both) { if (Orientation == TrackBarOrientation.Horizontal) { tX = GetTickPos(i); tY = Height - TickSize; tW = 1; tH = TickSize; } else { tX = Width - TickSize; tY = GetTickPos(i); tW = TickSize; tH = 1; } DrawingService.DrawRectangle(SpriteBatchProvider, Theme.Dot, ForeColor, OwnerX + X + tX, OwnerY + Y + tY, tW, tH, Z - 0.00001f); } if (TickStyle == TickStyle.TopLeft || TickStyle == TickStyle.Both) { if (Orientation == TrackBarOrientation.Horizontal) { tX = GetTickPos(i); tY = 0; tW = 1; tH = TickSize; } else { tX = 0; tY = GetTickPos(i); tW = TickSize; tH = 1; } DrawingService.DrawRectangle(SpriteBatchProvider, Theme.Dot, ForeColor, OwnerX + X + tX, OwnerY + Y + tY, tW, tH, Z - 0.00001f); } } private void ConfigureSlider() { btnSlider.X = 0; btnSlider.Y = 0; if (Orientation == TrackBarOrientation.Horizontal) { btnSlider.Width = sliderSize; if (TickStyle == TickStyle.None) btnSlider.Height = Height; else if (TickStyle == TickStyle.BottomRight || TickStyle == TickStyle.TopLeft) btnSlider.Height = Height - TickSize - 1; else if (TickStyle == TickStyle.Both) { btnSlider.Y = TickSize + 1; btnSlider.Height = Height - TickSize * 2 - 2; } if (TickStyle == TickStyle.TopLeft) btnSlider.Y = TickSize + 1; } else { btnSlider.Height = sliderSize; if (TickStyle == TickStyle.None) btnSlider.Width = Width; else if (TickStyle == TickStyle.BottomRight || TickStyle == TickStyle.TopLeft) btnSlider.Width = Width - TickSize - 1; else if (TickStyle == TickStyle.Both) { btnSlider.X = TickSize + 1; btnSlider.Width = Width - TickSize * 2 - 2; } if (TickStyle == TickStyle.TopLeft) btnSlider.X = TickSize + 1; } SetSliderPosAccordingToValue(); } private void SetSliderPosAccordingToValue() { if (Orientation == TrackBarOrientation.Horizontal) btnSlider.X = GetTickPos(Value - Minimum) - btnSlider.Width / 2; else btnSlider.Y = Height - GetTickPos(Value - Minimum) + btnSlider.Height / 2 - (Height - (Maximum - Minimum) * GetTickIntervalSize()); } private int GetTickIntervalSize() { int tIS = (int)((GetControlSize() - sliderSize) / (decimal)(Maximum - Minimum)); if (tIS <= 0) tIS = 1; return tIS; } private int GetControlSize() { if (Orientation == TrackBarOrientation.Horizontal) return Width; return Height; } private int GetWindowManagerMousePos() { if (Orientation == TrackBarOrientation.Horizontal) return WindowManager.MouseX; return WindowManager.MouseY; } private int GetTickPos(int position) { return GetTickIntervalSize() * position + sliderSize / 2; } } public delegate void DrawTickRoutine(int i); public enum TrackBarOrientation { Horizontal = 0, Vertical = 1 } public enum TickStyle { None = 0, TopLeft = 1, BottomRight = 2, Both = 3 } }
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.ContextMenus; using Server.Targeting; using Server.Network; namespace Server.Items { public enum BagOfSendingHue { Yellow, Blue, Red } public class BagOfSending : Item, TranslocationItem { public static BagOfSendingHue RandomHue() { switch ( Utility.Random( 3 ) ) { case 0: return BagOfSendingHue.Yellow; case 1: return BagOfSendingHue.Blue; default: return BagOfSendingHue.Red; } } private int m_Charges; private int m_Recharges; private BagOfSendingHue m_BagOfSendingHue; [CommandProperty( AccessLevel.GameMaster )] public int Charges { get{ return m_Charges; } set { if ( value > this.MaxCharges ) m_Charges = this.MaxCharges; else if ( value < 0 ) m_Charges = 0; else m_Charges = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public int Recharges { get{ return m_Recharges; } set { if ( value > this.MaxRecharges ) m_Recharges = this.MaxRecharges; else if ( value < 0 ) m_Recharges = 0; else m_Recharges = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public int MaxCharges{ get{ return 30; } } [CommandProperty( AccessLevel.GameMaster )] public int MaxRecharges{ get{ return 255; } } public string TranslocationItemName{ get{ return "bag of sending"; } } public override int LabelNumber{ get{ return 1054104; } } // a bag of sending [CommandProperty( AccessLevel.GameMaster )] public BagOfSendingHue BagOfSendingHue { get{ return m_BagOfSendingHue; } set { m_BagOfSendingHue = value; switch ( value ) { case BagOfSendingHue.Yellow: this.Hue = 0x8A5; break; case BagOfSendingHue.Blue: this.Hue = 0x8AD; break; case BagOfSendingHue.Red: this.Hue = 0x89B; break; } } } [Constructable] public BagOfSending() : this( RandomHue() ) { } [Constructable] public BagOfSending( BagOfSendingHue hue ) : base( 0xE76 ) { Weight = 2.0; this.BagOfSendingHue = hue; m_Charges = Utility.RandomMinMax( 3, 9 ); } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); list.Add( 1060741, m_Charges.ToString() ); // charges: ~1_val~ } public override void OnSingleClick( Mobile from ) { base.OnSingleClick( from ); LabelTo( from, 1060741, m_Charges.ToString() ); // charges: ~1_val~ } public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list ) { base.GetContextMenuEntries( from, list ); if ( from.Alive ) list.Add( new UseBagEntry( this, Charges > 0 && IsChildOf( from.Backpack ) ) ); } private class UseBagEntry : ContextMenuEntry { private BagOfSending m_Bag; public UseBagEntry( BagOfSending bag, bool enabled ) : base( 6189 ) { m_Bag = bag; if ( !enabled ) Flags |= CMEFlags.Disabled; } public override void OnClick() { if ( m_Bag.Deleted ) return; Mobile from = Owner.From; if ( from.CheckAlive() ) m_Bag.OnDoubleClick( from ); } } public override void OnDoubleClick( Mobile from ) { if( from.Region.IsPartOf( typeof( Regions.Jail ) ) ) { from.SendMessage( "You may not do that in jail." ); } else if( !this.IsChildOf( from.Backpack ) ) { MessageHelper.SendLocalizedMessageTo(this, from, 1062334, 0x59); // The bag of sending must be in your backpack. } else if( this.Charges == 0 ) { MessageHelper.SendLocalizedMessageTo( this, from, 1042544, 0x59 ); // This item is out of charges. } else { from.Target = new SendTarget( this ); } } private class SendTarget : Target { private BagOfSending m_Bag; public SendTarget( BagOfSending bag ) : base( -1, false, TargetFlags.None ) { m_Bag = bag; } protected override void OnTarget( Mobile from, object targeted ) { if ( m_Bag.Deleted ) return; if( from.Region.IsPartOf( typeof( Regions.Jail ) ) ) { from.SendMessage( "You may not do that in jail." ); } else if( !m_Bag.IsChildOf( from.Backpack ) ) { MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1054107, 0x59 ); // The bag of sending must be in your backpack. } else if ( m_Bag.Charges == 0 ) { MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1042544, 0x59 ); // This item is out of charges. } else if ( targeted is Item ) { Item item = (Item)targeted; int reqCharges = (int)Math.Max( 1, Math.Ceiling( item.TotalWeight / 10.0 ) ); if ( !item.IsChildOf( from.Backpack ) ) { MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1054152, 0x59 ); // You may only send items from your backpack to your bank box. } else if ( item is BagOfSending || item is Container ) { from.Send( new AsciiMessage( m_Bag.Serial, m_Bag.ItemID, MessageType.Regular, 0x3B2, 3, "", "You cannot send a container through the bag of sending." ) ); } else if ( item.LootType == LootType.Cursed ) { MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1054108, 0x59 ); // The bag of sending rejects the cursed item. } else if (!item.VerifyMove(from) || item is Server.Engines.Quests.QuestItem || item.Nontransferable) { MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1054109, 0x59 ); // The bag of sending rejects that item. } else if ( Spells.SpellHelper.IsDoomGauntlet( from.Map, from.Location ) ) { from.SendLocalizedMessage( 1062089 ); // You cannot use that here. } else if ( !from.BankBox.TryDropItem( from, item, false ) ) { MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1054110, 0x59 ); // Your bank box is full. } else if ( Core.ML && reqCharges > m_Bag.Charges ) { from.SendLocalizedMessage( 1079932 ); //You don't have enough charges to send that much weight } else { m_Bag.Charges -= (Core.ML ? reqCharges : 1); MessageHelper.SendLocalizedMessageTo( m_Bag, from, 1054150, 0x59 ); // The item was placed in your bank box. } } } } public BagOfSending( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( (int) 1 ); // version writer.WriteEncodedInt( (int) m_Recharges ); writer.WriteEncodedInt( (int) m_Charges ); writer.WriteEncodedInt( (int) m_BagOfSendingHue ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); switch ( version ) { case 1: { m_Recharges = reader.ReadEncodedInt(); goto case 0; } case 0: { m_Charges = Math.Min( reader.ReadEncodedInt(), MaxCharges ); m_BagOfSendingHue = (BagOfSendingHue) reader.ReadEncodedInt(); break; } } } } }
using System; using HappyGB.Core.Cpu; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace HappyGB.Core.Graphics { public class GraphicsController { private bool lcdcEqual, lcdcOamAccess, lcdcVblank, lcdcHblank; private const int SCANLINE_INTERVAL = 456; private byte[] vram; private byte[] oam; private int scanline; private int clock; public enum LCDState : byte { HBlank = 0x00, VBlank = 0x01, OamAccess = 0x02, LCDCopy = 0x03 } private LCDState state; //FIXME: Should be private; Hack to make VramViewer work. public GbPalette obp0, obp1, bgp; private ISurface buffer; public ISurface Surface { get { return buffer; } } //TODO: Registers. /// <summary> /// The LCD Control register. /// </summary> public byte LCDC { get; set; } /// <summary> /// The LCD Status register. /// </summary> public byte STAT { get { int res = 0; res |= lcdcEqual ? 0x40 : 0x00; res |= lcdcOamAccess ? 0x20 : 0x00; res |= lcdcVblank ? 0x10 : 0x00; res |= lcdcHblank ? 0x08 : 0x00; res |= (LY == LYC) ? 0x04 : 0x00; res |= (byte)state; return (byte)(res & 0xFF); } set { lcdcEqual = ((value & 0x40) == 0x40); lcdcOamAccess = ((value & 0x20) == 0x20); lcdcVblank = ((value & 0x10) == 0x10); lcdcHblank = ((value & 0x08) == 0x08); } } private const short SCREEN_WIDTH = 160; private const short TILEMAP_SIZE = 32; private const short TILE_PX = 8; private const int HBLANK_CYCLES = 207; private const int VBLANK_CYCLES = 4560; private const int OAM_CYCLES = 83; private const int LCDCOPY_CYCLES = 175; /// <summary> /// Y Scroll amount memory-mapped register. /// </summary> public byte SCY { get; set; } /// <summary> /// X Scroll amount memory-mapped register. /// </summary> public byte SCX { get; set; } /// <summary> /// Memory-mapped register with the current scanline. /// </summary> public byte LY { get { return (byte)scanline; } set { scanline = 0; } //FIXME: Should this actually do that? That'll f things up! } /// <summary> /// The LYC memory-mapped register. /// This is used for the LY=LYC Coincidence LCDC interrupt. /// </summary> public byte LYC { get; set; } //Palettes: Update the SurfaceBlitter. public byte BGP { get { return bgp.RegisterValue; } set { bgp.RegisterValue = value; } } public byte OBP0 { get { return obp0.RegisterValue; } set { obp0.RegisterValue = value; } } public byte OBP1 { get { return obp1.RegisterValue; } set { obp1.RegisterValue = value; } } public byte WY { get; set; } public byte WX { get; set; } public GraphicsController() { buffer = new ScreenSurface(); state = LCDState.OamAccess; clock = scanline = 0; lcdcHblank = lcdcOamAccess = lcdcEqual = lcdcVblank = false; vram = new byte[0x2000]; oam = new byte[0xA0]; bgp = new GbPalette(false); obp0 = new GbPalette(true); obp1 = new GbPalette(true); } /// <summary> /// Updates the graphics controller with the given clock. /// </summary> public InterruptType Update(int ticks) { clock += ticks; switch (state) { case LCDState.HBlank: //Mode 0 //Are we done with this one yet? if (clock > HBLANK_CYCLES) { if (scanline >= 144) //Should switch to VBlank. { clock = 0; state = LCDState.VBlank; //Raise the VBlank interrupt if enabled. if (lcdcVblank) return InterruptType.VBlank | InterruptType.LCDController; else return InterruptType.VBlank; } else { clock = 0; state = LCDState.OamAccess; scanline++; if (lcdcOamAccess) return InterruptType.LCDController; } } break; case LCDState.OamAccess: //Mode 2 if (clock > OAM_CYCLES) //Switch to LCD Copy. { clock = 0; state = LCDState.LCDCopy; //Also raise the LCDC interrupt if we have one and it's enabled. if ((LY == LYC) && (lcdcEqual)) { return InterruptType.LCDController; } } break; case LCDState.LCDCopy: //Mode 3 if (clock > LCDCOPY_CYCLES) //Switch to HBlank { clock = 0; state = LCDState.HBlank; if(scanline < 144) WriteScanline(); //Also raise the HBlank interrupt if it's enabled. if (lcdcHblank) return InterruptType.LCDController; } break; case LCDState.VBlank: //Mode 1 scanline = (144 + (clock / SCANLINE_INTERVAL)); if (clock > VBLANK_CYCLES) { clock = 0; scanline = 0; state = LCDState.OamAccess; if (lcdcOamAccess) return InterruptType.LCDController; } break; } //No interrupt! return InterruptType.None; } public byte ReadOAM8(ushort address) { return oam[address - 0xFE00]; } public void WriteOAM8(ushort address, byte value) { oam[address - 0xFE00] = value; } public byte ReadVRAM8(ushort address) { return vram[address - 0x8000]; } public void WriteVRAM8(ushort address, byte value) { vram[address - 0x8000] = value; } /// <summary> /// Writes one full scanline to the back buffer. /// </summary> private unsafe void WriteScanline() { ushort backAddrBase = ((LCDC & 0x08) == 0x08) ? (ushort)0x9C00 : (ushort)0x9800; ushort windAddrBase = ((LCDC & 0x40) == 0x40) ? (ushort)0x9C00 : (ushort)0x9800; ushort tileDataBase = ((LCDC & 0x10) == 0x10) ? (ushort)0x8000 : (ushort)0x8800; bool signedTileData = backAddrBase == 0x8000; bool windowEnabled = ((LCDC & 0x20) == 0x20); //Get the start of the first tile in the scanline rel to screen. int xscan = -(SCX % TILE_PX); //Compute these before. int bTileRow = ((SCY + scanline) / TILE_PX) % TILEMAP_SIZE; int bTileColBase = ((SCX + xscan) / TILE_PX) % TILEMAP_SIZE; int bTileOffset = backAddrBase + (bTileRow * TILEMAP_SIZE) + bTileColBase; for (int i = 0; i < 21; i++) //# of tiles in window + 1. We have to account for edges. { //get the tile at the x,y. //Do BG first. ushort dataOffsetAddr = 0; if (!signedTileData) { byte tileNumber = ReadVRAM8((ushort)(bTileOffset + i)); dataOffsetAddr = (ushort)(tileDataBase + 16*tileNumber); } else { sbyte tileNumber = unchecked((sbyte)ReadVRAM8((ushort)(bTileOffset + i))); dataOffsetAddr = (ushort)(tileDataBase + 16*tileNumber); } //Add scanline to tile offset so we get the correct tile scanline. ushort tileDataOffset = (ushort)((2 * (scanline + SCY)) % (TILE_PX * 2)); dataOffsetAddr += tileDataOffset; byte tileHi = ReadVRAM8(dataOffsetAddr); byte tileLo = ReadVRAM8((ushort)(dataOffsetAddr + 1)); //draw that tile to the buffer. DrawTileScan(bgp, tileHi, tileLo, xscan, scanline); //Now draw window //now draw sprites. xscan += TILE_PX; } } private void DrawTileScan(GbPalette pal, byte tileHigh, byte tileLow, int x, int y) { //Put both in the same int so we only have to shift once per thing. int bit = (tileHigh << 8) + tileLow; int absOffset = (y * SCREEN_WIDTH) + x; //Draw 8 pixels. for (int pixOffset = 0; pixOffset < 8; pixOffset++) { //Don't draw off the screen. if (x + pixOffset < 0) continue; if (x + pixOffset >= SCREEN_WIDTH) continue; //Get the color from the tile's data. byte paletteColor = 0; if ((bit & 0x8000) == 0x8000) paletteColor |= 0x02; if ((bit & 0x80) == 0x80) paletteColor |= 0x01; var systemColor = pal.GetColor(paletteColor); var c = new Color(systemColor.R, systemColor.G, systemColor.B, systemColor.A); //Draw to the thing. Surface.Buffer[(absOffset + pixOffset)] = c; bit = bit << 1; } } } }
// // PlayerEngine.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Runtime.InteropServices; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Data; using Banshee.Base; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Preferences; namespace Banshee.GStreamer { internal enum GstState { VoidPending = 0, Null = 1, Ready = 2, Paused = 3, Playing = 4 } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerEosCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerErrorCallback (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerStateChangedCallback (IntPtr player, GstState old_state, GstState new_state, GstState pending_state); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerBufferingCallback (IntPtr player, int buffering_progress); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerVisDataCallback (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerNextTrackStartingCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerAboutToFinishCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr VideoPipelineSetupHandler (IntPtr player, IntPtr bus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void VideoPrepareWindowHandler (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerVolumeChangedCallback (IntPtr player, double newVolume); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void GstTaggerTagFoundCallback (IntPtr player, string tagName, ref GLib.Value value); public class PlayerEngine : Banshee.MediaEngine.PlayerEngine, IEqualizer, IVisualizationDataSource, ISupportClutter { internal static string reserved1 = Catalog.GetString ("Enable _gapless playback"); internal static string reserved2 = Catalog.GetString ("Eliminate the small playback gap on track change. Useful for concept albums and classical music"); private uint GST_CORE_ERROR = 0; private uint GST_LIBRARY_ERROR = 0; private uint GST_RESOURCE_ERROR = 0; private uint GST_STREAM_ERROR = 0; private HandleRef handle; private bool is_initialized; private BansheePlayerEosCallback eos_callback; private BansheePlayerErrorCallback error_callback; private BansheePlayerStateChangedCallback state_changed_callback; private BansheePlayerBufferingCallback buffering_callback; private BansheePlayerVisDataCallback vis_data_callback; private VideoPipelineSetupHandler video_pipeline_setup_callback; private VideoPrepareWindowHandler video_prepare_window_callback; private GstTaggerTagFoundCallback tag_found_callback; private BansheePlayerNextTrackStartingCallback next_track_starting_callback; private BansheePlayerAboutToFinishCallback about_to_finish_callback; private BansheePlayerVolumeChangedCallback volume_changed_callback; private bool next_track_pending; private SafeUri pending_uri; private bool buffering_finished; private bool xid_is_set = false; private uint iterate_timeout_id = 0; private bool gapless_enabled; private EventWaitHandle next_track_set; private event VisualizationDataHandler data_available = null; public event VisualizationDataHandler DataAvailable { add { if (value == null) { return; } else if (data_available == null) { bp_set_vis_data_callback (handle, vis_data_callback); } data_available += value; } remove { if (value == null) { return; } data_available -= value; if (data_available == null) { bp_set_vis_data_callback (handle, null); } } } protected override bool DelayedInitialize { get { return true; } } public PlayerEngine () { IntPtr ptr = bp_new (); if (ptr == IntPtr.Zero) { throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library")); } handle = new HandleRef (this, ptr); bp_get_error_quarks (out GST_CORE_ERROR, out GST_LIBRARY_ERROR, out GST_RESOURCE_ERROR, out GST_STREAM_ERROR); eos_callback = new BansheePlayerEosCallback (OnEos); error_callback = new BansheePlayerErrorCallback (OnError); state_changed_callback = new BansheePlayerStateChangedCallback (OnStateChange); buffering_callback = new BansheePlayerBufferingCallback (OnBuffering); vis_data_callback = new BansheePlayerVisDataCallback (OnVisualizationData); video_pipeline_setup_callback = new VideoPipelineSetupHandler (OnVideoPipelineSetup); video_prepare_window_callback = new VideoPrepareWindowHandler (OnVideoPrepareWindow); tag_found_callback = new GstTaggerTagFoundCallback (OnTagFound); next_track_starting_callback = new BansheePlayerNextTrackStartingCallback (OnNextTrackStarting); about_to_finish_callback = new BansheePlayerAboutToFinishCallback (OnAboutToFinish); volume_changed_callback = new BansheePlayerVolumeChangedCallback (OnVolumeChanged); bp_set_eos_callback (handle, eos_callback); bp_set_error_callback (handle, error_callback); bp_set_state_changed_callback (handle, state_changed_callback); bp_set_buffering_callback (handle, buffering_callback); bp_set_tag_found_callback (handle, tag_found_callback); bp_set_next_track_starting_callback (handle, next_track_starting_callback); bp_set_video_pipeline_setup_callback (handle, video_pipeline_setup_callback); bp_set_video_prepare_window_callback (handle, video_prepare_window_callback); bp_set_volume_changed_callback (handle, volume_changed_callback); next_track_set = new EventWaitHandle (false, EventResetMode.ManualReset); } protected override void Initialize () { if (ServiceManager.Get<Banshee.GStreamer.Service> () == null) { var service = new Banshee.GStreamer.Service (); ((IExtensionService)service).Initialize (); } if (!bp_initialize_pipeline (handle)) { bp_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library")); } OnStateChanged (PlayerState.Ready); InstallPreferences (); ReplayGainEnabled = ReplayGainEnabledSchema.Get (); GaplessEnabled = GaplessEnabledSchema.Get (); is_initialized = true; if (!bp_audiosink_has_volume (handle)) { Volume = (ushort)PlayerEngineService.VolumeSchema.Get (); } } public override void Dispose () { UninstallPreferences (); base.Dispose (); bp_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); is_initialized = false; } public override void Close (bool fullShutdown) { bp_stop (handle, fullShutdown); base.Close (fullShutdown); } protected override void OpenUri (SafeUri uri) { // The GStreamer engine can use the XID of the main window if it ever // needs to bring up the plugin installer so it can be transient to // the main window. if (!xid_is_set) { var service = ServiceManager.Get ("GtkElementsService") as IPropertyStoreExpose; if (service != null) { bp_set_application_gdk_window (handle, service.PropertyStore.Get<IntPtr> ("PrimaryWindow.RawHandle")); } xid_is_set = true; } IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri); try { if (!bp_open (handle, uri_ptr)) { throw new ApplicationException ("Could not open resource"); } else { Log.WarningFormat ("Opened {0}", uri.AbsoluteUri); } } finally { GLib.Marshaller.Free (uri_ptr); } } public override void Play () { Log.Warning ("bp_Playing"); bp_play (handle); } public override void Pause () { bp_pause (handle); } public override void SetNextTrackUri (SafeUri uri) { next_track_pending = false; if (next_track_set.WaitOne (0, false)) { // We're not waiting for the next track to be set. // This means that we've missed the window for gapless. // Save this URI to be played when we receive EOS. pending_uri = uri; return; } // If there isn't a next track for us, release the block on the about-to-finish callback. if (uri == null) { next_track_set.Set (); return; } IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri); try { bp_set_next_track (handle, uri_ptr); } finally { GLib.Marshaller.Free (uri_ptr); next_track_set.Set (); } } public override void VideoExpose (IntPtr window, bool direct) { bp_video_window_expose (handle, window, direct); } public override void VideoWindowRealize (IntPtr window) { bp_video_window_realize (handle, window); } public override IntPtr [] GetBaseElements () { IntPtr [] elements = new IntPtr[3]; if (bp_get_pipeline_elements (handle, out elements[0], out elements[1], out elements[2])) { return elements; } return null; } private void OnEos (IntPtr player) { Close (false); OnEventChanged (PlayerEvent.EndOfStream); if (!next_track_pending) { OnEventChanged (PlayerEvent.RequestNextTrack); } else if (pending_uri != null) { Log.Warning ("[Gapless] EOS signalled while waiting for next track. This means that Banshee " + "was too slow at calculating what track to play next. " + "If this happens frequently, please file a bug"); OnStateChanged (PlayerState.Loading); OpenUri (pending_uri); Play (); pending_uri = null; } else { // This should be unreachable - the RequestNextTrack event is delegated to the main thread // and so blocks the bus callback from delivering the EOS message. // // Playback should continue as normal from here, when the RequestNextTrack message gets handled. Log.Warning ("[Gapless] EndOfStream message received before the next track has been set. " + "If this happens frequently, please file a bug"); } } private bool OnIterate () { // Actual iteration. OnEventChanged (PlayerEvent.Iterate); // Run forever until we are stopped return true; } private void StartIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); } iterate_timeout_id = GLib.Timeout.Add (200, OnIterate); } private void StopIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); } } private void OnNextTrackStarting (IntPtr player) { if (GaplessEnabled) { // Must do it here because the next track is already playing. ServiceManager.PlayerEngine.IncrementLastPlayed (1.0); OnEventChanged (PlayerEvent.EndOfStream); OnEventChanged (PlayerEvent.StartOfStream); } } private void OnAboutToFinish (IntPtr player) { // This is needed to make Shuffle-by-* work. // Shuffle-by-* uses the LastPlayed field to determine what track in the grouping to play next. // Therefore, we need to update this before requesting the next track. // // This will be overridden by IncrementLastPlayed () called by // PlaybackControllerService's EndOfStream handler. CurrentTrack.UpdateLastPlayed (); next_track_set.Reset (); pending_uri = null; next_track_pending = true; OnEventChanged (PlayerEvent.RequestNextTrack); // Gapless playback with Playbin2 requires that the about-to-finish callback does not return until // the next uri has been set. Block here for a second or until the RequestNextTrack event has // finished triggering. if (!next_track_set.WaitOne (1000, false)) { Log.Debug ("[Gapless] Timed out while waiting for next_track_set to be raised"); next_track_set.Set (); } } private void OnStateChange (IntPtr player, GstState old_state, GstState new_state, GstState pending_state) { Log.Warning ("OnStateChange"); Log.WarningFormat ("old state is {0}", Enum.GetName (typeof (GstState), old_state)); Log.WarningFormat ("new state is {0}", Enum.GetName (typeof (GstState), new_state)); Log.WarningFormat ("pending state is {0}", Enum.GetName (typeof (GstState), pending_state)); Log.WarningFormat ("current state is {0}", Enum.GetName (typeof (GstState), CurrentState)); // old = Null // new = Ready // pending = Playing // Start by clearing any timeout we might have StopIterating (); if (CurrentState != PlayerState.Loaded && old_state == GstState.Ready && new_state == GstState.Paused && pending_state == GstState.Playing) { Log.Warning ("1"); if (ready_timeout != 0) { Log.Warning ("1a"); Application.IdleTimeoutRemove (ready_timeout); ready_timeout = 0; } OnStateChanged (PlayerState.Loaded); return; } else if (old_state == GstState.Paused && new_state == GstState.Playing && pending_state == GstState.VoidPending) { Log.Warning ("2"); if (CurrentState == PlayerState.Loaded) { Log.Warning ("2a"); OnEventChanged (PlayerEvent.StartOfStream); } OnStateChanged (PlayerState.Playing); // Start iterating only when going to playing StartIterating (); return; } else if (CurrentState == PlayerState.Playing && old_state == GstState.Playing && new_state == GstState.Paused) { Log.Warning ("3"); OnStateChanged (PlayerState.Paused); return; } else if (new_state == GstState.Ready && pending_state == GstState.Playing) { Log.Warning ("4"); if (ready_timeout == 0) { Log.Warning ("4a"); ready_timeout = Application.RunTimeout (1000, OnReadyTimeout); } return; } Log.Warning ("5: none of the above"); } private uint ready_timeout; private bool OnReadyTimeout () { ready_timeout = 0; var uri = CurrentUri; if (CurrentState == PlayerState.Loading && uri != null && uri.IsLocalPath) { // This is a dirty workaround. I was seeing the playback get stuck on track transition, // about one in 20 songs, where it would load the new track's duration, but be stuck at 0:00, // but if I moved the seek slider it would unstick it, hence setting Position... Log.WarningFormat ("Seem to be stuck loading {0}, so re-trying", uri); Position = 0; } return false; } private void OnError (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug) { Close (true); string error_message = error == IntPtr.Zero ? Catalog.GetString ("Unknown Error") : GLib.Marshaller.Utf8PtrToString (error); if (domain == GST_RESOURCE_ERROR) { GstResourceError domain_code = (GstResourceError) code; if (CurrentTrack != null) { switch (domain_code) { case GstResourceError.NotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.ResourceNotFound); break; default: break; } } Log.Error (String.Format ("GStreamer resource error: {0}", domain_code), false); } else if (domain == GST_STREAM_ERROR) { GstStreamError domain_code = (GstStreamError) code; if (CurrentTrack != null) { switch (domain_code) { case GstStreamError.CodecNotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } Log.Error (String.Format("GStreamer stream error: {0}", domain_code), false); } else if (domain == GST_CORE_ERROR) { GstCoreError domain_code = (GstCoreError) code; if (CurrentTrack != null) { switch (domain_code) { case GstCoreError.MissingPlugin: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } if (domain_code != GstCoreError.MissingPlugin) { Log.Error (String.Format("GStreamer core error: {0}", (GstCoreError) code), false); } } else if (domain == GST_LIBRARY_ERROR) { Log.Error (String.Format("GStreamer library error: {0}", (GstLibraryError) code), false); } OnEventChanged (new PlayerEventErrorArgs (error_message)); } private void OnBuffering (IntPtr player, int progress) { if (buffering_finished && progress >= 100) { return; } buffering_finished = progress >= 100; OnEventChanged (new PlayerEventBufferingArgs ((double) progress / 100.0)); } private void OnTagFound (IntPtr player, string tagName, ref GLib.Value value) { OnTagFound (ProcessNativeTagResult (tagName, ref value)); } private void OnVisualizationData (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum) { VisualizationDataHandler handler = data_available; if (handler == null) { return; } float [] flat = new float[channels * samples]; Marshal.Copy (data, flat, 0, flat.Length); float [][] cbd = new float[channels][]; for (int i = 0; i < channels; i++) { float [] channel = new float[samples]; Array.Copy (flat, i * samples, channel, 0, samples); cbd[i] = channel; } float [] spec = new float[bands]; Marshal.Copy (spectrum, spec, 0, bands); try { handler (cbd, new float[][] { spec }); } catch (Exception e) { Log.Exception ("Uncaught exception during visualization data post.", e); } } private void OnVolumeChanged (IntPtr player, double newVolume) { OnEventChanged (PlayerEvent.Volume); } private static StreamTag ProcessNativeTagResult (string tagName, ref GLib.Value valueRaw) { if (tagName == String.Empty || tagName == null) { return StreamTag.Zero; } object value = null; try { value = valueRaw.Val; } catch { return StreamTag.Zero; } if (value == null) { return StreamTag.Zero; } StreamTag item; item.Name = tagName; item.Value = value; return item; } public override ushort Volume { get { return is_initialized ? (ushort)Math.Round (bp_get_volume (handle) * 100.0) : (ushort)0; } set { if (!is_initialized) { return; } bp_set_volume (handle, value / 100.0); if (!bp_audiosink_has_volume (handle)) { PlayerEngineService.VolumeSchema.Set ((int)value); } OnEventChanged (PlayerEvent.Volume); } } public override uint Position { get { return (uint)bp_get_position(handle); } set { bp_set_position (handle, (ulong)value); OnEventChanged (PlayerEvent.Seek); } } public override bool CanSeek { get { return bp_can_seek (handle); } } public override uint Length { get { return (uint)bp_get_duration (handle); } } public override string Id { get { return "gstreamer"; } } public override string Name { get { return "GStreamer 0.10"; } } private bool? supports_equalizer = null; public override bool SupportsEqualizer { get { if (supports_equalizer == null) { supports_equalizer = bp_equalizer_is_supported (handle); } return supports_equalizer.Value; } } public override VideoDisplayContextType VideoDisplayContextType { get { return bp_video_get_display_context_type (handle); } } public override IntPtr VideoDisplayContext { set { bp_video_set_display_context (handle, value); } get { return bp_video_get_display_context (handle); } } public double AmplifierLevel { set { double scale = Math.Pow (10.0, value / 20.0); bp_equalizer_set_preamp_level (handle, scale); } } public int [] BandRange { get { int min = -1; int max = -1; bp_equalizer_get_bandrange (handle, out min, out max); return new int [] { min, max }; } } public uint [] EqualizerFrequencies { get { uint count = bp_equalizer_get_nbands (handle); double [] freq = new double[count]; bp_equalizer_get_frequencies (handle, out freq); uint [] ret = new uint[count]; for (int i = 0; i < count; i++) { ret[i] = (uint)freq[i]; } return ret; } } public void SetEqualizerGain (uint band, double gain) { bp_equalizer_set_gain (handle, band, gain); } private static string [] source_capabilities = { "file", "http", "cdda", "dvd", "vcd" }; public override IEnumerable SourceCapabilities { get { return source_capabilities; } } private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac" }; public override IEnumerable ExplicitDecoderCapabilities { get { return decoder_capabilities; } } private bool ReplayGainEnabled { get { return bp_replaygain_get_enabled (handle); } set { bp_replaygain_set_enabled (handle, value); } } private bool GaplessEnabled { get { return gapless_enabled; } set { if (bp_supports_gapless (handle)) { gapless_enabled = value; if (value) { bp_set_about_to_finish_callback (handle, about_to_finish_callback); } else { bp_set_about_to_finish_callback (handle, null); } } else { gapless_enabled = false; } } } #region ISupportClutter private IntPtr clutter_video_sink; private IntPtr clutter_video_texture; private bool clutter_video_sink_enabled; public void EnableClutterVideoSink (IntPtr videoTexture) { clutter_video_sink_enabled = true; clutter_video_texture = videoTexture; } public void DisableClutterVideoSink () { clutter_video_sink_enabled = false; clutter_video_texture = IntPtr.Zero; } public bool IsClutterVideoSinkInitialized { get { return clutter_video_sink_enabled && clutter_video_texture != IntPtr.Zero && clutter_video_sink != IntPtr.Zero; } } private IntPtr OnVideoPipelineSetup (IntPtr player, IntPtr bus) { try { if (clutter_video_sink_enabled) { if (clutter_video_sink != IntPtr.Zero) { // FIXME: does this get unreffed by the pipeline? } clutter_video_sink = clutter_gst_video_sink_new (clutter_video_texture); } else if (!clutter_video_sink_enabled && clutter_video_sink != IntPtr.Zero) { clutter_video_sink = IntPtr.Zero; clutter_video_texture = IntPtr.Zero; } } catch (Exception e) { Log.Exception ("Clutter support could not be initialized", e); clutter_video_sink = IntPtr.Zero; clutter_video_texture = IntPtr.Zero; clutter_video_sink_enabled = false; } return clutter_video_sink; } private void OnVideoPrepareWindow (IntPtr player) { OnEventChanged (PlayerEvent.PrepareVideoWindow); } #endregion #region Preferences private PreferenceBase replaygain_preference; private PreferenceBase gapless_preference; private void InstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } replaygain_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (ReplayGainEnabledSchema, Catalog.GetString ("_Enable ReplayGain correction"), Catalog.GetString ("For tracks that have ReplayGain data, automatically scale (normalize) playback volume"), delegate { ReplayGainEnabled = ReplayGainEnabledSchema.Get (); } )); if (bp_supports_gapless (handle)) { gapless_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (GaplessEnabledSchema, Catalog.GetString ("Enable _gapless playback"), Catalog.GetString ("Eliminate the small playback gap on track change. Useful for concept albums and classical music."), delegate { GaplessEnabled = GaplessEnabledSchema.Get (); } )); } } private void UninstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } service["general"]["misc"].Remove (replaygain_preference); if (bp_supports_gapless (handle)) { service["general"]["misc"].Remove (gapless_preference); } replaygain_preference = null; gapless_preference = null; } public static readonly SchemaEntry<bool> ReplayGainEnabledSchema = new SchemaEntry<bool> ( "player_engine", "replay_gain_enabled", false, "Enable ReplayGain", "If ReplayGain data is present on tracks when playing, allow volume scaling" ); public static readonly SchemaEntry<bool> GaplessEnabledSchema = new SchemaEntry<bool> ( "player_engine", "gapless_playback_enabled", true, "Enable gapless playback", "Eliminate the small playback gap on track change. Useful for concept albums & classical music." ); #endregion [DllImport ("libbanshee.dll")] private static extern IntPtr bp_new (); [DllImport ("libbanshee.dll")] private static extern bool bp_initialize_pipeline (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_destroy (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_eos_callback (HandleRef player, BansheePlayerEosCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_error_callback (HandleRef player, BansheePlayerErrorCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_vis_data_callback (HandleRef player, BansheePlayerVisDataCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_state_changed_callback (HandleRef player, BansheePlayerStateChangedCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_buffering_callback (HandleRef player, BansheePlayerBufferingCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_video_pipeline_setup_callback (HandleRef player, VideoPipelineSetupHandler cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_tag_found_callback (HandleRef player, GstTaggerTagFoundCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_video_prepare_window_callback (HandleRef player, VideoPrepareWindowHandler cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_next_track_starting_callback (HandleRef player, BansheePlayerNextTrackStartingCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_about_to_finish_callback (HandleRef player, BansheePlayerAboutToFinishCallback cb); [DllImport ("libbanshee.dll")] private static extern bool bp_supports_gapless (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_open (HandleRef player, IntPtr uri); [DllImport ("libbanshee.dll")] private static extern void bp_stop (HandleRef player, bool nullstate); [DllImport ("libbanshee.dll")] private static extern void bp_pause (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_play (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_set_next_track (HandleRef player, IntPtr uri); [DllImport ("libbanshee.dll")] private static extern void bp_set_volume (HandleRef player, double volume); [DllImport("libbanshee.dll")] private static extern double bp_get_volume (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_volume_changed_callback (HandleRef player, BansheePlayerVolumeChangedCallback cb); [DllImport ("libbanshee.dll")] private static extern bool bp_can_seek (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_audiosink_has_volume (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_set_position (HandleRef player, ulong time_ms); [DllImport ("libbanshee.dll")] private static extern ulong bp_get_position (HandleRef player); [DllImport ("libbanshee.dll")] private static extern ulong bp_get_duration (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_get_pipeline_elements (HandleRef player, out IntPtr playbin, out IntPtr audiobin, out IntPtr audiotee); [DllImport ("libbanshee.dll")] private static extern void bp_set_application_gdk_window (HandleRef player, IntPtr window); [DllImport ("libbanshee.dll")] private static extern VideoDisplayContextType bp_video_get_display_context_type (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_video_set_display_context (HandleRef player, IntPtr displayContext); [DllImport ("libbanshee.dll")] private static extern IntPtr bp_video_get_display_context (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_video_window_expose (HandleRef player, IntPtr displayContext, bool direct); [DllImport ("libbanshee.dll")] private static extern void bp_video_window_realize (HandleRef player, IntPtr window); [DllImport ("libbanshee.dll")] private static extern void bp_get_error_quarks (out uint core, out uint library, out uint resource, out uint stream); [DllImport ("libbanshee.dll")] private static extern bool bp_equalizer_is_supported (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_set_preamp_level (HandleRef player, double level); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_set_gain (HandleRef player, uint bandnum, double gain); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_get_bandrange (HandleRef player, out int min, out int max); [DllImport ("libbanshee.dll")] private static extern uint bp_equalizer_get_nbands (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_get_frequencies (HandleRef player, [MarshalAs (UnmanagedType.LPArray)] out double [] freq); [DllImport ("libbanshee.dll")] private static extern void bp_replaygain_set_enabled (HandleRef player, bool enabled); [DllImport ("libbanshee.dll")] private static extern bool bp_replaygain_get_enabled (HandleRef player); [DllImport ("libbanshee.dll")] private static extern IntPtr clutter_gst_video_sink_new (IntPtr texture); } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.Devices.Bluetooth.Rfcomm; using Windows.Networking.Sockets; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; namespace SDKTemplate { public sealed partial class Scenario2_ChatServer : Page { private StreamSocket socket; private DataWriter writer; private RfcommServiceProvider rfcommProvider; private StreamSocketListener socketListener; // A pointer back to the main page is required to display status messages. MainPage rootPage = MainPage.Current; public Scenario2_ChatServer() { this.InitializeComponent(); } private void ListenButton_Click(object sender, RoutedEventArgs e) { InitializeRfcommServer(); } /// <summary> /// Initializes the server using RfcommServiceProvider to advertise the Chat Service UUID and start listening /// for incoming connections. /// </summary> private async void InitializeRfcommServer() { ListenButton.IsEnabled = false; DisconnectButton.IsEnabled = true; rfcommProvider = await RfcommServiceProvider.CreateAsync( RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid)); // Create a listener for this service and start listening socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(rfcommProvider); rfcommProvider.StartAdvertising(socketListener); rootPage.NotifyUser("Listening for incoming connections", NotifyType.StatusMessage); } /// <summary> /// Creates the SDP record that will be revealed to the Client device when pairing occurs. /// </summary> /// <param name="rfcommProvider">The RfcommServiceProvider that is being used to initialize the server</param> private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider) { var sdpWriter = new DataWriter(); // Write the Service Name Attribute. sdpWriter.WriteByte(Constants.SdpServiceNameAttributeType); // The length of the UTF-8 encoded Service Name SDP Attribute. sdpWriter.WriteByte((byte)Constants.SdpServiceName.Length); // The UTF-8 encoded Service Name value. sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; sdpWriter.WriteString(Constants.SdpServiceName); // Set the SDP Attribute on the RFCOMM Service Provider. rfcommProvider.SdpRawAttributes.Add(Constants.SdpServiceNameAttributeId, sdpWriter.DetachBuffer()); } private void SendButton_Click(object sender, RoutedEventArgs e) { SendMessage(); } public void KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter) { SendMessage(); } } private async void SendMessage() { // There's no need to send a zero length message if (MessageTextBox.Text.Length != 0) { // Make sure that the connection is still up and there is a message to send if (socket != null) { string message = MessageTextBox.Text; writer.WriteUInt32((uint)message.Length); writer.WriteString(message); ConversationListBox.Items.Add("Sent: " + message); // Clear the messageTextBox for a new message MessageTextBox.Text = ""; await writer.StoreAsync(); } else { rootPage.NotifyUser("No clients connected, please wait for a client to connect before attempting to send a message", NotifyType.StatusMessage); } } } private void DisconnectButton_Click(object sender, RoutedEventArgs e) { Disconnect(); rootPage.NotifyUser("Disconnected.", NotifyType.StatusMessage); } private async void Disconnect() { if (rfcommProvider != null) { rfcommProvider.StopAdvertising(); rfcommProvider = null; } if (socketListener != null) { socketListener.Dispose(); socketListener = null; } if (writer != null) { writer.DetachStream(); writer = null; } if (socket != null) { socket.Dispose(); socket = null; } await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ListenButton.IsEnabled = true; DisconnectButton.IsEnabled = false; ConversationListBox.Items.Clear(); }); } /// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; socket = args.Socket; writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Client Connected", NotifyType.StatusMessage); }); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ConversationListBox.Items.Add("Received: " + message); }); } catch(Exception ex) { switch ((uint)ex.HResult) { case (0x800703E3): await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage); }); break; default: throw; } break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Client disconnected.",NotifyType.StatusMessage); }); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Premotion.Mansion.Core; using Premotion.Mansion.Core.Data; using Premotion.Mansion.Repository.SqlServer.Queries; namespace Premotion.Mansion.Repository.SqlServer.Schemas { /// <summary> /// Represents a multi-value property table. /// </summary> public class SingleValuePropertyTable : Table { #region Nested type: SingleValuePropertyColumn /// <summary> /// Implements <see cref="Column"/> for single value properties. /// </summary> private class SingleValuePropertyColumn : Column { #region constructors /// <summary> /// </summary> /// <param name="columnName"></param> public SingleValuePropertyColumn(string columnName) : base("value", columnName) { } #endregion #region Overrides of Column /// <summary> /// Constructs a WHERE statements on this column for the given <paramref name="values"/>. /// </summary> /// <param name="context">The <see cref="IMansionContext"/>.</param> /// <param name="commandContext">The <see cref="QueryCommandContext"/>.</param> /// <param name="pair">The <see cref="TableColumnPair"/>.</param> /// <param name="values">The values on which to construct the where statement.</param> protected override void DoToWhereStatement(IMansionContext context, QueryCommandContext commandContext, TableColumnPair pair, IList<object> values) { // assemble the properties var buffer = new StringBuilder(); foreach (var value in values) buffer.AppendFormat("@{0},", commandContext.Command.AddParameter(value)); // append the query commandContext.QueryBuilder.AppendWhere(" [{0}].[id] IN ( SELECT [{1}].[id] FROM [{1}] WHERE [{1}].[{2}] IN ({3}) )", commandContext.QueryBuilder.RootTableName, pair.Table.Name, pair.Column.ColumnName, buffer.Trim()); } /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="queryBuilder"></param> /// <param name="properties"></param> protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties) { throw new NotSupportedException(); } /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="queryBuilder"></param> /// <param name="record"> </param> /// <param name="modifiedProperties"></param> protected override void DoToUpdateStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, Record record, IPropertyBag modifiedProperties) { throw new NotSupportedException(); } #endregion } #endregion #region Constructors /// <summary> /// Constructs this table with the given <paramref name="tableName"/>. /// </summary> /// <param name="tableName">The name of this table.</param> /// <param name="propertyName">The name of the property which to store.</param> public SingleValuePropertyTable(string tableName, string propertyName) : base(tableName) { // validate arguments if (string.IsNullOrEmpty(propertyName)) throw new ArgumentNullException("propertyName"); // add a column Add(new SingleValuePropertyColumn(propertyName)); // set value PropertyName = propertyName; } #endregion #region Overrides of Table /// <summary> /// Generates the insert statement for this table. /// </summary> /// <param name="context"></param> /// <param name="queryBuilder"></param> /// <param name="properties"></param> protected override void DoToInsertStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, IPropertyBag properties) { // check if there are any properties var values = properties.Get(context, PropertyName, string.Empty).Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); if (values.Length == 0) return; // loop through each value and write an insert statement foreach (var value in values) { // build the query var valueModificationQuery = new ModificationQueryBuilder(queryBuilder); // set column values valueModificationQuery.AddColumnValue("id", "@ScopeIdentity"); valueModificationQuery.AddColumnValue("value", value, DbType.String); // append the query queryBuilder.AppendQuery(valueModificationQuery.ToInsertStatement(Name)); } } /// <summary> /// Generates the update statement for this table. /// </summary> /// <param name="context"></param> /// <param name="queryBuilder"></param> /// <param name="record"> </param> /// <param name="modifiedProperties"></param> protected override void DoToUpdateStatement(IMansionContext context, ModificationQueryBuilder queryBuilder, Record record, IPropertyBag modifiedProperties) { // check if the property is modified string rawModifiedValue; if (!modifiedProperties.TryGet(context, PropertyName, out rawModifiedValue)) return; // get the current values var currentValues = GetCurrentValues(queryBuilder.Command, record).ToList(); // check if there are new properties var modifiedValues = rawModifiedValue.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); // get the deleted values var deletedValues = currentValues.Except(modifiedValues, StringComparer.OrdinalIgnoreCase); var newValues = modifiedValues.Except(currentValues, StringComparer.OrdinalIgnoreCase); // create identity parameter var idParameterName = queryBuilder.AddParameter("id", record.Id, DbType.Int32); // generate the delete statements foreach (var deletedValue in deletedValues) { // build the query var valueModificationQuery = new ModificationQueryBuilder(queryBuilder); // build clause var valueParameterName = valueModificationQuery.AddParameter("value", deletedValue, DbType.String); valueModificationQuery.AppendWhereClause("[id] = " + idParameterName + " AND [value] = " + valueParameterName); // append the query queryBuilder.AppendQuery(valueModificationQuery.ToDeleteStatement(Name)); } // generate the insert statements foreach (var newValue in newValues) { // build the query var valueModificationQuery = new ModificationQueryBuilder(queryBuilder); // set column values valueModificationQuery.AddColumnValue("id", idParameterName); valueModificationQuery.AddColumnValue("value", newValue, DbType.String); // append the query queryBuilder.AppendQuery(valueModificationQuery.ToInsertStatement(Name)); } } /// <summary> /// Generates an table sync statement for this table. /// </summary> /// <param name="context">The request context.</param> /// <param name="bulkContext"></param> /// <param name="records"></param> protected override void DoToSyncStatement(IMansionContext context, BulkOperationContext bulkContext, List<Record> records) { // start by clearing the table bulkContext.Add(command => { command.CommandType = CommandType.Text; command.CommandText = string.Format("TRUNCATE TABLE [{0}]", Name); }); // loop through all the properties foreach (var record in records) { // check if there are any properties var values = record.Get(context, PropertyName, string.Empty).Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToArray(); if (values.Length == 0) continue; // loop through each value and write an insert statement foreach (var value in values) { var currentRecord = record; var value1 = value; bulkContext.Add(command => { command.CommandType = CommandType.Text; command.CommandText = string.Format("INSERT INTO [{0}] ([id], [value]) VALUES ({1}, @{2});", Name, currentRecord.Id, command.AddParameter(value1)); }); } } } #endregion #region Helper Methods /// <summary> /// Gets the current values of this table. /// </summary> /// <param name="command"></param> /// <param name="record"></param> /// <returns></returns> private IEnumerable<string> GetCurrentValues(IDbCommand command, Record record) { using (var selectCommand = command.Connection.CreateCommand()) { selectCommand.CommandType = CommandType.Text; selectCommand.CommandText = string.Format("SELECT [value] FROM [{0}] WHERE [id] = '{1}'", Name, record.Id); selectCommand.Transaction = command.Transaction; using (var reader = selectCommand.ExecuteReader()) { if (reader == null) throw new InvalidOperationException("Something terrible happened"); while (reader.Read()) yield return reader.GetValue(0).ToString(); } } } #endregion #region Properties /// <summary> /// Gets the name of the property which to store. /// </summary> private string PropertyName { get; set; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus.Models { using Azure; using Management; using ServiceBus; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// Parameters supplied to the Create Or Update Subscription operation. /// </summary> [JsonTransformation] public partial class SubscriptionCreateOrUpdateParameters { /// <summary> /// Initializes a new instance of the /// SubscriptionCreateOrUpdateParameters class. /// </summary> public SubscriptionCreateOrUpdateParameters() { } /// <summary> /// Initializes a new instance of the /// SubscriptionCreateOrUpdateParameters class. /// </summary> /// <param name="location">Subscription data center location.</param> /// <param name="type">Resource manager type of the resource.</param> /// <param name="accessedAt">Last time there was a receive request to /// this subscription.</param> /// <param name="autoDeleteOnIdle">TimeSpan idle interval after which /// the topic is automatically deleted. The minimum duration is 5 /// minutes.</param> /// <param name="createdAt">Exact time the message was created.</param> /// <param name="defaultMessageTimeToLive">Default message time to live /// value. This is the duration after which the message expires, /// starting from when the message is sent to Service Bus. This is the /// default value used when TimeToLive is not set on a message /// itself.</param> /// <param name="deadLetteringOnFilterEvaluationExceptions">Value that /// indicates whether a subscription has dead letter support on filter /// evaluation exceptions.</param> /// <param name="deadLetteringOnMessageExpiration">Value that indicates /// whether a subscription has dead letter support when a message /// expires.</param> /// <param name="enableBatchedOperations">Value that indicates whether /// server-side batched operations are enabled.</param> /// <param name="entityAvailabilityStatus">Entity availability status /// for the topic. Possible values include: 'Available', 'Limited', /// 'Renaming', 'Restoring', 'Unknown'</param> /// <param name="isReadOnly">Value that indicates whether the entity /// description is read-only.</param> /// <param name="lockDuration">The lock duration time span for the /// subscription.</param> /// <param name="maxDeliveryCount">Number of maximum /// deliveries.</param> /// <param name="messageCount">Number of messages.</param> /// <param name="requiresSession">Value indicating if a subscription /// supports the concept of sessions.</param> /// <param name="status">Enumerates the possible values for the status /// of a messaging entity. Possible values include: 'Active', /// 'Creating', 'Deleting', 'Disabled', 'ReceiveDisabled', 'Renaming', /// 'Restoring', 'SendDisabled', 'Unknown'</param> /// <param name="updatedAt">The exact time the message was /// updated.</param> public SubscriptionCreateOrUpdateParameters(string location, string type = default(string), System.DateTime? accessedAt = default(System.DateTime?), string autoDeleteOnIdle = default(string), MessageCountDetails countDetails = default(MessageCountDetails), System.DateTime? createdAt = default(System.DateTime?), string defaultMessageTimeToLive = default(string), bool? deadLetteringOnFilterEvaluationExceptions = default(bool?), bool? deadLetteringOnMessageExpiration = default(bool?), bool? enableBatchedOperations = default(bool?), EntityAvailabilityStatus? entityAvailabilityStatus = default(EntityAvailabilityStatus?), bool? isReadOnly = default(bool?), string lockDuration = default(string), int? maxDeliveryCount = default(int?), long? messageCount = default(long?), bool? requiresSession = default(bool?), EntityStatus? status = default(EntityStatus?), System.DateTime? updatedAt = default(System.DateTime?)) { Location = location; Type = type; AccessedAt = accessedAt; AutoDeleteOnIdle = autoDeleteOnIdle; CountDetails = countDetails; CreatedAt = createdAt; DefaultMessageTimeToLive = defaultMessageTimeToLive; DeadLetteringOnFilterEvaluationExceptions = deadLetteringOnFilterEvaluationExceptions; DeadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration; EnableBatchedOperations = enableBatchedOperations; EntityAvailabilityStatus = entityAvailabilityStatus; IsReadOnly = isReadOnly; LockDuration = lockDuration; MaxDeliveryCount = maxDeliveryCount; MessageCount = messageCount; RequiresSession = requiresSession; Status = status; UpdatedAt = updatedAt; } /// <summary> /// Gets or sets subscription data center location. /// </summary> [JsonProperty(PropertyName = "location")] public string Location { get; set; } /// <summary> /// Gets or sets resource manager type of the resource. /// </summary> [JsonProperty(PropertyName = "type")] public string Type { get; set; } /// <summary> /// Gets last time there was a receive request to this subscription. /// </summary> [JsonProperty(PropertyName = "properties.accessedAt")] public System.DateTime? AccessedAt { get; protected set; } /// <summary> /// Gets or sets timeSpan idle interval after which the topic is /// automatically deleted. The minimum duration is 5 minutes. /// </summary> [JsonProperty(PropertyName = "properties.autoDeleteOnIdle")] public string AutoDeleteOnIdle { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "properties.countDetails")] public MessageCountDetails CountDetails { get; protected set; } /// <summary> /// Gets exact time the message was created. /// </summary> [JsonProperty(PropertyName = "properties.createdAt")] public System.DateTime? CreatedAt { get; protected set; } /// <summary> /// Gets or sets default message time to live value. This is the /// duration after which the message expires, starting from when the /// message is sent to Service Bus. This is the default value used when /// TimeToLive is not set on a message itself. /// </summary> [JsonProperty(PropertyName = "properties.defaultMessageTimeToLive")] public string DefaultMessageTimeToLive { get; set; } /// <summary> /// Gets or sets value that indicates whether a subscription has dead /// letter support on filter evaluation exceptions. /// </summary> [JsonProperty(PropertyName = "properties.deadLetteringOnFilterEvaluationExceptions")] public bool? DeadLetteringOnFilterEvaluationExceptions { get; set; } /// <summary> /// Gets or sets value that indicates whether a subscription has dead /// letter support when a message expires. /// </summary> [JsonProperty(PropertyName = "properties.deadLetteringOnMessageExpiration")] public bool? DeadLetteringOnMessageExpiration { get; set; } /// <summary> /// Gets or sets value that indicates whether server-side batched /// operations are enabled. /// </summary> [JsonProperty(PropertyName = "properties.enableBatchedOperations")] public bool? EnableBatchedOperations { get; set; } /// <summary> /// Gets or sets entity availability status for the topic. Possible /// values include: 'Available', 'Limited', 'Renaming', 'Restoring', /// 'Unknown' /// </summary> [JsonProperty(PropertyName = "properties.entityAvailabilityStatus")] public EntityAvailabilityStatus? EntityAvailabilityStatus { get; set; } /// <summary> /// Gets or sets value that indicates whether the entity description is /// read-only. /// </summary> [JsonProperty(PropertyName = "properties.isReadOnly")] public bool? IsReadOnly { get; set; } /// <summary> /// Gets or sets the lock duration time span for the subscription. /// </summary> [JsonProperty(PropertyName = "properties.lockDuration")] public string LockDuration { get; set; } /// <summary> /// Gets or sets number of maximum deliveries. /// </summary> [JsonProperty(PropertyName = "properties.maxDeliveryCount")] public int? MaxDeliveryCount { get; set; } /// <summary> /// Gets number of messages. /// </summary> [JsonProperty(PropertyName = "properties.messageCount")] public long? MessageCount { get; protected set; } /// <summary> /// Gets or sets value indicating if a subscription supports the /// concept of sessions. /// </summary> [JsonProperty(PropertyName = "properties.requiresSession")] public bool? RequiresSession { get; set; } /// <summary> /// Gets or sets enumerates the possible values for the status of a /// messaging entity. Possible values include: 'Active', 'Creating', /// 'Deleting', 'Disabled', 'ReceiveDisabled', 'Renaming', 'Restoring', /// 'SendDisabled', 'Unknown' /// </summary> [JsonProperty(PropertyName = "properties.status")] public EntityStatus? Status { get; set; } /// <summary> /// Gets the exact time the message was updated. /// </summary> [JsonProperty(PropertyName = "properties.updatedAt")] public System.DateTime? UpdatedAt { get; protected set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Location"); } } } }
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 MagicPotion.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); 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; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Net.Http; using System.Collections.Generic; namespace Microsoft.PowerShell.Commands { /// <summary> /// WebResponseObject. /// </summary> public partial class WebResponseObject { #region Properties /// <summary> /// Gets or protected sets the Content property. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public byte[] Content { get; protected set; } /// <summary> /// Gets the StatusCode property. /// </summary> public int StatusCode { get { return (WebResponseHelper.GetStatusCode(BaseResponse)); } } /// <summary> /// Gets the StatusDescription property. /// </summary> public string StatusDescription { get { return (WebResponseHelper.GetStatusDescription(BaseResponse)); } } private MemoryStream _rawContentStream; /// <summary> /// Gets the RawContentStream property. /// </summary> public MemoryStream RawContentStream { get { return (_rawContentStream); } } /// <summary> /// Gets the RawContentLength property. /// </summary> public long RawContentLength { get { return (RawContentStream == null ? -1 : RawContentStream.Length); } } /// <summary> /// Gets or protected sets the RawContent property. /// </summary> public string RawContent { get; protected set; } #endregion Properties #region Methods /// <summary> /// Reads the response content from the web response. /// </summary> private void InitializeContent() { this.Content = this.RawContentStream.ToArray(); } private bool IsPrintable(char c) { return (char.IsLetterOrDigit(c) || char.IsPunctuation(c) || char.IsSeparator(c) || char.IsSymbol(c) || char.IsWhiteSpace(c)); } /// <summary> /// Returns the string representation of this web response. /// </summary> /// <returns>The string representation of this web response.</returns> public sealed override string ToString() { char[] stringContent = System.Text.Encoding.ASCII.GetChars(Content); for (int counter = 0; counter < stringContent.Length; counter++) { if (!IsPrintable(stringContent[counter])) { stringContent[counter] = '.'; } } return new string(stringContent); } #endregion Methods } // TODO: Merge Partials /// <summary> /// WebResponseObject. /// </summary> public partial class WebResponseObject { #region Properties /// <summary> /// Gets or sets the BaseResponse property. /// </summary> public HttpResponseMessage BaseResponse { get; set; } /// <summary> /// Gets the Headers property. /// </summary> public Dictionary<string, IEnumerable<string>> Headers { get { if (_headers == null) { _headers = WebResponseHelper.GetHeadersDictionary(BaseResponse); } return _headers; } } private Dictionary<string, IEnumerable<string>> _headers = null; /// <summary> /// Gets the RelationLink property. /// </summary> public Dictionary<string, string> RelationLink { get; internal set; } #endregion #region Constructors /// <summary> /// Constructor for WebResponseObject. /// </summary> /// <param name="response"></param> public WebResponseObject(HttpResponseMessage response) : this(response, null) { } /// <summary> /// Constructor for WebResponseObject with contentStream. /// </summary> /// <param name="response"></param> /// <param name="contentStream"></param> public WebResponseObject(HttpResponseMessage response, Stream contentStream) { SetResponse(response, contentStream); InitializeContent(); InitializeRawContent(response); } #endregion Constructors #region Methods private void InitializeRawContent(HttpResponseMessage baseResponse) { StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); // Use ASCII encoding for the RawContent visual view of the content. if (Content.Length > 0) { raw.Append(this.ToString()); } this.RawContent = raw.ToString(); } private void SetResponse(HttpResponseMessage response, Stream contentStream) { if (response == null) { throw new ArgumentNullException("response"); } BaseResponse = response; MemoryStream ms = contentStream as MemoryStream; if (ms != null) { _rawContentStream = ms; } else { Stream st = contentStream; if (contentStream == null) { st = StreamHelper.GetResponseStream(response); } long contentLength = response.Content.Headers.ContentLength.Value; if (0 >= contentLength) { contentLength = StreamHelper.DefaultReadBuffer; } int initialCapacity = (int)Math.Min(contentLength, StreamHelper.DefaultReadBuffer); _rawContentStream = new WebResponseContentMemoryStream(st, initialCapacity, null); } // set the position of the content stream to the beginning _rawContentStream.Position = 0; } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Threading; using System.Threading.Tasks; using Windows.Media.MediaProperties; using Windows.Media.Transcoding; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario1_Default : Page { MainPage rootPage = MainPage.Current; CoreDispatcher _dispatcher = Window.Current.Dispatcher; CancellationTokenSource _cts; string _OutputFileName = "TranscodeSampleOutput"; MediaEncodingProfile _Profile; StorageFile _InputFile = null; StorageFile _OutputFile = null; MediaTranscoder _Transcoder = new MediaTranscoder(); string _OutputType = "MP4"; string _OutputFileExtension = ".mp4"; public Scenario1_Default() { this.InitializeComponent(); _cts = new CancellationTokenSource(); // Hook up UI PickFileButton.Click += new RoutedEventHandler(PickFile); SetOutputButton.Click += new RoutedEventHandler(PickOutput); TargetFormat.SelectionChanged += new SelectionChangedEventHandler(OnTargetFormatChanged); Transcode.Click += new RoutedEventHandler(TranscodePreset); Cancel.Click += new RoutedEventHandler(TranscodeCancel); // Media Controls InputPlayButton.Click += new RoutedEventHandler(InputPlayButton_Click); InputPauseButton.Click += new RoutedEventHandler(InputPauseButton_Click); InputStopButton.Click += new RoutedEventHandler(InputStopButton_Click); OutputPlayButton.Click += new RoutedEventHandler(OutputPlayButton_Click); OutputPauseButton.Click += new RoutedEventHandler(OutputPauseButton_Click); OutputStopButton.Click += new RoutedEventHandler(OutputStopButton_Click); // File is not selected, disable all buttons but PickFileButton DisableButtons(); SetPickFileButton(true); SetOutputFileButton(true); SetCancelButton(false); } public void Dispose() { _cts.Dispose(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { } async void TranscodePreset(Object sender, RoutedEventArgs e) { StopPlayers(); DisableButtons(); GetPresetProfile(ProfileSelect); // Clear messages StatusMessage.Text = ""; try { if ((_InputFile != null) && (_OutputFile != null)) { var preparedTranscodeResult = await _Transcoder.PrepareFileTranscodeAsync(_InputFile, _OutputFile, _Profile); if (EnableMrfCrf444.IsChecked.HasValue && (bool)EnableMrfCrf444.IsChecked) { _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.MrfCrf444; } else { _Transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default; } if (preparedTranscodeResult.CanTranscode) { SetCancelButton(true); var progress = new Progress<double>(TranscodeProgress); await preparedTranscodeResult.TranscodeAsync().AsTask(_cts.Token, progress); TranscodeComplete(); } else { TranscodeFailure(preparedTranscodeResult.FailureReason); } } } catch (TaskCanceledException) { OutputText(""); TranscodeError("Transcode Canceled"); } catch (Exception exception) { TranscodeError(exception.Message); } } void GetPresetProfile(ComboBox combobox) { _Profile = null; VideoEncodingQuality videoEncodingProfile = VideoEncodingQuality.Wvga; switch (combobox.SelectedIndex) { case 0: videoEncodingProfile = VideoEncodingQuality.HD1080p; break; case 1: videoEncodingProfile = VideoEncodingQuality.HD720p; break; case 2: videoEncodingProfile = VideoEncodingQuality.Wvga; break; case 3: videoEncodingProfile = VideoEncodingQuality.Ntsc; break; case 4: videoEncodingProfile = VideoEncodingQuality.Pal; break; case 5: videoEncodingProfile = VideoEncodingQuality.Vga; break; case 6: videoEncodingProfile = VideoEncodingQuality.Qvga; break; } switch (_OutputType) { case "AVI": _Profile = MediaEncodingProfile.CreateAvi(videoEncodingProfile); break; case "WMV": _Profile = MediaEncodingProfile.CreateWmv(videoEncodingProfile); break; default: _Profile = MediaEncodingProfile.CreateMp4(videoEncodingProfile); break; } /* For transcoding to audio profiles, create the encoding profile using one of these APIs: MediaEncodingProfile.CreateMp3(audioEncodingProfile) MediaEncodingProfile.CreateM4a(audioEncodingProfile) MediaEncodingProfile.CreateWma(audioEncodingProfile) MediaEncodingProfile.CreateWav(audioEncodingProfile) where audioEncodingProfile is one of these presets: AudioEncodingQuality.High AudioEncodingQuality.Medium AudioEncodingQuality.Low */ } void TranscodeProgress(double percent) { OutputText("Progress: " + percent.ToString().Split('.')[0] + "%"); } async void TranscodeComplete() { OutputText("Transcode completed."); OutputPathText("Output (" + _OutputFile.Path + ")"); IRandomAccessStream stream = await _OutputFile.OpenAsync(FileAccessMode.Read); await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { OutputVideo.SetSource(stream, _OutputFile.ContentType); }); EnableButtons(); SetCancelButton(false); } async void TranscodeCancel(object sender, RoutedEventArgs e) { try { _cts.Cancel(); _cts.Dispose(); _cts = new CancellationTokenSource(); if (_OutputFile != null) { await _OutputFile.DeleteAsync(); } } catch (Exception exception) { TranscodeError(exception.Message); } } async void TranscodeFailure(TranscodeFailureReason reason) { try { if (_OutputFile != null) { await _OutputFile.DeleteAsync(); } } catch (Exception exception) { TranscodeError(exception.Message); } switch (reason) { case TranscodeFailureReason.CodecNotFound: TranscodeError("Codec not found."); break; case TranscodeFailureReason.InvalidProfile: TranscodeError("Invalid profile."); break; default: TranscodeError("Unknown failure."); break; } } async void PickFile(object sender, RoutedEventArgs e) { FileOpenPicker picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.VideosLibrary; picker.FileTypeFilter.Add(".wmv"); picker.FileTypeFilter.Add(".mp4"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read); _InputFile = file; InputVideo.SetSource(stream, file.ContentType); InputVideo.Play(); // Enable buttons EnableButtons(); } } async void PickOutput(object sender, RoutedEventArgs e) { FileSavePicker picker = new FileSavePicker(); picker.SuggestedStartLocation = PickerLocationId.VideosLibrary; picker.SuggestedFileName = _OutputFileName; picker.FileTypeChoices.Add(_OutputType, new System.Collections.Generic.List<string>() { _OutputFileExtension }); _OutputFile = await picker.PickSaveFileAsync(); if (_OutputFile != null) { SetTranscodeButton(true); } } void OnTargetFormatChanged(object sender, SelectionChangedEventArgs e) { switch (TargetFormat.SelectedIndex) { case 1: _OutputType = "WMV"; _OutputFileExtension = ".wmv"; EnableNonSquarePARProfiles(); break; case 2: _OutputType = "AVI"; _OutputFileExtension = ".avi"; // Disable NTSC and PAL profiles as non-square pixel aspect ratios are not supported by AVI DisableNonSquarePARProfiles(); break; default: _OutputType = "MP4"; _OutputFileExtension = ".mp4"; EnableNonSquarePARProfiles(); break; } } void InputPlayButton_Click(Object sender, RoutedEventArgs e) { if (InputVideo.DefaultPlaybackRate == 0) { InputVideo.DefaultPlaybackRate = 1.0; InputVideo.PlaybackRate = 1.0; } InputVideo.Play(); } void InputStopButton_Click(Object sender, RoutedEventArgs e) { InputVideo.Stop(); } void InputPauseButton_Click(Object sender, RoutedEventArgs e) { InputVideo.Pause(); } void OutputPlayButton_Click(Object sender, RoutedEventArgs e) { if (OutputVideo.DefaultPlaybackRate == 0) { OutputVideo.DefaultPlaybackRate = 1.0; OutputVideo.PlaybackRate = 1.0; } OutputVideo.Play(); } void OutputStopButton_Click(Object sender, RoutedEventArgs e) { OutputVideo.Stop(); } void OutputPauseButton_Click(Object sender, RoutedEventArgs e) { OutputVideo.Pause(); } async void SetPickFileButton(bool isEnabled) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { PickFileButton.IsEnabled = isEnabled; }); } async void SetOutputFileButton(bool isEnabled) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { SetOutputButton.IsEnabled = isEnabled; }); } async void SetTranscodeButton(bool isEnabled) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Transcode.IsEnabled = isEnabled; }); } async void SetCancelButton(bool isEnabled) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Cancel.IsEnabled = isEnabled; }); } async void EnableButtons() { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { PickFileButton.IsEnabled = true; SetOutputButton.IsEnabled = true; TargetFormat.IsEnabled = true; ProfileSelect.IsEnabled = true; EnableMrfCrf444.IsEnabled = true; // The transcode button's initial state should be disabled until an output // file has been set. Transcode.IsEnabled = false; }); } async void DisableButtons() { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ProfileSelect.IsEnabled = false; Transcode.IsEnabled = false; PickFileButton.IsEnabled = false; SetOutputButton.IsEnabled = false; TargetFormat.IsEnabled = false; EnableMrfCrf444.IsEnabled = false; }); } void EnableNonSquarePARProfiles() { ComboBoxItem_NTSC.IsEnabled = true; ComboBoxItem_PAL.IsEnabled = true; } void DisableNonSquarePARProfiles() { ComboBoxItem_NTSC.IsEnabled = false; ComboBoxItem_PAL.IsEnabled = false; // Ensure a valid profile is set if ((ProfileSelect.SelectedIndex == 3) || (ProfileSelect.SelectedIndex == 4)) { ProfileSelect.SelectedIndex = 2; } } async void StopPlayers() { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { if (InputVideo.CurrentState != MediaElementState.Paused) { InputVideo.Pause(); } if (OutputVideo.CurrentState != MediaElementState.Paused) { OutputVideo.Pause(); } }); } async void PlayFile(StorageFile MediaFile) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { try { IRandomAccessStream stream = await MediaFile.OpenAsync(FileAccessMode.Read); OutputVideo.SetSource(stream, MediaFile.ContentType); OutputVideo.Play(); } catch (Exception exception) { TranscodeError(exception.Message); } }); } async void TranscodeError(string error) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { StatusMessage.Foreground = new SolidColorBrush(Windows.UI.Colors.Red); StatusMessage.Text = error; }); EnableButtons(); SetCancelButton(false); } async void OutputText(string text) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { OutputMsg.Foreground = new SolidColorBrush(Windows.UI.Colors.Green); OutputMsg.Text = text; }); } async void OutputPathText(string text) { await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { OutputPath.Text = text; }); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.MarkdigEngine.Extensions { using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using Markdig.Syntax; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.MarkdigEngine.Validators; using Microsoft.DocAsCode.Plugins; public class MarkdownValidatorBuilder { private readonly List<RuleWithId<MarkdownValidationRule>> _validators = new List<RuleWithId<MarkdownValidationRule>>(); private readonly List<RuleWithId<MarkdownTagValidationRule>> _tagValidators = new List<RuleWithId<MarkdownTagValidationRule>>(); private readonly Dictionary<string, MarkdownValidationRule> _globalValidators = new Dictionary<string, MarkdownValidationRule>(); private readonly List<MarkdownValidationSetting> _settings = new List<MarkdownValidationSetting>(); private List<IMarkdownObjectValidatorProvider> _validatorProviders = new List<IMarkdownObjectValidatorProvider>(); public const string DefaultValidatorName = "default"; public const string MarkdownValidatePhaseName = "Markdown style"; private ICompositionContainer Container { get; } public MarkdownValidatorBuilder(ICompositionContainer container) { Container = container; } public static MarkdownValidatorBuilder Create( MarkdownServiceParameters parameters, ICompositionContainer container) { var builder = new MarkdownValidatorBuilder(container); if (parameters != null) { LoadValidatorConfig(parameters.BasePath, parameters.TemplateDir, builder); } if (container != null) { builder.LoadEnabledRulesProvider(); } return builder; } public IMarkdownObjectRewriter CreateRewriter(MarkdownContext context) { var tagValidator = new TagValidator(GetEnabledTagRules().ToImmutableList(), context); var validators = from vp in _validatorProviders from p in vp.GetValidators() select p; return MarkdownObjectRewriterFactory.FromValidators( validators.Concat( new[] { MarkdownObjectValidatorFactory.FromLambda<IMarkdownObject>(tagValidator.Validate) })); } public void AddValidators(MarkdownValidationRule[] rules) { if (rules == null) { return; } foreach (var rule in rules) { if (string.IsNullOrEmpty(rule.ContractName)) { continue; } _globalValidators[rule.ContractName] = rule; } } public void AddValidators(string category, Dictionary<string, MarkdownValidationRule> validators) { if (validators == null) { return; } foreach (var pair in validators) { if (string.IsNullOrEmpty(pair.Value.ContractName)) { continue; } _validators.Add(new RuleWithId<MarkdownValidationRule> { Category = category, Id = pair.Key, Rule = pair.Value, }); } } public void AddTagValidators(MarkdownTagValidationRule[] validators) { if (validators == null) { return; } foreach (var item in validators) { _tagValidators.Add(new RuleWithId<MarkdownTagValidationRule> { Category = null, Id = null, Rule = item }); } } internal void AddTagValidators(string category, Dictionary<string, MarkdownTagValidationRule> validators) { if (validators == null) { return; } foreach (var pair in validators) { _tagValidators.Add(new RuleWithId<MarkdownTagValidationRule> { Category = category, Id = pair.Key, Rule = pair.Value, }); } } internal void AddSettings(MarkdownValidationSetting[] settings) { if (settings == null) { return; } foreach (var setting in settings) { _settings.Add(setting); } } private void EnsureDefaultValidator() { if (!_globalValidators.ContainsKey(DefaultValidatorName)) { _globalValidators[DefaultValidatorName] = new MarkdownValidationRule { ContractName = DefaultValidatorName }; } } private static void LoadValidatorConfig(string baseDir, string templateDir, MarkdownValidatorBuilder builder) { if (string.IsNullOrEmpty(baseDir)) { return; } if (templateDir != null) { var configFolder = Path.Combine(templateDir, MarkdownSytleDefinition.MarkdownStyleDefinitionFolderName); if (Directory.Exists(configFolder)) { LoadValidatorDefinition(configFolder, builder); } } var configFile = Path.Combine(baseDir, MarkdownSytleConfig.MarkdownStyleFileName); if (EnvironmentContext.FileAbstractLayer.Exists(configFile)) { var config = JsonUtility.Deserialize<MarkdownSytleConfig>(configFile); builder.AddValidators(config.Rules); builder.AddTagValidators(config.TagRules); builder.AddSettings(config.Settings); } builder.EnsureDefaultValidator(); } private static void LoadValidatorDefinition(string mdStyleDefPath, MarkdownValidatorBuilder builder) { if (Directory.Exists(mdStyleDefPath)) { foreach (var configFile in Directory.GetFiles(mdStyleDefPath, "*" + MarkdownSytleDefinition.MarkdownStyleDefinitionFilePostfix)) { var fileName = Path.GetFileName(configFile); var category = fileName.Remove(fileName.Length - MarkdownSytleDefinition.MarkdownStyleDefinitionFilePostfix.Length); var config = JsonUtility.Deserialize<MarkdownSytleDefinition>(configFile); builder.AddTagValidators(category, config.TagRules); builder.AddValidators(category, config.Rules); } } } public void LoadEnabledRulesProvider() { HashSet<string> enabledContractName = new HashSet<string>(); foreach (var item in _validators) { if (IsDisabledBySetting(item) ?? item.Rule.Disable) { enabledContractName.Remove(item.Rule.ContractName); } else { enabledContractName.Add(item.Rule.ContractName); } } foreach (var pair in _globalValidators) { if (pair.Value.Disable) { enabledContractName.Remove(pair.Value.ContractName); } else { enabledContractName.Add(pair.Value.ContractName); } } _validatorProviders = (from name in enabledContractName from vp in Container?.GetExports<IMarkdownObjectValidatorProvider>(name) select vp).ToList(); } private IEnumerable<MarkdownTagValidationRule> GetEnabledTagRules() { foreach (var item in _tagValidators) { if (IsDisabledBySetting(item) ?? item.Rule.Disable) { continue; } yield return item.Rule; } } private bool? IsDisabledBySetting<T>(RuleWithId<T> item) { bool? categoryDisable = null; bool? idDisable = null; if (item.Category != null) { foreach (var setting in _settings) { if (setting.Category == item.Category) { if (setting.Id == null) { categoryDisable = setting.Disable; } else if (setting.Id == item.Id) { idDisable = setting.Disable; } } } } return idDisable ?? categoryDisable; } #region Nested Classes private sealed class RuleWithId<T> { public T Rule { get; set; } public string Category { get; set; } public string Id { get; 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; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class FirstOrDefaultTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { IEnumerable<int> ieInt = Enumerable.Range(0, 0); var q = from x in ieInt select x; Assert.Equal(q.FirstOrDefault(), q.FirstOrDefault()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty } where !string.IsNullOrEmpty(x) select x; Assert.Equal(q.FirstOrDefault(), q.FirstOrDefault()); } private static void TestEmptyIList<T>() { T[] source = { }; T expected = default(T); Assert.IsAssignableFrom<IList<T>>(source); Assert.Equal(expected, source.RunOnce().FirstOrDefault()); } [Fact] public void EmptyIListT() { TestEmptyIList<int>(); TestEmptyIList<string>(); TestEmptyIList<DateTime>(); TestEmptyIList<FirstOrDefaultTests>(); } [Fact] public void IListTOneElement() { int[] source = { 5 }; int expected = 5; Assert.IsAssignableFrom<IList<int>>(source); Assert.Equal(expected, source.FirstOrDefault()); } [Fact] public void IListTManyElementsFirstIsDefault() { int?[] source = { null, -10, 2, 4, 3, 0, 2 }; int? expected = null; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.FirstOrDefault()); } [Fact] public void IListTManyElementsFirstIsNotDefault() { int?[] source = { 19, null, -10, 2, 4, 3, 0, 2 }; int? expected = 19; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.FirstOrDefault()); } private static IEnumerable<T> EmptySource<T>() { yield break; } private static void TestEmptyNotIList<T>() { var source = EmptySource<T>(); T expected = default(T); Assert.Null(source as IList<T>); Assert.Equal(expected, source.RunOnce().FirstOrDefault()); } [Fact] public void EmptyNotIListT() { TestEmptyNotIList<int>(); TestEmptyNotIList<string>(); TestEmptyNotIList<DateTime>(); TestEmptyNotIList<FirstOrDefaultTests>(); } [Fact] public void OneElementNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1); int expected = -5; Assert.Null(source as IList<int>); Assert.Equal(expected, source.FirstOrDefault()); } [Fact] public void ManyElementsNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10); int expected = 3; Assert.Null(source as IList<int>); Assert.Equal(expected, source.FirstOrDefault()); } [Fact] public void EmptySource() { int?[] source = { }; Assert.Null(source.FirstOrDefault(x => true)); Assert.Null(source.FirstOrDefault(x => false)); } [Fact] public void OneElementTruePredicate() { int[] source = { 4 }; Func<int, bool> predicate = IsEven; int expected = 4; Assert.Equal(expected, source.FirstOrDefault(predicate)); } [Fact] public void ManyElementsPredicateFalseForAll() { int[] source = { 9, 5, 1, 3, 17, 21 }; Func<int, bool> predicate = IsEven; int expected = default(int); Assert.Equal(expected, source.FirstOrDefault(predicate)); } [Fact] public void PredicateTrueOnlyForLast() { int[] source = { 9, 5, 1, 3, 17, 21, 50 }; Func<int, bool> predicate = IsEven; int expected = 50; Assert.Equal(expected, source.FirstOrDefault(predicate)); } [Fact] public void PredicateTrueForSome() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = IsEven; int expected = 10; Assert.Equal(expected, source.FirstOrDefault(predicate)); } [Fact] public void PredicateTrueForSomeRunOnce() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = IsEven; int expected = 10; Assert.Equal(expected, source.RunOnce().FirstOrDefault(predicate)); } [Fact] public void NullSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).FirstOrDefault()); } [Fact] public void NullSourcePredicateUsed() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).FirstOrDefault(i => i != 2)); } [Fact] public void NullPredicate() { Func<int, bool> predicate = null; AssertExtensions.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).FirstOrDefault(predicate)); } } }
// ******************************************************************************************************** // The contents of this file are subject to the Lesser GNU Public License (LGPL) // 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 Alternately, you can access an earlier version of this content from // the Net Topology Suite, which is also protected by the GNU Lesser Public License and the sourcecode // for the Net Topology Suite can be obtained here: http://sourceforge.net/projects/nts. // // 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. // // // Contributor(s): (Open source contributors should list themselves and their modifications here). // | Name | Date | Comment // |----------------------|------------|------------------------------------------------------------ // | | | // ******************************************************************************************************** using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; namespace DotSpatial.Projections.AuthorityCodes { /// <summary> /// AuthorityCodeHandler /// </summary> public sealed class AuthorityCodeHandler { #region Constructor /// <summary> /// Creates an instance of this class /// </summary> private AuthorityCodeHandler() { ReadDefault(); ReadCustom(); } #endregion #region Fields private static readonly Lazy<AuthorityCodeHandler> LazyInstance = new Lazy<AuthorityCodeHandler>(() => new AuthorityCodeHandler(), true); private readonly IDictionary<string, ProjectionInfo> _authorityCodeToProjectionInfo = new Dictionary<string, ProjectionInfo>(); private readonly IDictionary<string, ProjectionInfo> _authorityNameToProjectionInfo = new Dictionary<string, ProjectionInfo>(); #endregion /// <summary> /// The one and only <see cref="AuthorityCodeHandler"/> /// </summary> public static AuthorityCodeHandler Instance { get { return LazyInstance.Value; } } public ProjectionInfo this[string authorityCodeOrName] { get { ProjectionInfo pi; if (_authorityCodeToProjectionInfo.TryGetValue(authorityCodeOrName, out pi)) return pi; if (_authorityNameToProjectionInfo.TryGetValue(authorityCodeOrName, out pi)) return pi; return null; } } private void ReadDefault() { using (var str = DeflateStreamReader.DecodeEmbeddedResource("DotSpatial.Projections.AuthorityCodes.AuthorityCodeToProj4.ds")) { ReadFromStream(str, false); } } private void ReadCustom() { var fileName = Assembly.GetCallingAssembly().Location + "\\AdditionalProjections.proj4"; if (File.Exists(fileName)) { ReadFromStream(File.OpenRead(fileName), true); } } private void ReadFromStream(Stream s, bool replace) { using (var sr = new StreamReader(s)) { var seperator = new[] { '\t' }; while (!sr.EndOfStream) { var line = sr.ReadLine(); if (string.IsNullOrEmpty(line) || string.IsNullOrWhiteSpace(line) || line.StartsWith("#", StringComparison.Ordinal)) continue; var parts = line.Split(seperator, 3); if (parts.Length > 1) { if (parts.Length == 2) Add(parts[0], string.Empty, parts[1], replace); else Add(parts[0], parts[1], parts[2], replace); } } } } /// <summary> /// Adds the specified authority. /// </summary> /// <param name="authority">The authority.</param> /// <param name="code">The code.</param> /// <param name="proj4String">The proj4 string.</param> public void Add(string authority, int code, string proj4String) { Add(authority, code, proj4String, false); } /// <summary> /// Adds the specified authority. /// </summary> /// <param name="authority">The authority.</param> /// <param name="code">The code.</param> /// <param name="proj4String">The proj4 string.</param> /// <param name="replace">if set to <c>true</c> [replace].</param> public void Add(string authority, int code, string proj4String, bool replace) { Add(authority, code, string.Empty, proj4String, replace); } /// <summary> /// Adds the specified authority. /// </summary> /// <param name="authority">The authority.</param> /// <param name="code">The code.</param> /// <param name="name">The name.</param> /// <param name="proj4String">The proj4 string.</param> public void Add(string authority, int code, string name, string proj4String) { Add(authority, code, name, proj4String, false); } /// <summary> /// Adds a new projection info to the store, replaces the old one /// </summary> /// <param name="authority">The authority, e.g. EPSG</param> /// <param name="code">The code assigned by the authority</param> /// <param name="name">A declarative name</param> /// <param name="proj4String">the proj4 definition string</param> /// <param name="replace">a value indicating if a previously defined projection should be replaced or not.</param> public void Add(string authority, int code, string name, string proj4String, bool replace) { var authorityCode = string.Format("{0}:{1}", authority, code); Add(authorityCode, name, proj4String, replace); AddToAdditionalProjections(authorityCode, name, proj4String); } private static void AddToAdditionalProjections(string authorityCode, string name, string proj4String) { var fileName = Assembly.GetCallingAssembly().Location + "\\AdditionalProjections.proj4"; var fm = File.Exists(fileName) ? FileMode.Append : FileMode.CreateNew; using (var fileStream = File.Open(fileName, fm, FileAccess.Write, FileShare.None)) using (var sw = new StreamWriter(fileStream, Encoding.ASCII)) sw.WriteLine("{0}\t{1}\t{2}", authorityCode, name, proj4String); } private void Add(string authorityCode, string name, string proj4String, bool replace) { var pos = authorityCode.IndexOf(':'); if (pos == -1) throw new ArgumentOutOfRangeException("authorityCode", "Invalid authorityCode"); if (!replace && _authorityCodeToProjectionInfo.ContainsKey(authorityCode)) { throw new ArgumentOutOfRangeException("authorityCode", "Such projection already added."); } var pi = ProjectionInfo.FromProj4String(proj4String); pi.Authority = authorityCode.Substring(0, pos); pi.AuthorityCode = int.Parse(authorityCode.Substring(pos + 1)); pi.Name = string.IsNullOrEmpty(name) ? authorityCode : name; _authorityCodeToProjectionInfo[authorityCode] = pi; if (string.IsNullOrEmpty(name)) return; if (!replace && _authorityNameToProjectionInfo.ContainsKey(name)) { throw new ArgumentOutOfRangeException("name", "Such projection already added."); } _authorityNameToProjectionInfo[name] = pi; } } }
using System; using System.Collections.Generic; using System.Text; namespace DSPUtil { /// <summary> /// SlimPlayer class provides methods to access a single player's functionality. /// </summary> public class SlimPlayer { private SlimCLI _server; private Dictionary<string, string> _attributes; public SlimPlayer(SlimCLI server, string playerID) { _server = server; _attributes = new Dictionary<string, string>(); _attributes["playerid"] = playerID; } public SlimPlayer(SlimCLI server, Dictionary<string, string> attributes) { _server = server; _attributes = attributes; } public override string ToString() { if (_attributes.ContainsKey("name")) { return _attributes["name"]; } return base.ToString(); } public IEnumerable<string> Attributes { get { foreach (string key in _attributes.Keys) { yield return key; } } } public string Attribute(string name) { return _attributes[name]; } public string PlayerID { get { return _attributes["playerid"]; } } public bool Power { get { // command is: playerid power ? // response is: playerid power <poweron> // <poweron> can be 0 or 1 string[] response = _server.SendCommand(PlayerID, "power", "?"); return new Value(response[2]).BoolValue; } set { _server.SendCommand(PlayerID, "power", value ? "1" : "0"); } } public int SignalStrength { get { string[] response = _server.SendCommand(PlayerID, "signalstrength", "?"); return new Value(response[2]).IntValue; } } public bool Connected { get { string[] response = _server.SendCommand(PlayerID, "connected", "?"); return new Value(response[2]).BoolValue; } } public int LinesPerScreen { get { string[] response = _server.SendCommand(PlayerID, "linesperscreen", "?"); return new Value(response[2]).IntValue; } } /// <summary> /// Volume from 0 to 100 (fractional values are possible) /// </summary> public float Volume { get { string[] response = _server.SendCommand(PlayerID, "mixer volume", "?"); return new Value(response[2]).FloatValue; } set { _server.SendCommand(PlayerID, "mixer volume", value.ToString()); } } public int Rate { get { string[] response = _server.SendCommand(PlayerID, "rate", "?"); return new Value(response[2]).IntValue; } set { _server.SendCommand(PlayerID, "rate", value.ToString()); } } public int Sleep { get { string[] response = _server.SendCommand(PlayerID, "sleep", "?"); return new Value(response[2]).IntValue; } set { _server.SendCommand(PlayerID, "sleep", value.ToString()); } } public string[] Lines { get { string[] response = _server.SendCommand(PlayerID, "display", "?", "?"); string[] lines = new string[2]; lines[0] = response[2]; lines[1] = response[3]; return lines; } set { // Lines may have up to three parameters. Third is number of seconds (defaults to 1, I think) string[] lines = new string[3]; lines[0] = value.Length > 0 ? value[0] : ""; lines[1] = value.Length > 1 ? value[1] : ""; lines[1] = value.Length > 2 ? value[2] : ""; _server.SendCommand(PlayerID, "display", lines[0], lines[1], lines[2]); } } /// <summary> /// Show a message briefly on the player screen. /// </summary> /// <param name="message">Message to display</param> public void ShowBriefly(string message) { _server.SendCommand(PlayerID, "display", "", message, ""); } /// <summary> /// Show a message on the player screen. /// </summary> /// <param name="message">Message to display</param> public void Show(string header, string message, int secs) { _server.SendCommand(PlayerID, "display", header, message, secs.ToString()); } // public void Button(string button) { _server.SendCommand(PlayerID, "button", button); } // Playlist etcetera public string Mode { get { string[] response = _server.SendCommand(PlayerID, "mode", "?"); return new Value(response[2]).StringValue; } set { _server.SendCommand(PlayerID, "mode", value); } } public bool Paused { set { _server.SendCommand(PlayerID, "pause", value ? "1" : "0"); } } public float Time { get { string[] response = _server.SendCommand(PlayerID, "time", "?"); return new Value(response[2]).FloatValue; } set { _server.SendCommand(PlayerID, "time", value.ToString()); } } } }
// 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 Xunit; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using System.Collections.Generic; using System.Linq; namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting { public class WebAssemblyHostConfigurationTest { [Fact] public void CanSetAndGetConfigurationValue() { // Arrange var initialData = new Dictionary<string, string>() { { "color", "blue" }, { "type", "car" }, { "wheels:year", "2008" }, { "wheels:count", "4" }, { "wheels:brand", "michelin" }, { "wheels:brand:type", "rally" }, }; var memoryConfig = new MemoryConfigurationSource { InitialData = initialData }; var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(memoryConfig); configuration["type"] = "car"; configuration["wheels:count"] = "6"; // Assert Assert.Equal("car", configuration["type"]); Assert.Equal("blue", configuration["color"]); Assert.Equal("6", configuration["wheels:count"]); } [Fact] public void SettingValueUpdatesAllProviders() { // Arrange var initialData = new Dictionary<string, string>() { { "color", "blue" } }; var source1 = new MemoryConfigurationSource { InitialData = initialData }; var source2 = new CustomizedTestConfigurationSource(); var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(source1); configuration.Add(source2); configuration["type"] = "car"; // Assert Assert.Equal("car", configuration["type"]); IConfigurationRoot root = configuration; Assert.All(root.Providers, provider => { provider.TryGet("type", out var value); Assert.Equal("car", value); }); } [Fact] public void CanGetChildren() { // Arrange var initialData = new Dictionary<string, string>() { { "color", "blue" } }; var memoryConfig = new MemoryConfigurationSource { InitialData = initialData }; var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(memoryConfig); IConfiguration readableConfig = configuration; var children = readableConfig.GetChildren(); // Assert Assert.NotNull(children); Assert.NotEmpty(children); } [Fact] public void CanGetSection() { // Arrange var initialData = new Dictionary<string, string>() { { "color", "blue" }, { "type", "car" }, { "wheels:year", "2008" }, { "wheels:count", "4" }, { "wheels:brand", "michelin" }, { "wheels:brand:type", "rally" }, }; var memoryConfig = new MemoryConfigurationSource { InitialData = initialData }; var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(memoryConfig); var section = configuration.GetSection("wheels").AsEnumerable(makePathsRelative: true).ToDictionary(k => k.Key, v => v.Value); // Assert Assert.Equal(4, section.Count); Assert.Equal("2008", section["year"]); Assert.Equal("4", section["count"]); Assert.Equal("michelin", section["brand"]); Assert.Equal("rally", section["brand:type"]); } [Fact] public void CanDisposeProviders() { // Arrange var initialData = new Dictionary<string, string>() { { "color", "blue" } }; var memoryConfig = new MemoryConfigurationSource { InitialData = initialData }; var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(memoryConfig); Assert.Equal("blue", configuration["color"]); var exception = Record.Exception(() => configuration.Dispose()); // Assert Assert.Null(exception); } [Fact] public void CanSupportDeeplyNestedConfigs() { // Arrange var dic1 = new Dictionary<string, string>() { {"Mem1", "Value1"}, {"Mem1:", "NoKeyValue1"}, {"Mem1:KeyInMem1", "ValueInMem1"}, {"Mem1:KeyInMem1:Deep1", "ValueDeep1"} }; var dic2 = new Dictionary<string, string>() { {"Mem2", "Value2"}, {"Mem2:", "NoKeyValue2"}, {"Mem2:KeyInMem2", "ValueInMem2"}, {"Mem2:KeyInMem2:Deep2", "ValueDeep2"} }; var dic3 = new Dictionary<string, string>() { {"Mem3", "Value3"}, {"Mem3:", "NoKeyValue3"}, {"Mem3:KeyInMem3", "ValueInMem3"}, {"Mem3:KeyInMem4", "ValueInMem4"}, {"Mem3:KeyInMem3:Deep3", "ValueDeep3"}, {"Mem3:KeyInMem3:Deep4", "ValueDeep4"} }; var memConfigSrc1 = new MemoryConfigurationSource { InitialData = dic1 }; var memConfigSrc2 = new MemoryConfigurationSource { InitialData = dic2 }; var memConfigSrc3 = new MemoryConfigurationSource { InitialData = dic3 }; var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(memConfigSrc1); configuration.Add(memConfigSrc2); configuration.Add(memConfigSrc3); // Assert var dict = configuration.GetSection("Mem1").AsEnumerable(makePathsRelative: true).ToDictionary(k => k.Key, v => v.Value); Assert.Equal(3, dict.Count); Assert.Equal("NoKeyValue1", dict[""]); Assert.Equal("ValueInMem1", dict["KeyInMem1"]); Assert.Equal("ValueDeep1", dict["KeyInMem1:Deep1"]); var dict2 = configuration.GetSection("Mem2").AsEnumerable(makePathsRelative: true).ToDictionary(k => k.Key, v => v.Value); Assert.Equal(3, dict2.Count); Assert.Equal("NoKeyValue2", dict2[""]); Assert.Equal("ValueInMem2", dict2["KeyInMem2"]); Assert.Equal("ValueDeep2", dict2["KeyInMem2:Deep2"]); var dict3 = configuration.GetSection("Mem3").AsEnumerable(makePathsRelative: true).ToDictionary(k => k.Key, v => v.Value); Assert.Equal(5, dict3.Count); Assert.Equal("NoKeyValue3", dict3[""]); Assert.Equal("ValueInMem3", dict3["KeyInMem3"]); Assert.Equal("ValueInMem4", dict3["KeyInMem4"]); Assert.Equal("ValueDeep3", dict3["KeyInMem3:Deep3"]); Assert.Equal("ValueDeep4", dict3["KeyInMem3:Deep4"]); } [Fact] public void NewConfigurationProviderOverridesOldOneWhenKeyIsDuplicated() { // Arrange var dic1 = new Dictionary<string, string>() { {"Key1:Key2", "ValueInMem1"} }; var dic2 = new Dictionary<string, string>() { {"Key1:Key2", "ValueInMem2"} }; var memConfigSrc1 = new MemoryConfigurationSource { InitialData = dic1 }; var memConfigSrc2 = new MemoryConfigurationSource { InitialData = dic2 }; var configuration = new WebAssemblyHostConfiguration(); // Act configuration.Add(memConfigSrc1); configuration.Add(memConfigSrc2); // Assert Assert.Equal("ValueInMem2", configuration["Key1:Key2"]); } private class CustomizedTestConfigurationProvider : ConfigurationProvider { public CustomizedTestConfigurationProvider(string key, string value) => Data.Add(key, value.ToUpperInvariant()); public override void Set(string key, string value) { Data[key] = value; } } private class CustomizedTestConfigurationSource : IConfigurationSource { public IConfigurationProvider Build(IConfigurationBuilder builder) { return new CustomizedTestConfigurationProvider("initialKey", "initialValue"); } } } }
// // Wavelet2D.cs // // Author: // Stefan Moebius // Date: // 2016-04-24 // // Copyright (c) 2016 Stefan Moebius // // 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. /*! \mainpage TurboWavelets.Net documentation * TurboWavelets.Net provides very fast, flexible and compact implementations of discrete wavelet transformations in C#. * Unlike others this implementation has no limitation in sizes for the transformation (lengths like 39, 739,... are possible, not just power of two numbers) * At the moment only floating point numbers are supported. * \section Features * - 1D biorthogonal 5/3 wavelet using the lifting scheme (for arbitrary sizes, not just power of 2) * - 2D biorthogonal 5/3 wavelet using the lifting scheme (for arbitrary sizes, not just power of 2) * - 2D haar wavelet (for arbitrary sizes, not just power of 2) * - 2D cascade sorting of coefficients (for arbitrary sizes, not just power of 2) * - Scale/Crop coefficients in a defined grid * - apply a deadzone * - Multithreaded and threadsafe * * \section Licence * MIT License (MIT) */ using System; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; namespace TurboWavelets { /// <summary> /// A abstract basis class which provides common functionality /// for different implementations of a "2D Wavelet transformation" /// </summary> public abstract class Wavelet2D { /// <summary> /// Prototype of a delegate called to inform caller about progress and to provide possibility to abort /// </summary public delegate bool ProgressDelegate (float progress); #region protected attributes /// <summary> /// Width of the wavelet transformation /// </summary> protected int width; /// <summary> /// Height of the wavelet transformation /// </summary> protected int height; /// <summary> /// min. size for horizontal and vertical transformation /// </summary> protected int minSize; /// <summary> /// The allowed minimum value for minSize (limitation of the algorithmn implementation) /// </supmmary> protected int allowedMinSize; #endregion #region private attributes /// <summary> /// Setting whether threads should be used to accelerate execution /// </summary> private volatile bool enableParallel = true; /// <summary> /// Setting whether temporary memory should cached (or allocated if needed) /// </summary> private volatile bool enableCacheing = false; /// <summary> /// temporary buffer used to store transformation results /// </summary> private volatile float[,] cachedArray = null; /// <summary> //Synchronisaion object used to make all calls thread safe. //Note than using [MethodImpl(MethodImplOptions.Synchronized)] is not sufficient, as //the temporary and src array can be used by different methods at the same time /// </summary> private object threadSync = new object (); /// <summary> /// Delegate called to inform caller about progress and to provide possibility to abort /// </summary> private ProgressDelegate progressDelegate; /// <summary> /// Flag which indicates wheter the current task is aborted /// </summary> private volatile bool progressAbort; /// <summary> /// Synchronisaion object used for progress handling /// </summary> private object progressSync = null; /// <summary> /// The progress value of the current task /// </summary> private long progressValue; /// <summary> /// The maximal progress value of the current task /// </summary> private long progressMax; #endregion #region public constructors /// <summary> /// Initalizes a two dimensional wavelet cascade transformation. /// By the transformation the data is split up in a high- and a low-pass. The low-pass data /// is repeatedly transformed again until the horizontal or vertical length reaches "minSize". /// </summary> /// <param name="minSize">minimum size up to a transformation is applied (can be set arbitrary)</param> /// <param name="allowedMinSize">minimum size up to a transformation can be applied (implementation depended)</param> /// <param name="width">starting width of the transformation</param> /// <param name="height">starting height of the transformation</param> /// <exception cref="ArgumentException"></exception> public Wavelet2D (int minSize, int allowedMinSize, int width, int height) { if (allowedMinSize < 1) { throw new ArgumentException ("allowedMinSize cannot be less than one"); } if (minSize < allowedMinSize) { throw new ArgumentException ("minSize cannot be smaller than " + allowedMinSize); } if (width < minSize || height < minSize) { throw new ArgumentException ("width and height must be greater or equal to " + minSize); } this.width = width; this.height = height; this.minSize = minSize; this.allowedMinSize = allowedMinSize; } #endregion #region public properties /// <summary> /// returns the width for the two dimensional wavelet transformation /// </summary> public int Width { get { return width; } } /// <summary> /// returns the height for the two dimensional wavelet transformation /// </summary> public int Height { get { return height; } } /// <summary> /// enables or disables caching of memory (disabled by default) /// </summary> public bool EnableCaching { get { return enableCacheing; } set { enableCacheing = value; if (!value) { FlushCache (); } } } /// <summary> /// enables or disables parallel execution (enabled by default) /// </summary> public bool EnableParallel { get { return enableParallel; } set { enableParallel = value; } } /// <summary> /// Frees all cached memory /// </summary> public void FlushCache () { lock (threadSync) { cachedArray = null; } } #endregion #region private methods for progress handling /// <summary> /// Updates the progress value of the current task by the declared increment and /// calls a callback to notify the caller about the progress and give /// the possiblily to abort the current task. /// </summary> /// <param name="progressDelegate">a delegate to notify the caller about the progress and to give /// the possiblity to abort the current task. Can be set to null if notification is not required</param> /// <param name="maxValue">The maximal progress value (to calculate progress percentage). Can be set to 0 if used with TransformIsotropic2D() or BacktransformIsotropic2D() </param> private void initProgress (ProgressDelegate progressDelegate, long maxValue = 0) { if (progressDelegate != null) { this.progressSync = new object (); } else { this.progressSync = null; } int w = width, h = height; this.progressMax = maxValue; //Calculate the exact maximal value for the progress value if not declared (used by TransformIsotropic2D() and BacktransformIsotropic2D()) if (this.progressMax == 0) { while ((w >= minSize) && (h >= minSize)) { this.progressMax += 2 * w * h; w = -(-w >> 1); h = -(-h >> 1); } } this.progressDelegate = progressDelegate; this.progressValue = 0; this.progressAbort = false; } /// <summary> /// Updates the progress value of the current task by the declared increment and /// calls a callback to notify the caller about the progress and give /// the possiblily to abort the current task. /// </summary> /// <param name="increment">Value by which the progress is increased</param> /// </returns>True if the current task should be aborted. False otherwise.</returns> private bool updateProgress (long increment) { bool abort = false; if (progressSync != null) { lock (progressSync) { if (!progressAbort) { progressValue += increment; if (progressValue > progressMax) { progressValue = progressMax; } progressAbort = progressDelegate ((float)progressValue / (float)progressMax * 100.0f); } else { //Make sure delegate not called after abort } abort = progressAbort; } } return abort; } #endregion #region private helper methods /// <summary> /// Provides a temporary 2D float array with the in the constructor declared dimensions /// </summary> protected float[,] getTempArray () { float[,] tmp = cachedArray; if (tmp == null) { //Note: if we do transform the cols and rows in sequentally (not in parallel) we //do not need an temporary array of the same size as the source array. //Insead a one dimensional array (with the maximum of width and height as length //would be sufficient. However we do not use this fact here, as //different implementations of TransformCol(), TransformRow()... would be required tmp = new float[width, height]; if (enableCacheing) { cachedArray = tmp; } } return tmp; } /// <summary> /// Helper method to check a 2D float array to have the correct dimensions and is not null /// </summary> /// <param name="src">a 2D float array</param> /// <param name="name">name of src in the calling method</param> /// <exception cref="ArgumentException"></exception> private void checkArrayArgument (float[,] src, string name) { if (src == null) { throw new ArgumentException (name + " cannot be null"); } if (src.GetLength (0) < width) { throw new ArgumentException ("first dimension of " + name + " cannot be smaller than " + width); } if (src.GetLength (1) < height) { throw new ArgumentException ("second dimension of " + name + " cannot be smaller than " + height); } } /// <summary> /// Private method to modify the coefficients of a single block of the declared grid size. /// The coefficients in the block are sorted by their absolute values (from high to low). /// The first n coefficients are multiplied with the coresponding value in the "scaleFactorsMajors"-array. /// If "scaleFactorsMajors" is null the values remain unchanged. /// The remaining coefficients are mulitplied with the fixed value "scaleFactorsMinors". /// </summary> /// <param name="src">a 2D float array</param> /// <param name="n">n greatest coefficients multiplied by the coresponding value in the "scaleFactorsMajors"-array or remaing unchanged if "scaleFactorsMajors" is null</param> /// <param name="scaleFactorsMajors">float array of size n with scaling factors</param> /// <param name="scaleFactorsMinors">scaling factor for remaining coefficients</param> /// <param name="gridSize">Size of the grid (horizontally and vertically)</param> /// <param name="startX">start position in first dimension</param> /// <param name="startY">start position in second dimension</param> private void ModfiyBlock (float[,] src, int n, float[] scaleFactorsMajors, float scaleFactorsMinors, int gridSize, int startX, int startY) { //Note: ModfiyBlock should not be called directly, as //it is not thread safe. The critical section must be started //in the calling method int endX = startX + gridSize; int endY = startY + gridSize; if (endX > width) { endX = width; } if (endY > height) { endY = height; } bool[,] keep = new bool[gridSize, gridSize]; float[,] tmpBlock = new float[gridSize, gridSize]; for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { float val = src [x, y]; if (val < 0) { val = -val; } tmpBlock [x - startX, y - startY] = val; } } for (int k = 0; k < n; k++) { float max = -1.0f; int maxIdxX = -1, maxIdxY = -1; for (int y = 0; y < gridSize; y++) { for (int x = 0; x < gridSize; x++) { if (!keep [x, y]) if (tmpBlock [x, y] > max) { max = tmpBlock [x, y]; maxIdxX = x; maxIdxY = y; } } } keep [maxIdxX, maxIdxY] = true; //Scale all major coefficients (with greater amplitutes) //by the coresponding scale factor if (scaleFactorsMajors != null) { int x = startX + maxIdxX; int y = startY + maxIdxY; //x and y can be out of bounds! if (x > endX - 1) { x = endX - 1; } if (y > endY - 1) { y = endY - 1; } src [x, y] *= scaleFactorsMajors [k]; } } //all minor coefficients (with small amplitutes) //are multiplied by a certain factor (for denoising typically zero) for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { if (!keep [x - startX, y - startY]) src [x, y] *= scaleFactorsMinors; } } } /// <exception cref="ArgumentException"></exception> private void ModifyCoefficients (float[,] src, int n, float[] scaleFactorsMajors, float scaleFactorsMinors, int gridSize, ProgressDelegate progressDelegate) { //Note: ModifyCoefficients should not be called directly, as //it is not thread safe. The critical section must be started //in the calling method checkArrayArgument (src, "src"); if (scaleFactorsMajors != null) { if (scaleFactorsMajors.Length != n) { throw new ArgumentException ("scaleFactorsMajors must be null or the length must be of dimension n (" + n + ")"); } } if (gridSize < 1) { throw new ArgumentException ("gridSize (" + gridSize + ") cannot be smaller than 1"); } if (n < 0) { throw new ArgumentException ("n (" + n + ") cannot be negative"); } if (n > gridSize * gridSize) { throw new ArgumentException ("n (" + n + ") cannot be greater than " + gridSize + "*" + gridSize); } int w = width / gridSize; if ((width % gridSize) != 0) { w++; } int h = height / gridSize; if ((height % gridSize) != 0) { h++; } int numBlocks = w * h; initProgress (progressDelegate, numBlocks); if (this.enableParallel) { Parallel.For (0, numBlocks, (block, loopState) => { int startX = (block % w) * gridSize; int startY = (block / w) * gridSize; ModfiyBlock (src, n, scaleFactorsMajors, scaleFactorsMinors, gridSize, startX, startY); if (updateProgress (1)) { loopState.Stop (); } }); } else { for (int block = 0; block < numBlocks; block++) { int startX = (block % w) * gridSize; int startY = (block / w) * gridSize; ModfiyBlock (src, n, scaleFactorsMajors, scaleFactorsMinors, gridSize, startX, startY); if (updateProgress (1)) { break; } } } } private void getBlockCoefficientsRange (float[,] src, int offsetX, int offsetY, int width, int height, out float min, out float max, bool enableParallel, bool enableProgress, ProgressDelegate progressDelegate) { float minVal = float.MaxValue; float maxVal = float.MinValue; if (enableParallel) { object sync = new object (); Parallel.For (0, height, (y, loopState) => { float thrdMinVal = float.MaxValue; float thrdMaxVal = float.MinValue; for (int x = 0; x < width; x++) { float val = src [x, y]; if (val < 0) { val = -val; } if (val < thrdMinVal) { thrdMinVal = val; } else if (val > thrdMaxVal) { thrdMaxVal = val; } } lock (sync) { if (thrdMinVal < minVal) { minVal = thrdMinVal; } if (thrdMaxVal > maxVal) { maxVal = thrdMaxVal; } } if (enableProgress) { if (updateProgress (1)) { loopState.Stop (); } } }); } else { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float val = src [x, y]; if (val < 0) { val = -val; } if (val < minVal) { minVal = val; } else if (val > maxVal) { maxVal = val; } } if (enableProgress) { if (updateProgress (1)) { break; } } } } min = minVal; max = maxVal; } #endregion #region virtual methods which get overwritten by derived class /// <summary> /// Performs a single horizontal transformation (transformation of a single row) /// </summary> /// <param name="src">2d float array on which should be used as source for the transformation</param> /// <param name="dst">2d float array on which should be used as destination for the transformation</param> /// <param name="y">index of the row which should be transformed</param> /// <param name="length">number of entries to transform</param> virtual protected void TransformRow (float[,] src, float[,] dst, int y, int length) { //will be overwritten by method of derived class... } /// <summary> /// Performs a single vertical transformation (transformation of a single column) /// </summary> /// <param name="src">2d float array on which should be used as source for the transformation</param> /// <param name="dst">2d float array on which should be used as destination for the transformation</param> /// <param name="x">index of the row which should be transformed</param> /// <param name="length">number of entries to transform</param> virtual protected void TransformCol (float[,] src, float[,] dst, int x, int length) { //will be overwritten by method of derived class... } /// <summary> /// Performs a single inverse horizontal transformation (transformation of a single row) /// </summary> /// <param name="src">2d float array on which should be used as source for the transformation</param> /// <param name="dst">2d float array on which should be used as destination for the transformation</param> /// <param name="y">index of the row which should be transformed</param> /// <param name="length">number of entries to transform</param> virtual protected void InvTransformRow (float[,] src, float[,] dst, int y, int length) { //will be overwritten by method of derived class... } /// <summary> /// Performs a single inverse vertical transformation (transformation of a single column) /// </summary> /// <param name="src">2d float array on which should be used as source for the transformation</param> /// <param name="dst">2d float array on which should be used as destination for the transformation</param> /// <param name="x">index of the row which should be transformed</param> /// <param name="length">number of entries to transform</param> virtual protected void InvTransformCol (float[,] src, float[,] dst, int x, int length) { //will be overwritten by method of derived class... } #endregion virtual protected void TransformRows (float[,] src, float[,] dst, int w, int h) { if (enableParallel) { Parallel.For (0, h, (y, loopState) => { if (updateProgress (w)) { loopState.Stop (); } TransformRow (src, dst, y, w); }); } else { for (int y = 0; y < h; y++) { if (updateProgress (w)) { break; } TransformRow (src, dst, y, w); } } } virtual protected void TransformCols (float[,] src, float[,] dst, int w, int h) { if (enableParallel) { Parallel.For (0, w, (x, loopState) => { if (updateProgress (h)) { loopState.Stop (); } TransformCol (src, dst, x, h); }); } else { for (int x = 0; x < w; x++) { if (updateProgress (h)) { break; } TransformCol (src, dst, x, h); } } } virtual protected void InvTransformRows (float[,] src, float[,] dst, int w, int h) { if (enableParallel) { Parallel.For (0, h, (y, loopState) => { if (updateProgress (w)) { loopState.Stop (); } InvTransformRow (src, dst, y, w); }); } else { for (int y = 0; y < h; y++) { if (updateProgress (w)) { break; } InvTransformRow (src, dst, y, w); } } } virtual protected void InvTransformCols (float[,] src, float[,] dst, int w, int h) { if (enableParallel) { Parallel.For (0, w, (x, loopState) => { if (updateProgress (h)) { loopState.Stop (); } InvTransformCol (src, dst, x, h); }); } else { for (int x = 0; x < w; x++) { if (updateProgress (h)) { break; } InvTransformCol (src, dst, x, h); } } } /// <summary> /// Perfroms a two dimensional isotropic wavelet transformation for an array. The result is copied back to the declared array. /// </summary> /// <param name="src">two dimensional float array to perform the the wavelet transformation on</param> /// <exception cref="ArgumentException"></exception> virtual public void TransformIsotropic2D (float[,] src, ProgressDelegate progressDelegate = null) { lock (threadSync) { checkArrayArgument (src, "src"); float[,] tmp = getTempArray (); int w = width, h = height; initProgress (progressDelegate); while ((w >= minSize) && (h >= minSize) && (!updateProgress(0))) { TransformRows (src, tmp, w, h); TransformCols (tmp, src, w, h); // shift always rounds down (towards negative infinity) //However, for odd lengths we have one low-pass value more than //high-pass values. By shifting the negative value and negating the result //we get the desired result. w = -(-w >> 1); h = -(-h >> 1); } } } /// <summary> /// Perfroms a two dimensional isotropic wavelet transformation for an array. The result is copied back to the declared array. /// </summary> /// <exception cref="ArgumentException"></exception> virtual public void BacktransformIsotropic2D (float[,] src, ProgressDelegate progressDelegate = null) { lock (threadSync) { checkArrayArgument (src, "src"); //Calculate the integral digits of log to the base two of the maximum of "width" and "height" //The resulting number of "width | height" cannot have a greater log to the base 2 (integral digits) //than the greater of both values. int log2 = 1; int test = 1; while (test < (width | height)) { test <<= 1; log2++; } float[,] tmp = getTempArray (); int i = 1; initProgress (progressDelegate); while ((i <= log2) && (!updateProgress(0))) { //Shift always rounds down (towards negative infinity) //However, for odd lengths we have one more low-pass value than //high-pass values. By shifting the negative value and negating the result //we get the desired result. int w = -(-width >> (log2 - i)); int h = -(-height >> (log2 - i)); if ((w >= minSize) && (h >= minSize)) { InvTransformCols (src, tmp, w, h); InvTransformRows (tmp, src, w, h); } i++; } } } /// <summary> /// Scales the n (length of the scaleFactors array) greatest coefficinets (for a defined grid size) by the value declared in scaleFactors. /// </summary> /// <exception cref="ArgumentException"></exception> virtual public void ScaleCoefficients (float[,] src, float[] scaleFactors, int gridSize, ProgressDelegate progressDelegate = null) { lock (threadSync) { if (scaleFactors == null) { throw new ArgumentException ("scaleFactors cannot be null"); } if (scaleFactors.Length > gridSize * gridSize) { throw new ArgumentException ("scaleFactors lenght cannot be greater than " + gridSize * gridSize); } ModifyCoefficients (src, scaleFactors.Length, scaleFactors, 1.0f, gridSize, progressDelegate); } } /// <summary> /// Set all but the greatest n coefficient to zero in the defined grid size /// </summary> /// <exception cref="ArgumentException"></exception> virtual public void CropCoefficients (float[,] src, int n, int gridSize, ProgressDelegate progressDelegate = null) { lock (threadSync) { ModifyCoefficients (src, n, null, 0.0f, gridSize, progressDelegate); } } /// <summary> /// Set all coefficient with an absolute value smaller then "minAbsoluteValue" to zero (deadzone) /// </summary> /// <exception cref="ArgumentException"></exception> virtual public void CropCoefficients (float[,] src, float minAbsoluteValue, ProgressDelegate progressDelegate = null) { lock (threadSync) { checkArrayArgument (src, "src"); initProgress (progressDelegate, height); if (enableParallel) { Parallel.For (0, height, (y, loopState) => { for (int x = 0; x < width; x++) { float val = src [x, y]; if ((val < minAbsoluteValue) && (-val < minAbsoluteValue)) { //Same as Math.Abs(val) < minAbsoluteValue src [x, y] = 0.0f; } } if (updateProgress (1)) { loopState.Stop (); } }); } else { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float val = src [x, y]; if ((val < minAbsoluteValue) && (-val < minAbsoluteValue)) { //Same as Math.Abs(val) < minAbsoluteValue src [x, y] = 0.0f; } } if (updateProgress (1)) { break; } } } } } /// <summary> /// get the minimum and maximum amplitude (absolute values) of all coefficient values /// </summary> /// <exception cref="ArgumentException"></exception> virtual public void getCoefficientsRange (float[,] src, out float min, out float max, ProgressDelegate progressDelegate = null) { lock (threadSync) { checkArrayArgument (src, "src"); initProgress (progressDelegate, height); getBlockCoefficientsRange (src, 0, 0, width, height, out min, out max, enableParallel, true, progressDelegate); } } /* virtual public float getQuantil(float[,] src, float p) { int numCoeffs = p * width * height; int gridSize = (int)(Math.Sqrt(numCoeffs) + 1); int w = width / gridSize; if ((width % gridSize) != 0) { w++; } int h = height / gridSize; if ((height % gridSize) != 0) { h++; } float[,] minValues = new float[w, h]; float[,] maxValues = new float[w, h]; int numBlocks = w * h; initProgress (progressDelegate, numBlocks); if (this.enableParallel) { Parallel.For (0, numBlocks, (block, loopState) => { int startX = (block % w) * gridSize; int startY = (block / w) * gridSize; int endX = startX + gridSize; int endY = startY + gridSize; getBlockCoefficientsRange (src, startX, startY, endX - startX, endY - startY, minValues[], max, enableParallel, progressDelegate); ModfiyBlock (src, n, scaleFactorsMajors, scaleFactorsMinors, gridSize, startX, startY); if (updateProgress (1)) { loopState.Stop (); } }); } else { for (int block = 0; block < numBlocks; block++) { int startX = (block % w) * gridSize; int startY = (block / w) * gridSize; ModfiyBlock (src, n, scaleFactorsMajors, scaleFactorsMinors, gridSize, startX, startY); if (updateProgress (1)) { break; } } } } */ } }
using System; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; namespace SIMRS.DataAccess { public class RS_RM : DBInteractionBase { #region Class Member Declarations private SqlInt64 _registrasiId; private SqlBoolean _flagTerakhir; private SqlDateTime _tanggalMasuk, _tanggalKeluar, _createdDate, _modifiedDate, _tanggalPeriksa; private SqlInt32 _dokterId, _dokterIdOld, _statusRMId, _modifiedBy, _createdBy; private SqlString _obat, _tindakanMedis, _keteranganStatus, _keterangan, _keluhanTambahan, _pemeriksaanFisik, _keluhanUtama, _perawat, _jamPeriksa, _penyakitSebelumnya, _penyakitKeluarga, _penyakitSekarang, _pemeriksaanLab, _diagnosa; #endregion public RS_RM() { // Nothing for now. } public override bool Insert() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_Insert]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@DokterId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _dokterId)); cmdToExecute.Parameters.Add(new SqlParameter("@Perawat", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _perawat)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalPeriksa", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalPeriksa)); cmdToExecute.Parameters.Add(new SqlParameter("@JamPeriksa", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _jamPeriksa)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalMasuk", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalMasuk)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalKeluar", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalKeluar)); cmdToExecute.Parameters.Add(new SqlParameter("@KeluhanUtama", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keluhanUtama)); cmdToExecute.Parameters.Add(new SqlParameter("@KeluhanTambahan", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keluhanTambahan)); cmdToExecute.Parameters.Add(new SqlParameter("@PemeriksaanFisik", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _pemeriksaanFisik)); cmdToExecute.Parameters.Add(new SqlParameter("@PemeriksaanLab", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _pemeriksaanLab)); cmdToExecute.Parameters.Add(new SqlParameter("@Diagnosa", SqlDbType.VarChar, 1000, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _diagnosa)); cmdToExecute.Parameters.Add(new SqlParameter("@PenyakitSekarang", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _penyakitSekarang)); cmdToExecute.Parameters.Add(new SqlParameter("@PenyakitSebelumnya", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _penyakitSebelumnya)); cmdToExecute.Parameters.Add(new SqlParameter("@PenyakitKeluarga", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _penyakitKeluarga)); cmdToExecute.Parameters.Add(new SqlParameter("@TindakanMedis", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tindakanMedis)); cmdToExecute.Parameters.Add(new SqlParameter("@Obat", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _obat)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusRMId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusRMId)); cmdToExecute.Parameters.Add(new SqlParameter("@KeteranganStatus", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keteranganStatus)); cmdToExecute.Parameters.Add(new SqlParameter("@FlagTerakhir", SqlDbType.Bit, 1, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _flagTerakhir)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_Insert' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::Insert::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } public override bool Update() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_Update]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@DokterId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _dokterId)); cmdToExecute.Parameters.Add(new SqlParameter("@Perawat", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _perawat)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalPeriksa", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalPeriksa)); cmdToExecute.Parameters.Add(new SqlParameter("@JamPeriksa", SqlDbType.VarChar, 50, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _jamPeriksa)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalMasuk", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalMasuk)); cmdToExecute.Parameters.Add(new SqlParameter("@TanggalKeluar", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tanggalKeluar)); cmdToExecute.Parameters.Add(new SqlParameter("@KeluhanUtama", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keluhanUtama)); cmdToExecute.Parameters.Add(new SqlParameter("@KeluhanTambahan", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keluhanTambahan)); cmdToExecute.Parameters.Add(new SqlParameter("@PemeriksaanFisik", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _pemeriksaanFisik)); cmdToExecute.Parameters.Add(new SqlParameter("@PemeriksaanLab", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _pemeriksaanLab)); cmdToExecute.Parameters.Add(new SqlParameter("@Diagnosa", SqlDbType.VarChar, 1000, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _diagnosa)); cmdToExecute.Parameters.Add(new SqlParameter("@PenyakitSekarang", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _penyakitSekarang)); cmdToExecute.Parameters.Add(new SqlParameter("@PenyakitSebelumnya", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _penyakitSebelumnya)); cmdToExecute.Parameters.Add(new SqlParameter("@PenyakitKeluarga", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _penyakitKeluarga)); cmdToExecute.Parameters.Add(new SqlParameter("@TindakanMedis", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _tindakanMedis)); cmdToExecute.Parameters.Add(new SqlParameter("@Obat", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _obat)); cmdToExecute.Parameters.Add(new SqlParameter("@Keterangan", SqlDbType.VarChar, 500, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keterangan)); cmdToExecute.Parameters.Add(new SqlParameter("@StatusRMId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _statusRMId)); cmdToExecute.Parameters.Add(new SqlParameter("@KeteranganStatus", SqlDbType.VarChar, 255, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _keteranganStatus)); cmdToExecute.Parameters.Add(new SqlParameter("@FlagTerakhir", SqlDbType.Bit, 1, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _flagTerakhir)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _createdBy)); cmdToExecute.Parameters.Add(new SqlParameter("@CreatedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _createdDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedBy", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _modifiedBy)); cmdToExecute.Parameters.Add(new SqlParameter("@ModifiedDate", SqlDbType.DateTime, 8, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, _modifiedDate)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_Update' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::Update::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } public bool UpdateAllWDokterIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_UpdateAllWDokterIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@DokterId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _dokterId)); cmdToExecute.Parameters.Add(new SqlParameter("@DokterIdOld", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _dokterIdOld)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_UpdateAllWDokterIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::UpdateAllWDokterIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } public override bool Delete() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_Delete]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_Delete' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::Delete::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } public bool DeleteAllWDokterIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_DeleteAllWDokterIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@DokterId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _dokterId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_DeleteAllWDokterIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::DeleteAllWDokterIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } public override DataTable SelectOne() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_SelectOne]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_RM"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@RegistrasiId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _registrasiId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_SelectOne' reported the ErrorCode: " + _errorCode); } if(toReturn.Rows.Count > 0) { _registrasiId = (Int64)toReturn.Rows[0]["RegistrasiId"]; _dokterId = toReturn.Rows[0]["DokterId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["DokterId"]; _perawat = toReturn.Rows[0]["Perawat"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Perawat"]; _tanggalPeriksa = toReturn.Rows[0]["TanggalPeriksa"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalPeriksa"]; _jamPeriksa = toReturn.Rows[0]["JamPeriksa"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["JamPeriksa"]; _tanggalMasuk = toReturn.Rows[0]["TanggalMasuk"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalMasuk"]; _tanggalKeluar = toReturn.Rows[0]["TanggalKeluar"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["TanggalKeluar"]; _keluhanUtama = toReturn.Rows[0]["KeluhanUtama"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["KeluhanUtama"]; _keluhanTambahan = toReturn.Rows[0]["KeluhanTambahan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["KeluhanTambahan"]; _pemeriksaanFisik = toReturn.Rows[0]["PemeriksaanFisik"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["PemeriksaanFisik"]; _pemeriksaanLab = toReturn.Rows[0]["PemeriksaanLab"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["PemeriksaanLab"]; _diagnosa = toReturn.Rows[0]["Diagnosa"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Diagnosa"]; _penyakitSekarang = toReturn.Rows[0]["PenyakitSekarang"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["PenyakitSekarang"]; _penyakitSebelumnya = toReturn.Rows[0]["PenyakitSebelumnya"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["PenyakitSebelumnya"]; _penyakitKeluarga = toReturn.Rows[0]["PenyakitKeluarga"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["PenyakitKeluarga"]; _tindakanMedis = toReturn.Rows[0]["TindakanMedis"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["TindakanMedis"]; _obat = toReturn.Rows[0]["Obat"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Obat"]; _keterangan = toReturn.Rows[0]["Keterangan"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["Keterangan"]; _statusRMId = toReturn.Rows[0]["StatusRMId"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["StatusRMId"]; _keteranganStatus = toReturn.Rows[0]["KeteranganStatus"] == System.DBNull.Value ? SqlString.Null : (string)toReturn.Rows[0]["KeteranganStatus"]; _flagTerakhir = toReturn.Rows[0]["FlagTerakhir"] == System.DBNull.Value ? SqlBoolean.Null : (bool)toReturn.Rows[0]["FlagTerakhir"]; _createdBy = toReturn.Rows[0]["CreatedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["CreatedBy"]; _createdDate = toReturn.Rows[0]["CreatedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["CreatedDate"]; _modifiedBy = toReturn.Rows[0]["ModifiedBy"] == System.DBNull.Value ? SqlInt32.Null : (Int32)toReturn.Rows[0]["ModifiedBy"]; _modifiedDate = toReturn.Rows[0]["ModifiedDate"] == System.DBNull.Value ? SqlDateTime.Null : (DateTime)toReturn.Rows[0]["ModifiedDate"]; } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::SelectOne::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: SelectAll method. This method will Select all rows from the table. /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public override DataTable SelectAll() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_SelectAll]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_RM"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_SelectAll' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::SelectAll::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'DokterId' /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>DokterId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable SelectAllWDokterIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[RS_RM_SelectAllWDokterIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("RS_RM"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@DokterId", SqlDbType.Int, 4, ParameterDirection.Input, true, 10, 0, "", DataRowVersion.Proposed, _dokterId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, true, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'RS_RM_SelectAllWDokterIdLogic' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("RS_RM::SelectAllWDokterIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } #region Class Property Declarations public SqlInt64 RegistrasiId { get { return _registrasiId; } set { SqlInt64 registrasiIdTmp = (SqlInt64)value; if(registrasiIdTmp.IsNull) { throw new ArgumentOutOfRangeException("RegistrasiId", "RegistrasiId can't be NULL"); } _registrasiId = value; } } public SqlInt32 DokterId { get { return _dokterId; } set { _dokterId = value; } } public SqlInt32 DokterIdOld { get { return _dokterIdOld; } set { _dokterIdOld = value; } } public SqlString Perawat { get { return _perawat; } set { _perawat = value; } } public SqlDateTime TanggalPeriksa { get { return _tanggalPeriksa; } set { _tanggalPeriksa = value; } } public SqlString JamPeriksa { get { return _jamPeriksa; } set { _jamPeriksa = value; } } public SqlDateTime TanggalMasuk { get { return _tanggalMasuk; } set { _tanggalMasuk = value; } } public SqlDateTime TanggalKeluar { get { return _tanggalKeluar; } set { _tanggalKeluar = value; } } public SqlString KeluhanUtama { get { return _keluhanUtama; } set { _keluhanUtama = value; } } public SqlString KeluhanTambahan { get { return _keluhanTambahan; } set { _keluhanTambahan = value; } } public SqlString PemeriksaanFisik { get { return _pemeriksaanFisik; } set { _pemeriksaanFisik = value; } } public SqlString PemeriksaanLab { get { return _pemeriksaanLab; } set { _pemeriksaanLab = value; } } public SqlString Diagnosa { get { return _diagnosa; } set { _diagnosa = value; } } public SqlString PenyakitSekarang { get { return _penyakitSekarang; } set { _penyakitSekarang = value; } } public SqlString PenyakitSebelumnya { get { return _penyakitSebelumnya; } set { _penyakitSebelumnya = value; } } public SqlString PenyakitKeluarga { get { return _penyakitKeluarga; } set { _penyakitKeluarga = value; } } public SqlString TindakanMedis { get { return _tindakanMedis; } set { _tindakanMedis = value; } } public SqlString Obat { get { return _obat; } set { _obat = value; } } public SqlString Keterangan { get { return _keterangan; } set { _keterangan = value; } } public SqlInt32 StatusRMId { get { return _statusRMId; } set { _statusRMId = value; } } public SqlString KeteranganStatus { get { return _keteranganStatus; } set { _keteranganStatus = value; } } public SqlBoolean FlagTerakhir { get { return _flagTerakhir; } set { _flagTerakhir = value; } } public SqlInt32 CreatedBy { get { return _createdBy; } set { _createdBy = value; } } public SqlDateTime CreatedDate { get { return _createdDate; } set { _createdDate = value; } } public SqlInt32 ModifiedBy { get { return _modifiedBy; } set { _modifiedBy = value; } } public SqlDateTime ModifiedDate { get { return _modifiedDate; } set { _modifiedDate = value; } } #endregion } }
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.BackupServices; using Microsoft.Azure.Management.BackupServices.Models; namespace Microsoft.Azure.Management.BackupServices { public static partial class ContainerOperationsExtensions { /// <summary> /// Get the list of all container based on the given query filter /// string. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='parameters'> /// Optional. Container query parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a CSMContainerListOperationResponse. /// </returns> public static CSMContainerListOperationResponse List(this IContainerOperations operations, string resourceGroupName, string resourceName, ContainerQueryParameters parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IContainerOperations)s).ListAsync(resourceGroupName, resourceName, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all container based on the given query filter /// string. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='parameters'> /// Optional. Container query parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a CSMContainerListOperationResponse. /// </returns> public static Task<CSMContainerListOperationResponse> ListAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, ContainerQueryParameters parameters, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(resourceGroupName, resourceName, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Trigger the Discovery. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static OperationResponse Refresh(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IContainerOperations)s).RefreshAsync(resourceGroupName, resourceName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Trigger the Discovery. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static Task<OperationResponse> RefreshAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders) { return operations.RefreshAsync(resourceGroupName, resourceName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Register the container. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='containerName'> /// Required. Container to be register. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static OperationResponse Register(this IContainerOperations operations, string resourceGroupName, string resourceName, string containerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IContainerOperations)s).RegisterAsync(resourceGroupName, resourceName, containerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Register the container. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='containerName'> /// Required. Container to be register. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static Task<OperationResponse> RegisterAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string containerName, CustomRequestHeaders customRequestHeaders) { return operations.RegisterAsync(resourceGroupName, resourceName, containerName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Unregister the container. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='containerName'> /// Required. Container which we want to unregister. /// </param> /// <param name='customRequestHeaders'> /// Required. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static OperationResponse Unregister(this IContainerOperations operations, string resourceGroupName, string resourceName, string containerName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IContainerOperations)s).UnregisterAsync(resourceGroupName, resourceName, containerName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unregister the container. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.BackupServices.IContainerOperations. /// </param> /// <param name='resourceGroupName'> /// Required. /// </param> /// <param name='resourceName'> /// Required. /// </param> /// <param name='containerName'> /// Required. Container which we want to unregister. /// </param> /// <param name='customRequestHeaders'> /// Required. Request header parameters. /// </param> /// <returns> /// The definition of a Operation Response. /// </returns> public static Task<OperationResponse> UnregisterAsync(this IContainerOperations operations, string resourceGroupName, string resourceName, string containerName, CustomRequestHeaders customRequestHeaders) { return operations.UnregisterAsync(resourceGroupName, resourceName, containerName, customRequestHeaders, CancellationToken.None); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.Parallel; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [ParallelFixture] public class ShortKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStackAlloc() { VerifyKeyword( @"class C { int* foo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFixedStatement() { VerifyKeyword( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDelegateReturnType() { VerifyKeyword( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType() { VerifyKeyword(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType2() { VerifyKeyword(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOuterConst() { VerifyKeyword( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterInnerConst() { VerifyKeyword(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InEmptyStatement() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void EnumBaseTypes() { VerifyKeyword( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType1() { VerifyKeyword(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType2() { VerifyKeyword(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType3() { VerifyKeyword(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType4() { VerifyKeyword(AddInsideMethod( @"IList<IFoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInBaseList() { VerifyAbsence( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType_InBaseList() { VerifyKeyword( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIs() { VerifyKeyword(AddInsideMethod( @"var v = foo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterAs() { VerifyKeyword(AddInsideMethod( @"var v = foo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethod() { VerifyKeyword( @"class C { void Foo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterField() { VerifyKeyword( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterProperty() { VerifyKeyword( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAttribute() { VerifyKeyword( @"class C { [foo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideStruct() { VerifyKeyword( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideInterface() { VerifyKeyword( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideClass() { VerifyKeyword( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPartial() { VerifyAbsence(@"partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNestedPartial() { VerifyAbsence( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAbstract() { VerifyKeyword( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedInternal() { VerifyKeyword( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStaticPublic() { VerifyKeyword( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublicStatic() { VerifyKeyword( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterVirtualPublic() { VerifyKeyword( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublic() { VerifyKeyword( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPrivate() { VerifyKeyword( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedProtected() { VerifyKeyword( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedSealed() { VerifyKeyword( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStatic() { VerifyKeyword( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InLocalVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForeachVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InUsingVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFromVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InJoinVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodOpenParen() { VerifyKeyword( @"class C { void Foo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodComma() { VerifyKeyword( @"class C { void Foo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodAttribute() { VerifyKeyword( @"class C { void Foo(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorOpenParen() { VerifyKeyword( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorComma() { VerifyKeyword( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorAttribute() { VerifyKeyword( @"class C { public C(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateOpenParen() { VerifyKeyword( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateComma() { VerifyKeyword( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateAttribute() { VerifyKeyword( @"delegate void D(int i, [Foo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterThis() { VerifyKeyword( @"static class C { public static void Foo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterRef() { VerifyKeyword( @"class C { void Foo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOut() { VerifyKeyword( @"class C { void Foo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaRef() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaOut() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterParams() { VerifyKeyword( @"class C { void Foo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InImplicitOperator() { VerifyKeyword( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InExplicitOperator() { VerifyKeyword( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracket() { VerifyKeyword( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracketComma() { VerifyKeyword( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNewInExpression() { VerifyKeyword(AddInsideMethod( @"new $$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InTypeOf() { VerifyKeyword(AddInsideMethod( @"typeof($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefault() { VerifyKeyword(AddInsideMethod( @"default($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InSizeOf() { VerifyKeyword(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInObjectInitializerMemberContext() { VerifyAbsence(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContext() { VerifyKeyword(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContextNotAfterDot() { VerifyAbsence(@" /// <see cref=""System.$$"" /> class C { } "); } [WorkItem(18374)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterAsyncAsType() { VerifyAbsence(@"class c { async async $$ }"); } } }
// // 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.Collections.Generic; using Encog.App.Analyst.CSV.Basic; using Encog.ML.Prg.ExpValue; using Encog.ML.Prg.Ext; using Encog.Util.CSV; namespace Encog.App.Analyst.CSV.Process { public class ProcessExtension { public const String EXTENSION_DATA_NAME = "ENCOG-ANALYST-PROCESS"; // add field public static IProgramExtensionTemplate OPCODE_FIELD = new BasicTemplate( BasicTemplate.NoPrec, "field({s}{i}):{s}", NodeType.Function, true, 0, (actual) => { var pe = (ProcessExtension) actual.Owner.GetExtraData(EXTENSION_DATA_NAME); string fieldName = actual.GetChildNode(0).Evaluate().ToStringValue(); int fieldIndex = (int) actual.GetChildNode(1).Evaluate().ToFloatValue() + pe.BackwardWindowSize; String value = pe.GetField(fieldName, fieldIndex); return new ExpressionValue(value); }, null, null); // add fieldmax public static IProgramExtensionTemplate OPCODE_FIELDMAX = new BasicTemplate( BasicTemplate.NoPrec, "fieldmax({s}{i}{i}):{f}", NodeType.Function, true, 0, (actual) => { var pe = (ProcessExtension) actual.Owner.GetExtraData(EXTENSION_DATA_NAME); String fieldName = actual.GetChildNode(0).Evaluate().ToStringValue(); var startIndex = (int) actual.GetChildNode(1).Evaluate().ToIntValue(); var stopIndex = (int) actual.GetChildNode(2).Evaluate().ToIntValue(); double value = double.NegativeInfinity; for (int i = startIndex; i <= stopIndex; i++) { String str = pe.GetField(fieldName, pe.BackwardWindowSize + i); double d = pe.format.Parse(str); value = Math.Max(d, value); } return new ExpressionValue(value); }, null, null); // add fieldmaxpip public static IProgramExtensionTemplate OPCODE_FIELDMAXPIP = new BasicTemplate( BasicTemplate.NoPrec, "fieldmaxpip({s}{i}{i}):{f}", NodeType.Function, true, 0, (actual) => { var pe = (ProcessExtension) actual.Owner.GetExtraData(EXTENSION_DATA_NAME); String fieldName = actual.GetChildNode(0).Evaluate() .ToStringValue(); var startIndex = (int) actual.GetChildNode(1).Evaluate() .ToIntValue(); var stopIndex = (int) actual.GetChildNode(2).Evaluate() .ToIntValue(); int value = int.MinValue; String str = pe.GetField(fieldName, pe.BackwardWindowSize); double quoteNow = pe.Format.Parse(str); for (int i = startIndex; i <= stopIndex; i++) { str = pe.GetField(fieldName, pe.BackwardWindowSize + i); double d = pe.Format.Parse(str) - quoteNow; d /= 0.0001; d = Math.Round(d); value = Math.Max((int) d, value); } return new ExpressionValue(value); }, null, null); private readonly IList<LoadedRow> data = new List<LoadedRow>(); private readonly CSVFormat format; private readonly IDictionary<string, int> map = new Dictionary<string, int>(); private int backwardWindowSize; private int forwardWindowSize; private int totalWindowSize; /** * Add opcodes to the Encog resource registry. */ public ProcessExtension() { EncogOpcodeRegistry.Instance.Add(OPCODE_FIELD); EncogOpcodeRegistry.Instance.Add(OPCODE_FIELDMAX); EncogOpcodeRegistry.Instance.Add(OPCODE_FIELDMAXPIP); } public ProcessExtension(CSVFormat theFormat) { format = theFormat; } public int ForwardWindowSize { get { return forwardWindowSize; } } public int BackwardWindowSize { get { return backwardWindowSize; } } public int TotalWindowSize { get { return totalWindowSize; } } public CSVFormat Format { get { return format; } } public String GetField(String fieldName, int fieldIndex) { if (!map.ContainsKey(fieldName)) { throw new AnalystError("Unknown input field: " + fieldName); } int idx = map[fieldName]; if (fieldIndex >= data.Count || fieldIndex < 0) { throw new AnalystError( "The specified temporal index " + fieldIndex + " is out of bounds. You should probably increase the forward window size."); } return data[fieldIndex].Data[idx]; } public void LoadRow(LoadedRow row) { data.Insert(0, row); if (data.Count > totalWindowSize) { data.RemoveAt(data.Count - 1); } } public void Init(ReadCSV csv, int theBackwardWindowSize, int theForwardWindowSize) { forwardWindowSize = theForwardWindowSize; backwardWindowSize = theBackwardWindowSize; totalWindowSize = forwardWindowSize + backwardWindowSize + 1; int i = 0; foreach (string name in csv.ColumnNames) { map[name] = i++; } } public bool IsDataReady() { return data.Count >= totalWindowSize; } public void register(FunctionFactory functions) { functions.AddExtension(OPCODE_FIELD); functions.AddExtension(OPCODE_FIELDMAX); functions.AddExtension(OPCODE_FIELDMAXPIP); } } }
using Microsoft.Data.Entity.Migrations; namespace AllReady.Migrations { public partial class FeaturedArticleFlag : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.AddColumn<bool>( name: "Featured", table: "Campaign", nullable: false, defaultValue: false); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill"); migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill"); migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles"); migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles"); migrationBuilder.DropColumn(name: "Featured", table: "Campaign"); migrationBuilder.AddForeignKey( name: "FK_Activity_Campaign_CampaignId", table: "Activity", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill", column: "ActivityId", principalTable: "Activity", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign", column: "ManagingOrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact", column: "CampaignId", principalTable: "Campaign", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact", column: "ContactId", principalTable: "Contact", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact", column: "OrganizationId", principalTable: "Organization", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill", column: "TaskId", principalTable: "AllReadyTask", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_Skill_SkillId", table: "UserSkill", column: "SkillId", principalTable: "Skill", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles", column: "RoleId", principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles", column: "UserId", principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Zh.Web.Mvc.Framework.Test.Areas.HelpPage.ModelDescriptions; using Zh.Web.Mvc.Framework.Test.Areas.HelpPage.Models; namespace Zh.Web.Mvc.Framework.Test.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Runtime.InteropServices; using VulkanCore.Khr; namespace VulkanCore { /// <summary> /// Opaque handle to a image object. /// <para> /// Images represent multidimensional - up to 3 - arrays of data which can be used for various /// purposes (e.g. attachments, textures), by binding them to a graphics or compute pipeline via /// descriptor sets, or by directly specifying them as parameters to certain commands. /// </para> /// </summary> public unsafe class Image : DisposableHandle<long> { internal Image(Device parent, ref ImageCreateInfo createInfo, ref AllocationCallbacks? allocator) { Parent = parent; Allocator = allocator; fixed (int* queueFamilyIndicesPtr = createInfo.QueueFamilyIndices) { createInfo.ToNative(out ImageCreateInfo.Native nativeCreateInfo, queueFamilyIndicesPtr); long handle; Result result = vkCreateImage(parent, &nativeCreateInfo, NativeAllocator, &handle); VulkanException.ThrowForInvalidResult(result); Handle = handle; } } internal Image(Device parent, long handle, AllocationCallbacks? allocator) { Parent = parent; Allocator = allocator; Handle = handle; } /// <summary> /// Gets the parent of the resource. /// </summary> public Device Parent { get; } /// <summary> /// Bind device memory to an image object. /// </summary> /// <param name="memory">The object describing the device memory to attach.</param> /// <param name="memoryOffset"> /// The start offset of the region of memory which is to be bound to the image. The number of /// bytes returned in the <see cref="MemoryRequirements.Size"/> member in memory, starting /// from <paramref name="memoryOffset"/> bytes, will be bound to the specified image. /// </param> /// <exception cref="VulkanException">Vulkan returns an error code.</exception> public void BindMemory(DeviceMemory memory, long memoryOffset = 0) { Result result = vkBindImageMemory(Parent, this, memory, memoryOffset); VulkanException.ThrowForInvalidResult(result); } /// <summary> /// Returns the memory requirements for the image. /// </summary> /// <returns>Memory requirements of the image object.</returns> public MemoryRequirements GetMemoryRequirements() { MemoryRequirements requirements; vkGetImageMemoryRequirements(Parent, this, &requirements); return requirements; } /// <summary> /// Retrieve information about an image subresource. /// </summary> /// <returns>Subresource layout of an image.</returns> public SubresourceLayout GetSubresourceLayout(ImageSubresource subresource) { SubresourceLayout layout; vkGetImageSubresourceLayout(Parent, this, &subresource, &layout); return layout; } /// <summary> /// Create an image view from an existing image. /// </summary> /// <param name="createInfo"> /// The structure containing parameters to be used to create the image view. /// </param> /// <param name="allocator">Controls host memory allocation.</param> /// <exception cref="VulkanException">Vulkan returns an error code.</exception> public ImageView CreateView(ImageViewCreateInfo createInfo, AllocationCallbacks? allocator = null) { return new ImageView(Parent, this, &createInfo, ref allocator); } /// <summary> /// Query the memory requirements for a sparse image. /// <para> /// If the image was not created with <see cref="ImageCreateFlags.SparseResidency"/> then the /// result will be empty. /// </para> /// </summary> /// <returns>Memory requirements for a sparse image.</returns> public SparseImageMemoryRequirements[] GetSparseMemoryRequirements() { int count; vkGetImageSparseMemoryRequirements(Parent, this, &count, null); var requirements = new SparseImageMemoryRequirements[count]; fixed (SparseImageMemoryRequirements* requirementsPtr = requirements) vkGetImageSparseMemoryRequirements(Parent, this, &count, requirementsPtr); return requirements; } /// <summary> /// Destroy an image object. /// </summary> public override void Dispose() { if (!Disposed) vkDestroyImage(Parent, this, NativeAllocator); base.Dispose(); } private delegate Result vkCreateImageDelegate(IntPtr device, ImageCreateInfo.Native* createInfo, AllocationCallbacks.Native* allocator, long* image); private static readonly vkCreateImageDelegate vkCreateImage = VulkanLibrary.GetStaticProc<vkCreateImageDelegate>(nameof(vkCreateImage)); private delegate void vkGetImageMemoryRequirementsDelegate(IntPtr device, long image, MemoryRequirements* memoryRequirements); private static readonly vkGetImageMemoryRequirementsDelegate vkGetImageMemoryRequirements = VulkanLibrary.GetStaticProc<vkGetImageMemoryRequirementsDelegate>(nameof(vkGetImageMemoryRequirements)); private delegate void vkGetImageSparseMemoryRequirementsDelegate(IntPtr device, long image, int* sparseMemoryRequirementCount, SparseImageMemoryRequirements* sparseMemoryRequirements); private static readonly vkGetImageSparseMemoryRequirementsDelegate vkGetImageSparseMemoryRequirements = VulkanLibrary.GetStaticProc<vkGetImageSparseMemoryRequirementsDelegate>(nameof(vkGetImageSparseMemoryRequirements)); private delegate void vkDestroyImageDelegate(IntPtr device, long image, AllocationCallbacks.Native* allocator); private static readonly vkDestroyImageDelegate vkDestroyImage = VulkanLibrary.GetStaticProc<vkDestroyImageDelegate>(nameof(vkDestroyImage)); private delegate void vkGetImageSubresourceLayoutDelegate(IntPtr device, long image, ImageSubresource* subresource, SubresourceLayout* layout); private static readonly vkGetImageSubresourceLayoutDelegate vkGetImageSubresourceLayout = VulkanLibrary.GetStaticProc<vkGetImageSubresourceLayoutDelegate>(nameof(vkGetImageSubresourceLayout)); private delegate Result vkBindImageMemoryDelegate(IntPtr device, long image, long memory, long memoryOffset); private static readonly vkBindImageMemoryDelegate vkBindImageMemory = VulkanLibrary.GetStaticProc<vkBindImageMemoryDelegate>(nameof(vkBindImageMemory)); } /// <summary> /// Structure specifying the parameters of a newly created image object. /// </summary> public unsafe struct ImageCreateInfo { /// <summary> /// Is <see cref="IntPtr.Zero"/> or a pointer to an extension-specific structure. /// </summary> public IntPtr Next; /// <summary> /// Bitmask describing additional parameters of the image. /// </summary> public ImageCreateFlags Flags; /// <summary> /// Specifies the basic dimensionality of the image. /// <para> /// Layers in array textures do not count as a dimension for the purposes of the image type. /// </para> /// </summary> public ImageType ImageType; /// <summary> /// Describes the format and type of the data elements that will be contained in the image. /// </summary> public Format Format; /// <summary> /// Describes the number of data elements in each dimension of the base level. /// <para>The width, height, and depth members of extent must all be greater than 0.</para> /// </summary> public Extent3D Extent; /// <summary> /// Describes the number of levels of detail available for minified sampling of the image. /// </summary> public int MipLevels; /// <summary> /// The number of layers in the image. /// </summary> public int ArrayLayers; /// <summary> /// The number of sub-data element samples in the image. /// </summary> public SampleCounts Samples; /// <summary> /// Specifies the tiling arrangement of the data elements in memory. /// </summary> public ImageTiling Tiling; /// <summary> /// A bitmask describing the intended usage of the image. /// </summary> public ImageUsages Usage; /// <summary> /// Specifies the sharing mode of the image when it will be accessed by multiple queue families. /// </summary> public SharingMode SharingMode; /// <summary> /// A list of queue families that will access this image (ignored if <see /// cref="SharingMode"/> is not <see cref="VulkanCore.SharingMode.Concurrent"/>). /// </summary> public int[] QueueFamilyIndices; /// <summary> /// Specifies the initial <see cref="ImageLayout"/> of all image subresources of the image. /// </summary> public ImageLayout InitialLayout; [StructLayout(LayoutKind.Sequential)] internal struct Native { public StructureType Type; public IntPtr Next; public ImageCreateFlags Flags; public ImageType ImageType; public Format Format; public Extent3D Extent; public int MipLevels; public int ArrayLayers; public SampleCounts Samples; public ImageTiling Tiling; public ImageUsages Usage; public SharingMode SharingMode; public int QueueFamilyIndexCount; public int* QueueFamilyIndices; public ImageLayout InitialLayout; } internal void ToNative(out Native native, int* queueFamilyIndices) { native.Type = StructureType.ImageCreateInfo; native.Next = Next; native.Flags = Flags; native.ImageType = ImageType; native.Format = Format; native.Extent = Extent; native.MipLevels = MipLevels; native.ArrayLayers = ArrayLayers; native.Samples = Samples; native.Tiling = Tiling; native.Usage = Usage; native.SharingMode = SharingMode; native.QueueFamilyIndexCount = QueueFamilyIndices?.Length ?? 0; native.QueueFamilyIndices = queueFamilyIndices; native.InitialLayout = InitialLayout; } } /// <summary> /// Bitmask specifying additional parameters of an image. /// </summary> [Flags] public enum ImageCreateFlags { /// <summary> /// No flags. /// </summary> None = 0, /// <summary> /// Specifies that the image will be backed using sparse memory binding. /// </summary> SparseBinding = 1 << 0, /// <summary> /// Specifies that the image can be partially backed using sparse memory binding. Images /// created with this flag must also be created with the <see cref="SparseBinding"/> flag. /// </summary> SparseResidency = 1 << 1, /// <summary> /// Specifies that the image will be backed using sparse memory binding with memory ranges /// that might also simultaneously be backing another image (or another portion of the same /// image). Images created with this flag must also be created with the <see /// cref="SparseBinding"/> flag. /// </summary> SparseAliased = 1 << 2, /// <summary> /// Specifies that the image can be used to create an <see cref="ImageView"/> with a /// different format from the image. For multi-planar formats, <see cref="MutableFormat"/> /// indicates that a <see cref="ImageView"/> can be created of a plane of the image. /// </summary> MutableFormat = 1 << 3, /// <summary> /// Specifies that the image can be used to create an <see cref="ImageView"/> of type <see /// cref="ImageViewType.ImageCube"/> or <see cref="ImageViewType.ImageCubeArray"/>. /// </summary> CubeCompatible = 1 << 4, /// <summary> /// Specifies that the image can be used to create a <see cref="ImageView"/> of type <see /// cref="ImageViewType.Image2D"/> or <see cref="ImageViewType.Image2DArray"/>. /// </summary> Image2DArrayCompatibleKhr = 1 << 5, /// <summary> /// Indicates that the image having a compressed format can be used to create a <see /// cref="ImageView"/> with an uncompressed format where each texel in the image view /// corresponds to a compressed texel block of the image. /// </summary> BlockTexelViewCompatibleKhr = 1 << 7, /// <summary> /// Indicates that the image can be created with usage flags that are not supported for the /// format the image is created with but are supported for at least one format a <see /// cref="ImageView"/> created from the image can have. /// </summary> ExtendedUsageKhr = 1 << 8, /// <summary> /// Indicates that an image with a multi-planar format must have each plane separately bound /// to memory, rather than having a single memory binding for the whole image; the presence /// of this bit distinguishes a disjoint Image from an image without this bit set. /// </summary> DisjointKhr = 1 << 9, /// <summary> /// Indicates that two images created with the same creation parameters and aliased to the /// same memory can interpret the contents of the memory consistently with each other, /// subject to the rules described in the Memory Aliasing section. This flag further /// indicates that each plane of a disjoint image can share an in-memory non-linear /// representation with single-plane images, and that a single-plane image can share an /// in-memory non-linear representation with a plane of a multi-planar disjoint image, /// according to the rules in features-formats-compatible-planes. If the <c>PNext</c> chain /// includes a structure whose <c>HandleTypes</c> member is not `0`, it is as if <see /// cref="AliasKhr"/> is set. /// </summary> AliasKhr = 1 << 10, /// <summary> /// Specifies that an image with a depth or depth/stencil format can be used with custom /// sample locations when used as a depth/stencil attachment. /// </summary> SampleLocationsCompatibleDepthExt = 1 << 12 } /// <summary> /// Specifies the type of an image object. /// </summary> public enum ImageType { /// <summary> /// Specify a one-dimensional image. /// </summary> Image1D = 0, /// <summary> /// Specify a two-dimensional image. /// </summary> Image2D = 1, /// <summary> /// Specify a three-dimensional image. /// </summary> Image3D = 2 } /// <summary> /// Bitmask specifying intended usage of an image. /// </summary> [Flags] public enum ImageUsages { /// <summary> /// Specifies that the image can be used as the source of a transfer command. /// </summary> TransferSrc = 1 << 0, /// <summary> /// Specifies that the image can be used as the destination of a transfer command. /// </summary> TransferDst = 1 << 1, /// <summary> /// Specifies that the image can be used to create a <see cref="ImageView"/> suitable for /// occupying a <see cref="DescriptorSet"/> slot either of type <see /// cref="DescriptorType.SampledImage"/> or <see /// cref="DescriptorType.CombinedImageSampler"/>, and be sampled by a shader. /// </summary> Sampled = 1 << 2, /// <summary> /// Specifies that the image can be used to create a <see cref="ImageView"/> suitable for /// occupying a <see cref="DescriptorSet"/> slot of type <see cref="DescriptorType.StorageImage"/>. /// </summary> Storage = 1 << 3, /// <summary> /// Specifies that the image can be used to create a <see cref="ImageView"/> suitable for use /// as a color or resolve attachment in a <see cref="Framebuffer"/>. /// </summary> ColorAttachment = 1 << 4, /// <summary> /// Specifies that the image can be used to create a <see cref="ImageView"/> suitable for use /// as a depth/stencil attachment in a <see cref="Framebuffer"/>. /// </summary> DepthStencilAttachment = 1 << 5, /// <summary> /// Specifies that the memory bound to this image will have been allocated with the <see /// cref="MemoryProperties.LazilyAllocated"/>. This bit can be set for any image that can /// be used to create a <see cref="ImageView"/> suitable for use as a color, resolve, /// depth/stencil, or input attachment. /// </summary> TransientAttachment = 1 << 6, /// <summary> /// Specifies that the image can be used to create a <see cref="ImageView"/> suitable for /// occupying <see cref="DescriptorSet"/> slot of type <see /// cref="DescriptorType.InputAttachment"/>; be read from a shader as an input attachment; /// and be used as an input attachment in a framebuffer. /// </summary> InputAttachment = 1 << 7 } /// <summary> /// Layout of image and image subresources. /// </summary> public enum ImageLayout { /// <summary> /// Does not support device access. This layout must only be used as the <see /// cref="ImageCreateInfo.InitialLayout"/> or <see /// cref="AttachmentDescription.InitialLayout"/> member, or as the old layout in an image /// transition. When transitioning out of this layout, the contents of the memory are not /// guaranteed to be preserved. /// </summary> Undefined = 0, /// <summary> /// Supports all types of device access. /// </summary> General = 1, /// <summary> /// Must only be used as a color or resolve attachment in a <see cref="Framebuffer"/>. This /// layout is valid only for image subresources of images created with the <see /// cref="ImageUsages.ColorAttachment"/> usage bit enabled. /// </summary> ColorAttachmentOptimal = 2, /// <summary> /// Must only be used as a depth/stencil attachment in a <see cref="Framebuffer"/>. This /// layout is valid only for image subresources of images created with the <see /// cref="ImageUsages.DepthStencilAttachment"/> usage bit enabled. /// </summary> DepthStencilAttachmentOptimal = 3, /// <summary> /// Must only be used as a read-only depth/stencil attachment in a <see cref="Framebuffer"/> /// and/or as a read-only image in a shader (which can be read as a sampled image, combined /// image/sampler and/or input attachment). This layout is valid only for image subresources /// of images created with the <see cref="ImageUsages.DepthStencilAttachment"/> usage bit /// enabled. Only image subresources of images created with <see cref="ImageUsages.Sampled"/> /// can be used as a sampled image or combined image/sampler in a shader. Similarly, only /// image subresources of images created with <see cref="ImageUsages.InputAttachment"/> can /// be used as input attachments. /// </summary> DepthStencilReadOnlyOptimal = 4, /// <summary> /// Must only be used as a read-only image in a shader (which can be read as a sampled image, /// combined image/sampler and/or input attachment). This layout is valid only for image /// subresources of images created with the <see cref="ImageUsages.Sampled"/> or <see /// cref="ImageUsages.InputAttachment"/> usage bit enabled. /// </summary> ShaderReadOnlyOptimal = 5, /// <summary> /// Must only be used as a source image of a transfer command (see the definition of <see /// cref="PipelineStages.Transfer"/>. This layout is valid only for image subresources of /// images created with the <see cref="ImageUsages.TransferSrc"/> usage bit enabled. /// </summary> TransferSrcOptimal = 6, /// <summary> /// Must only be used as a destination image of a transfer command. This layout is valid only /// for image subresources of images created with the <see /// cref="ImageUsages.TransferDst"/> usage bit enabled. /// </summary> TransferDstOptimal = 7, /// <summary> /// Does not support device access. This layout must only be used as the <see /// cref="ImageCreateInfo.InitialLayout"/> or <see /// cref="AttachmentDescription.InitialLayout"/> member, or as the old layout in an image /// transition. When transitioning out of this layout, the contents of the memory are /// preserved. This layout is intended to be used as the initial layout for an image whose /// contents are written by the host, and hence the data can be written to memory /// immediately, without first executing a layout transition. Currently, <see /// cref="Preinitialized"/> is only useful with <see cref="ImageTiling.Linear"/> images /// because there is not a standard layout defined for <see cref="ImageTiling.Optimal"/> images. /// </summary> Preinitialized = 8, /// <summary> /// Must only be used for presenting a swapchain image for display. A swapchain's image must /// be transitioned to this layout before calling <see /// cref="QueueExtensions.PresentKhr(Queue, PresentInfoKhr)"/>, and must be transitioned away /// from this layout after calling <see cref="SwapchainKhr.vkAcquireNextImageKHR"/>. /// </summary> PresentSrcKhr = 1000001002, /// <summary> /// Is valid only for shared presentable images, and must be used for any usage the image supports. /// </summary> SharedPresentKhr = 1000111000, DepthReadOnlyStencilAttachmentOptimalKhr = 1000117000, DepthAttachmentStencilReadOnlyOptimalKhr = 1000117001 } /// <summary> /// Structure specifying an attachment description. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct AttachmentDescription { /// <summary> /// A bitmask specifying additional properties of the attachment. /// </summary> public AttachmentDescriptions Flags; /// <summary> /// Specifies the format of the image that will be used for the attachment. /// </summary> public Format Format; /// <summary> /// The number of samples of the image. /// </summary> public SampleCounts Samples; /// <summary> /// Specifies how the contents of color and depth components of the attachment are treated at /// the beginning of the subpass where it is first used. /// </summary> public AttachmentLoadOp LoadOp; /// <summary> /// Specifies how the contents of color and depth components of the attachment are treated at /// the end of the subpass where it is last used. /// </summary> public AttachmentStoreOp StoreOp; /// <summary> /// Specifies how the contents of stencil components of the attachment are treated at the /// beginning of the subpass where it is first used, and must be one of the same values /// allowed for <see cref="LoadOp"/> above. /// </summary> public AttachmentLoadOp StencilLoadOp; /// <summary> /// Specifies how the contents of stencil components of the attachment are treated at the end /// of the last subpass where it is used, and must be one of the same values allowed for <see /// cref="StoreOp"/> above. /// </summary> public AttachmentStoreOp StencilStoreOp; /// <summary> /// The layout the attachment image subresource will be in when a render pass instance begins. /// </summary> public ImageLayout InitialLayout; /// <summary> /// The layout the attachment image subresource will be transitioned to when a render pass /// instance ends. During a render pass instance, an attachment can use a different layout in /// each subpass, if desired. /// </summary> public ImageLayout FinalLayout; /// <summary> /// Initializes a new instance of the <see cref="AttachmentDescription"/> structure. /// </summary> /// <param name="flags">A bitmask specifying additional properties of the attachment.</param> /// <param name="format"> /// Specifies the format of the image that will be used for the attachment. /// </param> /// <param name="samples">The number of samples of the image.</param> /// <param name="loadOp"> /// Specifies how the contents of color and depth components of the attachment are treated at /// the beginning of the subpass where it is first used. /// </param> /// <param name="storeOp"> /// Specifies how the contents of color and depth components of the attachment are treated at /// the end of the subpass where it is last used. /// </param> /// <param name="stencilLoadOp"> /// Specifies how the contents of stencil components of the attachment are treated at the /// beginning of the subpass where it is first used, and must be one of the same values /// allowed for <see cref="LoadOp"/> above. /// </param> /// <param name="stencilStoreOp"> /// Specifies how the contents of stencil components of the attachment are treated at the end /// of the last subpass where it is used, and must be one of the same values allowed for <see /// cref="StoreOp"/> above. /// </param> /// <param name="initialLayout"> /// The layout the attachment image subresource will be in when a render pass instance begins. /// </param> /// <param name="finalLayout"> /// The layout the attachment image subresource will be transitioned to when a render pass /// instance ends. During a render pass instance, an attachment can use a different layout in /// each subpass, if desired. /// </param> public AttachmentDescription( AttachmentDescriptions flags, Format format, SampleCounts samples, AttachmentLoadOp loadOp, AttachmentStoreOp storeOp, AttachmentLoadOp stencilLoadOp, AttachmentStoreOp stencilStoreOp, ImageLayout initialLayout, ImageLayout finalLayout) { Flags = flags; Format = format; Samples = samples; LoadOp = loadOp; StoreOp = storeOp; StencilLoadOp = stencilLoadOp; StencilStoreOp = stencilStoreOp; InitialLayout = initialLayout; FinalLayout = finalLayout; } } /// <summary> /// Bitmask specifying additional properties of an attachment. /// </summary> [Flags] public enum AttachmentDescriptions { /// <summary> /// Specifies that the attachment aliases the same device memory as other attachments. /// </summary> MayAlias = 1 << 0 } /// <summary> /// Specify how contents of an attachment are treated at the beginning of a subpass. /// </summary> public enum AttachmentLoadOp { /// <summary> /// Specifies that the previous contents of the image within the render area will be /// preserved. For attachments with a depth/stencil format, this uses the access type <see /// cref="Accesses.DepthStencilAttachmentRead"/>. For attachments with a color format, this /// uses the access type <see cref="Accesses.ColorAttachmentRead"/>. /// </summary> Load = 0, /// <summary> /// Specifies that the contents within the render area will be cleared to a uniform value, /// which is specified when a render pass instance is begun. For attachments with a /// depth/stencil format, this uses the access type <see /// cref="Accesses.DepthStencilAttachmentWrite"/>. For attachments with a color format, this /// uses the access type <see cref="Accesses.ColorAttachmentWrite"/>. /// </summary> Clear = 1, /// <summary> /// Specifies that the previous contents within the area need not be preserved; the contents /// of the attachment will be undefined inside the render area. For attachments with a /// depth/stencil format, this uses the access type <see /// cref="Accesses.DepthStencilAttachmentWrite"/>. For attachments with a color format, this /// uses the access type <see cref="Accesses.ColorAttachmentWrite"/>. /// </summary> DontCare = 2 } /// <summary> /// Specify how contents of an attachment are treated at the end of a subpass. /// </summary> public enum AttachmentStoreOp { /// <summary> /// Specifies the contents generated during the render pass and within the render area are /// written to memory. For attachments with a depth/stencil format, this uses the access type /// <see cref="Accesses.DepthStencilAttachmentWrite"/>. For attachments with a color format, /// this uses the access type <see cref="Accesses.ColorAttachmentWrite"/>. /// </summary> Store = 0, /// <summary> /// Specifies the contents within the render area are not needed after rendering, and may be /// discarded; the contents of the attachment will be undefined inside the render area. For /// attachments with a depth/stencil format, this uses the access type <see /// cref="Accesses.DepthStencilAttachmentWrite"/>. For attachments with a color format, this /// uses the access type <see cref="Accesses.ColorAttachmentWrite"/>. /// </summary> DontCare = 1 } /// <summary> /// Structure specifying a image format properties. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ImageFormatProperties { /// <summary> /// Are the maximum image dimensions. /// </summary> public Extent3D MaxExtent; /// <summary> /// The maximum number of mipmap levels. Must either be equal to 1 (valid only if tiling is /// <see cref="ImageTiling.Linear"/>) or be equal to `ceil(log2(max(width, height, depth))) + /// 1`. Width, height and depth are taken from the corresponding members of <see cref="MaxExtent"/>. /// </summary> public int MaxMipLevels; /// <summary> /// The maximum number of array layers. Must either be equal to 1 or be greater than or equal /// to the <see cref="PhysicalDeviceLimits.MaxImageArrayLayers"/> member. A value of 1 is /// valid only if tiling is <see cref="ImageTiling.Linear"/> or if type is <see cref="ImageType.Image3D"/>. /// </summary> public int MaxArrayLayers; /// <summary> /// A bitmask of <see cref="VulkanCore.SampleCounts"/> specifying all the supported sample /// counts for this image. /// </summary> public SampleCounts SampleCounts; /// <summary> /// An upper bound on the total image size in bytes, inclusive of all image subresources. /// Implementations may have an address space limit on total size of a resource, which is /// advertised by this property. Must be at least 2^31. /// </summary> public long MaxResourceSize; } /// <summary> /// Structure specifying an image subresource. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ImageSubresource { /// <summary> /// An <see cref="ImageAspects"/> selecting the image aspect. /// </summary> public ImageAspects AspectMask; /// <summary> /// Selects the mipmap level. /// </summary> public int MipLevel; /// <summary> /// Selects the array layer. /// </summary> public int ArrayLayer; /// <summary> /// Initializes a new instance of <see cref="ImageSubresource"/> structure. /// </summary> /// <param name="aspectMask">An <see cref="ImageAspects"/> selecting the image aspect.</param> /// <param name="mipLevel">Selects the mipmap level.</param> /// <param name="arrayLayer">Selects the array layer.</param> public ImageSubresource(ImageAspects aspectMask, int mipLevel, int arrayLayer) { AspectMask = aspectMask; MipLevel = mipLevel; ArrayLayer = arrayLayer; } } /// <summary> /// Structure specifying sparse image format properties. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SparseImageFormatProperties { /// <summary> /// A bitmask specifying which aspects of the image the properties apply to. /// </summary> public ImageAspects AspectMask; /// <summary> /// The width, height, and depth of the sparse image block in texels or compressed texel blocks. /// </summary> public Extent3D ImageGranularity; /// <summary> /// A bitmask specifying additional information about the sparse resource. /// </summary> public SparseImageFormats Flags; } /// <summary> /// Bitmask specifying additional information about a sparse image resource. /// </summary> [Flags] public enum SparseImageFormats { /// <summary> /// Specifies that the image uses a single mip tail region for all array layers. /// </summary> SingleMiptail = 1 << 0, /// <summary> /// Specifies that the first mip level whose dimensions are not integer multiples of the /// corresponding dimensions of the sparse image block begins the mip tail region. /// </summary> AlignedMipSize = 1 << 1, /// <summary> /// Specifies that the image uses non-standard sparse image block dimensions, and the image /// granularity values do not match the standard sparse image block dimensions for the given format. /// </summary> NonstandardBlockSize = 1 << 2 } /// <summary> /// Structure specifying sparse image memory requirements. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SparseImageMemoryRequirements { /// <summary> /// The sparse image format properties. /// </summary> public SparseImageFormatProperties FormatProperties; /// <summary> /// The first mip level at which image subresources are included in the mip tail region. /// </summary> public int ImageMipTailFirstLod; /// <summary> /// The memory size (in bytes) of the mip tail region. If <see cref="FormatProperties"/> /// contains <see cref="SparseImageFormats.SingleMiptail"/>, this is the size of the /// whole mip tail, otherwise this is the size of the mip tail of a single array layer. This /// value is guaranteed to be a multiple of the sparse block size in bytes. /// </summary> public long ImageMipTailSize; /// <summary> /// The opaque memory offset used with <see cref="SparseImageOpaqueMemoryBindInfo"/> to bind /// the mip tail region(s). /// </summary> public long ImageMipTailOffset; /// <summary> /// The offset stride between each array-layer's mip tail, if <see cref="FormatProperties"/> /// does not contain <see cref="SparseImageFormats.SingleMiptail"/> (otherwise the value /// is undefined). /// </summary> public long ImageMipTailStride; } /// <summary> /// Structure specifying subresource layout. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct SubresourceLayout { /// <summary> /// The byte offset from the start of the image where the image subresource begins. /// </summary> public long Offset; /// <summary> /// The size in bytes of the image subresource. size includes any extra memory that is /// required based on <see cref="RowPitch"/>. /// </summary> public long Size; /// <summary> /// Describes the number of bytes between each row of texels in an image. /// </summary> public long RowPitch; /// <summary> /// Describes the number of bytes between each array layer of an image. /// </summary> public long ArrayPitch; /// <summary> /// Describes the number of bytes between each slice of 3D image. /// </summary> public long DepthPitch; } /// <summary> /// Bitmask specifying sample counts supported for an image used for storage /// operations. /// </summary> [Flags] public enum SampleCounts { /// <summary> /// Specifies an image with one sample per pixel. /// </summary> Count1 = 1 << 0, /// <summary> /// Specifies an image with 2 samples per pixel. /// </summary> Count2 = 1 << 1, /// <summary> /// Specifies an image with 4 samples per pixel. /// </summary> Count4 = 1 << 2, /// <summary> /// Specifies an image with 8 samples per pixel. /// </summary> Count8 = 1 << 3, /// <summary> /// Specifies an image with 16 samples per pixel. /// </summary> Count16 = 1 << 4, /// <summary> /// Specifies an image with 32 samples per pixel. /// </summary> Count32 = 1 << 5, /// <summary> /// Specifies an image with 64 samples per pixel. /// </summary> Count64 = 1 << 6 } }
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 Mastermind.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System.IO; using System.Text; using System.Collections.Generic; using RaptorDB.Common; namespace RaptorDB { internal class StorageData<T> { public StorageItem<T> meta; public byte[] data; } public class StorageItem<T> { public T key; public string typename; public DateTime date = FastDateTime.Now; public bool isDeleted; public bool isReplicated; public int dataLength; public byte isCompressed; // 0 = no, 1 = MiniLZO } public interface IDocStorage<T> { int RecordCount(); byte[] GetBytes(int rowid, out StorageItem<T> meta); object GetObject(int rowid, out StorageItem<T> meta); StorageItem<T> GetMeta(int rowid); bool GetObject(T key, out object doc); } public enum SF_FORMAT { BSON, JSON } internal struct SplitFile { public long start; public long uptolength; public FileStream file; } internal class StorageFile<T> { FileStream _datawrite; FileStream _recfilewrite; FileStream _recfileread = null; FileStream _dataread = null; private string _filename = ""; private string _recfilename = ""; private long _lastRecordNum = 0; private long _lastWriteOffset = _fileheader.Length; private object _readlock = new object(); private bool _dirty = false; IGetBytes<T> _T = null; ILog _log = LogManager.GetLogger(typeof(StorageFile<T>)); private SF_FORMAT _saveFormat = SF_FORMAT.BSON; // **** change this if storage format changed **** internal static int _CurrentVersion = 2; //private ushort _splitMegaBytes = 0; // 0 = off //private bool _enableSplits = false; private List<SplitFile> _files = new List<SplitFile>(); private List<long> _uptoindexes = new List<long>(); // no splits in view mode private bool _viewmode = false; private SplitFile _lastsplitfile; public static byte[] _fileheader = { (byte)'M', (byte)'G', (byte)'D', (byte)'B', 0, // 4 -- storage file version number, 0 // 5 -- not used }; private static string _splitfileExtension = "00000"; private const int _KILOBYTE = 1024; // record format : // 1 type (0 = raw no meta data, 1 = bson meta, 2 = json meta) // 4 byte meta/data length, // n byte meta serialized data if exists // m byte data (if meta exists then m is in meta.dataLength) /// <summary> /// View data storage mode (no splits, bson save) /// </summary> /// <param name="filename"></param> public StorageFile(string filename) { _viewmode = true; _saveFormat = SF_FORMAT.BSON; // add version number _fileheader[5] = (byte)_CurrentVersion; Initialize(filename, false); } /// <summary> /// /// </summary> /// <param name="filename"></param> /// <param name="format"></param> /// <param name="StorageOnlyMode">= true -> don't create mgrec files (used for backup and replication mode)</param> public StorageFile(string filename, SF_FORMAT format, bool StorageOnlyMode) { _saveFormat = format; if (StorageOnlyMode) _viewmode = true; // no file splits // add version number _fileheader[5] = (byte)_CurrentVersion; Initialize(filename, StorageOnlyMode); } private StorageFile(string filename, bool StorageOnlyMode) { Initialize(filename, StorageOnlyMode); } private void Initialize(string filename, bool StorageOnlyMode) { _T = RDBDataType<T>.ByteHandler(); _filename = filename; // search for mgdat00000 extensions -> split files load if (File.Exists(filename + _splitfileExtension)) { LoadSplitFiles(filename); } if (File.Exists(filename) == false) _datawrite = new FileStream(filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); else _datawrite = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); _dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (_datawrite.Length == 0) { // new file _datawrite.Write(_fileheader, 0, _fileheader.Length); _datawrite.Flush(); _lastWriteOffset = _fileheader.Length; } else { long i = _datawrite.Seek(0L, SeekOrigin.End); if (_files.Count == 0) _lastWriteOffset = i; else _lastWriteOffset += i; // add to the splits } if (StorageOnlyMode == false) { // load rec pointers _recfilename = filename.Substring(0, filename.LastIndexOf('.')) + ".mgrec"; if (File.Exists(_recfilename) == false) _recfilewrite = new FileStream(_recfilename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite); else _recfilewrite = new FileStream(_recfilename, FileMode.Open, FileAccess.Write, FileShare.ReadWrite); _recfileread = new FileStream(_recfilename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _lastRecordNum = (int)(_recfilewrite.Length / 8); _recfilewrite.Seek(0L, SeekOrigin.End); } } private void LoadSplitFiles(string filename) { _log.Debug("Loading split files..."); _lastWriteOffset = 0; for (int i = 0; ; i++) { string _filename = filename + i.ToString(_splitfileExtension); if (File.Exists(_filename) == false) break; FileStream file = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); SplitFile sf = new SplitFile(); sf.start = _lastWriteOffset; _lastWriteOffset += file.Length; sf.file = file; sf.uptolength = _lastWriteOffset; _files.Add(sf); _uptoindexes.Add(sf.uptolength); } _lastsplitfile = _files[_files.Count - 1]; _log.Debug("Number of split files = " + _files.Count); } public static int GetStorageFileHeaderVersion(string filename) { string fn = filename + _splitfileExtension; // if split files -> load the header from the first file -> mgdat00000 if (File.Exists(fn) == false) fn = filename; // else use the mgdat file if (File.Exists(fn)) { var fs = new FileStream(fn, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite); fs.Seek(0L, SeekOrigin.Begin); byte[] b = new byte[_fileheader.Length]; fs.Read(b, 0, _fileheader.Length); fs.Close(); return b[5]; } return _CurrentVersion; } public int Count() { return (int)_lastRecordNum;// (int)(_recfilewrite.Length >> 3); } public long WriteRawData(byte[] b) { return internalWriteData(null, b, true); } public long Delete(T key) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.isDeleted = true; return internalWriteData(meta, null, false); } public long DeleteReplicated(T key) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.isReplicated = true; meta.isDeleted = true; return internalWriteData(meta, null, false); } public long WriteObject(T key, object obj) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.typename = fastJSON.Reflection.Instance.GetTypeAssemblyName(obj.GetType()); byte[] data; if (_saveFormat == SF_FORMAT.BSON) data = fastBinaryJSON.BJSON.ToBJSON(obj); else data = Helper.GetBytes(fastJSON.JSON.ToJSON(obj)); if(data.Length > (int)Global.CompressDocumentOverKiloBytes*_KILOBYTE) { meta.isCompressed = 1; data = MiniLZO.Compress(data); //MiniLZO } return internalWriteData(meta, data, false); } public long WriteReplicationObject(T key, object obj) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; meta.isReplicated = true; meta.typename = fastJSON.Reflection.Instance.GetTypeAssemblyName(obj.GetType()); byte[] data; if (_saveFormat == SF_FORMAT.BSON) data = fastBinaryJSON.BJSON.ToBJSON(obj); else data = Helper.GetBytes(fastJSON.JSON.ToJSON(obj)); if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE) { meta.isCompressed = 1; data = MiniLZO.Compress(data); } return internalWriteData(meta, data, false); } public long WriteData(T key, byte[] data) { StorageItem<T> meta = new StorageItem<T>(); meta.key = key; if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE) { meta.isCompressed = 1; data = MiniLZO.Compress(data); } return internalWriteData(meta, data, false); } public byte[] ReadBytes(long recnum) { StorageItem<T> meta; return ReadBytes(recnum, out meta); } public object ReadObject(long recnum) { StorageItem<T> meta = null; return ReadObject(recnum, out meta); } public object ReadObject(long recnum, out StorageItem<T> meta) { byte[] b = ReadBytes(recnum, out meta); if (b == null) return null; if (b[0] < 32) return fastBinaryJSON.BJSON.ToObject(b); else return fastJSON.JSON.ToObject(Encoding.ASCII.GetString(b)); } /// <summary> /// used for views only /// </summary> /// <param name="recnum"></param> /// <returns></returns> public byte[] ViewReadRawBytes(long recnum) { // views can't be split if (recnum >= _lastRecordNum) return null; lock (_readlock) { long offset = ComputeOffset(recnum); _dataread.Seek(offset, System.IO.SeekOrigin.Begin); byte[] hdr = new byte[5]; // read header _dataread.Read(hdr, 0, 5); // meta length int len = Helper.ToInt32(hdr, 1); int type = hdr[0]; if (type == 0) { byte[] data = new byte[len]; _dataread.Read(data, 0, len); return data; } return null; } } public void Shutdown() { if (_files.Count > 0) _files.ForEach(s => FlushClose(s.file)); FlushClose(_dataread); FlushClose(_recfileread); FlushClose(_recfilewrite); FlushClose(_datawrite); _dataread = null; _recfileread = null; _recfilewrite = null; _datawrite = null; } public static StorageFile<Guid> ReadForward(string filename) { StorageFile<Guid> sf = new StorageFile<Guid>(filename, true); return sf; } public StorageItem<T> ReadMeta(long rowid) { if (rowid >= _lastRecordNum) return null; lock (_readlock) { int metalen = 0; long off = ComputeOffset(rowid); FileStream fs = GetReadFileStreamWithSeek(off); StorageItem<T> meta = ReadMetaData(fs, out metalen); return meta; } } #region [ private / internal ] private long internalWriteData(StorageItem<T> meta, byte[] data, bool raw) { lock (_readlock) { _dirty = true; // seek end of file long offset = _lastWriteOffset; if (_viewmode == false && Global.SplitStorageFilesMegaBytes > 0) { // current file size > _splitMegaBytes --> new file if (offset > (long)Global.SplitStorageFilesMegaBytes * 1024 * 1024) CreateNewStorageFile(); } if (raw == false) { if (data != null) meta.dataLength = data.Length; byte[] metabytes = fastBinaryJSON.BJSON.ToBJSON(meta, new fastBinaryJSON.BJSONParameters { UseExtensions = false }); // write header info _datawrite.Write(new byte[] { 1 }, 0, 1); // TODO : add json here, write bson for now _datawrite.Write(Helper.GetBytes(metabytes.Length, false), 0, 4); _datawrite.Write(metabytes, 0, metabytes.Length); // update pointer _lastWriteOffset += metabytes.Length + 5; } else { // write header info _datawrite.Write(new byte[] { 0 }, 0, 1); // write raw _datawrite.Write(Helper.GetBytes(data.Length, false), 0, 4); // update pointer _lastWriteOffset += 5; } if (data != null) { // write data block _datawrite.Write(data, 0, data.Length); _lastWriteOffset += data.Length; } // return starting offset -> recno long recno = _lastRecordNum++; if (_recfilewrite != null) _recfilewrite.Write(Helper.GetBytes(offset, false), 0, 8); if (Global.FlushStorageFileImmediately) { _datawrite.Flush(); if (_recfilewrite != null) _recfilewrite.Flush(); } return recno; } } private void CreateNewStorageFile() { _log.Debug("Split limit reached = " + _datawrite.Length); int i = _files.Count; // close files FlushClose(_datawrite); FlushClose(_dataread); long start = 0; if (i > 0) start = _lastsplitfile.uptolength; // last file offset // rename mgdat to mgdat0000n File.Move(_filename, _filename + i.ToString(_splitfileExtension)); FileStream file = new FileStream(_filename + i.ToString(_splitfileExtension), FileMode.Open, FileAccess.Read, FileShare.ReadWrite); SplitFile sf = new SplitFile(); sf.start = start; sf.uptolength = _lastWriteOffset; sf.file = file; _files.Add(sf); _uptoindexes.Add(sf.uptolength); _lastsplitfile = sf; // new mgdat file _datawrite = new FileStream(_filename, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite); _dataread = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _log.Debug("New storage file created, count = " + _files.Count); } internal byte[] ReadBytes(long recnum, out StorageItem<T> meta) { meta = null; if (recnum >= _lastRecordNum) return null; lock (_readlock) { long off = ComputeOffset(recnum); FileStream fs = GetReadFileStreamWithSeek(off); byte[] data = internalReadBytes(fs, out meta); if (meta.isCompressed > 0) data = MiniLZO.Decompress(data); return data; } } private long ComputeOffset(long recnum) { if (_dirty) { _datawrite.Flush(); _recfilewrite.Flush(); } long off = recnum << 3;// *8L; byte[] b = new byte[8]; _recfileread.Seek(off, SeekOrigin.Begin); _recfileread.Read(b, 0, 8); off = Helper.ToInt64(b, 0); if (off == 0)// kludge off = 6; return off; } private byte[] internalReadBytes(FileStream fs, out StorageItem<T> meta) { int metalen = 0; meta = ReadMetaData(fs, out metalen); if (meta != null) { if (meta.isDeleted == false) { byte[] data = new byte[meta.dataLength]; fs.Read(data, 0, meta.dataLength); return data; } } else { byte[] data = new byte[metalen]; fs.Read(data, 0, metalen); return data; } return null; } private StorageItem<T> ReadMetaData(FileStream fs, out int metasize) { byte[] hdr = new byte[5]; // read header fs.Read(hdr, 0, 5); // meta length int len = Helper.ToInt32(hdr, 1); int type = hdr[0]; if (type > 0) { metasize = len + 5; hdr = new byte[len]; fs.Read(hdr, 0, len); StorageItem<T> meta; if (type == 1) meta = fastBinaryJSON.BJSON.ToObject<StorageItem<T>>(hdr); else { string str = Helper.GetString(hdr, 0, (short)hdr.Length); meta = fastJSON.JSON.ToObject<StorageItem<T>>(str); } return meta; } else { metasize = len; return null; } } private void FlushClose(FileStream st) { if (st != null) { st.Flush(true); st.Close(); } } internal T GetKey(long recnum, out bool deleted) { lock (_readlock) { deleted = false; long off = ComputeOffset(recnum); FileStream fs = GetReadFileStreamWithSeek(off); int metalen = 0; StorageItem<T> meta = ReadMetaData(fs, out metalen); deleted = meta.isDeleted; return meta.key; } } internal int CopyTo(StorageFile<T> storageFile, long startrecord) { FileStream fs; bool inthefiles = false; // copy data here lock (_readlock) { long off = ComputeOffset(startrecord); fs = GetReadFileStreamWithSeek(off); if (fs != _dataread) inthefiles = true; Pump(fs, storageFile._datawrite); } // pump the remainder of the files also if (inthefiles && _files.Count > 0) { long off = ComputeOffset(startrecord); int i = binarysearch(off); i++; // next file stream for (int j = i; j < _files.Count; j++) { lock (_readlock) { fs = _files[j].file; fs.Seek(0L, SeekOrigin.Begin); Pump(fs, storageFile._datawrite); } } // pump the current mgdat lock(_readlock) { _dataread.Seek(0L, SeekOrigin.Begin); Pump(_dataread, storageFile._datawrite); } } return (int)_lastRecordNum; } private static void Pump(Stream input, Stream output) { byte[] bytes = new byte[4096 * 2]; int n; while ((n = input.Read(bytes, 0, bytes.Length)) != 0) output.Write(bytes, 0, n); } internal IEnumerable<StorageData<T>> ReadOnlyEnumerate() { // MGREC files may not exist //// the total number of records //long count = _recfileread.Length >> 3; //for (long i = 0; i < count; i++) //{ // StorageItem<T> meta; // byte[] data = ReadBytes(i, out meta); // StorageData<T> sd = new StorageData<T>(); // sd.meta = meta; // if (meta.dataLength > 0) // sd.data = data; // yield return sd; //} long offset = _fileheader.Length;// start; // skip header long size = _dataread.Length; while (offset < size) { StorageData<T> sd = new StorageData<T>(); lock (_readlock) { _dataread.Seek(offset, SeekOrigin.Begin); int metalen = 0; StorageItem<T> meta = ReadMetaData(_dataread, out metalen); offset += metalen; sd.meta = meta; if (meta.dataLength > 0) { byte[] data = new byte[meta.dataLength]; _dataread.Read(data, 0, meta.dataLength); sd.data = data; } offset += meta.dataLength; } yield return sd; } } private FileStream GetReadFileStreamWithSeek(long offset) { long fileoffset = offset; // search split _files for offset and compute fileoffset in the file if (_files.Count > 0) // we have splits { if (offset < _lastsplitfile.uptolength) // offset is in the list { int i = binarysearch(offset); var f = _files[i]; fileoffset -= f.start; // offset in the file f.file.Seek(fileoffset, SeekOrigin.Begin); return f.file; } else fileoffset -= _lastsplitfile.uptolength; // offset in the mgdat file } // seek to position in file _dataread.Seek(fileoffset, SeekOrigin.Begin); return _dataread; } private int binarysearch(long offset) { //// binary search int low = 0; int high = _files.Count - 1; int midpoint = 0; int lastlower = 0; while (low <= high) { midpoint = low + (high - low) / 2; long k = _uptoindexes[midpoint]; // check to see if value is equal to item in array if (offset == k) return midpoint + 1; else if (offset < k) { high = midpoint - 1; lastlower = midpoint; } else low = midpoint + 1; } return lastlower; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2.Models { using Fixtures.PetstoreV2; using Microsoft.Rest; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; public partial class Pet { /// <summary> /// Initializes a new instance of the Pet class. /// </summary> public Pet() { CustomInit(); } /// <summary> /// Initializes a new instance of the Pet class. /// </summary> /// <param name="status">pet status in the store. Possible values /// include: 'available', 'pending', 'sold'</param> public Pet(string name, IList<string> photoUrls, long? id = default(long?), Category category = default(Category), IList<Tag> tags = default(IList<Tag>), byte[] sByteProperty = default(byte[]), System.DateTime? birthday = default(System.DateTime?), IDictionary<string, Category> dictionary = default(IDictionary<string, Category>), string status = default(string)) { Id = id; Category = category; Name = name; PhotoUrls = photoUrls; Tags = tags; SByteProperty = sByteProperty; Birthday = birthday; Dictionary = dictionary; Status = status; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// </summary> [JsonProperty(PropertyName = "id")] public long? Id { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "category")] public Category Category { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "photoUrls")] public IList<string> PhotoUrls { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "tags")] public IList<Tag> Tags { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "sByte")] public byte[] SByteProperty { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "birthday")] public System.DateTime? Birthday { get; set; } /// <summary> /// </summary> [JsonProperty(PropertyName = "dictionary")] public IDictionary<string, Category> Dictionary { get; set; } /// <summary> /// Gets or sets pet status in the store. Possible values include: /// 'available', 'pending', 'sold' /// </summary> [JsonProperty(PropertyName = "status")] public string Status { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "Name"); } if (PhotoUrls == null) { throw new ValidationException(ValidationRules.CannotBeNull, "PhotoUrls"); } } /// <summary> /// Serializes the object to an XML node /// </summary> internal XElement XmlSerialize(XElement result) { if( null != Id ) { result.Add(new XElement("id", Id) ); } if( null != Category ) { result.Add(Category.XmlSerialize(new XElement( "category" ))); } if( null != Name ) { result.Add(new XElement("name", Name) ); } if( null != PhotoUrls ) { var seq = new XElement("photoUrl"); foreach( var value in PhotoUrls ){ seq.Add(new XElement( "photoUrl", value ) ); } result.Add(seq); } if( null != Tags ) { var seq = new XElement("tag"); foreach( var value in Tags ){ seq.Add(value.XmlSerialize( new XElement( "tag") ) ); } result.Add(seq); } if( null != SByteProperty ) { result.Add(new XElement("sByte", SByteProperty) ); } if( null != Birthday ) { result.Add(new XElement("birthday", Birthday) ); } if( null != Dictionary ) { var dict = new XElement("dictionary"); foreach( var key in Dictionary.Keys ) { dict.Add(Dictionary[key].XmlSerialize(new XElement(key) ) ); } result.Add(dict); } if( null != Status ) { result.Add(new XElement("status", Status) ); } return result; } /// <summary> /// Deserializes an XML node to an instance of Pet /// </summary> internal static Pet XmlDeserialize(string payload) { // deserialize to xml and use the overload to do the work return XmlDeserialize( XElement.Parse( payload ) ); } internal static Pet XmlDeserialize(XElement payload) { var result = new Pet(); var deserializeId = XmlSerialization.ToDeserializer(e => (long?)e); long? resultId; if (deserializeId(payload, "id", out resultId)) { result.Id = resultId; } var deserializeCategory = XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e)); Category resultCategory; if (deserializeCategory(payload, "category", out resultCategory)) { result.Category = resultCategory; } var deserializeName = XmlSerialization.ToDeserializer(e => (string)e); string resultName; if (deserializeName(payload, "name", out resultName)) { result.Name = resultName; } var deserializePhotoUrls = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => (string)e), "photoUrl"); IList<string> resultPhotoUrls; if (deserializePhotoUrls(payload, "photoUrl", out resultPhotoUrls)) { result.PhotoUrls = resultPhotoUrls; } var deserializeTags = XmlSerialization.CreateListXmlDeserializer(XmlSerialization.ToDeserializer(e => Tag.XmlDeserialize(e)), "tag"); IList<Tag> resultTags; if (deserializeTags(payload, "tag", out resultTags)) { result.Tags = resultTags; } var deserializeSByteProperty = XmlSerialization.ToDeserializer(e => System.Convert.FromBase64String(e.Value)); byte[] resultSByteProperty; if (deserializeSByteProperty(payload, "sByte", out resultSByteProperty)) { result.SByteProperty = resultSByteProperty; } var deserializeBirthday = XmlSerialization.ToDeserializer(e => (System.DateTime?)e); System.DateTime? resultBirthday; if (deserializeBirthday(payload, "birthday", out resultBirthday)) { result.Birthday = resultBirthday; } var deserializeDictionary = XmlSerialization.CreateDictionaryXmlDeserializer(XmlSerialization.ToDeserializer(e => Category.XmlDeserialize(e))); IDictionary<string, Category> resultDictionary; if (deserializeDictionary(payload, "dictionary", out resultDictionary)) { result.Dictionary = resultDictionary; } var deserializeStatus = XmlSerialization.ToDeserializer(e => (string)e); string resultStatus; if (deserializeStatus(payload, "status", out resultStatus)) { result.Status = resultStatus; } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Resources; using System.Security.Permissions; namespace System.ComponentModel { /// <summary> /// The ComponentResourceManager is a resource manager object that /// provides simple functionality for enumerating resources for /// a component or object. /// </summary> public class ComponentResourceManager : ResourceManager { private Hashtable _resourceSets; private CultureInfo _neutralResourcesCulture; public ComponentResourceManager() { } public ComponentResourceManager(Type t) : base(t) { } /// <summary> /// The culture of the main assembly's neutral resources. If someone is asking for this culture's resources, /// we don't need to walk up the parent chain. /// </summary> private CultureInfo NeutralResourcesCulture { get { if (_neutralResourcesCulture == null && MainAssembly != null) { _neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly); } return _neutralResourcesCulture; } } /// <summary> /// This method examines all the resources for the current culture. /// When it finds a resource with a key in the format of /// &quot;[objectName].[property name]&quot; it will apply that resource's value /// to the corresponding property on the object. If there is no matching /// property the resource will be ignored. /// </summary> public void ApplyResources(object value, string objectName) { ApplyResources(value, objectName, null); } /// <summary> /// This method examines all the resources for the provided culture. /// When it finds a resource with a key in the format of /// &quot[objectName].[property name]&quot; it will apply that resource's value /// to the corresponding property on the object. If there is no matching /// property the resource will be ignored. /// </summary> public virtual void ApplyResources(object value, string objectName, CultureInfo culture) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (objectName == null) { throw new ArgumentNullException(nameof(objectName)); } if (culture == null) { culture = CultureInfo.CurrentUICulture; } // The general case here will be to always use the same culture, so optimize for // that. The resourceSets hashtable uses culture as a key. It's value is // a sorted dictionary that contains ALL the culture values (so it traverses up // the parent culture chain) for that culture. This means that if ApplyResources // is called with different cultures there could be some redundancy in the // table, but it allows the normal case of calling with a single culture to // be much faster. // // The reason we use a SortedDictionary here is to ensure the resources are applied // in an order consistent with codedom deserialization. SortedList<string, object> resources; if (_resourceSets == null) { ResourceSet dummy; _resourceSets = new Hashtable(); resources = FillResources(culture, out dummy); _resourceSets[culture] = resources; } else { resources = (SortedList<string, object>)_resourceSets[culture]; if (resources == null || (resources.Comparer.Equals(StringComparer.OrdinalIgnoreCase) != IgnoreCase)) { ResourceSet dummy; resources = FillResources(culture, out dummy); _resourceSets[culture] = resources; } } BindingFlags flags = BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance; if (IgnoreCase) { flags |= BindingFlags.IgnoreCase; } bool componentReflect = false; if (value is IComponent) { ISite site = ((IComponent)value).Site; if (site != null && site.DesignMode) { componentReflect = true; } } foreach (KeyValuePair<string, object> kvp in resources) { // See if this key matches our object. string key = kvp.Key; if (IgnoreCase) { if (string.Compare(key, 0, objectName, 0, objectName.Length, StringComparison.OrdinalIgnoreCase) != 0) { continue; } } else { if (string.CompareOrdinal(key, 0, objectName, 0, objectName.Length) != 0) { continue; } } // Character after objectName.Length should be a ".", or else we should continue. // int idx = objectName.Length; if (key.Length <= idx || key[idx] != '.') { continue; } // Bypass type descriptor if we are not in design mode. TypeDescriptor does an attribute // scan which is quite expensive. // string propName = key.Substring(idx + 1); if (componentReflect) { PropertyDescriptor prop = TypeDescriptor.GetProperties(value).Find(propName, IgnoreCase); if (prop != null && !prop.IsReadOnly && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value))) { prop.SetValue(value, kvp.Value); } } else { PropertyInfo prop = null; try { prop = value.GetType().GetProperty(propName, flags); } catch (AmbiguousMatchException) { // Looks like we ran into a conflict between a declared property and an inherited one. // In such cases, we choose the most declared one. Type t = value.GetType(); do { prop = t.GetProperty(propName, flags | BindingFlags.DeclaredOnly); t = t.BaseType; } while (prop == null && t != null && t != typeof(object)); } if (prop != null && prop.CanWrite && (kvp.Value == null || prop.PropertyType.IsInstanceOfType(kvp.Value))) { prop.SetValue(value, kvp.Value, null); } } } } /// <summary> /// Recursive routine that creates a resource hashtable /// populated with resources for culture and all parent /// cultures. /// </summary> private SortedList<string, object> FillResources(CultureInfo culture, out ResourceSet resourceSet) { SortedList<string, object> sd; ResourceSet parentResourceSet = null; // Traverse parents first, so we always replace more // specific culture values with less specific. // if (!culture.Equals(CultureInfo.InvariantCulture) && !culture.Equals(NeutralResourcesCulture)) { sd = FillResources(culture.Parent, out parentResourceSet); } else { // We're at the bottom, so create the sorted dictionary // if (IgnoreCase) { sd = new SortedList<string, object>(StringComparer.OrdinalIgnoreCase); } else { sd = new SortedList<string, object>(StringComparer.Ordinal); } } // Now walk culture's resource set. Another thing we // do here is ask ResourceManager to traverse up the // parent chain. We do NOT want to do this because // we are trawling up the parent chain ourselves, but by // passing in true for the second parameter the resource // manager will cache the culture it did find, so when we // do recurse all missing resources will be filled in // so we are very fast. That's why we remember what our // parent resource set's instance was -- if they are the // same, we're looking at a cache we've already applied. // resourceSet = GetResourceSet(culture, true, true); if (resourceSet != null && !object.ReferenceEquals(resourceSet, parentResourceSet)) { foreach (DictionaryEntry de in resourceSet) { sd[(string)de.Key] = de.Value; } } return sd; } } }
/* * 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; using System.Collections.Generic; using System.Text; using System.Threading; namespace Apache.Geode.Client.FwkLib { using Apache.Geode.DUnitFramework; using Apache.Geode.Client; //----------------------------------- DoOpsTask start ------------------------ public class DoFETask<TKey, TVal> : ClientTask { private IRegion<TKey, TVal> m_region; private const int INVALIDATE = 1; private const int LOCAL_INVALIDATE = 2; private const int DESTROY = 3; private const int LOCAL_DESTROY = 4; private const int UPDATE_EXISTING_KEY = 5; private const int GET = 6; private const int ADD_NEW_KEY = 7; private const int PUTALL_NEW_KEY = 8; //private const int QUERY = 8; private const int NUM_EXTRA_KEYS = 100; private static bool m_istransaction = false; private static string m_funcName; CacheTransactionManager txManager = null; private object CLASS_LOCK = new object(); private object SKIPS_LOCK = new object(); protected int[] operations = { INVALIDATE, LOCAL_INVALIDATE, DESTROY, LOCAL_DESTROY, UPDATE_EXISTING_KEY, GET, ADD_NEW_KEY, PUTALL_NEW_KEY }; public DoFETask(IRegion<TKey, TVal> region, bool istransaction) : base() { m_region = region; m_istransaction = istransaction; m_funcName = FwkTest<TKey, TVal>.CurrentTest.GetStringValue("funcName"); } public override void DoTask(int iters, object data) { Random random = new Random(); List<int> availableOps = new List<int>(operations); lock (SKIPS_LOCK) { FwkTest<TKey, TVal>.CurrentTest.ResetKey("isSkipOps"); bool isSkipOps = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isSkipOps"); if (isSkipOps) { availableOps.Remove(LOCAL_INVALIDATE); availableOps.Remove(LOCAL_DESTROY); } } while (Running && (availableOps.Count != 0)) { int opcode = -1; lock (CLASS_LOCK) { bool doneWithOps = false; int i = random.Next(0, availableOps.Count); try { opcode = availableOps[i]; if (m_istransaction) { txManager = CacheHelper<TKey, TVal>.DCache.CacheTransactionManager; txManager.Begin(); } switch (opcode) { case ADD_NEW_KEY: doneWithOps = addNewKeyFunction(); break; /*case QUERY: doneWithOps = queryFunction(); break;*/ case PUTALL_NEW_KEY: doneWithOps = putAllNewKeyFunction(); break; case INVALIDATE: doneWithOps = invalidateFunction(); break; case DESTROY: doneWithOps = destroyFunction(); break; case UPDATE_EXISTING_KEY: doneWithOps = updateExistingKeyFunction(); break; case GET: doneWithOps = getFunction(); break; case LOCAL_INVALIDATE: doneWithOps = localInvalidateFunction(); break; case LOCAL_DESTROY: doneWithOps = localDestroyFunction(); break; default: { throw new Exception("Invalid operation specified:" + opcode); } } if (m_istransaction && (txManager != null) && (!doneWithOps)) { try { txManager.Commit(); } catch (CommitConflictException) { // can occur with concurrent execution Util.Log("Caught CommitConflictException. Expected with concurrent execution, continuing test."); } catch (TransactionDataNodeHasDepartedException e) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught TransactionDataNodeHasDepartedException in doEntry : {0}", e); } catch (Exception ex) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught unexpected in doEntry : {0}", ex); } } } catch (TimeoutException e) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught unexpected timeout exception during entry operation: " + opcode + " " + e); } catch (IllegalStateException e) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught IllegalStateException during entry operation:" + opcode + " " + e); } catch (Exception e) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught exception during entry operation: " + opcode + " exiting task.\n" + e); } if (doneWithOps) { if (m_istransaction && txManager != null) { try { txManager.Rollback(); } catch (IllegalStateException e) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught IllegalStateException during rollback: " + e); } catch (Exception e) { FwkTest<TKey, TVal>.CurrentTest.FwkException("Caught exception during entry operation: " + e + " exiting task.\n"); } } availableOps.Remove(opcode); } } } } //end doTask function private void checkContainsValueForKey(TKey key, bool expected, string logStr) { //RegionPtr regionPtr = getRegion(); bool containsValue = m_region.ContainsValueForKey(key); if (containsValue != expected) FwkTest<TKey, TVal>.CurrentTest.FwkException("DoOpsTask::checkContainsValueForKey: Expected containsValueForKey(" + key + ") to be " + expected + ", but it was " + containsValue + ": " + logStr); } bool addNewKeyFunction() { int numNewKeysCreated = (int)Util.BBGet("ImageBB", "NUM_NEW_KEYS_CREATED"); Util.BBIncrement("ImageBB", "NUM_NEW_KEYS_CREATED"); FwkTest<TKey, TVal>.CurrentTest.ResetKey("NumNewKeys"); int numNewKeys = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("NumNewKeys"); if (numNewKeysCreated > numNewKeys) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All new keys created; returning from addNewKey"); return true; } FwkTest<TKey, TVal>.CurrentTest.ResetKey("entryCount"); int entryCount = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("entryCount"); entryCount = (entryCount < 1) ? 10000 : entryCount; TKey key = (TKey)(object)(entryCount + numNewKeysCreated); checkContainsValueForKey(key, false, "before addNewKey"); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); FwkTest<TKey, TVal>.CurrentTest.ResetKey("isPdxObject"); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("addKey"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do addKey execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "addNewKeyFunction"); return (numNewKeysCreated >= numNewKeys); } bool putAllNewKeyFunction() { int numNewKeysCreated = (int)Util.BBGet("ImageBB", "NUM_NEW_KEYS_CREATED"); Util.BBIncrement("ImageBB", "NUM_NEW_KEYS_CREATED"); FwkTest<TKey, TVal>.CurrentTest.ResetKey("NumNewKeys"); int numNewKeys = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("NumNewKeys"); if (numNewKeysCreated > numNewKeys) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All new keys created; returning from addNewKey"); return true; } FwkTest<TKey, TVal>.CurrentTest.ResetKey("entryCount"); int entryCount = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("entryCount"); entryCount = (entryCount < 1) ? 10000 : entryCount; TKey key = (TKey)(object)(entryCount + numNewKeysCreated); if(m_region.Attributes.CloningEnabled != false) checkContainsValueForKey(key, false, "before addNewKey"); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); FwkTest<TKey, TVal>.CurrentTest.ResetKey("isPdxObject"); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("putAll"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do addKey execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "putAllNewKeyFunction"); return (numNewKeysCreated >= numNewKeys); } bool invalidateFunction() { int nextKey = (int)Util.BBGet("ImageBB", "LASTKEY_INVALIDATE"); Util.BBIncrement("ImageBB", "LASTKEY_INVALIDATE"); int firstKey = (int)Util.BBGet("ImageBB", "First_Invalidate"); int lastKey = (int)Util.BBGet("ImageBB", "Last_Invalidate"); if (!((nextKey >= firstKey) && (nextKey <= lastKey))) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All existing keys invalidated; returning from invalidate"); return true; } TKey key = (TKey)(object)(nextKey); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("invalidate"); if(pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do invalidate execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "invalidateFunction"); return (nextKey >= lastKey); } bool localInvalidateFunction() { int nextKey = (int)Util.BBGet("ImageBB", "LASTKEY_LOCAL_INVALIDATE"); Util.BBIncrement("ImageBB", "LASTKEY_LOCAL_INVALIDATE"); int firstKey = (int)Util.BBGet("ImageBB", "First_LocalInvalidate"); int lastKey = (int)Util.BBGet("ImageBB", "Last_LocalInvalidate"); if (!((nextKey >= firstKey) && (nextKey <= lastKey))) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All local invalidates completed; returning from localInvalidate"); return true; } TKey key = (TKey)(object)(nextKey); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("localinvalidate"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do locally invalidate execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "localInvalidateFunction"); return (nextKey >= lastKey); } bool destroyFunction() { int nextKey = (int)Util.BBGet("ImageBB", "LASTKEY_DESTROY"); Util.BBIncrement("ImageBB", "LASTKEY_DESTROY"); int firstKey = (int)Util.BBGet("ImageBB", "First_Destroy"); int lastKey = (int)Util.BBGet("ImageBB", "Last_Destroy"); if (!((nextKey >= firstKey) && (nextKey <= lastKey))) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All destroys completed; returning from destroy"); return true; } TKey key = (TKey)(object)(nextKey); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("destroy"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do destroy execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "destroyFunction"); return (nextKey >= lastKey); } bool localDestroyFunction() { int nextKey = (int)Util.BBGet("ImageBB", "LASTKEY_LOCAL_DESTROY"); Util.BBIncrement("ImageBB", "LASTKEY_LOCAL_DESTROY"); int firstKey = (int)Util.BBGet("ImageBB", "First_LocalDestroy"); int lastKey = (int)Util.BBGet("ImageBB", "Last_LocalDestroy"); if (!((nextKey >= firstKey) && (nextKey <= lastKey))) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All local destroys completed; returning from localDestroy"); return true; } TKey key = (TKey)(object)(nextKey); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("localdestroy"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do local destroy execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "localDestroyFunction"); return (nextKey >= lastKey); } bool updateExistingKeyFunction() { int nextKey = (int)Util.BBGet("ImageBB", "LASTKEY_UPDATE_EXISTING_KEY"); Util.BBIncrement("ImageBB", "LASTKEY_UPDATE_EXISTING_KEY"); int firstKey = (int)Util.BBGet("ImageBB", "First_UpdateExistingKey"); int lastKey = (int)Util.BBGet("ImageBB", "Last_UpdateExistingKey"); if (!((nextKey >= firstKey) && (nextKey <= lastKey))) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All existing keys updated; returning from updateExistingKey"); return true; } TKey key = (TKey)(object)(nextKey); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); FwkTest<TKey, TVal>.CurrentTest.ResetKey("isPdxObject"); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("update"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do update execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "updateExistingKeyFunction"); return (nextKey >= lastKey); } bool getFunction() { int nextKey = (int)Util.BBGet("ImageBB", "LASTKEY_GET"); Util.BBIncrement("ImageBB", "LASTKEY_GET"); int firstKey = (int)Util.BBGet("ImageBB", "First_Get"); int lastKey = (int)Util.BBGet("ImageBB", "Last_Get"); if (!((nextKey >= firstKey) && (nextKey <= lastKey))) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All gets completed; returning from get"); return true; } TKey key = (TKey)(object)(nextKey); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); FwkTest<TKey, TVal>.CurrentTest.ResetKey("isPdxObject"); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("get"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do get execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "getFunction"); return (nextKey >= lastKey); } bool queryFunction() { int numNewKeysCreated = (int)Util.BBGet("ImageBB", "NUM_NEW_KEYS_CREATED"); FwkTest<TKey, TVal>.CurrentTest.ResetKey("NumNewKeys"); int numThread = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("numThreads"); numNewKeysCreated = numNewKeysCreated - (numThread - 1); FwkTest<TKey, TVal>.CurrentTest.ResetKey("NumNewKeys"); int numNewKeys = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("NumNewKeys"); if (numNewKeysCreated > numNewKeys) { FwkTest<TKey, TVal>.CurrentTest.FwkInfo("All query executed; returning from addNewKey"); return true; } int entryCount = FwkTest<TKey, TVal>.CurrentTest.GetUIntValue("entryCount"); entryCount = (entryCount < 1) ? 10000 : entryCount; TKey key = (TKey)(object)(entryCount + numNewKeysCreated); checkContainsValueForKey(key, false, "before addNewKey"); //TVal value = GetValue((TVal)(object)(entryCount + numNewKeysCreated)); //GetValue(value); //m_region.Add(key, value); Object[] filterObj = new Object[1]; filterObj[0] = (TKey)(object)key; ArrayList args = new ArrayList(); FwkTest<TKey, TVal>.CurrentTest.ResetKey("isPdxObject"); bool pdxobject = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("isPdxObject"); args.Add("query"); if (pdxobject) args.Add(pdxobject); args.Add(filterObj[0]); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(m_region); //FwkTest<TKey, TVal>.CurrentTest.FwkInfo("Going to do query execute"); ICollection<object> executeFunctionResult = null; FwkTest<TKey, TVal>.CurrentTest.ResetKey("replicated"); bool isReplicate = FwkTest<TKey, TVal>.CurrentTest.GetBoolValue("replicated"); if (!isReplicate){ executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<object>(filterObj).Execute(m_funcName).GetResult(); }else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(m_funcName).GetResult(); } verifyFEResult(executeFunctionResult, "queryFunction"); return (numNewKeysCreated >= numNewKeys); } private void verifyFEResult(ICollection<object> exefuncResult, string funcName) { if (exefuncResult != null) { foreach (object item in exefuncResult) { if ((bool)item != true) { FwkTest<TKey, TVal>.CurrentTest.FwkException("DoFETask::" + funcName + "failed, last result is not true"); } } } } } //------------------------------------DoOpsTask end -------------------------- public class FunctionExecution<TKey,TVal> : FwkTest<TKey, TVal> { private const int NUM_EXTRA_KEYS = 100; private static bool m_istransaction = false; private static List<TKey> destroyedKeys = new List<TKey>(); protected IRegion<TKey,TVal> GetRegion() { return GetRegion(null); } protected IRegion<TKey,TVal> GetRegion(string regionName) { IRegion<TKey, TVal> region; if (regionName == null) { region = GetRootRegion(); if (region == null) { IRegion<TKey, TVal>[] rootRegions = CacheHelper<TKey, TVal>.DCache.RootRegions<TKey, TVal>(); if (rootRegions != null && rootRegions.Length > 0) { region = rootRegions[Util.Rand(rootRegions.Length)]; } } } else { region = CacheHelper<TKey, TVal>.GetRegion(regionName); } return region; } public virtual void DoCreateRegion() { FwkInfo("In DoCreateRegion()"); try { IRegion<TKey, TVal> region = CreateRootRegion(); ResetKey("useTransactions"); m_istransaction = GetBoolValue("useTransactions"); if (region == null) { FwkException("DoCreateRegion() could not create region."); } FwkInfo("DoCreateRegion() Created region '{0}'", region.Name); } catch (Exception ex) { FwkException("DoCreateRegion() Caught Exception: {0}", ex); } FwkInfo("DoCreateRegion() complete."); } public void DoCloseCache() { FwkInfo("DoCloseCache() Closing cache and disconnecting from" + " distributed system."); CacheHelper<TKey, TVal>.Close(); } public virtual void DoClearRegion() { FwkInfo("In DoClearRegion()"); try { IRegion<TKey, TVal> region = GetRegion(); region.Clear(); } catch (Exception ex) { FwkException("DoClearRegion() Caught Exception: {0}", ex); } FwkInfo("DoClearRegion() complete."); } public void DoLoadRegion() { FwkInfo("In DoLoadRegion()"); try { IRegion<TKey, TVal> region = GetRegion(); ResetKey("distinctKeys"); int numKeys = GetUIntValue("distinctKeys"); bool isUpdate = GetBoolValue("update"); //string key = null; //string value = null; TKey key; TVal value; for (int j = 1; j < numKeys; j++) { string k = "key-" + j; string v = null; key = (TKey)(object)(k.ToString()); if (isUpdate) { v = "valueUpdate-" + j; value = (TVal)(object)(v.ToString()); } else { v = "valueCreate-" + j; value = (TVal)(object)(v.ToString()); } // region.Put(key, value); region[key] = value; } } catch (Exception ex) { FwkException("DoLoadRegion() Caught Exception: {0}", ex); } FwkInfo("DoLoadRegion() complete."); } public void DoAddDestroyNewKeysFunction() { FwkInfo("In DoAddDestroyNewKeysFunction()"); IRegion<TKey, TVal> region = GetRegion(); ResetKey("distinctKeys"); Int32 numKeys = GetUIntValue("distinctKeys"); int clientNum = Util.ClientNum; //IGeodeSerializable[] filterObj = new IGeodeSerializable[numKeys]; Object[] filterObj = new Object[numKeys]; try { for(int j = 0; j < numKeys; j++) { //filterObj[j] = new CacheableString("KEY--" + clientNum + "--" + j); filterObj[j] = "KEY--" + clientNum + "--" + j; } string opcode = GetStringValue( "entryOps" ); if(opcode == "destroy") ExecuteFunction(filterObj, "destroy"); else ExecuteFunction(filterObj,"addKey"); } catch (Exception ex) { FwkException("DoAddDestroyNewKeysFunction() Caught Exception: {0}", ex); } FwkInfo("DoAddDestroyNewKeysFunction() complete."); } private void ExecuteFunction(Object[] filterObj, string ops) { FwkInfo("In ExecuteFunction() ops is {0}", ops); try { ResetKey( "getResult" ); Boolean getresult = GetBoolValue("getResult"); ResetKey( "replicated" ); bool isReplicate = GetBoolValue("replicated"); ResetKey( "distinctKeys" ); Int32 numKeys = GetUIntValue( "distinctKeys" ); // CacheableVector args = new CacheableVector(); ArrayList args = new ArrayList(); if (filterObj == null) { int clntId = Util.ClientNum; filterObj = new Object[1]; //filterObj = new IGeodeSerializable[1]; Random rnd = new Random(); //filterObj[0] = new CacheableString("KEY--" + clntId + "--" + rnd.Next(numKeys)); filterObj[0] = "KEY--" + clntId + "--" + rnd.Next(numKeys); args.Add(filterObj[0]); } else { for (int i = 0; i < filterObj.Length; i++) { args.Add(filterObj[i]); } } if (ops.Equals("destroy")) { for (int i = 0; i < filterObj.Length; i++) { destroyedKeys.Add((TKey)filterObj[i]); } } //Execution<object> exc = null; Apache.Geode.Client.Execution<object> exc = null; //Execution exc = null; Pool/*<TKey, TVal>*/ pptr = null; IRegion<TKey, TVal> region = GetRegion(); ResetKey("executionMode"); string executionMode = GetStringValue( "executionMode" ); ResetKey("poolName"); string poolname = GetStringValue( "poolName" ); string funcName = null; if(executionMode == "onServers" || executionMode == "onServer"){ pptr = PoolManager/*<TKey, TVal>*/.Find(poolname); if(getresult) funcName = "ServerOperationsFunction"; else funcName = "ServerOperationsWithOutResultFunction"; } if ( executionMode == "onServers") { /*exc = Client.FunctionService.OnServers<TKey,TVal,object>(pptr);*/ exc = Client.FunctionService<object>.OnServers(pptr); } if ( executionMode == "onServer"){ exc = Client.FunctionService<object>.OnServer(pptr); }else if( executionMode == "onRegion"){ exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region); if(getresult) funcName = "RegionOperationsFunction"; else funcName = "RegionOperationsWithOutResultFunction"; } //FwkInfo("ExecuteFunction - function name is{0} ", funcName); //IGeodeSerializable[] executeFunctionResult = null; ICollection<object> executeFunctionResult = null; if(!isReplicate){ if(getresult == true){ if(executionMode == "onRegion"){ executeFunctionResult = exc.WithArgs<string>(ops).WithFilter<object>(filterObj).Execute(funcName, 15).GetResult(); }else{ args.Add(ops); executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(funcName, 15).GetResult(); } }else { if(executionMode == "onRegion"){ exc.WithArgs<string>(ops).WithFilter<object>(filterObj).Execute(funcName, 15); } else { args.Add(ops); exc.WithArgs<ArrayList>(args).Execute(funcName, 15); } } } else { args.Add(ops); if (getresult) { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(funcName, 15).GetResult(); } else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(funcName, 15).GetResult(); } } Thread.Sleep(30000); if (ops == "addKey") { VerifyAddNewResult(executeFunctionResult, filterObj); } else { VerifyResult(executeFunctionResult, filterObj, ops); } } catch (Exception ex) { FwkException("ExecuteFunction() Caught Exception: {0}", ex); } FwkInfo("ExecuteFunction() complete."); } public void VerifyAddNewResult(ICollection<object> exefuncResult, Object[] filterObj) { FwkInfo("In VerifyAddNewResult()"); try { Thread.Sleep(30000); IRegion<TKey, TVal> region = GetRegion(); //CacheableString value = null; string value = null; if (filterObj != null) { for (int i = 0; i < filterObj.Length; i++) { // CacheableKey key = filterObj[i] as CacheableKey; TKey key = (TKey)filterObj[i]; for (int cnt = 0; cnt < 100; cnt++) { // value = region.Get(key) as CacheableString; value = region[key].ToString(); } //CacheableString expectedVal = filterObj[i] as CacheableString; string expectedVal = (String)filterObj[i]; if (!(expectedVal.Equals(value))) { FwkException("VerifyAddNewResult Failed: expected value is {0} and found {1} for key {2}", expectedVal, value, key.ToString()); } } } } catch (Apache.Geode.Client.KeyNotFoundException ex) { FwkInfo("VerifyAddNewResult() caught exception: {0}", ex); } catch (Exception ex) { FwkException("VerifyAddNewResult() Caught Exception: {0}", ex); } FwkInfo("VerifyAddNewResult() complete."); } public void VerifyResult(ICollection<object> exefuncResult, Object[] filterObj, string ops) { FwkInfo("In VerifyResult()"); Boolean getresult = GetBoolValue("getResult"); FwkInfo("In VerifyResult() getresult = {0} ", getresult); try { IRegion<TKey, TVal> region = GetRegion(); string buf = null; if(exefuncResult != null) { IEnumerator<object> enm = exefuncResult.GetEnumerator(); enm.MoveNext(); Boolean lastResult = (Boolean)enm.Current; //exefuncResult[0]; if (lastResult!= true) FwkException("FunctionExecution::VerifyResult failed, last result is not true"); } string value = null; if(filterObj != null ) { //CacheableKey key = filterObj[0] as CacheableKey; TKey key = (TKey)filterObj[0]; for (int i = 0; i<50;i++){ try { value = region[key].ToString(); } catch (Apache.Geode.Client.KeyNotFoundException) { if(ops.Equals("destroy") && destroyedKeys.Remove(key)) { FwkInfo("FunctionExecution.VerifyResults() key {0} has been destroyed " + " in read for index {1} ", key,i); break; } else { if (getresult) { FwkException("FunctionExecution.VerifyResults() Caught KeyNotFoundException " + " in read for key: {0} for index {1}", key, i); } else { FwkInfo("FunctionExecution.VerifyResults() key {0} Caught KeyNotFoundException for getResult false" + " in read for index {1} ", key, i); break; } } } } if(ops == "update" || ops == "get"){ if (value != null) { if (value.IndexOf("update_") == 0) buf = "update_" + key.ToString(); else buf = key.ToString(); if (!(buf.Equals(value))) FwkException("VerifyResult Failed: expected value is {0} and found {1} for key {2} for operation {3}", buf, value, key.ToString(), ops); } } else if(ops == "destroy"){ if(value == null){ ExecuteFunction(filterObj,"addKey"); }else{ FwkException("FunctionExecution::VerifyResult failed to destroy key {0}",key.ToString()); } } else if(ops == "invalidate"){ if(value == null) { ExecuteFunction(filterObj,"update"); }else { FwkException("FunctionExecution::VerifyResult Failed for invalidate key {0}" ,key.ToString()); } } } } catch (Exception ex) { FwkException("VerifyResult() Caught Exception: {0}", ex); } FwkInfo("VerifyResult() complete."); } public void DoExecuteFunctions() { FwkInfo("In DoExecuteFunctions()"); int secondsToRun = GetTimeValue("workTime"); secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun; DateTime now = DateTime.Now; DateTime end = now.AddSeconds(secondsToRun); string opcode = null; bool rolledback = false; CacheTransactionManager txManager = null; while (now < end) { try { if (m_istransaction) { txManager = CacheHelper<TKey, TVal>.DCache.CacheTransactionManager; txManager.Begin(); } opcode = GetStringValue("entryOps"); ExecuteFunction(null, opcode); if (m_istransaction && !rolledback) { try { txManager.Commit(); } catch (CommitConflictException) { // can occur with concurrent execution Util.Log("Caught CommitConflictException. Expected with concurrent execution, continuing test."); } catch (Exception ex) { throw new Exception("Caught unexpected in doEntry : {0}", ex); } } } catch (Exception ex) { FwkException("DoExecuteFunctions() Caught Exception: {0}", ex); } now = DateTime.Now; } FwkInfo("DoExecuteFunctions() complete."); } public void DoExecuteExceptionHandling() { FwkInfo("In DoExecuteExceptionHandling()"); int secondsToRun = GetTimeValue("workTime"); secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun; DateTime now = DateTime.Now; DateTime end = now.AddSeconds(secondsToRun); string opcode = null; bool rolledback = false; CacheTransactionManager txManager = null; while (now < end) { try { if (m_istransaction) { txManager = CacheHelper<TKey, TVal>.DCache.CacheTransactionManager; txManager.Begin(); } opcode = GetStringValue("entryOps"); if(opcode == "ParitionedRegionFunctionExecution") { DoParitionedRegionFunctionExecution(); } else if (opcode == "ReplicatedRegionFunctionExecution") { DoReplicatedRegionFunctionExecution(); } else if (opcode == "FireAndForgetFunctionExecution") { DoFireAndForgetFunctionExecution(); } else if (opcode == "OnServersFunctionExcecution") { DoOnServersFunctionExcecution(); } if (m_istransaction && !rolledback) { try { txManager.Commit(); } catch (CommitConflictException) { // can occur with concurrent execution Util.Log("Caught CommitConflictException. Expected with concurrent execution, continuing test."); } catch (Exception ex) { throw new Exception("Caught unexpected in doEntry : {0}", ex); } } } catch (Exception ex) { FwkException( "Caught unexpected {0} during exception handling for {1} operation: {2} : exiting task." ,ex.ToString(), opcode,ex.Message); } now = DateTime.Now; } FwkInfo("DoExecuteExceptionHandling() complete."); } public void DoParitionedRegionFunctionExecution() { FwkInfo("In DoParitionedRegionFunctionExecution()"); Apache.Geode.Client.Execution<object> exc = null; IRegion<TKey, TVal> region = GetRegion("partitionedRegion"); try { exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region); MyResultCollector<object> myRC = new MyResultCollector<object>(); Random rnd = new Random(); if(rnd.Next(100) % 2 == 0) { //Execution on partitionedRegion with no filter exc = exc.WithCollector(myRC); } else { //Execution on partitionedRegion with filter // ICacheableKey<TKey>[]keys = region.GetKeys(); ICollection<TKey> keys = region.GetLocalView().Keys; //IGeodeSerializable[] filterObj = new IGeodeSerializable[keys.Count]; Object[] filterObj = new Object[keys.Count]; for (int i = 0; i < keys.Count; i++) { //filterObj[i] = (IGeodeSerializable)keys; filterObj[i] = keys; } exc = exc.WithFilter(filterObj).WithCollector(myRC); } // execute function Client.IResultCollector<object> rc = exc.Execute("ExceptionHandlingFunction", 30); } catch (Apache.Geode.Client.FunctionExecutionException) { //expected exception } catch (Apache.Geode.Client.TimeoutException) { //expected exception } FwkInfo("DoParitionedRegionFunctionExecution() complete."); } public void DoReplicatedRegionFunctionExecution() { FwkInfo("In DoReplicatedRegionFunctionExecution()"); Apache.Geode.Client.Execution<object> exc = null; IRegion<TKey, TVal> region = GetRegion("replicatedRegion"); try { exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region); MyResultCollector<object> myRC = new MyResultCollector<object>(); exc = exc.WithCollector(myRC); // execute function Client.IResultCollector<object> rc = exc.Execute("ExceptionHandlingFunction", 30); } catch (Apache.Geode.Client.FunctionExecutionException) { //expected exception } catch (Apache.Geode.Client.TimeoutException) { //expected exception } FwkInfo("DoReplicatedRegionFunctionExecution() complete."); } public void DoFireAndForgetFunctionExecution() { FwkInfo("In DoFireAndForgetFunctionExecution()"); string name = null; Random rnd = new Random(); if(rnd.Next(100) % 2 == 0){ //Execution Fire and forget on partitioned region name = "partitionedRegion"; } else { //Execution Fire and forget on replicated region name = "replicatedRegion"; } IRegion<TKey, TVal> region = GetRegion(name); try { MyResultCollector<object> myRC = new MyResultCollector<object>(); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region).WithCollector(myRC); // execute function Client.IResultCollector<object> rc = exc.Execute("FireNForget", 30); } catch (Apache.Geode.Client.FunctionExecutionException) { //expected exception } catch (Apache.Geode.Client.TimeoutException) { //expected exception } FwkInfo("DoFireAndForgetFunctionExecution() complete."); } public void DoOnServersFunctionExcecution() { FwkInfo("In DoOnServersFunctionExcecution()"); ResetKey("poolName"); string poolname = GetStringValue("poolName"); Apache.Geode.Client.Execution<object> exc = null; try { Pool/*<TKey, TVal>*/ pptr = PoolManager/*<TKey, TVal>*/.Find(poolname); MyResultCollector<object> myRC = new MyResultCollector<object>(); exc = Client.FunctionService<object>.OnServers(pptr).WithCollector(myRC); // execute function Client.IResultCollector<object> rc = exc.Execute("ExceptionHandlingFunction", 30); } catch (Apache.Geode.Client.FunctionExecutionException) { //expected exception } catch (Apache.Geode.Client.TimeoutException) { //expected exception } FwkInfo("DoOnServersFunctionExcecution() complete."); } public void DoExecuteFunctionsHA() { ResetKey("getResult"); bool getresult = GetBoolValue("getResult"); ResetKey("distinctKeys"); int numKeys = GetUIntValue("distinctKeys"); IRegion<TKey, TVal> region = GetRegion(); ICollection<object> executeFunctionResult = null; string funcName = "GetFunctionExeHA"; Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region); MyResultCollectorHA<object> myRC = new MyResultCollectorHA<object>(); exc = exc.WithCollector(myRC); Client.IResultCollector<object> rc = exc.Execute(funcName, 120); executeFunctionResult = myRC.GetResult(); if (executeFunctionResult != null) { IEnumerator<object> enmtor = executeFunctionResult.GetEnumerator(); enmtor.MoveNext(); //Boolean lastResult = (Boolean)enmtor.Current; //exefuncResult[0]; //Boolean lastResult = (Boolean)executeFunctionResult[0]; // if (lastResult!= true) // FwkException("FunctionExecution::DoExecuteFunctionHA failed, last result is not true"); ICollection<object> resultListColl = myRC.GetResult(60); string[] resultList = new string[resultListColl.Count]; resultList.CopyTo(resultList, 0); //FwkInfo("FunctionExecution::DoExecuteFunctionHA GetClearResultCount {0} GetGetResultCount {1} GetAddResultCount {2}", myRC.GetClearResultCount(), myRC.GetGetResultCount(), myRC.GetAddResultCount()); if (resultList != null) { if (numKeys == resultList.Length) { for (int i = 1; i < numKeys; i++) { int count = 0; string key = "key-" + i; for (int j = 0; j < resultList.Length; j++) { if ((key.Equals(resultList[j]))) { count++; if (count > 1) { FwkException("FunctionExecution::DoExecuteFunctionHA: duplicate entry found for key {0} ", key); } } } if(count == 0) { FwkException("FunctionExecution::DoExecuteFunctionHA failed: key is missing in result list {0}", key); } } } } else { FwkException("FunctionExecution::DoExecuteFunctionHA failed: result size {0} doesn't match with number of keys {1}", resultList.Length, numKeys); } } else { FwkException("FunctionExecution::DoExecuteFunctionHA executeFunctionResult is null"); } } public void DoGetServerKeys() { try { FwkInfo("FunctionExecution:DoGetServerKeys"); IRegion<TKey, TVal> region = GetRegion(); TKey[] keys = (TKey[])(object)region.Keys; bool pdxobject = GetBoolValue("isPdxObject"); ArrayList args = new ArrayList(); args.Add("get"); if (pdxobject) args.Add(pdxobject); //args.Add("pdxobject"); for (int i = 0; i < keys.Length; i++) args.Add(keys[i]); string funcName = GetStringValue("funcName"); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region); //FwkInfo("Going to do get execute"); ICollection<object> executeFunctionResult = null; ResetKey("replicated"); bool isReplicate = GetBoolValue("replicated"); if (!isReplicate) { executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<TKey>(keys).Execute(funcName).GetResult(); } else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(funcName).GetResult(); } if (executeFunctionResult != null) { foreach (object item in executeFunctionResult) { if ((bool)item != true) FwkException("FunctionExecution:DoGetServerKeys:: failed, last result is not true"); } } } catch (CacheServerException ex) { FwkException("DoGetServerKeys() Caught CacheServerException: {0}", ex); } catch (Exception ex) { FwkException("DoGetServerKeys() Caught Exception: {0}", ex); } } public void DoUpdateServerKeys() { try { FwkInfo("FunctionExecution:DoGetServerKeys"); IRegion<TKey, TVal> region = GetRegion(); TKey[] keys = (TKey[])(object)region.Keys; bool pdxobject = GetBoolValue("isPdxObject"); ArrayList args = new ArrayList(); args.Add("update"); if (pdxobject) args.Add(pdxobject); //args.Add("pdxobject"); for (int i = 0; i < keys.Length; i++) args.Add(keys[i]); string funcName = GetStringValue("funcName"); Apache.Geode.Client.Execution<object> exc = Client.FunctionService<object>.OnRegion<TKey, TVal>(region); //FwkInfo("Going to do get execute"); ICollection<object> executeFunctionResult = null; ResetKey("replicated"); bool isReplicate = GetBoolValue("replicated"); if (!isReplicate) { executeFunctionResult = exc.WithArgs<ArrayList>(args).WithFilter<TKey>(keys).Execute(funcName).GetResult(); } else { executeFunctionResult = exc.WithArgs<ArrayList>(args).Execute(funcName).GetResult(); } if (executeFunctionResult != null) { foreach (object item in executeFunctionResult) { if ((bool)item != true) FwkException("FunctionExecution:DoGetServerKeys:: failed, last result is not true"); } } } catch (CacheServerException ex) { FwkException("DoGetServerKeys() Caught CacheServerException: {0}", ex); } catch (Exception ex) { FwkException("DoGetServerKeys() Caught Exception: {0}", ex); } } public void doOps() { FwkInfo("FunctionExcution:doOps called."); int opsSec = GetUIntValue("opsSecond"); opsSec = (opsSec < 1) ? 0 : opsSec; int secondsToRun = GetTimeValue("workTime"); secondsToRun = (secondsToRun < 1) ? 30 : secondsToRun; int valSize = GetUIntValue("valueSizes"); valSize = ((valSize < 0) ? 32 : valSize); ResetKey("entryCount"); int entryCount = GetUIntValue("entryCount"); ResetKey("NumNewKeys"); int numNewKeys = GetUIntValue("NumNewKeys"); //TestClient * clnt = TestClient::getTestClient(); IRegion<TKey, TVal> regionPtr = GetRegion(); if (regionPtr == null) { FwkSevere("FunctionExcution:doOps(): No region to perform operations on."); //now = end; // Do not do the loop } ResetKey("useTransactions"); bool m_istransaction = GetBoolValue("useTransactions"); try { DoFETask<TKey, TVal> dooperation = new DoFETask<TKey, TVal>(regionPtr, m_istransaction); ResetKey("numThreads"); int numThreads = GetUIntValue("numThreads"); RunTask(dooperation, numThreads, entryCount + numNewKeys + NUM_EXTRA_KEYS, -1, -1, null); } catch (ClientTimeoutException) { FwkException("In FunctionExcution:doOps() Timed run timed out."); } catch (FwkException e) { FwkException("Caught Exception exception during FunctionExcution:doOps: " + e); } catch (Exception e) { FwkException("Caught unexpected exception during FunctionExcution:doOps: " + e); } FwkInfo("Done in FunctionExcution:doOps"); Thread.Sleep(10000); } } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; using Dynastream.Utility; namespace Dynastream.Fit { /// <summary> /// Architecture defaults to Little Endian (unless decoded from an binary defn as Big Endian) /// This could be exposed in the future to programatically create BE streams. /// </summary> public class MesgDefinition { #region Fields private byte architecture; private byte localMesgNum; private List<FieldDefinition> fieldDefs = new List<FieldDefinition>(); #endregion #region Properties public ushort GlobalMesgNum { get; set; } public byte LocalMesgNum { get { return localMesgNum; } set { if (value > Fit.LocalMesgNumMask) { throw new FitException("MesgDefinition:LocalMesgNum - Invalid Local message number " + value + ". Local message number must be < " + Fit.LocalMesgNumMask); } else { localMesgNum = value; } } } public byte NumFields { get; set; } public bool IsBigEndian { get { if (architecture == Fit.BigEndian) { return true; } else { return false; } } } #endregion #region Constructors internal MesgDefinition() { LocalMesgNum = 0; GlobalMesgNum = (ushort)MesgNum.Invalid; architecture = Fit.LittleEndian; } public MesgDefinition(Stream fitSource) { Read(fitSource); } public MesgDefinition(Mesg mesg) { LocalMesgNum = mesg.LocalNum; GlobalMesgNum = mesg.Num; architecture = Fit.LittleEndian; NumFields = (byte)mesg.fields.Count; foreach (Field field in mesg.fields) { fieldDefs.Add(new FieldDefinition(field)); } } public MesgDefinition(MesgDefinition mesgDef) { LocalMesgNum = mesgDef.LocalMesgNum; GlobalMesgNum = mesgDef.GlobalMesgNum; architecture = mesgDef.IsBigEndian ? Fit.BigEndian : Fit.LittleEndian; NumFields = mesgDef.NumFields; foreach (FieldDefinition fieldDef in mesgDef.fieldDefs) { fieldDefs.Add(new FieldDefinition(fieldDef)); } } #endregion #region Methods public void Read(Stream fitSource) { fitSource.Position = 0; EndianBinaryReader br = new EndianBinaryReader(fitSource, false); LocalMesgNum = (byte)(br.ReadByte() & Fit.LocalMesgNumMask); byte reserved = br.ReadByte(); architecture = br.ReadByte(); br.IsBigEndian = this.IsBigEndian; GlobalMesgNum = br.ReadUInt16(); NumFields = br.ReadByte(); for (int i=0; i<NumFields; i++) { FieldDefinition newField = new FieldDefinition(); newField.Num = br.ReadByte(); newField.Size = br.ReadByte(); newField.Type = br.ReadByte(); fieldDefs.Add(newField); } } public void Write (Stream fitDest) { BinaryWriter bw = new BinaryWriter(fitDest); bw.Write((byte)(LocalMesgNum + Fit.MesgDefinitionMask)); bw.Write((byte)Fit.MesgDefinitionReserved); bw.Write((byte)Fit.LittleEndian); bw.Write(GlobalMesgNum); bw.Write(NumFields); if (NumFields != fieldDefs.Count) { throw new FitException("MesgDefinition:Write - Field Count Internal Error"); } for (int i = 0; i < fieldDefs.Count; i++) { bw.Write(fieldDefs[i].Num); bw.Write(fieldDefs[i].Size); bw.Write(fieldDefs[i].Type); } } public int GetMesgSize() { int mesgSize = 1; // header foreach (FieldDefinition field in fieldDefs) { mesgSize += field.Size; } return mesgSize; } public void AddField(FieldDefinition field) { fieldDefs.Add(field); } public void ClearFields() { fieldDefs.Clear(); } public int GetNumFields() { return fieldDefs.Count; } public List<FieldDefinition> GetFields() { // This is a reference to the real list return fieldDefs; } public FieldDefinition GetField(byte num) { foreach (FieldDefinition fieldDef in fieldDefs) { if (fieldDef.Num == num) { return fieldDef; } } return null; } public bool Supports(Mesg mesg) { return Supports(new MesgDefinition(mesg)); } public bool Supports(MesgDefinition mesgDef) { if (mesgDef == null) { return false; } if (GlobalMesgNum != mesgDef.GlobalMesgNum) { return false; } if (LocalMesgNum != mesgDef.LocalMesgNum) { return false; } foreach (FieldDefinition fieldDef in mesgDef.GetFields()) { FieldDefinition supportedFieldDef = GetField(fieldDef.Num); if (supportedFieldDef == null) { return false; } if (fieldDef.Size > supportedFieldDef.Size) { return false; } } return true; } #endregion } } // namespace
using System; using System.IO; using System.Collections; using System.Threading; using System.Text; using JovianJavaScript; namespace JovianAnvil { class StringPair { public string data; public string tail; } class WorkUnit { public string name; public int order; public string data; } class WorkUnitComparer : IComparer { public int Compare(object a, object b) { int x = ((WorkUnit)a).order; int y = ((WorkUnit)b).order; if (x < y) return -1; if (x > y) return 0; return 1; } } class WorkPool { ArrayList WaitingUnits; ArrayList FinishedUnits; int FinishedAt; public WorkPool() { WaitingUnits = new ArrayList(); FinishedUnits = new ArrayList(); FinishedAt = 0; } public void Add(WorkUnit wu) { wu.order = WaitingUnits.Count; WaitingUnits.Add(wu); FinishedAt = WaitingUnits.Count; } public void Finished(WorkUnit wu) { System.Threading.Monitor.Enter(this); FinishedUnits.Add(wu); System.Threading.Monitor.Exit(this); } public void Finalize() { FinishedUnits.Sort(new WorkUnitComparer()); } public bool Done() { System.Threading.Monitor.Enter(this); bool rz = FinishedUnits.Count >= FinishedAt; System.Threading.Monitor.Exit(this); return rz; } public WorkUnit GetUnit() { WorkUnit rz = null; System.Threading.Monitor.Enter(this); if (WaitingUnits.Count > 0) { rz = WaitingUnits[0] as WorkUnit; WaitingUnits.RemoveAt(0); } System.Threading.Monitor.Exit(this); return rz; } } class Program { static int ComputeBrace(string code) { int d = 1; for (int k = code.IndexOf("{") + 1; k < code.Length; k++) { if (code[k] == '{') { d++; } else if (code[k] == '}') { d--; if (d == 0) return k + 1; } } return -1; } static StringPair Extract(string code) { if (code.IndexOf("{") < 0) return null; // no segment int LastBrace = ComputeBrace(code); if (LastBrace < 0) return null; string analyze = code.Substring(0, code.IndexOf("{")).Trim(); if (analyze[analyze.Length - 1] == ')') { } else { LastBrace = code.IndexOf(";", LastBrace); if (LastBrace < 0) return null; LastBrace++; } string tot, tail; if (LastBrace < code.Length) { tot = code.Substring(0, LastBrace); tail = code.Substring(LastBrace + 1); } else { tot = code; tail = ""; } StringPair sp = new StringPair(); sp.data = tot.Trim(); sp.tail = tail.Trim(); return sp; } static ArrayList Breakdown(string x) { ArrayList l = new ArrayList(); string code = x; StringPair i = Extract(code); while (i != null) { l.Add(i.data); code = i.tail; i = Extract(code); } if (code.Length > 0) { l.Add(code); } return l; } static void PrepareFile(string filename, ArrayList C, JovianJavaScript.Adv.CommandEnv CE) { if (filename[0] == '_') return; C.Add(Prepare.PrepareFile(filename, CE)); } static void BreakFile(CommandFile CF, WorkPool WP) { Console.WriteLine("Breaking Up:" + CF.name); ArrayList l = Breakdown(CF.processed); WorkUnit wu = new WorkUnit(); wu.name = CF.name + "_0"; wu.data = ""; for(int k = 0; k < l.Count; k++) { wu.data += (string)l[k]; if (wu.data.Length > 1024 * 32) { WP.Add(wu); wu = new WorkUnit(); wu.name = CF.name + "_" + k; wu.data = ""; } } if (wu.data.Length > 0) { WP.Add(wu); } } /* */ public static void ThreadLoop(object o) { WorkPool WP = o as WorkPool; while (!WP.Done()) { WorkUnit WU = WP.GetUnit(); if (WU != null) { Console.WriteLine("Checking:" + WU.name); try { //System.Threading.Monitor.Enter(WP); // JSM.ParseAndCompile(WU.data); StreamWriter writ = new StreamWriter("temp\\" + WU.name + ".js"); writ.Write(WU.data); writ.Flush(); writ.Close(); System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents=false; proc.StartInfo.FileName="JovianAnvil.exe"; string fname = "temp\\" + WU.name + ".js"; proc.StartInfo.Arguments = "c " + fname; proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.LoadUserProfile = false; proc.StartInfo.UseShellExecute = false; proc.Start(); proc.WaitForExit(); if (File.Exists(fname + ".lisp")) { } if (File.Exists(fname + ".error")) { } /* if (Thread.CurrentThread.Name.Equals("Drone.2")) { Console.WriteLine("Processor 3:"); } if (Thread.CurrentThread.Name.Equals("Drone.3")) { Console.WriteLine("Processor 4:"); } */ //System.Threading.Monitor.Exit(WP); //Thread.Sleep(100); } catch (Exception e) { //System.Threading.Monitor.Exit(WP); Console.WriteLine("\tProblem [" + WU.name + "]:" + e.Message); Console.WriteLine("--------"); Console.WriteLine(WU.data); Console.WriteLine("--------"); } WP.Finished(WU); } else { } } } static void Main(string[] args) { if (args.Length > 0) { StreamReader SR = new StreamReader(args[0]); string js = SR.ReadToEnd(); SR.Close(); try { js = JSM.Clean(js); ASTree.LispNode node = JSM.ParseAndCompile(js); string output = JSM.Optimize1(node, true, "stage1\\c_" + args[0] + ".stat"); StreamWriter SW = new StreamWriter("stage1\\c_" + args[0]); SW.Write(output); SW.Flush(); SW.Close(); } catch (Exception E) { Console.WriteLine("error:" + E.Message); } } /* if (args.Length > 0) { if (args[0] == "c") { StreamReader SR = new StreamReader(args[1]); string js = SR.ReadToEnd(); SR.Close(); if (File.Exists(args[1] + ".lisp")) File.Delete(args[1] + ".lisp"); if (File.Exists(args[1] + ".error")) File.Delete(args[1] + ".error"); try { ASTree.LispNode node = JSM.ParseAndCompile(js); StreamWriter SW = new StreamWriter(args[1] + ".lisp"); SW.Write(node.str()); SW.Flush(); SW.Close(); } catch(Exception e) { StreamWriter SW = new StreamWriter(args[1] + ".error"); SW.Write(e.Message+ ":" + js); SW.Flush(); SW.Close(); } return; } } Win32.HiPerfTimer hpf = new Win32.HiPerfTimer(); hpf.Start(); if (!Directory.Exists("temp")) Directory.CreateDirectory("temp"); JovianJavaScript.Adv.CommandEnv CE = new JovianJavaScript.Adv.CommandEnv(); ArrayList C = new ArrayList(); string[] files = Directory.GetFiles("."); foreach (string f in files) { string File = f.Substring(2); if (File.ToUpper().Substring(File.Length - 2).Equals("JS")) { PrepareFile(File,C,CE); } } WorkPool WP = new WorkPool(); foreach (CommandFile CF in C) { BreakFile(CF, WP); } Thread[] Drones = new Thread[4]; for (int k = 0; k < Drones.Length; k++) { Drones[k] = new Thread(new ParameterizedThreadStart(ThreadLoop)); Drones[k].Name = "Drone." + k; Drones[k].Start(WP); } while (!WP.Done()) { Thread.Sleep(100); } hpf.Stop(); Console.WriteLine("Took:" + Math.Round(hpf.Duration * 10)/10.0 + "sec"); StreamWriter S = new StreamWriter("__Stage0.js"); S.Flush(); S.Close(); */ } } }
namespace OmniXaml.ObjectAssembler { using System.Collections; using System.Linq; using System.Reflection; using Commands; using Glass.Core; using TypeConversion; using Typing; public class StateCommuter { private readonly IInstanceLifeCycleListener lifecycleListener; private readonly IValueContext valueContext; private StackingLinkedList<Level> stack; public StateCommuter(StackingLinkedList<Level> stack, IRuntimeTypeSource typeSource, IInstanceLifeCycleListener lifecycleListener, IValueContext valueContext) { Guard.ThrowIfNull(stack, nameof(stack)); Guard.ThrowIfNull(typeSource, nameof(typeSource)); Stack = stack; this.lifecycleListener = lifecycleListener; this.valueContext = valueContext; } public CurrentLevelWrapper Current { get; private set; } public PreviousLevelWrapper Previous { get; private set; } public int Level => stack.Count; private bool HasParentToAssociate => Level > 1; public bool WasAssociatedRightAfterCreation => Current.WasAssociatedRightAfterCreation; public IValueContext ValueContext => valueContext; public ValueProcessingMode ValueProcessingMode { get; set; } public object ValueOfPreviousInstanceAndItsMember => GetValueTuple(Previous.Instance, (MutableMember) Previous.Member); private StackingLinkedList<Level> Stack { get { return stack; } set { stack = value; UpdateLevelWrappers(); } } public bool ParentIsOneToMany => Previous.XamlMemberIsOneToMany; public InstanceProperties InstanceProperties => Current.InstanceProperties; public bool HasParent => !Previous.IsEmpty; public ITopDownValueContext TopDownValueContext => valueContext.TopDownValueContext; public void SetKey(object value) { InstanceProperties.Key = value; } public void AssignChildToParentProperty() { var previousMember = (MutableMember) Previous.Member; object compatibleValue; var success = CommonValueConversion.TryConvert(Current.Instance, previousMember.XamlType, valueContext, out compatibleValue); if (!success) { compatibleValue = Current.Instance; } previousMember.SetValue(Previous.Instance, compatibleValue, valueContext); } public void RaiseLevel() { stack.Push(new Level()); UpdateLevelWrappers(); } private void UpdateLevelWrappers() { Current = new CurrentLevelWrapper(stack.Current != null ? stack.CurrentValue : new NullLevel(), valueContext); Previous = new PreviousLevelWrapper(stack.Previous != null ? stack.PreviousValue : new NullLevel()); } public void DecreaseLevel() { stack.Pop(); UpdateLevelWrappers(); } public void CreateInstanceOfCurrentXamlTypeIfNotCreatedBefore() { if (!Current.HasInstance) { MaterializeInstanceOfCurrentType(); } } private void MaterializeInstanceOfCurrentType() { var xamlType = Current.XamlType; if (xamlType == null) { throw new ParseException("A type must be set before invoking MaterializeInstanceOfCurrentType"); } var parameters = GatherConstructionArguments(); var instance = xamlType.CreateInstance(parameters); Current.Instance = instance; lifecycleListener.OnBegin(instance); } public object GetValueProvidedByMarkupExtension(IMarkupExtension instance) { var markupExtensionContext = GetExtensionContext(); return instance.ProvideValue(markupExtensionContext); } private MarkupExtensionContext GetExtensionContext() { var inflationContext = new MarkupExtensionContext { TargetObject = Previous.Instance, TargetProperty = Previous.Instance.GetType().GetRuntimeProperty(Previous.Member.Name), ValueContext = ValueContext, }; return inflationContext; } private object[] GatherConstructionArguments() { if (Current.CtorArguments == null) { return null; } var arguments = Current.CtorArguments.Select(argument => argument.Value).ToArray(); return arguments.Any() ? arguments : null; } private void AddChildToCurrentCollection() { TypeOperations.AddToCollection(Previous.Collection, Current.Instance); } public void AddCtorArgument(string stringValue) { Current.CtorArguments.Add(new ConstructionArgument(stringValue)); } public void AssociateCurrentInstanceToParent() { if (HasParentToAssociate && !Current.IsMarkupExtension) { if (Previous.CanHostChildren) { AddChildToHost(); } else { AssignChildToParentProperty(); } lifecycleListener.OnAssociatedToParent(Current.Instance); } } public void RegisterInstanceNameToNamescope() { if (InstanceProperties.Name != null) { var nameScope = FindNamescope(); nameScope?.Register(InstanceProperties.Name, Current.Instance); } InstanceProperties.Name = null; InstanceProperties.HadPreviousName = false; } public void PutNameToCurrentInstanceIfAny() { if (InstanceProperties.Name != null) { if (Current.InstanceName != null) { Current.InstanceProperties.HadPreviousName = true; } Current.InstanceName = InstanceProperties.Name; } } private INameScope FindNamescope() { if (Current.InstanceProperties.HadPreviousName) { return FindNamescopeForInstanceThatHadPreviousName(); } else { return FindNamescopeForInstanceWithNoName(); } } private INameScope FindNamescopeForInstanceWithNoName() { return FindNamescopeSkippingAncestor(0); } private INameScope FindNamescopeForInstanceThatHadPreviousName() { return FindNamescopeSkippingAncestor(1); } private INameScope FindNamescopeSkippingAncestor(int skip) { return stack.GetAncestors() .Skip(skip) .Select(level => level.XamlType?.GetNamescope(level.Instance)) .FirstOrDefault(x => x != null); } private void AddChildToHost() { if (Previous.IsDictionary) { AddChildToDictionary(); } else { AddChildToCurrentCollection(); } } private void AddChildToDictionary() { TypeOperations.AddToDictionary((IDictionary) Previous.Collection, InstanceProperties.Key, Current.Instance); ClearKey(); } private void ClearKey() { SetKey(null); } private static object GetValueTuple(object instance, MutableMember member) { var xamlMemberBase = member; return xamlMemberBase.GetValue(instance); } public void SetNameForCurrentInstance(string value) { InstanceProperties.Name = value; } public void AssociateCurrentInstanceToParentForCreation() { AssociateCurrentInstanceToParent(); Current.WasAssociatedRightAfterCreation = true; } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using SubSonic.Utilities; namespace SubSonic { /// <summary> /// This set of classes abstracts out commands and their parameters so that /// the DataProviders can work their magic regardless of the client type. The /// System.Data.Common class was supposed to do this, but sort of fell flat /// when it came to MySQL and other DB Providers that don't implement the Data /// Factory pattern. Abstracts out the assignment of parameters, etc /// </summary> public class QueryParameter { internal const ParameterDirection DefaultParameterDirection = ParameterDirection.Input; internal const int DefaultSize = 50; private ParameterDirection _mode = DefaultParameterDirection; private int _size = DefaultSize; /// <summary> /// Gets or sets the size. /// </summary> /// <value>The size.</value> public int Size { get { return _size; } set { _size = value; } } /// <summary> /// Gets or sets the mode. /// </summary> /// <value>The mode.</value> public ParameterDirection Mode { get { return _mode; } set { _mode = value; } } /// <summary> /// Gets or sets the name of the parameter. /// </summary> /// <value>The name of the parameter.</value> public string ParameterName { get; set; } /// <summary> /// Gets or sets the parameter value. /// </summary> /// <value>The parameter value.</value> public object ParameterValue { get; set; } /// <summary> /// Gets or sets the type of the data. /// </summary> /// <value>The type of the data.</value> public DbType DataType { get; set; } /// <summary> /// Gets or sets the scale. /// </summary> /// <value>The scale.</value> public int? Scale { get; set; } /// <summary> /// Gets or sets the precision. /// </summary> /// <value>The precision.</value> public int? Precision { get; set; } } /// <summary> /// Summary for the QueryParameterCollection class /// </summary> public class QueryParameterCollection : List<QueryParameter> { /// <summary> /// Checks to see if specified parameter exists in the current collection /// </summary> /// <param name="parameterName"></param> /// <returns></returns> public bool Contains(string parameterName) { foreach(QueryParameter p in this) { if(Utility.IsMatch(p.ParameterName, parameterName, true)) return true; } return false; } /// <summary> /// returns the specified QueryParameter, if it exists in this collection /// </summary> /// <param name="parameterName"></param> /// <returns></returns> public QueryParameter GetParameter(string parameterName) { foreach(QueryParameter p in this) { if(Utility.IsMatch(p.ParameterName, parameterName, true)) return p; } return null; } /// <summary> /// Adds the specified parameter name. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="value">The value.</param> public void Add(string parameterName, object value) { Add(parameterName, value, DbType.AnsiString, ParameterDirection.Input); } /// <summary> /// Adds the specified parameter name. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="value">The value.</param> /// <param name="dataType">Type of the data.</param> public void Add(string parameterName, object value, DbType dataType) { Add(parameterName, value, dataType, ParameterDirection.Input); } /// <summary> /// Adds the specified parameter name. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="value">The value.</param> /// <param name="dataType">Type of the data.</param> /// <param name="mode">The mode.</param> public void Add(string parameterName, object value, DbType dataType, ParameterDirection mode) { //remove if already added, and replace with last in if(Contains(parameterName)) Remove(GetParameter(parameterName)); QueryParameter param = new QueryParameter { ParameterName = parameterName, ParameterValue = value, DataType = dataType, Mode = mode }; Add(param); } } /// <summary> /// Summary for the QueryCommandCollection class /// </summary> public class QueryCommandCollection : List<QueryCommand> {} /// <summary> /// Summary for the QueryCommand class /// </summary> public class QueryCommand { private string _providerName = String.Empty; private int commandTimeout = 60; /// <summary> /// /// </summary> public List<object> OutputValues; private QueryParameterCollection parameters; /// <summary> /// Initializes a new instance of the <see cref="QueryCommand"/> class. /// </summary> /// <param name="sql">The SQL.</param> /// <param name="providerName">Name of the provider.</param> public QueryCommand(string sql, string providerName) { ProviderName = providerName; Provider = DataService.GetInstance(providerName); CommandSql = sql; CommandType = CommandType.Text; parameters = new QueryParameterCollection(); OutputValues = new List<object>(); } /// <summary> /// Initializes a new instance of the <see cref="QueryCommand"/> class. /// </summary> /// <param name="sql">The SQL.</param> [Obsolete("Deprecated: Use QueryCommand(string sql, string providerName) instead.")] public QueryCommand(string sql) { //use the default ProviderName = DataService.Provider.Name; Provider = DataService.Provider; CommandSql = sql; CommandType = CommandType.Text; parameters = new QueryParameterCollection(); OutputValues = new List<object>(); } /// <summary> /// Gets or sets the command timeout (in seconds). /// </summary> /// <value>The command timeout.</value> public int CommandTimeout { get { return commandTimeout; } set { commandTimeout = value; } } /// <summary> /// Gets or sets the name of the provider. /// </summary> /// <value>The name of the provider.</value> public string ProviderName { get { return _providerName; } set { _providerName = value; } } /// <summary> /// Gets or sets the provider. /// </summary> /// <value>The provider.</value> public DataProvider Provider { get; set; } /// <summary> /// Gets or sets the type of the command. /// </summary> /// <value>The type of the command.</value> public CommandType CommandType { get; set; } /// <summary> /// Gets or sets the command SQL. /// </summary> /// <value>The command SQL.</value> public string CommandSql { get; set; } /// <summary> /// Gets or sets the parameters. /// </summary> /// <value>The parameters.</value> public QueryParameterCollection Parameters { get { return parameters; } set { parameters = value; } } /// <summary> /// Determines whether [has output params]. /// </summary> /// <returns> /// <c>true</c> if [has output params]; otherwise, <c>false</c>. /// </returns> public bool HasOutputParams() { bool bOut = false; //loop the params and see if one is in/out foreach(QueryParameter param in Parameters) { if(param.Mode != ParameterDirection.Input) { bOut = true; break; } } return bOut; } /// <summary> /// Adds the parameter. The public AddParameter methods should call this one. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterValue">The parameter value.</param> /// <param name="maxSize">Size of the max.</param> /// <param name="dbType">Type of the db.</param> /// <param name="direction">The direction.</param> /// <param name="scale">The scale.</param> /// <param name="precision">The precision.</param> private void AddParameter(string parameterName, object parameterValue, int maxSize, DbType dbType, ParameterDirection direction, int? scale, int? precision) { if(parameters == null) parameters = new QueryParameterCollection(); QueryParameter param = new QueryParameter { ParameterName = CommandType == CommandType.StoredProcedure ? parameterName : Provider.FormatParameterNameForSQL(parameterName), ParameterValue = parameterValue ?? DBNull.Value, Mode = direction, DataType = dbType, Scale = scale, Precision = precision }; if(maxSize > -1 && direction != ParameterDirection.Output) param.Size = maxSize; parameters.Add(param); } /// <summary> /// Adds the parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterValue">The parameter value.</param> /// <param name="dataType">Type of the data.</param> /// <param name="parameterDirection">The parameter direction.</param> public void AddParameter(string parameterName, object parameterValue, DbType dataType, ParameterDirection parameterDirection) { AddParameter(parameterName, parameterValue, QueryParameter.DefaultSize, dataType, parameterDirection, null, null); } /// <summary> /// Adds the parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterValue">The parameter value.</param> /// <param name="dataType">Type of the data.</param> /// <param name="parameterDirection">The parameter direction.</param> /// <param name="scale">The scale.</param> /// <param name="precision">The precision.</param> public void AddParameter(string parameterName, object parameterValue, DbType dataType, ParameterDirection parameterDirection, int? scale, int? precision) { AddParameter(parameterName, parameterValue, QueryParameter.DefaultSize, dataType, parameterDirection, scale, precision); } /// <summary> /// Adds the parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterValue">The parameter value.</param> /// <param name="dataType">Type of the data.</param> public void AddParameter(string parameterName, object parameterValue, DbType dataType) { AddParameter(parameterName, parameterValue, QueryParameter.DefaultSize, dataType, QueryParameter.DefaultParameterDirection, null, null); } /// <summary> /// Adds the parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterValue">The parameter value.</param> /// <param name="dataType">Type of the data.</param> /// <param name="scale">The scale.</param> /// <param name="precision">The precision.</param> public void AddParameter(string parameterName, object parameterValue, DbType dataType, int? scale, int? precision) { AddParameter(parameterName, parameterValue, QueryParameter.DefaultSize, dataType, QueryParameter.DefaultParameterDirection, scale, precision); } /// <summary> /// Adds the output parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="maxSize">Size of the max.</param> /// <param name="dbType">Type of the db.</param> public void AddOutputParameter(string parameterName, int maxSize, DbType dbType) { AddOutputParameter(parameterName, maxSize, dbType, null, null); } /// <summary> /// Adds the output parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="maxSize">Size of the max.</param> /// <param name="dbType">Type of the db.</param> /// <param name="scale">The scale.</param> /// <param name="precision">The precision.</param> public void AddOutputParameter(string parameterName, int maxSize, DbType dbType, int? scale, int? precision) { AddParameter(parameterName, DBNull.Value, maxSize, dbType, ParameterDirection.Output, scale, precision); } /// <summary> /// Adds the output parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="maxSize">Size of the max.</param> public void AddOutputParameter(string parameterName, int maxSize) { AddOutputParameter(parameterName, maxSize, DbType.AnsiString, null, null); } /// <summary> /// Adds the output parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> public void AddOutputParameter(string parameterName) { AddOutputParameter(parameterName, -1, DbType.AnsiString, null, null); } /// <summary> /// Adds the output parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="dbType">Type of the db.</param> public void AddOutputParameter(string parameterName, DbType dbType) { AddOutputParameter(parameterName, -1, dbType, null, null); } /// <summary> /// Adds the output parameter. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="dbType">Type of the db.</param> /// <param name="scale">The scale.</param> /// <param name="precision">The precision.</param> public void AddOutputParameter(string parameterName, DbType dbType, int? scale, int? precision) { AddOutputParameter(parameterName, -1, dbType, scale, precision); } /// <summary> /// Adds a return parameter (RETURN_VALUE) to the command. /// </summary> public void AddReturnParameter() { if(Provider != null) AddParameter(String.Concat(Provider.GetParameterPrefix(), "RETURN_VALUE"), null, DbType.Int32, ParameterDirection.ReturnValue); else AddParameter("@RETURN_VALUE", null, DbType.Int32, ParameterDirection.ReturnValue); } /// <summary> /// Converts the QueryCommand to an IDbCommand. /// </summary> /// <returns></returns> public IDbCommand ToIDbCommand() { return DataService.GetIDbCommand(this); } /// <summary> /// Converts the QueryCommand to a DbCommand. /// </summary> /// <returns></returns> public DbCommand ToDbCommand() { return DataService.GetDbCommand(this); } } }
//----------------------------------------------------------------------- // <copyright file="HelpAttributeDrawer.cs" company="Google LLC"> // // Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System.Reflection; using UnityEditor; using UnityEngine; /// <summary> /// HelpAttribute drawer that draws a HelpBox below the property to display the help content. /// </summary> [CustomPropertyDrawer(typeof(HelpAttribute))] internal class HelpAttributeDrawer : PropertyDrawer { private const float k_IconOffset = 40; /// <summary> /// Override Unity GetPropertyHeight to specify how tall the GUI for this field is /// in pixels. /// </summary> /// <param name="property">The SerializedProperty to make the custom GUI for.</param> /// <param name="label">The label of this property.</param> /// <returns>The height in pixels.</returns> public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { if (_IsHelpBoxEmpty()) { return _GetOriginalPropertyHeight(property, label); } return _GetOriginalPropertyHeight(property, label) + _GetHelpAttributeHeight() + EditorStyles.helpBox.padding.vertical; } /// <summary> /// Override Unity OnGUI to make a custom GUI for the property with HelpAttribute. /// </summary> /// <param name="position">Rectangle on the screen to use for the property GUI.</param> /// <param name="property">The SerializedProperty to make the custom GUI for.</param> /// <param name="label">The label of this property.</param> public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); Rect labelPosition = position; float labelHeight = base.GetPropertyHeight(property, label); float propertyHeight = _GetOriginalPropertyHeight(property, label); labelPosition.height = labelHeight; // Draw property based on defualt Unity GUI behavior. string warningMessage = _GetIncompatibleAttributeWarning(property); if (!string.IsNullOrEmpty(warningMessage)) { var warningContent = new GUIContent(warningMessage); EditorGUI.LabelField(labelPosition, label, warningContent); } else if (_GetPropertyAttribute<TextAreaAttribute>() != null) { Rect textAreaPosition = position; textAreaPosition.y += labelHeight; textAreaPosition.height = propertyHeight - labelHeight; EditorGUI.LabelField(labelPosition, label); EditorGUI.BeginChangeCheck(); string text = EditorGUI.TextArea(textAreaPosition, property.stringValue); if (EditorGUI.EndChangeCheck()) { property.stringValue = text; } } else if (_GetPropertyAttribute<MultilineAttribute>() != null) { Rect multilinePosition = position; multilinePosition.x += EditorGUIUtility.labelWidth; multilinePosition.width -= EditorGUIUtility.labelWidth; multilinePosition.height = propertyHeight; EditorGUI.LabelField(labelPosition, label); EditorGUI.BeginChangeCheck(); string text = EditorGUI.TextArea(multilinePosition, property.stringValue); if (EditorGUI.EndChangeCheck()) { property.stringValue = text; } } else if (_GetPropertyAttribute<RangeAttribute>() != null) { var rangeAttribute = _GetPropertyAttribute<RangeAttribute>(); if (property.propertyType == SerializedPropertyType.Integer) { EditorGUI.IntSlider(labelPosition, property, (int)rangeAttribute.min, (int)rangeAttribute.max, label); } else { EditorGUI.Slider(labelPosition, property, rangeAttribute.min, rangeAttribute.max, label); } } else { EditorGUI.PropertyField(labelPosition, property); } if (!_IsHelpBoxEmpty()) { var helpBoxPosition = position; helpBoxPosition.y += propertyHeight + EditorStyles.helpBox.padding.top; helpBoxPosition.height = _GetHelpAttributeHeight(); EditorGUI.HelpBox(helpBoxPosition, _GetHelpAttribute().HelpMessage, (MessageType)_GetHelpAttribute().MessageType); } EditorGUI.EndProperty(); } private HelpAttribute _GetHelpAttribute() { return attribute as HelpAttribute; } private bool _IsHelpBoxEmpty() { return string.IsNullOrEmpty(_GetHelpAttribute().HelpMessage); } private bool _IsIconVisible() { return _GetHelpAttribute().MessageType != HelpAttribute.HelpMessageType.None; } private T _GetPropertyAttribute<T>() where T : PropertyAttribute { var attributes = fieldInfo.GetCustomAttributes(typeof(T), true); return attributes != null && attributes.Length > 0 ? (T)attributes[0] : null; } private float _GetOriginalPropertyHeight(SerializedProperty property, GUIContent label) { float labelHeight = base.GetPropertyHeight(property, label); string warningMessage = _GetIncompatibleAttributeWarning(property); if (!string.IsNullOrEmpty(warningMessage)) { return labelHeight; } // Calculate property height for TextArea attribute. // TextArea is below property label. var textAreaAttribute = _GetPropertyAttribute<TextAreaAttribute>(); if (textAreaAttribute != null) { var textAreaContent = new GUIContent(property.stringValue); var textAreaStyle = new GUIStyle(EditorStyles.textArea); var minHeight = (textAreaAttribute.minLines * textAreaStyle.lineHeight) + textAreaStyle.margin.vertical; var maxHeight = (textAreaAttribute.maxLines * textAreaStyle.lineHeight) + textAreaStyle.margin.vertical; var textAreaHeight = textAreaStyle.CalcHeight( textAreaContent, EditorGUIUtility.currentViewWidth); textAreaHeight = Mathf.Max(textAreaHeight, minHeight); textAreaHeight = Mathf.Min(textAreaHeight, maxHeight); return labelHeight + textAreaHeight; } // Calculate property height for Multiline attribute. // Multiline is on the same line of property label. var multilineAttribute = _GetPropertyAttribute<MultilineAttribute>(); if (multilineAttribute != null) { var textFieldStyle = new GUIStyle(EditorStyles.textField); var multilineHeight = (textFieldStyle.lineHeight * multilineAttribute.lines) + textFieldStyle.margin.vertical; return Mathf.Max(labelHeight, multilineHeight); } return labelHeight; } [System.Diagnostics.CodeAnalysis.SuppressMessage( "UnityRules.UnityStyleRules", "US1300:LinesMustBe100CharactersOrShorter", Justification = "Unity issue URL length > 100")] private float _GetTextAreaWidth() { // Use reflection to determine contextWidth, to workaround the following Unity issue: // https://issuetracker.unity3d.com/issues/decoratordrawers-ongui-rect-has-a-different-width-compared-to-editorguiutility-dot-currentviewwidth float contextWidth = (float)typeof(EditorGUIUtility) .GetProperty("contextWidth", BindingFlags.NonPublic | BindingFlags.Static) .GetValue(null, null); float textAreaWidth = contextWidth - EditorStyles.inspectorDefaultMargins.padding.horizontal; // In Unity 2019.1 and later context width must be further reduced by up to 4px when the inspector // window is docked inside the main editor: // - 2px border when docked inside the editor with an adjacent window to the left // - 2px border when docked inside the editor with an adjacent window to the right #if UNITY_2019_1_OR_NEWER textAreaWidth -= 4; #endif return textAreaWidth; } private float _GetHelpAttributeHeight() { float attributeHeight = 0; if (_IsHelpBoxEmpty()) { return attributeHeight; } var content = new GUIContent(_GetHelpAttribute().HelpMessage); var iconOffset = _IsIconVisible() ? k_IconOffset : 0; float textAreaWidth = _GetTextAreaWidth(); // When HelpBox icon is visble, part of the width is occupied by the icon. attributeHeight = EditorStyles.helpBox.CalcHeight(content, textAreaWidth - iconOffset); // When HelpBox icon is visble, HelpAttributeHeight should as least // be the icon offset to prevent icon shrinking. attributeHeight = Mathf.Max(attributeHeight, iconOffset); return attributeHeight; } private string _GetIncompatibleAttributeWarning(SerializedProperty property) { // Based on Unity default behavior, potential incompatible attributes have // following priorities: TextAreaAttribute > MultilineAttribute > RangeAttribute. // If higher priority exists, lower one will be ignored. if (_GetPropertyAttribute<TextAreaAttribute>() != null) { return property.propertyType == SerializedPropertyType.String ? null : "Use TextArea with string."; } if (_GetPropertyAttribute<MultilineAttribute>() != null) { return property.propertyType == SerializedPropertyType.String ? null : "Use Multiline with string."; } if (_GetPropertyAttribute<RangeAttribute>() != null) { return property.propertyType == SerializedPropertyType.Float || property.propertyType == SerializedPropertyType.Integer ? null : "Use Range with float or int."; } return null; } } }
/* File Description * Original Works/Author: Thomas Slusny * Other Contributors: None * Author Website: http://indiearmory.com * License: MIT */ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using SFML.Graphics; using SFML.Window; using CookieLib.Utils; namespace CookieLib.Graphics { /// <summary> /// An implementation of SpriteBatch using the RenderWindow. /// Warning: this spritebatch do not provides optimized drawing of sprites. /// It just provides most of functionality of XNA spritebatch. /// For optimized spritebatch with less functionality, use VertexBatch. /// </summary> public class SpriteBatch { private Sprite _sprite = new Sprite(); private Text _str = new Text(); private View _view = new View(); private RenderStates _renderState = RenderStates.Default; private bool _isDisposed; private bool _isStarted; private RenderTarget _rt; #region Helpers protected static bool IsAssetValid(Texture asset) { if (asset == null) return false; return true; } protected static bool IsAssetValid(Font asset) { if (asset == null) return false; return true; } protected static Vector2f GetScaleEffectMultiplier(SpriteEffects effects) { return new Vector2f( ((effects & SpriteEffects.FlipHorizontally) != 0) ? -1 : 1, ((effects & SpriteEffects.FlipVertically) != 0) ? -1 : 1 ); } #endregion #region Variables public BlendMode BlendMode { get { return _renderState.BlendMode; } set { _renderState.BlendMode = value; } } public bool IsDisposed { get { return _isDisposed; } } public bool IsStarted { get { return _isStarted; } } public RenderTarget RenderTarget { get { return _rt; } set { _rt = value; } } #endregion #region Constructors public SpriteBatch(RenderTarget renderTarget) { _rt = renderTarget; } public SpriteBatch() { } #endregion #region General functions public void Begin(BlendMode blendMode, Vector2f position, Vector2f size, float rotation) { _view.Reset(new FloatRect(position.X, position.Y, size.X, size.Y)); _view.Rotate(rotation); _rt.SetView(_view); _renderState.BlendMode = blendMode; _isStarted = true; } public void Begin(BlendMode blendMode) { Begin (blendMode, new Vector2f (0f, 0f), new Vector2f(_rt.Size.X, _rt.Size.Y), 0f); } public void Begin() { Begin(BlendMode.Alpha); } public void Dispose() { _isDisposed = true; } public void End() { _isStarted = false; } public void Draw(Drawable drawable, Shader shader = null) { if (drawable == null) return; _renderState.Shader = shader; _rt.Draw(drawable, _renderState); } #endregion #region Sprites public void Draw(Sprite sprite, Shader shader = null) { if (sprite == null || !IsAssetValid(sprite.Texture)) return; _renderState.Shader = shader; _rt.Draw(sprite, _renderState); } public void Draw(Texture texture, IntRect destinationRectangle, IntRect? sourceRectangle, Color color, float rotation, Vector2f origin, SpriteEffects effects = SpriteEffects.None, Shader shader = null) { if (!IsAssetValid(texture)) return; if (sourceRectangle.HasValue) { _sprite.TextureRect = sourceRectangle.Value; } else { _sprite.TextureRect = new IntRect(0, 0, (int)texture.Size.X, (int)texture.Size.Y); } var spriteTextureRect = _sprite.TextureRect; _sprite.Texture = texture; _sprite.Position = new Vector2f(destinationRectangle.Left, destinationRectangle.Top); _sprite.Color = color; _sprite.Rotation = FloatMath.ToDegrees(rotation); _sprite.Origin = origin; _sprite.Scale = new Vector2f( (destinationRectangle.Width / spriteTextureRect.Width) * GetScaleEffectMultiplier(effects).X, (destinationRectangle.Height / spriteTextureRect.Height) * GetScaleEffectMultiplier(effects).Y); _renderState.Shader = shader; _rt.Draw(_sprite, _renderState); } public void Draw(Texture texture, IntRect destinationRectangle, IntRect? sourceRectangle, Color color, Shader shader = null) { Draw(texture, destinationRectangle, sourceRectangle, color, 0f, new Vector2f(), SpriteEffects.None, shader); } public void Draw(Texture texture, IntRect destinationRectangle, Color color, Shader shader = null) { Draw(texture, destinationRectangle, null, color, 0f, new Vector2f(), SpriteEffects.None, shader); } public void Draw(Texture texture, Vector2f position, IntRect? sourceRectangle, Color color, float rotation, Vector2f origin, Vector2f scale, SpriteEffects effects = SpriteEffects.None, Shader shader = null) { if (!IsAssetValid(texture)) return; if (sourceRectangle.HasValue) { _sprite.TextureRect = (IntRect)sourceRectangle.Value; } else { _sprite.TextureRect = new IntRect(0, 0, (int)texture.Size.X, (int)texture.Size.Y); } _sprite.Texture = texture; _sprite.Position = position; _sprite.Color = color; _sprite.Rotation = FloatMath.ToDegrees(rotation); _sprite.Origin = origin; _sprite.Scale = new Vector2f ( scale.X * GetScaleEffectMultiplier (effects).X, scale.Y * GetScaleEffectMultiplier (effects).Y); _renderState.Shader = shader; _rt.Draw(_sprite, _renderState); } public void Draw(Texture texture, Vector2f position, IntRect? sourceRectangle, Color color, float rotation, Vector2f origin, float scale, SpriteEffects effects = SpriteEffects.None, Shader shader = null) { Draw(texture, position, sourceRectangle, color, rotation, origin, new Vector2f(scale, scale), effects, shader); } public void Draw(Texture texture, Vector2f position, IntRect? sourceRectangle, Color color, Shader shader = null) { Draw(texture, position, sourceRectangle, color, 0, new Vector2f(), 1.0f, SpriteEffects.None, shader); } public void Draw(Texture texture, Vector2f position, Color color, Shader shader = null) { Draw(texture, position, null, color, 0, new Vector2f(), 1.0f, SpriteEffects.None, shader); } #endregion #region Text public void DrawString(Font font, StringBuilder text, Vector2f position, Color color, float rotation, Vector2f origin, Vector2f scale, Text.Styles style = Text.Styles.Regular, Shader shader = null) { if (!IsAssetValid(font)) return; DrawString(font, text.ToString(), position, color, rotation, origin, scale, style, shader); } public void DrawString(Font font, string text, Vector2f position, Color color, float rotation, Vector2f origin, Vector2f scale, Text.Styles style = Text.Styles.Regular, Shader shader = null) { if (!IsAssetValid(font) || string.IsNullOrEmpty(text)) return; _str.Font = font; _str.DisplayedString = text; _str.Position = position; _str.Color = color; _str.Rotation = rotation; _str.Origin = origin; _str.Scale = scale; _str.Style = style; _str.CharacterSize = 12; _renderState.Shader = shader; _rt.Draw(_str, _renderState); } public void DrawString(Font font, StringBuilder text, Vector2f position, Color color, float rotation, Vector2f origin, float scale, Text.Styles style = Text.Styles.Regular, Shader shader = null) { if (!IsAssetValid(font)) return; DrawString(font, text.ToString(), position, color, rotation, origin, new Vector2f(scale, scale), style, shader); } public void DrawString(Font font, string text, Vector2f position, Color color, float rotation, Vector2f origin, float scale, Text.Styles style = Text.Styles.Regular, Shader shader = null) { if (!IsAssetValid(font)) return; DrawString(font, text, position, color, rotation, origin, new Vector2f(scale,scale), style, shader); } public void DrawString(Font font, StringBuilder text, Vector2f position, Color color) { if (!IsAssetValid(font)) return; DrawString(font, text.ToString(), position, color, 0.0f, new Vector2f(), 1.0f); } public void DrawString(Font font, string text, Vector2f position, Color color) { if (!IsAssetValid(font)) return; DrawString(font, text, position, color, 0.0f, new Vector2f(), 1.0f); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using NMahjong.Aux; using NMahjong.Base; using NMahjong.Japanese; using NMahjong.Japanese.Engine; using TA = NMahjong.Japanese.TileAnnotations; namespace NMahjong.Drivers.Mjai { using OpenMeldCreateFunc = Func<IEnumerable<CanonicalTile>, CanonicalTile, PlayerId, RevealedMeld>; internal class MjaiMessageProcessor { private readonly IEventSender mEventSender; private readonly int mBaseId; private PlayerId? mReachActor; internal MjaiMessageProcessor(IEventSender eventSender, int baseId) { mEventSender = eventSender; mBaseId = baseId; } [VisibleForTesting] internal bool IsRiichi { get { return mReachActor.HasValue; } } [VisibleForTesting] internal int Counters { get; set; } [VisibleForTesting] internal int RiichiSticks { get; set; } internal void Process(MjaiJson json) { switch (json.Type) { case "start_kyoku": ProcessStartKyoku(json); break; case "end_kyoku": ProcessEndKyoku(json); break; case "tsumo": ProcessTsumo(json); break; case "dahai": ProcessDahai(json); break; case "pon": ProcessPonChiKan(json, OpenPung.Create); break; case "chi": ProcessPonChiKan(json, OpenChow.Create); break; case "daiminkan": ProcessPonChiKan(json, OpenKong.Create); break; case "ankan": ProcessAnkan(json); break; case "kakan": ProcessKakan(json); break; case "dora": ProcessDora(json); break; case "reach": ProcessReach(json); break; case "reach_accepted": ProcessReachAccepted(json); break; case "hora": ProcessHora(json); break; case "ryukyoku": ProcessRyukyoku(json); break; default: throw new MjaiInvalidFieldException("type", json); } } private void ProcessStartKyoku(MjaiJson json) { mEventSender.OnHandStarting(new HandStartingEventArgs( Wall.Simple(), GetPlayerId(json, "oya"), json.Get<Wind>("bakaze"), json.Get<Int32>("kyoku"))); Counters = json.Get<Int32>("honba"); RiichiSticks= json.Get<Int32>("kyotaku"); mEventSender.OnSticksUpdated(new SticksUpdatedEventArgs(Counters, RiichiSticks)); var tehais = json.Get<CanonicalTile[][]>("tehais"); for (int i = 0; i < 4; i++) { IPlayerHand playerHand = (IsTehaiHidden(tehais[i])) ? PlayerHand.Hidden(tehais[i].Length) : PlayerHand.Showed(tehais[i]); mEventSender.OnPlayerHandUpdated( new PlayerHandUpdatedEventArgs(GetPlayerId(i), playerHand)); } ProcessDoraMarker(json); mEventSender.OnHandStarted(EventArgs.Empty); } private void ProcessEndKyoku(MjaiJson json) { mEventSender.OnHandEnded(EventArgs.Empty); } private void ProcessTsumo(MjaiJson json) { mEventSender.OnTileDrawn(new TileDrawnEventArgs( GetPlayerId(json, "actor"), json.Get<CanonicalTile>("pai"))); } private void ProcessDahai(MjaiJson json) { AnnotatedTile discard = json.Get<CanonicalTile>("pai") .With(IsRiichi ? TA.Riichi : TA.None) .With(json.Get<Boolean>("tsumogiri") ? TA.Drawn : TA.None); mEventSender.OnTileDiscarded( new TileDiscardedEventArgs(GetPlayerId(json, "actor"), discard)); mReachActor = null; // "reach" has now been fully processed. } private void ProcessPonChiKan(MjaiJson json, OpenMeldCreateFunc create) { RevealedMeld meld = create(json.Get<CanonicalTile[]>("consumed"), json.Get<CanonicalTile>("pai"), GetPlayerId(json, "target")); mEventSender.OnMeldRevealed( new MeldRevealedEventArgs(GetPlayerId(json, "actor"), meld)); } private void ProcessAnkan(MjaiJson json) { var kong = ConcealedKong.Create(json.Get<CanonicalTile[]>("consumed")); mEventSender.OnMeldRevealed(new MeldRevealedEventArgs( GetPlayerId(json, "actor"), kong)); } private void ProcessKakan(MjaiJson json) { mEventSender.OnMeldExtended(new MeldExtendedEventArgs( GetPlayerId(json, "actor"), json.Get<CanonicalTile>("pai"))); } private void ProcessDora(MjaiJson json) { ProcessDoraMarker(json); } private void ProcessReach(MjaiJson json) { mEventSender.OnRiichiDeclared(new RiichiEventArgs(GetPlayerId(json, "actor"))); mReachActor = GetPlayerId(json, "actor"); } private void ProcessReachAccepted(MjaiJson json) { ProcessScores(json); ++RiichiSticks; mEventSender.OnSticksUpdated(new SticksUpdatedEventArgs(Counters, RiichiSticks)); mEventSender.OnRiichiAccepted(new RiichiEventArgs(GetPlayerId(json, "actor"))); } private void ProcessHora(MjaiJson json) { PlayerId winner = GetPlayerId(json, "actor"); PlayerId feeder = GetPlayerId(json, "target"); WinningInfo winningInfo = new WinningInfo.Builder() .SetWinner(winner).SetFeeder(feeder) .SetFan(json.Get<Int32>("fan")) .SetMinipoints(json.Get<Int32>("fu")) .SetPoints(json.Get<Int32>("hora_points")).Build(); mEventSender.OnWinningDeclared(new WinningDeclaredEventArgs( winningInfo, json.Get<CanonicalTile[]>("uradora_markers").Select(Dora.Next))); Winning winning = (winner == feeder) ? Winning.SelfDraw : Winning.Discard; var tiles = json.Get<List<CanonicalTile>>("hora_tehais"); if (winning == Winning.Discard) { tiles.Add(json.Get<CanonicalTile>("pai")); } mEventSender.OnPlayerHandUpdated( new PlayerHandUpdatedEventArgs(winner, PlayerHand.Winning(tiles, winning))); ProcessScores(json); } private void ProcessRyukyoku(MjaiJson json) { mEventSender.OnHandDrawn(new HandDrawnEventArgs(json.Get<DrawHand>("reason"))); var tehais = json.Get<CanonicalTile[][]>("tehais"); for (int i = 0; i < 4; i++) { if (IsTehaiHidden(tehais[i])) { continue; } mEventSender.OnPlayerHandUpdated( new PlayerHandUpdatedEventArgs(GetPlayerId(i), PlayerHand.Waiting(tehais[i]))); } ProcessScores(json); } private void ProcessDoraMarker(MjaiJson json) { mEventSender.OnDoraAdded( new DoraAddedEventArgs(Dora.Next(json.Get<CanonicalTile>("dora_marker")))); } private void ProcessScores(MjaiJson json) { int[] scores = json.Get<Int32[]>("scores"); int[] deltas = json.Get<Int32[]>("deltas"); for (int i = 0; i < 4; i++) { if (deltas[i] == 0) { continue; } mEventSender.OnScoreUpdated( new ScoreUpdatedEventArgs(GetPlayerId(i), scores[i], deltas[i])); } } private PlayerId GetPlayerId(int mjaiId) { return new PlayerId((mjaiId - mBaseId + 4) % 4); } private PlayerId GetPlayerId(MjaiJson json, string field) { return new PlayerId((json.Get<Int32>(field) - mBaseId + 4) % 4); } private static bool IsTehaiHidden(IEnumerable<CanonicalTile> tehai) { if (tehai.All(tile => tile == null)) { return true; } if (tehai.All(tile => tile != null)) { return false; } throw new ArgumentException( "Tiles must be either all showed or all hidden.", "tehai"); } } }
using System; using System.Text; using System.Collections.Generic; using System.Linq; using Antlr4.Runtime.Misc; using IFC4.Generators; namespace Express { /// <summary> /// TypeReference stores information about a reference to a type. /// </summary> public class TypeReference { protected ILanguageGenerator generator; /// <summary> /// Name will be a type name or a path. /// </summary> /// <returns></returns> public TypeReference(ILanguageGenerator generator, string type, bool isCollection, int rank, bool isGeneric) { this.generator = generator; this.IsCollection = isCollection; this.Rank = rank; this.IsGeneric = isGeneric; this.type = type; } internal string type; /// <summary> /// The name of the Type that is referenced. /// </summary> /// <returns></returns> public string Type { get { return generator.AttributeDataType(IsCollection, Rank, type, IsGeneric); } } /// <summary> /// Is this attribute a collection type such as ARRAY, SET, LIST, or BAG? /// </summary> /// <returns></returns> public bool IsCollection { get; } /// <summary> /// The dimension of the collection type. Ex: Rank=2 => List<List<T>> /// </summary> /// <returns></returns> public int Rank { get; } public bool IsGeneric { get; } } /// <summary> /// ParameterData stores the name and type information for a parameter. /// </summary> public class ParameterData : TypeReference { public string Name { get; protected set;} /// <summary> /// A string representing the parameter corresponding to an attribute's info. /// </summary> /// <returns></returns> public string ParameterName { get { var name = Name; if (name == "Operator") { name = "op"; } return Char.ToLowerInvariant(name[0]) + name.Substring(1); } } public ParameterData(ILanguageGenerator generator, string name, bool isCollection, int rank, bool isGeneric, string type) : base(generator, type, isCollection, rank, isGeneric) { this.Name = name; } } /// <summary> /// AttributeData stores information about type attributes. /// </summary> public class AttributeData : ParameterData { /// <summary> /// Is this attribute INVERSE? /// </summary> /// <returns></returns> public bool IsInverse { get; } /// <summary> /// Is this attribute DERIVED? /// </summary> /// <returns></returns> public bool IsDerived { get; } /// <summary> /// Does this attribute hide a parent's attribute by /// the same name? /// </summary> /// <returns></returns> public bool HidesParentAttributeOfSameName{get;} /// <summary> /// Is this attribute marked as OPTIONAL? /// </summary> /// <returns></returns> public bool IsOptional { get; } public AttributeData(ILanguageGenerator generator, string name, string type, int rank, bool isCollection, bool isGeneric, bool isDerived = false, bool isOptional = false, bool isInverse = false) : base(generator, name, isCollection, rank, isGeneric, type) { this.IsDerived = isDerived; this.IsOptional = isOptional; this.IsInverse = isInverse; // A derived attribute which replaces a base class's version of // the attribute will have a name that is a path to the // parent class' attribute of the form SELF\IfcNamedUnit.Dimensions. if(isDerived && Name.Contains("SELF\\")) { HidesParentAttributeOfSameName = true; Name = Name.Split('.').Last(); } } public override string ToString() { return generator.AttributeDataString(this); } public string ToStepString(bool isDerivedInChild) { return generator.AttributeStepString(this, isDerivedInChild); } } /// <summary> /// FunctionData stores information about functions. /// </summary> public class FunctionData { public string Name { get; set; } public List<ParameterData> Parameters { get; } public TypeReference ReturnType { get; } public FunctionData(string name, TypeReference returnType, List<ParameterData> parameterData) { this.Name = name; this.Parameters = parameterData; this.ReturnType = returnType; } } /// <summary> /// A TypeData object stores data about IFC types. /// </summary> public abstract class TypeData { public string Name { get; set; } protected ILanguageGenerator generator; public TypeData(string name, ILanguageGenerator generator) { this.generator = generator; Name = name; } } /// <summary> /// Base class for types which store a collection of values such as IFC SELECT and ENUM types. /// </summary> public abstract class CollectionTypeData : TypeData { /// <summary> /// For a TypeData which wraps a Select or an Enum, the Values /// collection will contain the items that are enumerated or selected. /// </summary> /// <returns></returns> public IEnumerable<string> Values { get; } public CollectionTypeData(string name, ILanguageGenerator generator, IEnumerable<string> values) : base(name, generator) { this.Values = values; } } /// <summary> /// A WrapperType object stores data about IFC TYPEs. /// </summary> public class WrapperType : TypeData { public bool IsCollectionType { get; } /// <summary> /// For a TypeData which wraps a collection, the rank is the depth of /// the collection. Ex: A collection with Rank=1 will be a List<List<object>>. /// </summary> /// <returns></returns> public int Rank { get; } /// <summary> /// In the case of a simple type, the WrappedType /// will be the name of type which is wrapped in an IfcType. /// </summary> /// <returns></returns> public string WrappedType{get;} public WrapperType(string name, string wrappedType, ILanguageGenerator generator, bool isCollectionType, int rank) : base(name, generator) { this.IsCollectionType = isCollectionType; this.Rank = rank; this.WrappedType = wrappedType; } public override string ToString() { return generator.SimpleTypeString(this); } } /// <summary> /// A CollectionTypeData object stores information about IFC ENUM types. /// </summary> public class EnumType : CollectionTypeData { public EnumType(string name, ILanguageGenerator generator, IEnumerable<string> values) : base(name, generator, values) { } public override string ToString() { return generator.EnumTypeString(this); } } /// <summary> /// A SelectType object stores information about IFC SELECT types. /// </summary> public class SelectType : CollectionTypeData { public SelectType(string name, ILanguageGenerator generator, IEnumerable<string> values) : base(name, generator, values) { } public override string ToString() { return generator.SelectTypeString(this); } } /// <summary> /// An Entity object stores information about IFC ENTITY types. /// </summary> public class Entity : TypeData { public List<Entity> Supers { get; set; } public List<Entity> Subs { get; set; } public List<AttributeData> Attributes { get; set; } public bool IsAbstract { get; set; } public Entity(string name, ILanguageGenerator generator) : base(name, generator) { Name = name; Supers = new List<Entity>(); Subs = new List<Entity>(); Attributes = new List<AttributeData>(); } /// <summary> /// Return all parents to this type all the way to the root. /// </summary> /// <returns></returns> internal IEnumerable<Entity> Parents() { var parents = new List<Entity>(); parents.AddRange(Subs); foreach (var s in Subs) { parents.AddRange(s.Parents()); } return parents; } internal IEnumerable<Entity> ParentsAndSelf() { var parents = new List<Entity>(); parents.Add(this); parents.AddRange(Subs); foreach (var s in Subs) { parents.AddRange(s.Parents()); } return parents; } /// <summary> /// Determine whether this is the provided type or a sub-type of the provided type. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public bool IsTypeOrSubtypeOfEntity(string typeName) { if (this.Name == typeName) { return true; } foreach (var s in Subs) { var found = s.IsTypeOrSubtypeOfEntity(typeName); if (found) { return true; } } return false; } public string Properties(Dictionary<string, SelectType> selectData) { var attrs = Attributes; if (!attrs.Any()) { return string.Empty; } var propBuilder = new StringBuilder(); foreach (var a in attrs) { var prop = a.ToString(); if (!string.IsNullOrEmpty(prop)) { propBuilder.AppendLine(prop); } } return propBuilder.ToString(); } public string StepProperties() { // Build a set of step properties for all parent classes and this class. var attrs = this.ParentsAndSelf(). Reverse(). SelectMany(t=>t.Attributes). Where(a => !a.IsInverse && !a.IsDerived); var derAttrs = this.ParentsAndSelf(). Reverse(). SelectMany(t=>t.Attributes). Where(a=>!a.IsInverse && a.IsDerived && a.HidesParentAttributeOfSameName); if (!attrs.Any()) { return string.Empty; } var propBuilder = new StringBuilder(); foreach (var a in attrs) { // Attributes which are hidden by a derived attribute // of the same name in a child need to be written to // STEP as *. var isDerivedInChild = false; if(derAttrs.Any(d=>d.Name == a.Name)) { isDerivedInChild = true; } var prop = a.ToStepString(isDerivedInChild); if (!string.IsNullOrEmpty(prop)) { propBuilder.AppendLine(prop); } } return propBuilder.ToString(); } public override string ToString() { return generator.EntityString(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Tests { public static class BitArray_GetSetTests { private const int BitsPerByte = 8; private const int BitsPerInt32 = 32; public static IEnumerable<object[]> Get_Set_Data() { foreach (int size in new[] { 0, 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 }) { foreach (bool def in new[] { true, false }) { yield return new object[] { def, Enumerable.Repeat(true, size).ToArray() }; yield return new object[] { def, Enumerable.Repeat(false, size).ToArray() }; yield return new object[] { def, Enumerable.Range(0, size).Select(i => i % 2 == 1).ToArray() }; } } } [Theory] [MemberData(nameof(Get_Set_Data))] public static void Get_Set(bool def, bool[] newValues) { BitArray bitArray = new BitArray(newValues.Length, def); for (int i = 0; i < newValues.Length; i++) { bitArray.Set(i, newValues[i]); Assert.Equal(newValues[i], bitArray[i]); Assert.Equal(newValues[i], bitArray.Get(i)); } } [Fact] public static void Get_InvalidIndex_ThrowsArgumentOutOfRangeException() { BitArray bitArray = new BitArray(4); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Get(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Get(bitArray.Length)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[bitArray.Length]); } [Fact] public static void Set_InvalidIndex_ThrowsArgumentOutOfRangeException() { BitArray bitArray = new BitArray(4); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Set(-1, true)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Set(bitArray.Length, true)); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[-1] = true); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[bitArray.Length] = true); } [Theory] [InlineData(0, true)] [InlineData(0, false)] [InlineData(1, true)] [InlineData(1, false)] [InlineData(BitsPerByte, true)] [InlineData(BitsPerByte, false)] [InlineData(BitsPerByte + 1, true)] [InlineData(BitsPerByte + 1, false)] [InlineData(BitsPerInt32, true)] [InlineData(BitsPerInt32, false)] [InlineData(BitsPerInt32 + 1, true)] [InlineData(BitsPerInt32 + 1, false)] public static void SetAll(int size, bool defaultValue) { BitArray bitArray = new BitArray(size, defaultValue); bitArray.SetAll(!defaultValue); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(!defaultValue, bitArray[i]); Assert.Equal(!defaultValue, bitArray.Get(i)); } bitArray.SetAll(defaultValue); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(defaultValue, bitArray[i]); Assert.Equal(defaultValue, bitArray.Get(i)); } } public static IEnumerable<object[]> GetEnumerator_Data() { foreach (int size in new[] { 0, 1, BitsPerByte, BitsPerByte + 1, BitsPerInt32, BitsPerInt32 + 1 }) { foreach (bool lead in new[] { true, false }) { yield return new object[] { Enumerable.Range(0, size).Select(i => lead ^ (i % 2 == 0)).ToArray() }; } } } [Theory] [MemberData(nameof(GetEnumerator_Data))] public static void GetEnumerator(bool[] values) { BitArray bitArray = new BitArray(values); Assert.NotSame(bitArray.GetEnumerator(), bitArray.GetEnumerator()); IEnumerator enumerator = bitArray.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(bitArray[counter], enumerator.Current); counter++; } Assert.Equal(bitArray.Length, counter); enumerator.Reset(); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(BitsPerByte)] [InlineData(BitsPerByte + 1)] [InlineData(BitsPerInt32)] [InlineData(BitsPerInt32 + 1)] public static void GetEnumerator_Invalid(int size) { BitArray bitArray = new BitArray(size, true); IEnumerator enumerator = bitArray.GetEnumerator(); // Has not started enumerating Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Has finished enumerating while (enumerator.MoveNext()) ; Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Has resetted enumerating enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Has modified underlying collection if (size > 0) { enumerator.MoveNext(); bitArray[0] = false; Assert.True((bool)enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } } public static IEnumerable<object[]> Length_Set_Data() { int[] sizes = { 1, BitsPerByte, BitsPerByte + 1, BitsPerInt32, BitsPerInt32 + 1 }; foreach (int original in sizes.Concat(new[] { 16384 })) { foreach (int n in sizes) { yield return new object[] { original, n }; } } } [Theory] [MemberData(nameof(Length_Set_Data))] public static void Length_Set(int originalSize, int newSize) { BitArray bitArray = new BitArray(originalSize, true); bitArray.Length = newSize; Assert.Equal(newSize, bitArray.Length); for (int i = 0; i < Math.Min(originalSize, bitArray.Length); i++) { Assert.True(bitArray[i]); Assert.True(bitArray.Get(i)); } for (int i = originalSize; i < newSize; i++) { Assert.False(bitArray[i]); Assert.False(bitArray.Get(i)); } Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray[newSize]); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.Get(newSize)); // Decrease then increase size bitArray.Length = 0; Assert.Equal(0, bitArray.Length); bitArray.Length = newSize; Assert.Equal(newSize, bitArray.Length); Assert.False(bitArray.Get(0)); Assert.False(bitArray.Get(newSize - 1)); } [Fact] public static void Length_Set_InvalidLength_ThrowsArgumentOutOfRangeException() { BitArray bitArray = new BitArray(1); Assert.Throws<ArgumentOutOfRangeException>(() => bitArray.Length = -1); } public static IEnumerable<object[]> CopyTo_Array_TestData() { yield return new object[] { new BitArray(0), 0, 0, new bool[0], default(bool) }; yield return new object[] { new BitArray(0), 0, 0, new byte[0], default(byte) }; yield return new object[] { new BitArray(0), 0, 0, new int[0], default(int) }; foreach (int bitArraySize in new[] { 0, 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 }) { BitArray allTrue = new BitArray(Enumerable.Repeat(true, bitArraySize).ToArray()); BitArray allFalse = new BitArray(Enumerable.Repeat(false, bitArraySize).ToArray()); BitArray alternating = new BitArray(Enumerable.Range(0, bitArraySize).Select(i => i % 2 == 1).ToArray()); foreach (var d in new[] { Tuple.Create(bitArraySize, 0), Tuple.Create(bitArraySize * 2 + 1, 0), Tuple.Create(bitArraySize * 2 + 1, bitArraySize + 1), Tuple.Create(bitArraySize * 2 + 1, bitArraySize / 2 + 1) }) { int arraySize = d.Item1; int index = d.Item2; yield return new object[] { allTrue, arraySize, index, Enumerable.Repeat(true, bitArraySize).ToArray(), default(bool) }; yield return new object[] { allFalse, arraySize, index, Enumerable.Repeat(false, bitArraySize).ToArray(), default(bool) }; yield return new object[] { alternating, arraySize, index, Enumerable.Range(0, bitArraySize).Select(i => i % 2 == 1).ToArray(), default(bool) }; if (bitArraySize >= BitsPerByte) { yield return new object[] { allTrue, arraySize / BitsPerByte, index / BitsPerByte, Enumerable.Repeat((byte)0xff, bitArraySize / BitsPerByte).ToArray(), default(byte) }; yield return new object[] { allFalse, arraySize / BitsPerByte, index / BitsPerByte, Enumerable.Repeat((byte)0x00, bitArraySize / BitsPerByte).ToArray(), default(byte) }; yield return new object[] { alternating, arraySize / BitsPerByte, index / BitsPerByte, Enumerable.Repeat((byte)0xaa, bitArraySize / BitsPerByte).ToArray(), default(byte) }; } if (bitArraySize >= BitsPerInt32) { yield return new object[] { allTrue, arraySize / BitsPerInt32, index / BitsPerInt32, Enumerable.Repeat(unchecked((int)0xffffffff), bitArraySize / BitsPerInt32).ToArray(), default(int) }; yield return new object[] { allFalse, arraySize / BitsPerInt32, index / BitsPerInt32, Enumerable.Repeat(0x00000000, bitArraySize / BitsPerInt32).ToArray(), default(int) }; yield return new object[] { alternating, arraySize / BitsPerInt32, index / BitsPerInt32, Enumerable.Repeat(unchecked((int)0xaaaaaaaa), bitArraySize / BitsPerInt32).ToArray(), default(int) }; } } } } [Theory] [MemberData(nameof(CopyTo_Array_TestData))] public static void CopyTo<T>(BitArray bitArray, int length, int index, T[] expected, T def) { T[] array = (T[])Array.CreateInstance(typeof(T), length); ICollection collection = bitArray; collection.CopyTo(array, index); for (int i = 0; i < index; i++) { Assert.Equal(def, array[i]); } for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], array[i + index]); } for (int i = index + expected.Length; i < array.Length; i++) { Assert.Equal(def, array[i]); } } [Fact] public static void CopyTo_Type_Invalid() { ICollection bitArray = new BitArray(10); Assert.Throws<ArgumentNullException>("array", () => bitArray.CopyTo(null, 0)); Assert.Throws<ArgumentException>(() => bitArray.CopyTo(new long[10], 0)); Assert.Throws<ArgumentException>(() => bitArray.CopyTo(new int[10, 10], 0)); } [Theory] [InlineData(default(bool), 1, 0, 0)] [InlineData(default(bool), 1, 1, 1)] [InlineData(default(bool), BitsPerByte, BitsPerByte - 1, 0)] [InlineData(default(bool), BitsPerByte, BitsPerByte, 1)] [InlineData(default(bool), BitsPerInt32, BitsPerInt32 - 1, 0)] [InlineData(default(bool), BitsPerInt32, BitsPerInt32, 1)] [InlineData(default(byte), BitsPerByte, 0, 0)] [InlineData(default(byte), BitsPerByte, 1, 1)] [InlineData(default(byte), BitsPerByte * 4, 4 - 1, 0)] [InlineData(default(byte), BitsPerByte * 4, 4, 1)] [InlineData(default(int), BitsPerInt32, 0, 0)] [InlineData(default(int), BitsPerInt32, 1, 1)] [InlineData(default(int), BitsPerInt32 * 4, 4 - 1, 0)] [InlineData(default(int), BitsPerInt32 * 4, 4, 1)] public static void CopyTo_Size_Invalid<T>(T def, int bits, int arraySize, int index) { ICollection bitArray = new BitArray(bits); T[] array = (T[])Array.CreateInstance(typeof(T), arraySize); Assert.Throws<ArgumentOutOfRangeException>("index", () => bitArray.CopyTo(array, -1)); Assert.Throws<ArgumentException>(def is int ? string.Empty : null, () => bitArray.CopyTo(array, index)); } [Fact] public static void SyncRoot() { ICollection bitArray = new BitArray(10); Assert.Same(bitArray.SyncRoot, bitArray.SyncRoot); Assert.NotSame(bitArray.SyncRoot, ((ICollection)new BitArray(10)).SyncRoot); } } }
using System; using System.Collections; using System.IO; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Xml; using Umbraco.Core.Logging; using umbraco.BasePages; using umbraco.BusinessLogic; using umbraco.cms.businesslogic.media; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.presentation.channels.businesslogic; using umbraco.uicontrols; using umbraco.providers; using umbraco.cms.presentation.Trees; using umbraco.IO; using Umbraco.Core; namespace umbraco.cms.presentation.user { /// <summary> /// Summary description for EditUser. /// </summary> public partial class EditUser : UmbracoEnsuredPage { public EditUser() { CurrentApp = BusinessLogic.DefaultApps.users.ToString(); } protected HtmlTable macroProperties; protected TextBox uname = new TextBox(); protected TextBox lname = new TextBox(); protected PlaceHolder passw = new PlaceHolder(); protected CheckBoxList lapps = new CheckBoxList(); protected TextBox email = new TextBox(); protected DropDownList userType = new DropDownList(); protected DropDownList userLanguage = new DropDownList(); protected CheckBox NoConsole = new CheckBox(); protected CheckBox Disabled = new CheckBox(); protected CheckBox DefaultToLiveEditing = new CheckBox(); protected controls.ContentPicker mediaPicker = new umbraco.controls.ContentPicker(); protected controls.ContentPicker contentPicker = new umbraco.controls.ContentPicker(); protected TextBox cName = new TextBox(); protected CheckBox cFulltree = new CheckBox(); protected DropDownList cDocumentType = new DropDownList(); protected DropDownList cDescription = new DropDownList(); protected DropDownList cCategories = new DropDownList(); protected DropDownList cExcerpt = new DropDownList(); protected controls.ContentPicker cMediaPicker = new umbraco.controls.ContentPicker(); protected controls.ContentPicker cContentPicker = new umbraco.controls.ContentPicker(); protected CustomValidator sectionValidator = new CustomValidator(); protected Pane pp = new Pane(); private User u; protected void Page_Load(object sender, EventArgs e) { int UID = int.Parse(Request.QueryString["id"]); u = BusinessLogic.User.GetUser(UID); // do initial check for edit rights if (u.Id == 0 && CurrentUser.Id != 0) { throw new Exception("Only the root user can edit the 'root' user (id:0)"); } else if (u.IsAdmin() && !CurrentUser.IsAdmin()) { throw new Exception("Admin users can only be edited by admins"); } // check if canvas editing is enabled DefaultToLiveEditing.Visible = UmbracoSettings.EnableCanvasEditing; // Populate usertype list foreach (UserType ut in UserType.getAll) { if (CurrentUser.IsAdmin() || ut.Alias != "admin") { ListItem li = new ListItem(ui.Text("user", ut.Name.ToLower(), base.getUser()), ut.Id.ToString()); if (ut.Id == u.UserType.Id) li.Selected = true; userType.Items.Add(li); } } // Populate ui language lsit foreach ( string f in Directory.GetFiles(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang"), "*.xml") ) { XmlDocument x = new XmlDocument(); x.Load(f); ListItem li = new ListItem(x.DocumentElement.Attributes.GetNamedItem("intName").Value, x.DocumentElement.Attributes.GetNamedItem("alias").Value); if (x.DocumentElement.Attributes.GetNamedItem("alias").Value == u.Language) li.Selected = true; userLanguage.Items.Add(li); } // Console access and disabling NoConsole.Checked = u.NoConsole; Disabled.Checked = u.Disabled; DefaultToLiveEditing.Checked = u.DefaultToLiveEditing; PlaceHolder medias = new PlaceHolder(); mediaPicker.AppAlias = Constants.Applications.Media; mediaPicker.TreeAlias = "media"; if (u.StartMediaId > 0) mediaPicker.Value = u.StartMediaId.ToString(); else mediaPicker.Value = "-1"; medias.Controls.Add(mediaPicker); PlaceHolder content = new PlaceHolder(); contentPicker.AppAlias = Constants.Applications.Content; contentPicker.TreeAlias = "content"; if (u.StartNodeId > 0) contentPicker.Value = u.StartNodeId.ToString(); else contentPicker.Value = "-1"; content.Controls.Add(contentPicker); // Add password changer passw.Controls.Add(new UserControl().LoadControl(SystemDirectories.Umbraco + "/controls/passwordChanger.ascx")); pp.addProperty(ui.Text("user", "username", base.getUser()), uname); pp.addProperty(ui.Text("user", "loginname", base.getUser()), lname); pp.addProperty(ui.Text("user", "password", base.getUser()), passw); pp.addProperty(ui.Text("email", base.getUser()), email); pp.addProperty(ui.Text("user", "usertype", base.getUser()), userType); pp.addProperty(ui.Text("user", "language", base.getUser()), userLanguage); //Media / content root nodes Pane ppNodes = new Pane(); ppNodes.addProperty(ui.Text("user", "startnode", base.getUser()), content); ppNodes.addProperty(ui.Text("user", "mediastartnode", base.getUser()), medias); //Generel umrbaco access Pane ppAccess = new Pane(); if (UmbracoSettings.EnableCanvasEditing) { ppAccess.addProperty(ui.Text("user", "defaultToLiveEditing", base.getUser()), DefaultToLiveEditing); } ppAccess.addProperty(ui.Text("user", "noConsole", base.getUser()), NoConsole); ppAccess.addProperty(ui.Text("user", "disabled", base.getUser()), Disabled); //access to which modules... Pane ppModules = new Pane(); ppModules.addProperty(ui.Text("user", "modules", base.getUser()), lapps); ppModules.addProperty(" ", sectionValidator); TabPage userInfo = UserTabs.NewTabPage(u.Name); userInfo.Controls.Add(pp); userInfo.Controls.Add(ppNodes); userInfo.Controls.Add(ppAccess); userInfo.Controls.Add(ppModules); userInfo.Style.Add("text-align", "center"); userInfo.HasMenu = true; ImageButton save = userInfo.Menu.NewImageButton(); save.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif"; save.Click += new ImageClickEventHandler(saveUser_Click); sectionValidator.ServerValidate += new ServerValidateEventHandler(sectionValidator_ServerValidate); sectionValidator.ControlToValidate = lapps.ID; sectionValidator.ErrorMessage = ui.Text("errorHandling", "errorMandatoryWithoutTab", ui.Text("user", "modules", base.getUser()), base.getUser()); sectionValidator.CssClass = "error"; setupForm(); setupChannel(); ClientTools .SetActiveTreeType(TreeDefinitionCollection.Instance.FindTree<loadUsers>().Tree.Alias) .SyncTree(UID.ToString(), IsPostBack); } void sectionValidator_ServerValidate(object source, ServerValidateEventArgs args) { args.IsValid = false; if (lapps.SelectedIndex >= 0) args.IsValid = true; } private void setupChannel() { Channel userChannel; try { userChannel = new Channel(u.Id); } catch { userChannel = new Channel(); } // Populate dropdowns foreach (DocumentType dt in DocumentType.GetAllAsList()) cDocumentType.Items.Add( new ListItem(dt.Text, dt.Alias) ); // populate fields ArrayList fields = new ArrayList(); cDescription.ID = "cDescription"; cCategories.ID = "cCategories"; cExcerpt.ID = "cExcerpt"; cDescription.Items.Add(new ListItem(ui.Text("choose"), "")); cCategories.Items.Add(new ListItem(ui.Text("choose"), "")); cExcerpt.Items.Add(new ListItem(ui.Text("choose"), "")); foreach (PropertyType pt in PropertyType.GetAll()) { if (!fields.Contains(pt.Alias)) { cDescription.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias)); cCategories.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias)); cExcerpt.Items.Add(new ListItem(string.Format("{0} ({1})", pt.Name, pt.Alias), pt.Alias)); fields.Add(pt.Alias); } } // Handle content and media pickers PlaceHolder medias = new PlaceHolder(); cMediaPicker.AppAlias = Constants.Applications.Media; cMediaPicker.TreeAlias = "media"; if (userChannel.MediaFolder > 0) cMediaPicker.Value = userChannel.MediaFolder.ToString(); else cMediaPicker.Value = "-1"; medias.Controls.Add(cMediaPicker); PlaceHolder content = new PlaceHolder(); cContentPicker.AppAlias = Constants.Applications.Content; cContentPicker.TreeAlias = "content"; if (userChannel.StartNode > 0) cContentPicker.Value = userChannel.StartNode.ToString(); else cContentPicker.Value = "-1"; content.Controls.Add(cContentPicker); // Setup the panes Pane ppInfo = new Pane(); ppInfo.addProperty(ui.Text("name", base.getUser()), cName); ppInfo.addProperty(ui.Text("user", "startnode", base.getUser()), content); ppInfo.addProperty(ui.Text("user", "searchAllChildren", base.getUser()), cFulltree); ppInfo.addProperty(ui.Text("user", "mediastartnode", base.getUser()), medias); Pane ppFields = new Pane(); ppFields.addProperty(ui.Text("user", "documentType", base.getUser()), cDocumentType); ppFields.addProperty(ui.Text("user", "descriptionField", base.getUser()), cDescription); ppFields.addProperty(ui.Text("user", "categoryField", base.getUser()), cCategories); ppFields.addProperty(ui.Text("user", "excerptField", base.getUser()), cExcerpt); TabPage channelInfo = UserTabs.NewTabPage(ui.Text("user", "contentChannel", base.getUser())); channelInfo.Controls.Add(ppInfo); channelInfo.Controls.Add(ppFields); channelInfo.HasMenu = true; ImageButton save = channelInfo.Menu.NewImageButton(); save.ImageUrl = SystemDirectories.Umbraco + "/images/editor/save.gif"; save.Click += new ImageClickEventHandler(saveUser_Click); save.ID = "save"; if (!IsPostBack) { cName.Text = userChannel.Name; cDescription.SelectedValue = userChannel.FieldDescriptionAlias; cCategories.SelectedValue = userChannel.FieldCategoriesAlias; cExcerpt.SelectedValue = userChannel.FieldExcerptAlias; cDocumentType.SelectedValue = userChannel.DocumentTypeAlias; cFulltree.Checked = userChannel.FullTree; } } /// <summary> /// Setups the form. /// </summary> private void setupForm() { if (!IsPostBack) { MembershipUser user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(u.LoginName, true); uname.Text = u.Name; lname.Text = (user == null) ? u.LoginName : user.UserName; email.Text = (user == null) ? u.Email : user.Email; // Prevent users from changing information if logged in through active directory membership provider // active directory-mapped accounts have empty passwords by default... so set update user fields to read only // this will not be a security issue because empty passwords are not allowed in membership provider. // This might change in version 4.0 if (string.IsNullOrEmpty(u.GetPassword())) { uname.ReadOnly = true; lname.ReadOnly = true; email.ReadOnly = true; passw.Visible = false; } contentPicker.Value = u.StartNodeId.ToString(); mediaPicker.Value = u.StartMediaId.ToString(); // get the current users applications string currentUserApps = ";"; foreach (Application a in CurrentUser.Applications) currentUserApps += a.alias + ";"; Application[] uapps = u.Applications; foreach (Application app in BusinessLogic.Application.getAll()) { if (CurrentUser.IsRoot() || currentUserApps.Contains(";" + app.alias + ";")) { ListItem li = new ListItem(ui.Text("sections", app.alias), app.alias); if (!IsPostBack) foreach (Application tmp in uapps) if (app.alias == tmp.alias) li.Selected = true; lapps.Items.Add(li); } } } } protected override void OnInit(EventArgs e) { //lapps.SelectionMode = ListSelectionMode.Multiple; lapps.RepeatLayout = RepeatLayout.Flow; lapps.RepeatDirection = RepeatDirection.Vertical; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/CMSNode.asmx")); // ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/legacyAjaxCalls.asmx")); } /// <summary> /// Handles the Click event of the saveUser control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Web.UI.ImageClickEventArgs"/> instance containing the event data.</param> private void saveUser_Click(object sender, ImageClickEventArgs e) { if (base.IsValid) { try { MembershipUser user = Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].GetUser(u.LoginName, true); string tempPassword = ((controls.passwordChanger)passw.Controls[0]).Password; if (!string.IsNullOrEmpty(tempPassword.Trim())) { // make sure password is not empty if (string.IsNullOrEmpty(u.Password)) u.Password = "default"; user.ChangePassword(u.Password, tempPassword); } // Is it using the default membership provider if (Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is UsersMembershipProvider) { // Save user in membership provider UsersMembershipUser umbracoUser = user as UsersMembershipUser; umbracoUser.FullName = uname.Text.Trim(); umbracoUser.Language = userLanguage.SelectedValue; umbracoUser.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue)); Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(umbracoUser); // Save user details u.Email = email.Text.Trim(); u.Language = userLanguage.SelectedValue; } else { u.Name = uname.Text.Trim(); u.Language = userLanguage.SelectedValue; u.UserType = UserType.GetUserType(int.Parse(userType.SelectedValue)); if (!(Membership.Providers[UmbracoSettings.DefaultBackofficeProvider] is ActiveDirectoryMembershipProvider)) Membership.Providers[UmbracoSettings.DefaultBackofficeProvider].UpdateUser(user); } u.LoginName = lname.Text; //u.StartNodeId = int.Parse(startNode.Value); int startNode; if (!int.TryParse(contentPicker.Value, out startNode)) { //set to default if nothing is choosen if (u.StartNodeId > 0) startNode = u.StartNodeId; else startNode = -1; } u.StartNodeId = startNode; u.Disabled = Disabled.Checked; u.DefaultToLiveEditing = DefaultToLiveEditing.Checked; u.NoConsole = NoConsole.Checked; //u.StartMediaId = int.Parse(mediaStartNode.Value); int mstartNode; if (!int.TryParse(mediaPicker.Value, out mstartNode)) { //set to default if nothing is choosen if (u.StartMediaId > 0) mstartNode = u.StartMediaId; else mstartNode = -1; } u.StartMediaId = mstartNode; u.clearApplications(); foreach (ListItem li in lapps.Items) { if (li.Selected) u.addApplication(li.Value); } u.Save(); // save data if (cName.Text != "") { Channel c; try { c = new Channel(u.Id); } catch { c = new Channel(); c.User = u; } c.Name = cName.Text; c.FullTree = cFulltree.Checked; c.StartNode = int.Parse(cContentPicker.Value); c.MediaFolder = int.Parse(cMediaPicker.Value); c.FieldCategoriesAlias = cCategories.SelectedValue; c.FieldDescriptionAlias = cDescription.SelectedValue; c.FieldExcerptAlias = cExcerpt.SelectedValue; c.DocumentTypeAlias = cDocumentType.SelectedValue; // c.MediaTypeAlias = Constants.Conventions.MediaTypes.Image; // [LK:2013-03-22] This was previously lowercase; unsure if using const will cause an issue. c.MediaTypeFileProperty = Constants.Conventions.Media.File; c.ImageSupport = true; c.Save(); } ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "editUserSaved", base.getUser()), ""); } catch (Exception ex) { ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", base.getUser()), ""); LogHelper.Error<EditUser>("Exception", ex); } } else { ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "editUserError", base.getUser()), ""); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Xml.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using MSXML; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets { internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient { protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService; protected readonly Guid LanguageServiceGuid; protected readonly ITextView TextView; protected readonly ITextBuffer SubjectBuffer; protected bool indentCaretOnCommit; protected int indentDepth; protected bool earlyEndExpansionHappened; internal IVsExpansionSession ExpansionSession; public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) { this.LanguageServiceGuid = languageServiceGuid; this.TextView = textView; this.SubjectBuffer = subjectBuffer; this.EditorAdaptersFactoryService = editorAdaptersFactoryService; } public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc); protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan(); internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken); public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer) { // Formatting a snippet isn't cancellable. var cancellationToken = CancellationToken.None; // At this point, the $selection$ token has been replaced with the selected text and // declarations have been replaced with their default text. We need to format the // inserted snippet text while carefully handling $end$ position (where the caret goes // after Return is pressed). The IVsExpansionSession keeps a tracking point for this // position but we do the tracking ourselves to properly deal with virtual space. To // ensure the end location is correct, we take three extra steps: // 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior // to formatting), and keep a tracking span for the comment. // 2. After formatting the new snippet text, find and delete the empty multiline // comment (via the tracking span) and notify the IVsExpansionSession of the new // $end$ location. If the line then contains only whitespace (due to the formatter // putting the empty comment on its own line), then delete the white space and // remember the indentation depth for that line. // 3. When the snippet is finally completed (via Return), and PositionCaretForEditing() // is called, check to see if the end location was on a line containing only white // space in the previous step. If so, and if that line is still empty, then position // the caret in virtual space. // This technique ensures that a snippet like "if($condition$) { $end$ }" will end up // as: // if ($condition$) // { // $end$ // } SnapshotSpan snippetSpan; if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan)) { return VSConstants.S_OK; } // Insert empty comment and track end position var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive); var fullSnippetSpan = new VsTextSpan[1]; ExpansionSession.GetSnippetSpan(fullSnippetSpan); var isFullSnippetFormat = fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine && fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex && fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine && fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex; var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null; var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot)); SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None); if (isFullSnippetFormat) { CleanUpEndLocation(endPositionTrackingSpan); // Unfortunately, this is the only place we can safely add references and imports // specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the // snippet xml will be available, and changing the buffer during OnAfterInsertion can // cause the underlying tracking spans to get out of sync. AddReferencesAndImports(ExpansionSession, cancellationToken); SetNewEndPosition(endPositionTrackingSpan); } return VSConstants.S_OK; } private void SetNewEndPosition(ITrackingSpan endTrackingSpan) { if (SetEndPositionIfNoneSpecified(ExpansionSession)) { return; } if (endTrackingSpan != null) { SnapshotSpan endSpanInSurfaceBuffer; if (!TryGetSurfaceBufferSpan(endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot), out endSpanInSurfaceBuffer)) { return; } int endLine, endColumn; TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn); ExpansionSession.SetEndSpan(new VsTextSpan { iStartLine = endLine, iStartIndex = endColumn, iEndLine = endLine, iEndIndex = endColumn }); } } private void CleanUpEndLocation(ITrackingSpan endTrackingSpan) { if (endTrackingSpan != null) { // Find the empty comment and remove it... var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot); SubjectBuffer.Delete(endSnapshotSpan.Span); // Remove the whitespace before the comment if necessary. If whitespace is removed, // then remember the indentation depth so we can appropriately position the caret // in virtual space when the session is ended. var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position); var lineText = line.GetText(); if (lineText.Trim() == string.Empty) { indentCaretOnCommit = true; indentDepth = lineText.Length; SubjectBuffer.Delete(new Span(line.Start.Position, line.Length)); endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0)); } } } /// <summary> /// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it /// defaults to the beginning of the snippet code. /// </summary> private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return false; } var ns = snippetNode.Name.NamespaceName; var codeNode = snippetNode.Element(XName.Get("Code", ns)); if (codeNode == null) { return false; } var delimiterAttribute = codeNode.Attribute("Delimiter"); var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$"; if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1) { return false; } var snippetSpan = new VsTextSpan[1]; if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK) { return false; } var newEndSpan = new VsTextSpan { iStartLine = snippetSpan[0].iEndLine, iStartIndex = snippetSpan[0].iEndIndex, iEndLine = snippetSpan[0].iEndLine, iEndIndex = snippetSpan[0].iEndIndex }; pSession.SetEndSpan(newEndSpan); return true; } protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode) { IXMLDOMNode xmlNode = null; snippetNode = null; try { // Cast to our own version of IVsExpansionSession so that we can get pNode as an // IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is // released before leaving this method. Otherwise, a second invocation of the same // snippet may cause an AccessViolationException. var session = (IVsExpansionSessionInternal)pSession; IntPtr pNode; if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK) { return false; } xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode); snippetNode = XElement.Parse(xmlNode.xml); return true; } finally { if (xmlNode != null && Marshal.IsComObject(xmlNode)) { Marshal.ReleaseComObject(xmlNode); } } } public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts) { // If the formatted location of the $end$ position (the inserted comment) was on an // empty line and indented, then we have already removed the white space on that line // and the navigation location will be at column 0 on a blank line. We must now // position the caret in virtual space. if (indentCaretOnCommit) { int lineLength; pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength); string lineText; pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out lineText); if (lineText == string.Empty) { int endLinePosition; pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition); TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth)); } } return VSConstants.S_OK; } public virtual bool TryHandleTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleBackTab() { if (ExpansionSession != null) { var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField(); if (!tabbedInsideSnippetField) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; } return tabbedInsideSnippetField; } return false; } public virtual bool TryHandleEscape() { if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1); ExpansionSession = null; return true; } return false; } public virtual bool TryHandleReturn() { // TODO(davip): Only move the caret if the enter was hit within the editable spans if (ExpansionSession != null) { ExpansionSession.EndCurrentExpansion(fLeaveCaret: 0); ExpansionSession = null; return true; } return false; } public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer) { int startLine = 0; int startIndex = 0; int endLine = 0; int endIndex = 0; // The expansion itself needs to be created in the surface buffer, so map everything up var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer); var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer); SnapshotSpan surfaceBufferSpan; if (!TryGetSurfaceBufferSpan(SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer), out surfaceBufferSpan)) { return false; } var buffer = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextBuffer); buffer.GetLineIndexOfPosition(surfaceBufferSpan.Start.Position, out startLine, out startIndex); buffer.GetLineIndexOfPosition(surfaceBufferSpan.End.Position, out endLine, out endIndex); var textSpan = new VsTextSpan { iStartLine = startLine, iStartIndex = startIndex, iEndLine = endLine, iEndIndex = endIndex }; var expansion = buffer as IVsExpansion; return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK; } public int EndExpansion() { if (ExpansionSession == null) { earlyEndExpansionHappened = true; } ExpansionSession = null; indentCaretOnCommit = false; return VSConstants.S_OK; } public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind) { pfIsValidKind = 1; return VSConstants.S_OK; } public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType) { pfIsValidType = 1; return VSConstants.S_OK; } public int OnAfterInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnAfterInsertion); return VSConstants.S_OK; } public int OnBeforeInsertion(IVsExpansionSession pSession) { Logger.Log(FunctionId.Snippet_OnBeforeInsertion); this.ExpansionSession = pSession; return VSConstants.S_OK; } public int OnItemChosen(string pszTitle, string pszPath) { var hr = VSConstants.S_OK; try { VsTextSpan textSpan; GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex); textSpan.iEndLine = textSpan.iStartLine; textSpan.iEndIndex = textSpan.iStartIndex; IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(TextView.TextBuffer) as IVsExpansion; earlyEndExpansionHappened = false; hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession); if (earlyEndExpansionHappened) { // EndExpansion was called before InsertNamedExpansion returned, so set // expansionSession to null to indicate that there is no active expansion // session. This can occur when the snippet inserted doesn't have any expansion // fields. ExpansionSession = null; earlyEndExpansionHappened = false; } } catch (COMException ex) { hr = ex.ErrorCode; } return hr; } private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn) { var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView); vsTextView.GetCaretPos(out caretLine, out caretColumn); IVsTextLines textLines; vsTextView.GetBuffer(out textLines); // Handle virtual space (e.g, see Dev10 778675) int lineLength; textLines.GetLengthOfLine(caretLine, out lineLength); if (caretColumn > lineLength) { caretColumn = lineLength; } } private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken) { XElement snippetNode; if (!TryGetSnippetNode(pSession, out snippetNode)) { return; } var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (documentWithImports == null) { return; } var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService<IOptionService>(); var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language); documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken); AddReferences(documentWithImports.Project, snippetNode); } private void AddReferences(Project originalProject, XElement snippetNode) { var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName)); if (referencesNode == null) { return; } var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display)); var workspace = originalProject.Solution.Workspace; var projectId = originalProject.Id; var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName); var failedReferenceAdditions = new List<string>(); var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl; foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName))) { // Note: URL references are not supported var assemblyElement = reference.Element(assemblyXmlName); var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null; if (string.IsNullOrEmpty(assemblyName)) { continue; } if (visualStudioWorkspace == null || !visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName)) { failedReferenceAdditions.Add(assemblyName); } } if (failedReferenceAdditions.Any()) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( string.Join(Environment.NewLine, failedReferenceAdditions), string.Format(ServicesVSResources.ReferencesNotFound, Environment.NewLine), NotificationSeverity.Warning); } } protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces) { var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl; if (vsWorkspace == null) { return false; } var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument; if (containedDocument == null) { return false; } var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal; if (containedLanguageHost != null) { foreach (var importClause in memberImportsNamespaces) { if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK) { return false; } } } return true; } protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param) { if (xmlFunctionNode.text.IndexOf('(') == -1 || xmlFunctionNode.text.IndexOf(')') == -1 || xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('(')) { snippetFunctionName = null; param = null; return false; } snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('(')); var paramStart = xmlFunctionNode.text.IndexOf('(') + 1; var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1; param = xmlFunctionNode.text.Substring(paramStart, paramLength); return true; } internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan) { var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan); var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer); // Bail if a snippet span does not map down to exactly one subject buffer span. if (subjectBufferSpanCollection.Count == 1) { subjectBufferSpan = subjectBufferSpanCollection.Single(); return true; } subjectBufferSpan = default(SnapshotSpan); return false; } internal bool TryGetSurfaceBufferSpan(SnapshotSpan snapshotSpan, out SnapshotSpan surfaceBufferSpan) { var surfaceBufferSpanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, TextView.TextBuffer); // Bail if a snippet span does not map up to exactly one surface buffer span. if (surfaceBufferSpanCollection.Count == 1) { surfaceBufferSpan = surfaceBufferSpanCollection.Single(); return true; } surfaceBufferSpan = default(SnapshotSpan); return false; } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry 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.Dynamic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text.RegularExpressions; using FakeItEasy; using FluentAssertions; using Xunit; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.ObjectFactories; namespace YamlDotNet.Test.Serialization { public class SerializationTests : SerializationTestHelper { [Fact] public void DeserializeEmptyDocument() { var emptyText = string.Empty; var array = Deserializer.Deserialize<int[]>(UsingReaderFor(emptyText)); array.Should().BeNull(); } [Fact] public void DeserializeScalar() { var stream = Yaml.StreamFrom("02-scalar-in-imp-doc.yaml"); var result = Deserializer.Deserialize(stream); result.Should().Be("a scalar"); } [Fact] public void RoundtripEnums() { var flags = EnumExample.One | EnumExample.Two; var result = DoRoundtripFromObjectTo<EnumExample>(flags); result.Should().Be(flags); } [Fact] public void SerializeCircularReference() { var obj = new CircularReference(); obj.Child1 = new CircularReference { Child1 = obj, Child2 = obj }; Action action = () => RoundtripSerializer.Serialize(new StringWriter(), obj, typeof(CircularReference)); action.ShouldNotThrow(); } [Fact] public void DeserializeCustomTags() { var stream = Yaml.StreamFrom("tags.yaml"); Deserializer.RegisterTagMapping("tag:yaml.org,2002:point", typeof(Point)); var result = Deserializer.Deserialize(stream); result.Should().BeOfType<Point>().And .Subject.As<Point>().ShouldHave() .SharedProperties().EqualTo(new { X = 10, Y = 20 }); } [Fact] public void DeserializeExplicitType() { var text = Yaml.StreamFrom("explicit-type.template").TemplatedOn<Simple>(); var result = Deserializer.Deserialize<Simple>(UsingReaderFor(text)); result.aaa.Should().Be("bbb"); } [Fact] public void DeserializeConvertible() { var text = Yaml.StreamFrom("convertible.template").TemplatedOn<Convertible>(); var result = Deserializer.Deserialize<Simple>(UsingReaderFor(text)); result.aaa.Should().Be("[hello, world]"); } [Fact] public void DeserializationOfObjectsHandlesForwardReferences() { var text = Lines( "Nothing: *forward", "MyString: &forward ForwardReference"); var result = Deserializer.Deserialize<Example>(UsingReaderFor(text)); result.ShouldHave().SharedProperties().EqualTo( new { Nothing = "ForwardReference", MyString = "ForwardReference" }); } [Fact] public void DeserializationFailsForUndefinedForwardReferences() { var text = Lines( "Nothing: *forward", "MyString: ForwardReference"); Action action = () => Deserializer.Deserialize<Example>(UsingReaderFor(text)); action.ShouldThrow<AnchorNotFoundException>(); } [Fact] public void RoundtripObject() { var obj = new Example(); var result = DoRoundtripFromObjectTo<Example>(obj, RoundtripSerializer); result.ShouldHave().AllProperties().EqualTo(obj); } [Fact] public void RoundtripObjectWithDefaults() { var obj = new Example(); var result = DoRoundtripFromObjectTo<Example>(obj, RoundtripEmitDefaultsSerializer); result.ShouldHave().AllProperties().EqualTo(obj); } [Fact] public void RoundtripAnonymousType() { var data = new { Key = 3 }; var result = DoRoundtripFromObjectTo<Dictionary<string, string>>(data); result.Should().Equal(new Dictionary<string, string> { { "Key", "3" } }); } [Fact] public void RoundtripWithYamlTypeConverter() { var obj = new MissingDefaultCtor("Yo"); RoundtripSerializer.RegisterTypeConverter(new MissingDefaultCtorConverter()); Deserializer.RegisterTypeConverter(new MissingDefaultCtorConverter()); var result = DoRoundtripFromObjectTo<MissingDefaultCtor>(obj, RoundtripSerializer, Deserializer); result.Value.Should().Be("Yo"); } [Fact] public void RoundtripAlias() { var writer = new StringWriter(); var input = new NameConvention { AliasTest = "Fourth" }; Serializer.Serialize(writer, input, input.GetType()); var text = writer.ToString(); // Todo: use RegEx once FluentAssertions 2.2 is released text.TrimEnd('\r', '\n').Should().Be("fourthTest: Fourth"); var output = Deserializer.Deserialize<NameConvention>(UsingReaderFor(text)); output.AliasTest.Should().Be(input.AliasTest); } [Fact] // Todo: is the assert on the string necessary? public void RoundtripDerivedClass() { var obj = new InheritanceExample { SomeScalar = "Hello", RegularBase = new Derived { BaseProperty = "foo", DerivedProperty = "bar" }, }; var result = DoRoundtripFromObjectTo<InheritanceExample>(obj, RoundtripSerializer); result.SomeScalar.Should().Be("Hello"); result.RegularBase.Should().BeOfType<Derived>().And .Subject.As<Derived>().ShouldHave().SharedProperties().EqualTo(new { ChildProp = "bar" }); } [Fact] public void RoundtripDerivedClassWithSerializeAs() { var obj = new InheritanceExample { SomeScalar = "Hello", BaseWithSerializeAs = new Derived { BaseProperty = "foo", DerivedProperty = "bar" }, }; var result = DoRoundtripFromObjectTo<InheritanceExample>(obj, RoundtripSerializer); result.BaseWithSerializeAs.Should().BeOfType<Base>().And .Subject.As<Base>().ShouldHave().SharedProperties().EqualTo(new { ParentProp = "foo" }); } [Fact] public void RoundtripInterfaceProperties() { AssumingDeserializerWith(new LambdaObjectFactory(t => { if (t == typeof(InterfaceExample)) { return new InterfaceExample(); } else if (t == typeof(IDerived)) { return new Derived(); } return null; })); var obj = new InterfaceExample { Derived = new Derived { BaseProperty = "foo", DerivedProperty = "bar" } }; var result = DoRoundtripFromObjectTo<InterfaceExample>(obj); result.Derived.Should().BeOfType<Derived>().And .Subject.As<IDerived>().ShouldHave().SharedProperties().EqualTo(new { BaseProperty = "foo", DerivedProperty = "bar" }); } [Fact] public void DeserializeGuid() { var stream = Yaml.StreamFrom("guid.yaml"); var result = Deserializer.Deserialize<Guid>(stream); result.Should().Be(new Guid("9462790d5c44468985425e2dd38ebd98")); } [Fact] public void DeserializationOfOrderedProperties() { TextReader stream = Yaml.StreamFrom("ordered-properties.yaml"); var orderExample = Deserializer.Deserialize<OrderExample>(stream); orderExample.Order1.Should().Be("Order1 value"); orderExample.Order2.Should().Be("Order2 value"); } [Fact] public void DeserializeEnumerable() { var obj = new[] { new Simple { aaa = "bbb" } }; var result = DoRoundtripFromObjectTo<IEnumerable<Simple>>(obj); result.Should().ContainSingle(item => "bbb".Equals(item.aaa)); } [Fact] public void DeserializeArray() { var stream = Yaml.StreamFrom("list.yaml"); var result = Deserializer.Deserialize<String[]>(stream); result.Should().Equal(new[] { "one", "two", "three" }); } [Fact] public void DeserializeList() { var stream = Yaml.StreamFrom("list.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IList>().And .Subject.As<IList>().Should().Equal(new[] { "one", "two", "three" }); } [Fact] public void DeserializeExplicitList() { var stream = Yaml.StreamFrom("list-explicit.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IList<int>>().And .Subject.As<IList<int>>().Should().Equal(3, 4, 5); } [Fact] public void DeserializationOfGenericListsHandlesForwardReferences() { var text = Lines( "- *forward", "- &forward ForwardReference"); var result = Deserializer.Deserialize<string[]>(UsingReaderFor(text)); result.Should().Equal(new[] { "ForwardReference", "ForwardReference" }); } [Fact] public void DeserializationOfNonGenericListsHandlesForwardReferences() { var text = Lines( "- *forward", "- &forward ForwardReference"); var result = Deserializer.Deserialize<ArrayList>(UsingReaderFor(text)); result.Should().Equal(new[] { "ForwardReference", "ForwardReference" }); } [Fact] public void RoundtripList() { var obj = new List<int> { 2, 4, 6 }; var result = DoRoundtripOn<List<int>>(obj, RoundtripSerializer); result.Should().Equal(obj); } [Fact] public void RoundtripArrayWithTypeConversion() { var obj = new object[] { 1, 2, "3" }; var result = DoRoundtripFromObjectTo<int[]>(obj); result.Should().Equal(1, 2, 3); } [Fact] public void RoundtripArrayOfIdenticalObjects() { var z = new Simple { aaa = "bbb" }; var obj = new[] { z, z, z }; var result = DoRoundtripOn<Simple[]>(obj); result.Should().HaveCount(3).And.OnlyContain(x => z.aaa.Equals(x.aaa)); result[0].Should().BeSameAs(result[1]).And.BeSameAs(result[2]); } [Fact] public void DeserializeDictionary() { var stream = Yaml.StreamFrom("dictionary.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IDictionary<object, object>>().And.Subject .As<IDictionary<object, object>>().Should().Equal(new Dictionary<object, object> { { "key1", "value1" }, { "key2", "value2" } }); } [Fact] public void DeserializeExplicitDictionary() { var stream = Yaml.StreamFrom("dictionary-explicit.yaml"); var result = Deserializer.Deserialize(stream); result.Should().BeAssignableTo<IDictionary<string, int>>().And.Subject .As<IDictionary<string, int>>().Should().Equal(new Dictionary<string, int> { { "key1", 1 }, { "key2", 2 } }); } [Fact] public void RoundtripDictionary() { var obj = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" }, { "key3", "value3" }, }; var result = DoRoundtripFromObjectTo<Dictionary<string, string>>(obj); result.Should().Equal(obj); } [Fact] public void DeserializationOfGenericDictionariesHandlesForwardReferences() { var text = Lines( "key1: *forward", "*forwardKey: ForwardKeyValue", "*forward: *forward", "key2: &forward ForwardReference", "key3: &forwardKey key4"); var result = Deserializer.Deserialize<Dictionary<string, string>>(UsingReaderFor(text)); result.Should().Equal(new Dictionary<string, string> { { "ForwardReference", "ForwardReference" }, { "key1", "ForwardReference" }, { "key2", "ForwardReference" }, { "key4", "ForwardKeyValue" }, { "key3", "key4" } }); } [Fact] public void DeserializationOfNonGenericDictionariesHandlesForwardReferences() { var text = Lines( "key1: *forward", "*forwardKey: ForwardKeyValue", "*forward: *forward", "key2: &forward ForwardReference", "key3: &forwardKey key4"); var result = Deserializer.Deserialize<Hashtable>(UsingReaderFor(text)); result.Should().BeEquivalentTo( Entry("ForwardReference", "ForwardReference"), Entry("key1", "ForwardReference"), Entry("key2", "ForwardReference"), Entry("key4", "ForwardKeyValue"), Entry("key3", "key4")); } [Fact] public void DeserializeListOfDictionaries() { var stream = Yaml.StreamFrom("list-of-dictionaries.yaml"); var result = Deserializer.Deserialize<List<Dictionary<string, string>>>(stream); result.ShouldBeEquivalentTo(new[] { new Dictionary<string, string> { { "connection", "conn1" }, { "path", "path1" } }, new Dictionary<string, string> { { "connection", "conn2" }, { "path", "path2" } }}, opt => opt.WithStrictOrderingFor(root => root)); } [Fact] public void DeserializeTwoDocuments() { var reader = EventReaderFor(Lines( "---", "aaa: 111", "---", "aaa: 222", "...")); reader.Expect<StreamStart>(); var one = Deserializer.Deserialize<Simple>(reader); var two = Deserializer.Deserialize<Simple>(reader); one.ShouldHave().AllProperties().EqualTo(new { aaa = "111" }); two.ShouldHave().AllProperties().EqualTo(new { aaa = "222" }); } [Fact] public void DeserializeThreeDocuments() { var reader = EventReaderFor(Lines( "---", "aaa: 111", "---", "aaa: 222", "---", "aaa: 333", "...")); reader.Expect<StreamStart>(); var one = Deserializer.Deserialize<Simple>(reader); var two = Deserializer.Deserialize<Simple>(reader); var three = Deserializer.Deserialize<Simple>(reader); reader.Accept<StreamEnd>().Should().BeTrue("reader should have reached StreamEnd"); one.ShouldHave().AllProperties().EqualTo(new { aaa = "111" }); two.ShouldHave().AllProperties().EqualTo(new { aaa = "222" }); three.ShouldHave().AllProperties().EqualTo(new { aaa = "333" }); } [Fact] public void SerializeGuid() { var guid = new Guid("{9462790D-5C44-4689-8542-5E2DD38EBD98}"); var writer = new StringWriter(); Serializer.Serialize(writer, guid); var serialized = writer.ToString(); Dump.WriteLine(writer.ToString()); Regex.IsMatch(serialized, "^" + guid.ToString("D")).Should().BeTrue("serialized content should contain the guid"); } [Fact] public void SerializationOfNullInListsAreAlwaysEmittedWithoutUsingEmitDefaults() { var writer = new StringWriter(); var obj = new[] { "foo", null, "bar" }; Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); Regex.Matches(serialized, "-").Count.Should().Be(3, "there should have been 3 elements"); } [Fact] public void SerializationOfNullInListsAreAlwaysEmittedWhenUsingEmitDefaults() { var writer = new StringWriter(); var obj = new[] { "foo", null, "bar" }; EmitDefaultsSerializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); Regex.Matches(serialized, "-").Count.Should().Be(3, "there should have been 3 elements"); } [Fact] public void SerializationIncludesKeyWhenEmittingDefaults() { var writer = new StringWriter(); var obj = new Example { MyString = null }; EmitDefaultsSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); writer.ToString().Should().Contain("MyString"); } [Fact] [Trait("Motive", "Bug fix")] public void SerializationIncludesKeyFromAnonymousTypeWhenEmittingDefaults() { var writer = new StringWriter(); var obj = new { MyString = (string)null }; EmitDefaultsSerializer.Serialize(writer, obj, obj.GetType()); Dump.WriteLine(writer); writer.ToString().Should().Contain("MyString"); } [Fact] public void SerializationDoesNotIncludeKeyWhenDisregardingDefaults() { var writer = new StringWriter(); var obj = new Example { MyString = null }; Serializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); writer.ToString().Should().NotContain("MyString"); } [Fact] public void SerializationOfDefaultsWorkInJson() { var writer = new StringWriter(); var obj = new Example { MyString = null }; EmitDefaultsJsonCompatibleSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); writer.ToString().Should().Contain("MyString"); } [Fact] // Todo: this is actualy roundtrip public void DeserializationOfDefaultsWorkInJson() { var writer = new StringWriter(); var obj = new Example { MyString = null }; RoundtripEmitDefaultsJsonCompatibleSerializer.Serialize(writer, obj, typeof(Example)); Dump.WriteLine(writer); var result = Deserializer.Deserialize<Example>(UsingReaderFor(writer)); result.MyString.Should().BeNull(); } [Fact] public void SerializationOfOrderedProperties() { var obj = new OrderExample(); var writer = new StringWriter(); Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should() .Be("Order1: Order1 value\r\nOrder2: Order2 value\r\n", "the properties should be in the right order"); } [Fact] public void SerializationRespectsYamlIgnoreAttribute() { var writer = new StringWriter(); var obj = new IgnoreExample(); Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().NotContain("IgnoreMe"); } [Fact] public void SerializationRespectsScalarStyle() { var writer = new StringWriter(); var obj = new ScalarStyleExample(); Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should() .Be("LiteralString: |-\r\n Test\r\nDoubleQuotedString: \"Test\"\r\n", "the properties should be specifically styled"); } [Fact] public void SerializationSkipsPropertyWhenUsingDefaultValueAttribute() { var writer = new StringWriter(); var obj = new DefaultsExample { Value = DefaultsExample.DefaultValue }; Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().NotContain("Value"); } [Fact] public void SerializationEmitsPropertyWhenUsingEmitDefaultsAndDefaultValueAttribute() { var writer = new StringWriter(); var obj = new DefaultsExample { Value = DefaultsExample.DefaultValue }; EmitDefaultsSerializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().Contain("Value"); } [Fact] public void SerializationEmitsPropertyWhenValueDifferFromDefaultValueAttribute() { var writer = new StringWriter(); var obj = new DefaultsExample { Value = "non-default" }; Serializer.Serialize(writer, obj); var serialized = writer.ToString(); Dump.WriteLine(serialized); serialized.Should().Contain("Value"); } [Fact] public void SerializingAGenericDictionaryShouldNotThrowTargetException() { var obj = new CustomGenericDictionary { { "hello", "world" }, }; Action action = () => Serializer.Serialize(new StringWriter(), obj); action.ShouldNotThrow<TargetException>(); } [Fact] public void SerializaionUtilizeNamingConventions() { var convention = A.Fake<INamingConvention>(); A.CallTo(() => convention.Apply(A<string>._)).ReturnsLazily((string x) => x); var obj = new NameConvention { FirstTest = "1", SecondTest = "2" }; var serializer = new Serializer(namingConvention: convention); serializer.Serialize(new StringWriter(), obj); A.CallTo(() => convention.Apply("FirstTest")).MustHaveHappened(); A.CallTo(() => convention.Apply("SecondTest")).MustHaveHappened(); } [Fact] public void DeserializationUtilizeNamingConventions() { var convention = A.Fake<INamingConvention>(); A.CallTo(() => convention.Apply(A<string>._)).ReturnsLazily((string x) => x); var text = Lines( "FirstTest: 1", "SecondTest: 2"); var deserializer = new Deserializer(namingConvention: convention); deserializer.Deserialize<NameConvention>(UsingReaderFor(text)); A.CallTo(() => convention.Apply("FirstTest")).MustHaveHappened(); A.CallTo(() => convention.Apply("SecondTest")).MustHaveHappened(); } [Fact] public void TypeConverterIsUsedOnListItems() { var text = Lines( "- !<!{type}>", " Left: hello", " Right: world") .TemplatedOn<Convertible>(); var list = Deserializer.Deserialize<List<string>>(UsingReaderFor(text)); list .Should().NotBeNull() .And.ContainSingle(c => c.Equals("[hello, world]")); } [Fact] public void BackreferencesAreMergedWithMappings() { var stream = Yaml.StreamFrom("backreference.yaml"); var parser = new MergingParser(new Parser(stream)); var result = Deserializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(new EventReader(parser)); var alias = result["alias"]; alias.Should() .Contain("key1", "value1", "key1 should be inherited from the backreferenced mapping") .And.Contain("key2", "Overriding key2", "key2 should be overriden by the actual mapping") .And.Contain("key3", "value3", "key3 is defined in the actual mapping"); } [Fact] public void MergingDoesNotProduceDuplicateAnchors() { var parser = new MergingParser(Yaml.ParserForText(@" anchor: &default key1: &myValue value1 key2: value2 alias: <<: *default key2: Overriding key2 key3: value3 useMyValue: key: *myValue ")); var result = Deserializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(new EventReader(parser)); var alias = result["alias"]; alias.Should() .Contain("key1", "value1", "key1 should be inherited from the backreferenced mapping") .And.Contain("key2", "Overriding key2", "key2 should be overriden by the actual mapping") .And.Contain("key3", "value3", "key3 is defined in the actual mapping"); result["useMyValue"].Should() .Contain("key", "value1", "key should be copied"); } [Fact] public void ExampleFromSpecificationIsHandledCorrectly() { var parser = new MergingParser(Yaml.ParserForText(@" obj: - &CENTER { x: 1, y: 2 } - &LEFT { x: 0, y: 2 } - &BIG { r: 10 } - &SMALL { r: 1 } # All the following maps are equal: results: - # Explicit keys x: 1 y: 2 r: 10 label: center/big - # Merge one map << : *CENTER r: 10 label: center/big - # Merge multiple maps << : [ *CENTER, *BIG ] label: center/big - # Override #<< : [ *BIG, *LEFT, *SMALL ] # This does not work because, in the current implementation, # later keys override former keys. This could be fixed, but that # is not trivial because the deserializer allows aliases to refer to # an anchor that is defined later in the document, and the way it is # implemented, the value is assigned later when the anchored value is # deserialized. << : [ *SMALL, *LEFT, *BIG ] x: 1 label: center/big ")); var result = Deserializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(new EventReader(parser)); int index = 0; foreach (var mapping in result["results"]) { mapping.Should() .Contain("x", "1", "'x' should be '1' in result #{0}", index) .And.Contain("y", "2", "'y' should be '2' in result #{0}", index) .And.Contain("r", "10", "'r' should be '10' in result #{0}", index) .And.Contain("label", "center/big", "'label' should be 'center/big' in result #{0}", index); ++index; } } [Fact] public void IgnoreExtraPropertiesIfWanted() { var text = Lines("aaa: hello", "bbb: world"); var des = new Deserializer(ignoreUnmatched: true); var actual = des.Deserialize<Simple>(UsingReaderFor(text)); actual.aaa.Should().Be("hello"); } [Fact] public void DontIgnoreExtraPropertiesIfWanted() { var text = Lines("aaa: hello", "bbb: world"); var des = new Deserializer(ignoreUnmatched: false); var actual = Record.Exception(() => des.Deserialize<Simple>(UsingReaderFor(text))); Assert.IsType<YamlException>(actual); } [Fact] public void IgnoreExtraPropertiesIfWantedBefore() { var text = Lines("bbb: [200,100]", "aaa: hello"); var des = new Deserializer(ignoreUnmatched: true); var actual = des.Deserialize<Simple>(UsingReaderFor(text)); actual.aaa.Should().Be("hello"); } [Fact] public void IgnoreExtraPropertiesIfWantedNamingScheme() { var text = Lines( "scratch: 'scratcher'", "deleteScratch: false", "notScratch: 9443", "notScratch: 192.168.1.30", "mappedScratch:", "- '/work/'" ); var des = new Deserializer(namingConvention: new CamelCaseNamingConvention(), ignoreUnmatched: true); var actual = des.Deserialize<SimpleScratch>(UsingReaderFor(text)); actual.Scratch.Should().Be("scratcher"); actual.DeleteScratch.Should().Be(false); actual.MappedScratch.Should().ContainInOrder(new[] { "/work/" }); } [Fact] public void InvalidTypeConversionsProduceProperExceptions() { var text = Lines("- 1", "- two", "- 3"); var sut = new Deserializer(); var exception = Assert.Throws<YamlException>(() => sut.Deserialize<List<int>>(UsingReaderFor(text))); Assert.Equal(2, exception.Start.Line); Assert.Equal(3, exception.Start.Column); } [Fact] public void SerializeDynamicPropertyAndApplyNamingConvention() { dynamic obj = new ExpandoObject(); obj.property_one = new ExpandoObject(); ((IDictionary<string, object>)obj.property_one).Add("new_key_here", "new_value"); var mockNamingConvention = A.Fake<INamingConvention>(); A.CallTo(() => mockNamingConvention.Apply(A<string>.Ignored)).Returns("xxx"); var serializer = new Serializer(namingConvention: mockNamingConvention); var writer = new StringWriter(); serializer.Serialize(writer, obj); writer.ToString().Should().Contain("xxx: new_value"); } [Fact] public void SerializeGenericDictionaryPropertyAndDoNotApplyNamingConvention() { var obj = new Dictionary<string, object>(); obj["property_one"] = new GenericTestDictionary<string, object>(); ((IDictionary<string, object>)obj["property_one"]).Add("new_key_here", "new_value"); var mockNamingConvention = A.Fake<INamingConvention>(); A.CallTo(() => mockNamingConvention.Apply(A<string>.Ignored)).Returns("xxx"); var serializer = new Serializer(namingConvention: mockNamingConvention); var writer = new StringWriter(); serializer.Serialize(writer, obj); writer.ToString().Should().Contain("new_key_here: new_value"); } #region Test Dictionary that implements IDictionary<,>, but not IDictionary public class GenericTestDictionary<TKey, TValue> : IDictionary<TKey, TValue> { private readonly Dictionary<TKey, TValue> _dictionary; public GenericTestDictionary() { _dictionary = new Dictionary<TKey, TValue>(); } public void Add(TKey key, TValue value) { _dictionary.Add(key, value); } public bool ContainsKey(TKey key) { return _dictionary.ContainsKey(key); } public ICollection<TKey> Keys { get { return _dictionary.Keys; } } public bool Remove(TKey key) { return _dictionary.Remove(key); } public bool TryGetValue(TKey key, out TValue value) { return _dictionary.TryGetValue(key, out value); } public ICollection<TValue> Values { get { return _dictionary.Values; } } public TValue this[TKey key] { get { return _dictionary[key]; } set { _dictionary[key] = value; } } public void Add(KeyValuePair<TKey, TValue> item) { ((IDictionary<TKey, TValue>)_dictionary).Add(item); } public void Clear() { _dictionary.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { return ((IDictionary<TKey, TValue>)_dictionary).Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((IDictionary<TKey, TValue>)_dictionary).CopyTo(array, arrayIndex); } public int Count { get { return _dictionary.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair<TKey, TValue> item) { return ((IDictionary<TKey, TValue>)_dictionary).Remove(item); } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _dictionary.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _dictionary.GetEnumerator(); } } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Item.cs" company="Exit Games GmbH"> // Copyright (c) Exit Games GmbH. All rights reserved. // </copyright> // <summary> // Represents an entity in a <see cref="IWorld">world</see>. // Items are event publisher and the counterpart to <see cref="InterestArea">InterestAreas</see>. // <para> // Items have // <list type="bullet"> // <item> // a <see cref="Type" />, // </item> // <item> // a per type unique <see cref="Id" />, // </item> // <item> // a <see cref="Position" />, // </item> // <item> // <see cref="Properties" /> with a <see cref="PropertiesRevision">revision number</see> // </item> // <item> // and 3 different <see cref="MessageChannel{T}">MessageChannels</see>: // <list type="bullet"> // <item> // <see cref="EventChannel" />: <see cref="EventData" /> for <see cref="ClientInterestArea">interest areas</see>. // </item> // <item> // <see cref="PositionUpdateChannel" />: Position updates for attached and subscribed <see cref="InterestArea">interest areas</see>. // Attached <see cref="InterestArea">interest areas</see> move to the same position and subscribed <see cref="InterestArea">interest areas</see> // unsubscribe when the item leaves the outer threshold (one position update is analyzed every few seconds). // </item> // <item> // <see cref="DisposeChannel" />: Subscribed <see cref="InterestArea">interest areas</see> are informed when the item is disposed in order to unsubscribe. // </item> // </list> // </item> // </list> // </para> // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Photon.SocketServer.Mmo { using System; using System.Collections; using ExitGames.Concurrency.Fibers; using Photon.SocketServer.Concurrency; using Photon.SocketServer.Mmo.Messages; /// <summary> /// Represents an entity in a <see cref = "IWorld">world</see>. /// Items are event publisher and the counterpart to <see cref = "InterestArea">InterestAreas</see>. /// <para> /// Items have /// <list type = "bullet"> /// <item> /// a <see cref = "Type" />, /// </item> /// <item> /// a per type unique <see cref = "Id" />, /// </item> /// <item> /// a <see cref = "Position" />, /// </item> /// <item> /// <see cref = "Properties" /> with a <see cref = "PropertiesRevision">revision number</see> /// </item> /// <item> /// and 3 different <see cref = "MessageChannel{T}">MessageChannels</see>: /// <list type = "bullet"> /// <item> /// <see cref = "EventChannel" />: <see cref = "EventData" /> for <see cref = "ClientInterestArea">interest areas</see>. /// </item> /// <item> /// <see cref = "PositionUpdateChannel" />: Position updates for attached and subscribed <see cref = "InterestArea">interest areas</see>. /// Attached <see cref = "InterestArea">interest areas</see> move to the same position and subscribed <see cref = "InterestArea">interest areas</see> /// unsubscribe when the item leaves the outer threshold (one position update is analyzed every few seconds). /// </item> /// <item> /// <see cref = "DisposeChannel" />: Subscribed <see cref = "InterestArea">interest areas</see> are informed when the item is disposed in order to unsubscribe. /// </item> /// </list> /// </item> /// </list> /// </para> /// </summary> /// <remarks> /// Item accessing operations are required to be invoked on the item's <see cref = "Fiber" />. /// </remarks> public class Item : IDisposable { #if MissingSubscribeDebug private static readonly ExitGames.Logging.ILogger log = ExitGames.Logging.LogManager.GetCurrentClassLogger(); #endif /// <summary> /// The dispose channel. /// </summary> private readonly MessageChannel<ItemDisposedMessage> disposeChannel; /// <summary> /// The item eventChannel. /// </summary> private readonly MessageChannel<ItemEventMessage> eventChannel; /// <summary> /// The fiber. /// </summary> private readonly IFiber fiber; /// <summary> /// The id. /// </summary> private readonly string id; /// <summary> /// The position region. /// </summary> private readonly MessageChannel<ItemPositionMessage> positionUpdateChannel; /// <summary> /// The properties. /// </summary> private readonly Hashtable properties; /// <summary> /// The type. /// </summary> private readonly byte type; /// <summary> /// The world. /// </summary> private readonly IWorld world; /// <summary> /// The disposed. /// </summary> private bool disposed; /// <summary> /// Initializes a new instance of the <see cref = "Item" /> class. /// </summary> /// <param name = "position"> /// The position. /// </param> /// <param name = "properties"> /// The properties. /// </param> /// <param name = "id"> /// The id. /// </param> /// <param name = "type"> /// The type. /// </param> /// <param name = "world"> /// The world. /// </param> /// <param name = "fiber"> /// The fiber. Typically identical to the owner's <see cref = "PeerBase.RequestFiber">request fiber</see>. /// </param> public Item(Vector position, Hashtable properties, string id, byte type, IWorld world, IFiber fiber) { this.Position = position; this.eventChannel = new MessageChannel<ItemEventMessage>(ItemEventMessage.CounterEventSend); this.disposeChannel = new MessageChannel<ItemDisposedMessage>(MessageCounters.CounterSend); this.positionUpdateChannel = new MessageChannel<ItemPositionMessage>(MessageCounters.CounterSend); this.properties = properties ?? new Hashtable(); if (properties != null) { this.PropertiesRevision++; } this.fiber = fiber; this.id = id; this.world = world; this.type = type; } /// <summary> /// Finalizes an instance of the <see cref = "Item" /> class. /// Suppressed by Dispose. /// </summary> ~Item() { this.Dispose(false); } /// <summary> /// Gets the item fiber. /// </summary> public IFiber Fiber { get { return this.fiber; } } /// <summary> /// Gets the <see cref = "Region" /> where at the item's current <see cref = "Position" />. /// </summary> public Region CurrentWorldRegion { get; private set; } /// <summary> /// Gets the channel that is used to publish <see cref = "ItemDisposedMessage">dispose messages</see>. /// Subscribed <see cref = "InterestArea">interest areas</see> unsubscribe when receiving the message. /// <see cref = "Dispose(bool)" /> publishes the <see cref = "ItemDisposedMessage" /> message. /// </summary> public MessageChannel<ItemDisposedMessage> DisposeChannel { get { return this.disposeChannel; } } /// <summary> /// Gets a value indicating whether this item has been disposed. /// Actions that where enqueued on the <see cref = "Fiber" /> could arrive after the item has been disposed. /// Check this property to ensure that your operation is legal. /// </summary> public bool Disposed { get { return this.disposed; } } /// <summary> /// Gets the channel that is used to publish <see cref = "ItemEventMessage">ItemEventMessages</see>. /// <see cref = "ClientInterestArea">ClientInterestAreas</see> subscribe this channel to forward all received <see cref = "EventData">events</see> to the client <see cref = "PeerBase" />. /// <see cref = "ItemEventMessage">ItemEventMessages</see> are published by the developer's application. /// </summary> public MessageChannel<ItemEventMessage> EventChannel { get { return this.eventChannel; } } /// <summary> /// Gets the item's Id. /// Unique per <see cref = "Type" /> and <see cref = "ItemCache" />. /// </summary> public string Id { get { return this.id; } } /// <summary> /// Gets or sets the item's current position. /// The position is used for interest management internal calculations. /// </summary> public Vector Position { get; set; } /// <summary> /// Gets the channel that is used to publish <see cref = "ItemPositionMessage">ItemPositionMessages</see>. /// Subscribed <see cref = "InterestArea">interest areas</see> use this channel to determine when to unsubscribe. /// Attached <see cref = "InterestArea">interest areas</see> use this channel to update their current position accordingly. /// <see cref = "ItemPositionMessage" /> are published with <see cref = "UpdateInterestManagement" />. /// </summary> public MessageChannel<ItemPositionMessage> PositionUpdateChannel { get { return this.positionUpdateChannel; } } /// <summary> /// Gets the item properties. /// Set with <see cref = "SetProperties">SetProperties</see>. /// </summary> public Hashtable Properties { get { return this.properties; } } /// <summary> /// Gets or sets the current properties revision number. /// Incremented with <see cref = "SetProperties">SetProperties</see>. /// </summary> public int PropertiesRevision { get; set; } /// <summary> /// Gets the item type. /// This is for the client to distinguish what kind of item to display. /// </summary> public byte Type { get { return this.type; } } /// <summary> /// Gets the world the item is member of. /// </summary> public IWorld World { get { return this.world; } } /// <summary> /// Gets or sets CurrentWorldRegionSubscription. /// </summary> private IDisposable CurrentWorldRegionSubscription { get; set; } /// <summary> /// Does nothing but calling <see cref = "OnDestroy" />. /// </summary> public void Destroy() { this.OnDestroy(); } /// <summary> /// Publishes a <see cref = "ItemPositionMessage" /> in the <see cref = "PositionUpdateChannel" /> /// and in the current <see cref = "Region" /> if it changes /// and then updates the <see cref = "CurrentWorldRegion" />. /// </summary> public void UpdateInterestManagement() { Region newRegion = this.World.GetRegion(this.Position); // inform attached and auto subscribed (delayed) interest areas ItemPositionMessage message = this.GetPositionUpdateMessage(this.Position, newRegion); this.positionUpdateChannel.Publish(message); if (this.SetCurrentWorldRegion(newRegion)) { // inform unsubscribed interest areas in new region ItemSnapshot snapshot = this.GetItemSnapshot(); newRegion.Publish(snapshot); #if MissingSubscribeDebug if (log.IsDebugEnabled) { log.DebugFormat("{0} sent snap shot to region {1}", this.id, newRegion.Coordinate); } #endif } } /// <summary> /// Sets the <see cref = "Position" /> and calls <see cref = "UpdateInterestManagement" />. /// </summary> /// <param name = "position"> /// The position. /// </param> [Obsolete("Use Position_set and UpdateInterestManagement() instead")] public void Move(Vector position) { this.Position = position; this.UpdateInterestManagement(); } /// <summary> /// Updates the <see cref = "Properties" /> and increments the <see cref = "PropertiesRevision" />. /// </summary> /// <param name = "propertiesSet"> /// The properties to set. /// </param> /// <param name = "propertiesUnset"> /// The property keys to unset. /// </param> public void SetProperties(Hashtable propertiesSet, ArrayList propertiesUnset) { if (propertiesSet != null) { foreach (DictionaryEntry entry in propertiesSet) { this.properties[entry.Key] = entry.Value; } } if (propertiesUnset != null) { foreach (object key in propertiesUnset) { this.properties.Remove(key); } } this.PropertiesRevision++; } /// <summary> /// Sets the <see cref = "Position" /> and calls <see cref = "UpdateInterestManagement" />. /// </summary> /// <param name = "position"> /// The new position. /// </param> [Obsolete("Use Position_set and UpdateInterestManagement() instead")] public void Spawn(Vector position) { this.Position = position; this.UpdateInterestManagement(); } #region Implemented Interfaces #region IDisposable /// <summary> /// Calls <see cref = "Dispose(bool)" /> and suppresses finalization. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion #endregion /// <summary> /// Requests an <see cref = "ItemSnapshot" />. /// </summary> /// <param name = "snapShotRequest"> /// The snap shot request. /// </param> internal void EnqueueItemSnapshotRequest(ItemSnapshotRequest snapShotRequest) { this.fiber.Enqueue( () => { if (this.disposed) { return; } snapShotRequest.OnItemReceive(this); }); } /// <summary> /// Creates an <see cref = "ItemSnapshot" /> with a snapshot of the current attributes. /// Override this method to return a subclass of <see cref = "ItemSnapshot" /> that includes more data. /// The return value is published through the <see cref = "CurrentWorldRegion" /> or sent directly to an <see cref = "InterestArea" />. /// </summary> /// <returns> /// A new <see cref = "ItemSnapshot" />. /// </returns> protected internal virtual ItemSnapshot GetItemSnapshot() { return new ItemSnapshot(this, this.Position, this.CurrentWorldRegion, this.PropertiesRevision); } /// <summary> /// Publishes a <see cref = "ItemDisposedMessage" /> through the <see cref = "DisposeChannel" /> and disposes all channels. /// <see cref = "Disposed" /> is set to true. /// </summary> /// <param name = "disposing"> /// True if called from <see cref = "Dispose()" />, false if called from the finalizer. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) { this.SetCurrentWorldRegion(null); this.disposeChannel.Publish(new ItemDisposedMessage(this)); this.eventChannel.Dispose(); this.disposeChannel.Dispose(); this.positionUpdateChannel.Dispose(); this.disposed = true; } } /// <summary> /// Creates an <see cref = "ItemPositionMessage" /> with the current position and region. /// The return value is published through the <see cref = "PositionUpdateChannel" />. /// </summary> /// <param name = "position"> /// The position. /// </param> /// <param name = "region"> /// The region. /// </param> /// <returns> /// An instance of <see cref = "ItemPositionMessage" />. /// </returns> protected virtual ItemPositionMessage GetPositionUpdateMessage(Vector position, Region region) { return new ItemPositionMessage(this, position, region); } /// <summary> /// Called from <see cref = "Destroy" />. /// Does nothing. /// </summary> protected virtual void OnDestroy() { } /// <summary> /// The set current world region. /// </summary> /// <param name = "newRegion"> /// The new region. /// </param> /// <returns> /// True if the current region changed. /// </returns> protected bool SetCurrentWorldRegion(Region newRegion) { // out of bounds if (newRegion == null) { // was not out of bounce before if (this.CurrentWorldRegion != null) { #if MissingSubscribeDebug if (log.IsDebugEnabled) { log.DebugFormat("{0} unsubscribed from region {1}", this.id, this.CurrentWorldRegion.Coordinate); } #endif this.CurrentWorldRegion = null; this.CurrentWorldRegionSubscription.Dispose(); this.CurrentWorldRegionSubscription = null; } #if MissingSubscribeDebug else if (log.IsDebugEnabled) { log.DebugFormat("{0} out of bounds", this.id); } #endif return false; } // was out of bounce before if (this.CurrentWorldRegion == null) { this.CurrentWorldRegionSubscription = newRegion.Subscribe(this.fiber, this.Region_OnReceive); #if MissingSubscribeDebug if (log.IsDebugEnabled) { log.DebugFormat("{0} subscribed to region {1} - before null", this.id, newRegion.Coordinate); } #endif this.CurrentWorldRegion = newRegion; return true; } // current region changed if (newRegion != this.CurrentWorldRegion) { IDisposable newSubscription = newRegion.Subscribe(this.fiber, this.Region_OnReceive); #if MissingSubscribeDebug if (log.IsDebugEnabled) { log.DebugFormat("{0} subscribed to region {1} - before {2}", this.id, newRegion.Coordinate, this.CurrentWorldRegion.Coordinate); } #endif this.CurrentWorldRegionSubscription.Dispose(); this.CurrentWorldRegionSubscription = newSubscription; this.CurrentWorldRegion = newRegion; return true; } return false; } /// <summary> /// The on region message receive. /// </summary> /// <param name = "message"> /// The message. /// </param> private void Region_OnReceive(RegionMessage message) { if (this.disposed) { return; } message.OnItemReceive(this); } } }
using System; using System.IO; using System.Diagnostics; using Microsoft.Xna.Framework; namespace CocosSharp { public class CCSprite : CCNode, ICCTexture { bool flipX; bool flipY; bool isTextureRectRotated; bool opacityModifyRGB; bool texQuadDirty; CCPoint unflippedOffsetPositionFromCenter; CCSize untrimmedSizeInPixels; CCRect textureRectInPixels; CCQuadCommand quadCommand; #region Properties // Static properties public static float DefaultTexelToContentSizeRatio { set { DefaultTexelToContentSizeRatios = new CCSize(value, value); } } public static CCSize DefaultTexelToContentSizeRatios { get; set; } // Instance properties public int AtlasIndex { get ; internal set; } internal CCTextureAtlas TextureAtlas { get; set; } public bool IsAntialiased { get { return Texture.IsAntialiased; } set { Texture.IsAntialiased = value; } } public override bool IsColorModifiedByOpacity { get { return opacityModifyRGB; } set { if (opacityModifyRGB != value) { opacityModifyRGB = value; UpdateColor(); } } } public bool IsTextureRectRotated { get { return isTextureRectRotated; } set { if (isTextureRectRotated != value) { isTextureRectRotated = value; texQuadDirty = true; } } } public bool FlipX { get { return flipX; } set { if (flipX != value) { flipX = value; texQuadDirty = true; } } } public bool FlipY { get { return flipY; } set { if (flipY != value) { flipY = value; texQuadDirty = true; } } } public override bool Visible { get { return base.Visible; } set { base.Visible = value; texQuadDirty = true; } } public override byte Opacity { get { return base.Opacity; } set { base.Opacity = value; UpdateColor(); } } public CCBlendFunc BlendFunc { get { return quadCommand.BlendType; } set { quadCommand.BlendType = value; } } public override CCColor3B Color { get { return base.Color; } set { base.Color = value; UpdateColor(); } } public override CCSize ContentSize { get { return base.ContentSize; } set { base.ContentSize = value; texQuadDirty = true; } } public CCRect TextureRectInPixels { get { return textureRectInPixels; } set { if(textureRectInPixels != value) { textureRectInPixels = value; if(ContentSize == CCSize.Zero) ContentSize = textureRectInPixels.Size / DefaultTexelToContentSizeRatios; texQuadDirty = true; } } } public CCSpriteFrame SpriteFrame { get { return new CCSpriteFrame( ContentSize, Texture, TextureRectInPixels, UntrimmedSizeInPixels, IsTextureRectRotated, unflippedOffsetPositionFromCenter ); } set { if (value != null) { CCTexture2D newTexture = value.Texture; // update texture before updating texture rect if (newTexture != Texture) { Texture = newTexture; } // update rect IsTextureRectRotated = value.IsRotated; textureRectInPixels = value.TextureRectInPixels; unflippedOffsetPositionFromCenter = value.OffsetInPixels; UntrimmedSizeInPixels = value.OriginalSizeInPixels; ContentSize = UntrimmedSizeInPixels / DefaultTexelToContentSizeRatios; texQuadDirty = true; } } } public CCTexture2D Texture { get { return quadCommand.Texture; } set { if (Texture != value) { quadCommand.Texture = value; if(TextureRectInPixels == CCRect.Zero) { CCSize texSize = value.ContentSizeInPixels; TextureRectInPixels = new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height); } if(ContentSize == CCSize.Zero) ContentSize = textureRectInPixels.Size / DefaultTexelToContentSizeRatios; UpdateBlendFunc(); } } } protected internal CCSize UntrimmedSizeInPixels { get { if(untrimmedSizeInPixels == CCSize.Zero) return TextureRectInPixels.Size; return untrimmedSizeInPixels; } set { if (untrimmedSizeInPixels != value) { untrimmedSizeInPixels = value; texQuadDirty = true; } } } protected internal CCV3F_C4B_T2F_Quad Quad { get { if(texQuadDirty) UpdateSpriteTextureQuads(); return quadCommand.Quads[0]; } } #endregion Properties #region Constructors static CCSprite() { DefaultTexelToContentSizeRatios = CCSize.One; } public CCSprite() { quadCommand = new CCQuadCommand(1); IsTextureRectRotated = false; opacityModifyRGB = true; BlendFunc = CCBlendFunc.AlphaBlend; texQuadDirty = true; } public CCSprite(CCTexture2D texture=null, CCRect? texRectInPixels=null, bool rotated=false) : this() { InitWithTexture(texture, texRectInPixels, rotated); } public CCSprite(CCSpriteFrame spriteFrame) : this(spriteFrame.ContentSize, spriteFrame) { } public CCSprite(CCSize contentSize, CCSpriteFrame spriteFrame) : this() { ContentSize = contentSize; InitWithSpriteFrame(spriteFrame); } public CCSprite(string fileName, CCRect? texRectInPixels=null) : this() { InitWithFile(fileName, texRectInPixels); } void InitWithTexture(CCTexture2D texture, CCRect? texRectInPixels=null, bool rotated=false) { IsTextureRectRotated = rotated; CCSize texSize = (texture != null) ? texture.ContentSizeInPixels : CCSize.Zero; textureRectInPixels = texRectInPixels ?? new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height); opacityModifyRGB = true; BlendFunc = CCBlendFunc.AlphaBlend; AnchorPoint = CCPoint.AnchorMiddle; Texture = texture; // If content size not initialized, assume worldspace dimensions match texture dimensions if(ContentSize == CCSize.Zero) ContentSize = textureRectInPixels.Size / CCSprite.DefaultTexelToContentSizeRatios; texQuadDirty = true; } void InitWithSpriteFrame(CCSpriteFrame spriteFrame) { opacityModifyRGB = true; BlendFunc = CCBlendFunc.AlphaBlend; AnchorPoint = CCPoint.AnchorMiddle; SpriteFrame = spriteFrame; } void InitWithFile(string fileName, CCRect? rectInPoints=null) { Debug.Assert(!String.IsNullOrEmpty(fileName), "Invalid filename for sprite"); // Try sprite frame cache first CCSpriteFrame frame = CCSpriteFrameCache.SharedSpriteFrameCache[fileName]; if (frame != null) { InitWithSpriteFrame(frame); } else { // If frame doesn't exist, try texture cache CCTexture2D texture = CCTextureCache.SharedTextureCache.AddImage(fileName); if (texture != null) { InitWithTexture(texture, rectInPoints); } } } #endregion Constructors protected override void VisitRenderer(ref CCAffineTransform worldTransform) { if(texQuadDirty) UpdateSpriteTextureQuads(); quadCommand.GlobalDepth = worldTransform.Tz; quadCommand.WorldTransform = worldTransform; Renderer.AddCommand(quadCommand); } public bool IsSpriteFrameDisplayed(CCSpriteFrame frame) { CCRect r = frame.TextureRectInPixels; return ( CCRect.Equal(ref r, ref textureRectInPixels) && frame.Texture.Name == Texture.Name ); } public void SetSpriteFrameWithAnimationName(string animationName, int frameIndex) { Debug.Assert(!String.IsNullOrEmpty(animationName), "CCSprite#setDisplayFrameWithAnimationName. animationName must not be NULL"); CCAnimation a = CCAnimationCache.SharedAnimationCache[animationName]; Debug.Assert(a != null, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); var frame = (CCAnimationFrame)a.Frames[frameIndex]; Debug.Assert(frame != null, "CCSprite#setDisplayFrame. Invalid frame"); SpriteFrame = frame.SpriteFrame; } #region Color managment #region Texture management public void ReplaceTexture(CCTexture2D texture, CCRect textureRectInPixels) { Texture = texture; TextureRectInPixels = textureRectInPixels; } public void MaximizeTextureRect() { if(Texture != null) { CCSize texSize = Texture.ContentSizeInPixels; TextureRectInPixels = new CCRect(0.0f, 0.0f, texSize.Width, texSize.Height); } } #endregion Texture management public override void UpdateColor() { quadCommand.RequestUpdateQuads(UpdateColorCallback); } void UpdateColorCallback(ref CCV3F_C4B_T2F_Quad[] quads) { var color4 = new CCColor4B(DisplayedColor.R, DisplayedColor.G, DisplayedColor.B, DisplayedOpacity); if(opacityModifyRGB) { color4.R = (byte)(color4.R * DisplayedOpacity / 255.0f); color4.G = (byte)(color4.G * DisplayedOpacity / 255.0f); color4.B = (byte)(color4.B * DisplayedOpacity / 255.0f); } quads[0].BottomLeft.Colors = color4; quads[0].BottomRight.Colors = color4; quads[0].TopLeft.Colors = color4; quads[0].TopRight.Colors = color4; } protected void UpdateBlendFunc() { // it's possible to have an untextured sprite if (Texture == null || !Texture.HasPremultipliedAlpha) { BlendFunc = CCBlendFunc.NonPremultiplied; IsColorModifiedByOpacity = false; } else { BlendFunc = CCBlendFunc.AlphaBlend; IsColorModifiedByOpacity = true; } } #endregion Color managment #region Updating quads void UpdateSpriteTextureQuads() { quadCommand.RequestUpdateQuads(UpdateSpriteTextureQuadsCallback); texQuadDirty = false; } void UpdateSpriteTextureQuadsCallback(ref CCV3F_C4B_T2F_Quad[] quads) { if (!Visible) { quads[0].BottomRight.Vertices = quads[0].TopLeft.Vertices = quads[0].TopRight.Vertices = quads[0].BottomLeft.Vertices = CCVertex3F.Zero; } else { CCPoint relativeOffset = unflippedOffsetPositionFromCenter; if (flipX) { relativeOffset.X = -relativeOffset.X; } if (flipY) { relativeOffset.Y = -relativeOffset.Y; } CCPoint centerPoint = UntrimmedSizeInPixels.Center + relativeOffset; CCPoint subRectOrigin; subRectOrigin.X = centerPoint.X - textureRectInPixels.Size.Width / 2.0f; subRectOrigin.Y = centerPoint.Y - textureRectInPixels.Size.Height / 2.0f; CCRect subRectRatio = CCRect.Zero; if (UntrimmedSizeInPixels.Width > 0 && UntrimmedSizeInPixels.Height > 0) { subRectRatio = new CCRect( subRectOrigin.X / UntrimmedSizeInPixels.Width, subRectOrigin.Y / UntrimmedSizeInPixels.Height, textureRectInPixels.Size.Width / UntrimmedSizeInPixels.Width, textureRectInPixels.Size.Height / UntrimmedSizeInPixels.Height); } // Atlas: Vertex float x1 = subRectRatio.Origin.X * ContentSize.Width; float y1 = subRectRatio.Origin.Y * ContentSize.Height; float x2 = x1 + (subRectRatio.Size.Width * ContentSize.Width); float y2 = y1 + (subRectRatio.Size.Height * ContentSize.Height); // Don't set z-value: The node's transform will be set to include z offset quads[0].BottomLeft.Vertices = new CCVertex3F(x1, y1, 0); quads[0].BottomRight.Vertices = new CCVertex3F(x2, y1, 0); quads[0].TopLeft.Vertices = new CCVertex3F(x1, y2, 0); quads[0].TopRight.Vertices = new CCVertex3F(x2, y2, 0); if (Texture == null) { return; } float atlasWidth = Texture.PixelsWide; float atlasHeight = Texture.PixelsHigh; float left, right, top, bottom; if (IsTextureRectRotated) { #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL left = (2 * textureRectInPixels.Origin.X + 1) / (2 * atlasWidth); right = left + (textureRectInPixels.Size.Height * 2 - 2) / (2 * atlasWidth); top = (2 * textureRectInPixels.Origin.Y + 1) / (2 * atlasHeight); bottom = top + (textureRectInPixels.Size.Width * 2 - 2) / (2 * atlasHeight); #else left = textureRectInPixels.Origin.X / atlasWidth; right = (textureRectInPixels.Origin.X + textureRectInPixels.Size.Height) / atlasWidth; top = textureRectInPixels.Origin.Y / atlasHeight; bottom = (textureRectInPixels.Origin.Y + textureRectInPixels.Size.Width) / atlasHeight; #endif if (flipX) { CCMacros.CCSwap(ref top, ref bottom); } if (flipY) { CCMacros.CCSwap(ref left, ref right); } quads[0].BottomLeft.TexCoords.U = left; quads[0].BottomLeft.TexCoords.V = top; quads[0].BottomRight.TexCoords.U = left; quads[0].BottomRight.TexCoords.V = bottom; quads[0].TopLeft.TexCoords.U = right; quads[0].TopLeft.TexCoords.V = top; quads[0].TopRight.TexCoords.U = right; quads[0].TopRight.TexCoords.V = bottom; } else { #if CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL left = (2 * textureRectInPixels.Origin.X + 1) / (2 * atlasWidth); right = left + (textureRectInPixels.Size.Width * 2 - 2) / (2 * atlasWidth); top = (2 * textureRectInPixels.Origin.Y + 1) / (2 * atlasHeight); bottom = top + (textureRectInPixels.Size.Height * 2 - 2) / (2 * atlasHeight); #else left = textureRectInPixels.Origin.X / atlasWidth; right = (textureRectInPixels.Origin.X + textureRectInPixels.Size.Width) / atlasWidth; top = textureRectInPixels.Origin.Y / atlasHeight; bottom = (textureRectInPixels.Origin.Y + textureRectInPixels.Size.Height) / atlasHeight; #endif if (flipX) { CCMacros.CCSwap(ref left, ref right); } if (flipY) { CCMacros.CCSwap(ref top, ref bottom); } quads[0].BottomLeft.TexCoords.U = left; quads[0].BottomLeft.TexCoords.V = bottom; quads[0].BottomRight.TexCoords.U = right; quads[0].BottomRight.TexCoords.V = bottom; quads[0].TopLeft.TexCoords.U = left; quads[0].TopLeft.TexCoords.V = top; quads[0].TopRight.TexCoords.U = right; quads[0].TopRight.TexCoords.V = top; } } } public void UpdateLocalTransformedSpriteTextureQuads() { if(texQuadDirty) UpdateSpriteTextureQuads(); quadCommand.RequestUpdateQuads(UpdateLocalTransformedSpriteTextureQuadsCallback); } void UpdateLocalTransformedSpriteTextureQuadsCallback(ref CCV3F_C4B_T2F_Quad[] quads) { if(AtlasIndex == CCMacros.CCSpriteIndexNotInitialized) return; CCV3F_C4B_T2F_Quad transformedQuad = quads[0]; AffineLocalTransform.Transform(ref transformedQuad); if(TextureAtlas != null && TextureAtlas.TotalQuads > AtlasIndex) TextureAtlas.UpdateQuad(ref transformedQuad, AtlasIndex); } #endregion Updating texture quads #region Child management public override void ReorderChild(CCNode child, int zOrder) { Debug.Assert(child != null); Debug.Assert(Children.Contains(child)); if (zOrder == child.ZOrder) { return; } base.ReorderChild(child, zOrder); } #endregion Child management } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesGetAlias1 { public partial class IndicesGetAlias1YamlTests { public class IndicesGetAlias110BasicYamlBase : YamlTestsBase { public IndicesGetAlias110BasicYamlBase() : base() { //do indices.create this.Do(()=> _client.IndicesCreate("test_index", null)); //do indices.create this.Do(()=> _client.IndicesCreate("test_index_2", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test_index", "test_alias", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test_index", "test_blias", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test_index_2", "test_alias", null)); //do indices.put_alias this.Do(()=> _client.IndicesPutAlias("test_index_2", "test_blias", null)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllAliasesViaAlias2Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAllAliasesViaAlias2Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll()); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_blias: this.IsMatch(_response.test_index_2.aliases.test_blias, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllAliasesViaIndexAlias3Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAllAliasesViaIndexAlias3Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetSpecificAliasViaIndexAliasName4Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetSpecificAliasViaIndexAliasName4Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAliasAll5Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAliasAll5Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "_all")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAlias6Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAlias6Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "*")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAliasPrefix7Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAliasPrefix7Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_a*")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaIndexAliasNameName8Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaIndexAliasNameName8Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias,test_blias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index.aliases.test_blias: this.IsMatch(_response.test_index.aliases.test_blias, new {}); //is_false _response.test_index_2; this.IsFalse(_response.test_index_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaAliasName9Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaAliasName9Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll("test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaAllAliasName10Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaAllAliasName10Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("_all", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaAliasName11Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaAliasName11Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("*", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaPrefAliasName12Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaPrefAliasName12Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("*2", "test_alias")); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_alias; this.IsFalse(_response.test_index.aliases.test_alias); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasesViaNameNameAliasName13Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasesViaNameNameAliasName13Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index,test_index_2", "test_alias")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //match _response.test_index_2.aliases.test_alias: this.IsMatch(_response.test_index_2.aliases.test_alias, new {}); //is_false _response.test_index.aliases.test_blias; this.IsFalse(_response.test_index.aliases.test_blias); //is_false _response.test_index_2.aliases.test_blias; this.IsFalse(_response.test_index_2.aliases.test_blias); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class NonExistentAliasOnAnExistingIndexReturnsAnEmptyBody14Tests : IndicesGetAlias110BasicYamlBase { [Test] public void NonExistentAliasOnAnExistingIndexReturnsAnEmptyBody14Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "non-existent")); //match this._status: this.IsMatch(this._status, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class ExistentAndNonExistentAliasReturnsJustTheExisting15Tests : IndicesGetAlias110BasicYamlBase { [Test] public void ExistentAndNonExistentAliasReturnsJustTheExisting15Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("test_index", "test_alias,non-existent")); //match _response.test_index.aliases.test_alias: this.IsMatch(_response.test_index.aliases.test_alias, new {}); //is_false _response[@"test_index"][@"aliases"][@"non-existent"]; this.IsFalse(_response[@"test_index"][@"aliases"][@"non-existent"]); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GettingAliasOnAnNonExistentIndexShouldReturn40416Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GettingAliasOnAnNonExistentIndexShouldReturn40416Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAlias("non-existent", "foo"), shouldCatch: @"missing"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAliasWithLocalFlag17Tests : IndicesGetAlias110BasicYamlBase { [Test] public void GetAliasWithLocalFlag17Test() { //do indices.get_alias this.Do(()=> _client.IndicesGetAliasForAll(nv=>nv .AddQueryString("local", @"true") )); //is_true _response.test_index; this.IsTrue(_response.test_index); //is_true _response.test_index_2; this.IsTrue(_response.test_index_2); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class WorkCoordinatorRegistrationService { private partial class WorkCoordinator { private const int MinimumDelayInMS = 50; private readonly LogAggregator _logAggregator; private readonly IAsynchronousOperationListener _listener; private readonly IOptionService _optionService; private readonly int _correlationId; private readonly Workspace _workspace; private readonly CancellationTokenSource _shutdownNotificationSource; private readonly CancellationToken _shutdownToken; private readonly SimpleTaskQueue _eventProcessingQueue; // points to processor task private readonly IncrementalAnalyzerProcessor _documentAndProjectWorkerProcessor; private readonly SemanticChangeProcessor _semanticChangeProcessor; public WorkCoordinator( IAsynchronousOperationListener listener, IEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>> analyzerProviders, int correlationId, Workspace workspace) { _logAggregator = new LogAggregator(); _listener = listener; _optionService = workspace.Services.GetService<IOptionService>(); _optionService.OptionChanged += OnOptionChanged; // set up workspace _correlationId = correlationId; _workspace = workspace; // event and worker queues _shutdownNotificationSource = new CancellationTokenSource(); _shutdownToken = _shutdownNotificationSource.Token; _eventProcessingQueue = new SimpleTaskQueue(TaskScheduler.Default); var activeFileBackOffTimeSpanInMS = _optionService.GetOption(SolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS); var allFilesWorkerBackOffTimeSpanInMS = _optionService.GetOption(SolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS); var entireProjectWorkerBackOffTimeSpanInMS = _optionService.GetOption(SolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS); _documentAndProjectWorkerProcessor = new IncrementalAnalyzerProcessor( listener, correlationId, workspace, analyzerProviders, activeFileBackOffTimeSpanInMS, allFilesWorkerBackOffTimeSpanInMS, entireProjectWorkerBackOffTimeSpanInMS, _shutdownToken); var semanticBackOffTimeSpanInMS = _optionService.GetOption(SolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS); var projectBackOffTimeSpanInMS = _optionService.GetOption(SolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS); _semanticChangeProcessor = new SemanticChangeProcessor(listener, correlationId, workspace, _documentAndProjectWorkerProcessor, semanticBackOffTimeSpanInMS, projectBackOffTimeSpanInMS, _shutdownToken); // if option is on if (_optionService.GetOption(SolutionCrawlerOptions.SolutionCrawler)) { _workspace.WorkspaceChanged += OnWorkspaceChanged; _workspace.DocumentOpened += OnDocumentOpened; _workspace.DocumentClosed += OnDocumentClosed; } } public int CorrelationId { get { return _correlationId; } } public void Shutdown(bool blockingShutdown) { _optionService.OptionChanged -= OnOptionChanged; // detach from the workspace _workspace.WorkspaceChanged -= OnWorkspaceChanged; _workspace.DocumentOpened -= OnDocumentOpened; _workspace.DocumentClosed -= OnDocumentClosed; // cancel any pending blocks _shutdownNotificationSource.Cancel(); _documentAndProjectWorkerProcessor.Shutdown(); SolutionCrawlerLogger.LogWorkCoordiantorShutdown(_correlationId, _logAggregator); if (blockingShutdown) { var shutdownTask = Task.WhenAll( _eventProcessingQueue.LastScheduledTask, _documentAndProjectWorkerProcessor.AsyncProcessorTask, _semanticChangeProcessor.AsyncProcessorTask); shutdownTask.Wait(TimeSpan.FromSeconds(5)); if (!shutdownTask.IsCompleted) { SolutionCrawlerLogger.LogWorkCoordiantorShutdownTimeout(_correlationId); } } } private void OnOptionChanged(object sender, OptionChangedEventArgs e) { // if solution crawler got turned off or on. if (e.Option == SolutionCrawlerOptions.SolutionCrawler) { var value = (bool)e.Value; if (value) { _workspace.WorkspaceChanged += OnWorkspaceChanged; _workspace.DocumentOpened += OnDocumentOpened; _workspace.DocumentClosed += OnDocumentClosed; } else { _workspace.WorkspaceChanged -= OnWorkspaceChanged; _workspace.DocumentOpened -= OnDocumentOpened; _workspace.DocumentClosed -= OnDocumentClosed; } SolutionCrawlerLogger.LogOptionChanged(_correlationId, value); return; } ReanalyzeOnOptionChange(sender, e); } private void ReanalyzeOnOptionChange(object sender, OptionChangedEventArgs e) { // otherwise, let each analyzer decide what they want on option change ISet<DocumentId> set = null; foreach (var analyzer in _documentAndProjectWorkerProcessor.Analyzers) { if (analyzer.NeedsReanalysisOnOptionChanged(sender, e)) { set = set ?? _workspace.CurrentSolution.Projects.SelectMany(p => p.DocumentIds).ToSet(); this.Reanalyze(analyzer, set); } } } public void Reanalyze(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var asyncToken = _listener.BeginAsyncOperation("Reanalyze"); _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItem(analyzer, documentIds), _shutdownToken).CompletesAsyncOperation(asyncToken); SolutionCrawlerLogger.LogReanalyze(_correlationId, analyzer, documentIds); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs args) { // guard us from cancellation try { ProcessEvents(args, _listener.BeginAsyncOperation("OnWorkspaceChanged")); } catch (OperationCanceledException oce) { if (NotOurShutdownToken(oce)) { throw; } // it is our cancellation, ignore } catch (AggregateException ae) { ae = ae.Flatten(); // If we had a mix of exceptions, don't eat it if (ae.InnerExceptions.Any(e => !(e is OperationCanceledException)) || ae.InnerExceptions.Cast<OperationCanceledException>().Any(NotOurShutdownToken)) { // We had a cancellation with a different token, so don't eat it throw; } // it is our cancellation, ignore } } private bool NotOurShutdownToken(OperationCanceledException oce) { return oce.CancellationToken == _shutdownToken; } private void ProcessEvents(WorkspaceChangeEventArgs args, IAsyncToken asyncToken) { SolutionCrawlerLogger.LogWorkspaceEvent(_logAggregator, (int)args.Kind); // TODO: add telemetry that record how much it takes to process an event (max, min, average and etc) switch (args.Kind) { case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: case WorkspaceChangeKind.SolutionCleared: ProcessSolutionEvent(args, asyncToken); break; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: ProcessProjectEvent(args, asyncToken); break; case WorkspaceChangeKind.DocumentAdded: case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: case WorkspaceChangeKind.DocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: ProcessDocumentEvent(args, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnDocumentOpened(object sender, DocumentEventArgs e) { EnqueueWorkItem(e.Document, InvocationReasons.DocumentOpened); } private void OnDocumentClosed(object sender, DocumentEventArgs e) { EnqueueWorkItem(e.Document, InvocationReasons.DocumentClosed); } private void ProcessDocumentEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.DocumentAdded: EnqueueEvent(e.NewSolution, e.DocumentId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.DocumentRemoved: EnqueueEvent(e.OldSolution, e.DocumentId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.DocumentReloaded: case WorkspaceChangeKind.DocumentChanged: EnqueueEvent(e.OldSolution, e.NewSolution, e.DocumentId, asyncToken); break; case WorkspaceChangeKind.AdditionalDocumentAdded: case WorkspaceChangeKind.AdditionalDocumentRemoved: case WorkspaceChangeKind.AdditionalDocumentChanged: case WorkspaceChangeKind.AdditionalDocumentReloaded: // If an additional file has changed we need to reanalyze the entire project. EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.AdditionalDocumentChanged, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessProjectEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.ProjectAdded: OnProjectAdded(e.NewSolution.GetProject(e.ProjectId)); EnqueueEvent(e.NewSolution, e.ProjectId, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.ProjectRemoved: EnqueueEvent(e.OldSolution, e.ProjectId, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, e.ProjectId, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void ProcessSolutionEvent(WorkspaceChangeEventArgs e, IAsyncToken asyncToken) { switch (e.Kind) { case WorkspaceChangeKind.SolutionAdded: OnSolutionAdded(e.NewSolution); EnqueueEvent(e.NewSolution, InvocationReasons.DocumentAdded, asyncToken); break; case WorkspaceChangeKind.SolutionRemoved: EnqueueEvent(e.OldSolution, InvocationReasons.SolutionRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionCleared: EnqueueEvent(e.OldSolution, InvocationReasons.DocumentRemoved, asyncToken); break; case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionReloaded: EnqueueEvent(e.OldSolution, e.NewSolution, asyncToken); break; default: throw ExceptionUtilities.Unreachable; } } private void OnSolutionAdded(Solution solution) { var asyncToken = _listener.BeginAsyncOperation("OnSolutionAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(solution); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void OnProjectAdded(Project project) { var asyncToken = _listener.BeginAsyncOperation("OnProjectAdded"); _eventProcessingQueue.ScheduleTask(() => { var semanticVersionTrackingService = project.Solution.Workspace.Services.GetService<ISemanticVersionTrackingService>(); if (semanticVersionTrackingService != null) { semanticVersionTrackingService.LoadInitialSemanticVersions(project); } }, _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAsync(oldSolution, newSolution), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, InvocationReasons invocationReasons, IAsyncToken asyncToken) { var task = _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForSolution(solution, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, ProjectId projectId, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, projectId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, ProjectId projectId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForProject(solution, projectId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution solution, DocumentId documentId, InvocationReasons invocationReasons, IAsyncToken asyncToken) { _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemForDocument(solution, documentId, invocationReasons), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueEvent(Solution oldSolution, Solution newSolution, DocumentId documentId, IAsyncToken asyncToken) { // document changed event is the special one. _eventProcessingQueue.ScheduleTask( () => EnqueueWorkItemAfterDiffAsync(oldSolution, newSolution, documentId), _shutdownToken).CompletesAsyncOperation(asyncToken); } private void EnqueueWorkItem(Document document, InvocationReasons invocationReasons, SyntaxNode changedMember = null) { // we are shutting down _shutdownToken.ThrowIfCancellationRequested(); var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); var currentMember = GetSyntaxPath(changedMember); // call to this method is serialized. and only this method does the writing. _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(document.Id, document.Project.Language, invocationReasons, priorityService != null && priorityService.IsLowPriority(document), currentMember, _listener.BeginAsyncOperation("WorkItem"))); // enqueue semantic work planner if (invocationReasons.Contains(PredefinedInvocationReasons.SemanticChanged)) { // must use "Document" here so that the snapshot doesn't go away. we need the snapshot to calculate p2p dependency graph later. // due to this, we might hold onto solution (and things kept alive by it) little bit longer than usual. _semanticChangeProcessor.Enqueue(document, currentMember); } } private SyntaxPath GetSyntaxPath(SyntaxNode changedMember) { // using syntax path might be too expansive since it will be created on every keystroke. // but currently, we have no other way to track a node between two different tree (even for incrementally parsed one) if (changedMember == null) { return null; } return new SyntaxPath(changedMember); } private void EnqueueWorkItem(Project project, InvocationReasons invocationReasons) { foreach (var documentId in project.DocumentIds) { var document = project.GetDocument(documentId); EnqueueWorkItem(document, invocationReasons); } } private void EnqueueWorkItem(IIncrementalAnalyzer analyzer, IEnumerable<DocumentId> documentIds) { var solution = _workspace.CurrentSolution; foreach (var documentId in documentIds) { var document = solution.GetDocument(documentId); if (document == null) { continue; } var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>(); _documentAndProjectWorkerProcessor.Enqueue( new WorkItem(documentId, document.Project.Language, InvocationReasons.Reanalyze, priorityService != null && priorityService.IsLowPriority(document), analyzer, _listener.BeginAsyncOperation("WorkItem"))); } } private async Task EnqueueWorkItemAsync(Solution oldSolution, Solution newSolution) { var solutionChanges = newSolution.GetChanges(oldSolution); // TODO: Async version for GetXXX methods? foreach (var addedProject in solutionChanges.GetAddedProjects()) { EnqueueWorkItem(addedProject, InvocationReasons.DocumentAdded); } foreach (var projectChanges in solutionChanges.GetProjectChanges()) { await EnqueueWorkItemAsync(projectChanges).ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedProject in solutionChanges.GetRemovedProjects()) { EnqueueWorkItem(removedProject, InvocationReasons.DocumentRemoved); } } private async Task EnqueueWorkItemAsync(ProjectChanges projectChanges) { EnqueueProjectConfigurationChangeWorkItem(projectChanges); foreach (var addedDocumentId in projectChanges.GetAddedDocuments()) { EnqueueWorkItem(projectChanges.NewProject.GetDocument(addedDocumentId), InvocationReasons.DocumentAdded); } foreach (var changedDocumentId in projectChanges.GetChangedDocuments()) { await EnqueueWorkItemAsync(projectChanges.OldProject.GetDocument(changedDocumentId), projectChanges.NewProject.GetDocument(changedDocumentId)) .ConfigureAwait(continueOnCapturedContext: false); } foreach (var removedDocumentId in projectChanges.GetRemovedDocuments()) { EnqueueWorkItem(projectChanges.OldProject.GetDocument(removedDocumentId), InvocationReasons.DocumentRemoved); } } private void EnqueueProjectConfigurationChangeWorkItem(ProjectChanges projectChanges) { var oldProject = projectChanges.OldProject; var newProject = projectChanges.NewProject; // TODO: why solution changes return Project not ProjectId but ProjectChanges return DocumentId not Document? var projectConfigurationChange = InvocationReasons.Empty; if (!object.Equals(oldProject.ParseOptions, newProject.ParseOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectParseOptionChanged); } if (projectChanges.GetAddedMetadataReferences().Any() || projectChanges.GetAddedProjectReferences().Any() || projectChanges.GetAddedAnalyzerReferences().Any() || projectChanges.GetRemovedMetadataReferences().Any() || projectChanges.GetRemovedProjectReferences().Any() || projectChanges.GetRemovedAnalyzerReferences().Any() || !object.Equals(oldProject.CompilationOptions, newProject.CompilationOptions)) { projectConfigurationChange = projectConfigurationChange.With(InvocationReasons.ProjectConfigurationChanged); } if (!projectConfigurationChange.IsEmpty) { EnqueueWorkItem(projectChanges.NewProject, projectConfigurationChange); } } private async Task EnqueueWorkItemAsync(Document oldDocument, Document newDocument) { var differenceService = newDocument.GetLanguageService<IDocumentDifferenceService>(); if (differenceService != null) { var differenceResult = await differenceService.GetDifferenceAsync(oldDocument, newDocument, _shutdownToken).ConfigureAwait(false); if (differenceResult != null) { EnqueueWorkItem(newDocument, differenceResult.ChangeType, differenceResult.ChangedMember); } } } private void EnqueueWorkItemForDocument(Solution solution, DocumentId documentId, InvocationReasons invocationReasons) { var document = solution.GetDocument(documentId); EnqueueWorkItem(document, invocationReasons); } private void EnqueueWorkItemForProject(Solution solution, ProjectId projectId, InvocationReasons invocationReasons) { var project = solution.GetProject(projectId); EnqueueWorkItem(project, invocationReasons); } private void EnqueueWorkItemForSolution(Solution solution, InvocationReasons invocationReasons) { foreach (var projectId in solution.ProjectIds) { EnqueueWorkItemForProject(solution, projectId, invocationReasons); } } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, ProjectId projectId) { var oldProject = oldSolution.GetProject(projectId); var newProject = newSolution.GetProject(projectId); await EnqueueWorkItemAsync(newProject.GetChanges(oldProject)).ConfigureAwait(continueOnCapturedContext: false); } private async Task EnqueueWorkItemAfterDiffAsync(Solution oldSolution, Solution newSolution, DocumentId documentId) { var oldProject = oldSolution.GetProject(documentId.ProjectId); var newProject = newSolution.GetProject(documentId.ProjectId); await EnqueueWorkItemAsync(oldProject.GetDocument(documentId), newProject.GetDocument(documentId)).ConfigureAwait(continueOnCapturedContext: false); } internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> workers) { var solution = _workspace.CurrentSolution; var list = new List<WorkItem>(); foreach (var project in solution.Projects) { foreach (var document in project.Documents) { list.Add( new WorkItem(document.Id, document.Project.Language, InvocationReasons.DocumentAdded, false, _listener.BeginAsyncOperation("WorkItem"))); } } _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(workers, list); } internal void WaitUntilCompletion_ForTestingPurposesOnly() { _documentAndProjectWorkerProcessor.WaitUntilCompletion_ForTestingPurposesOnly(); } } } }
using System; using System.Runtime.InteropServices; using System.Security; using System.IO; using SFML.Window; using SFML.Graphics; using Vector3f = SFML.Graphics.Vector3; namespace SFML { namespace Audio { //////////////////////////////////////////////////////////// /// <summary> /// Music defines a big sound played using streaming, /// so usually what we call a music :) /// </summary> //////////////////////////////////////////////////////////// public class Music : ObjectBase { //////////////////////////////////////////////////////////// /// <summary> /// Construct the music from a file /// </summary> /// <param name="filename">Path of the music file to load</param> //////////////////////////////////////////////////////////// public Music(string filename) : base(sfMusic_createFromFile(filename)) { if (CPointer == IntPtr.Zero) throw new LoadingFailedException("music", filename); } //////////////////////////////////////////////////////////// /// <summary> /// Construct the music from a custom stream /// </summary> /// <param name="stream">Source stream to read from</param> //////////////////////////////////////////////////////////// public Music(Stream stream) : base(IntPtr.Zero) { myStream = new StreamAdaptor(stream); SetThis(sfMusic_createFromStream(myStream.InputStreamPtr)); if (CPointer == IntPtr.Zero) throw new LoadingFailedException("music"); } //////////////////////////////////////////////////////////// /// <summary> /// Play the music /// </summary> //////////////////////////////////////////////////////////// public void Play() { sfMusic_play(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Pause the music /// </summary> //////////////////////////////////////////////////////////// public void Pause() { sfMusic_pause(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Stop the music /// </summary> //////////////////////////////////////////////////////////// public void Stop() { sfMusic_stop(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Samples rate, in samples per second /// </summary> //////////////////////////////////////////////////////////// public uint SampleRate { get { return sfMusic_getSampleRate(CPointer); } } //////////////////////////////////////////////////////////// /// <summary> /// Number of channels (1 = mono, 2 = stereo) /// </summary> //////////////////////////////////////////////////////////// public uint ChannelCount { get { return sfMusic_getChannelCount(CPointer); } } //////////////////////////////////////////////////////////// /// <summary> /// Current status of the music (see SoundStatus enum) /// </summary> //////////////////////////////////////////////////////////// public SoundStatus Status { get { return sfMusic_getStatus(CPointer); } } //////////////////////////////////////////////////////////// /// <summary> /// Total duration of the music /// </summary> //////////////////////////////////////////////////////////// public TimeSpan Duration { get { long microseconds = sfMusic_getDuration(CPointer); return TimeSpan.FromTicks(microseconds * TimeSpan.TicksPerMillisecond / 1000); } } //////////////////////////////////////////////////////////// /// <summary> /// Loop state of the sound. Default value is false /// </summary> //////////////////////////////////////////////////////////// public bool Loop { get { return sfMusic_getLoop(CPointer); } set { sfMusic_setLoop(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Pitch of the music. Default value is 1 /// </summary> //////////////////////////////////////////////////////////// public float Pitch { get { return sfMusic_getPitch(CPointer); } set { sfMusic_setPitch(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Volume of the music, in range [0, 100]. Default value is 100 /// </summary> //////////////////////////////////////////////////////////// public float Volume { get { return sfMusic_getVolume(CPointer); } set { sfMusic_setVolume(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// 3D position of the music. Default value is (0, 0, 0) /// </summary> //////////////////////////////////////////////////////////// public Vector3f Position { get { return sfMusic_getPosition(CPointer); ;} set { sfMusic_setPosition(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Is the music's position relative to the listener's position, /// or is it absolute? /// Default value is false (absolute) /// </summary> //////////////////////////////////////////////////////////// public bool RelativeToListener { get { return sfMusic_isRelativeToListener(CPointer); } set { sfMusic_setRelativeToListener(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Minimum distance of the music. Closer than this distance, /// the listener will hear the sound at its maximum volume. /// The default value is 1 /// </summary> //////////////////////////////////////////////////////////// public float MinDistance { get { return sfMusic_getMinDistance(CPointer); } set { sfMusic_setMinDistance(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Attenuation factor. The higher the attenuation, the /// more the sound will be attenuated with distance from listener. /// The default value is 1 /// </summary> //////////////////////////////////////////////////////////// public float Attenuation { get { return sfMusic_getAttenuation(CPointer); } set { sfMusic_setAttenuation(CPointer, value); } } //////////////////////////////////////////////////////////// /// <summary> /// Current playing position /// </summary> //////////////////////////////////////////////////////////// public TimeSpan PlayingOffset { get { long microseconds = sfMusic_getPlayingOffset(CPointer); return TimeSpan.FromTicks(microseconds * TimeSpan.TicksPerMillisecond / 1000); } set { long microseconds = value.Ticks / (TimeSpan.TicksPerMillisecond / 1000); sfMusic_setPlayingOffset(CPointer, microseconds); } } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[Music]" + " SampleRate(" + SampleRate + ")" + " ChannelCount(" + ChannelCount + ")" + " Status(" + Status + ")" + " Duration(" + Duration + ")" + " Loop(" + Loop + ")" + " Pitch(" + Pitch + ")" + " Volume(" + Volume + ")" + " Position(" + Position + ")" + " RelativeToListener(" + RelativeToListener + ")" + " MinDistance(" + MinDistance + ")" + " Attenuation(" + Attenuation + ")" + " PlayingOffset(" + PlayingOffset + ")"; } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { if (disposing) { if (myStream != null) myStream.Dispose(); } sfMusic_destroy(CPointer); } private StreamAdaptor myStream = null; #region Imports [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfMusic_createFromFile(string Filename); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] unsafe static extern IntPtr sfMusic_createFromStream(IntPtr stream); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_destroy(IntPtr MusicStream); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_play(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_pause(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_stop(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern SoundStatus sfMusic_getStatus(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern long sfMusic_getDuration(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfMusic_getChannelCount(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern uint sfMusic_getSampleRate(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setPitch(IntPtr Music, float Pitch); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setLoop(IntPtr Music, bool Loop); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setVolume(IntPtr Music, float Volume); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setPosition(IntPtr Music, Vector3f position); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setRelativeToListener(IntPtr Music, bool Relative); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setMinDistance(IntPtr Music, float MinDistance); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setAttenuation(IntPtr Music, float Attenuation); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfMusic_setPlayingOffset(IntPtr Music, long TimeOffset); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfMusic_getLoop(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfMusic_getPitch(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfMusic_getVolume(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern Vector3f sfMusic_getPosition(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfMusic_isRelativeToListener(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfMusic_getMinDistance(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern float sfMusic_getAttenuation(IntPtr Music); [DllImport("csfml-audio-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern long sfMusic_getPlayingOffset(IntPtr Music); #endregion } } }
using System; using System.Drawing; using System.Media; using System.IO.Ports; using System.Threading; using System.Collections; namespace Bipedal5Link { public struct PointD { public double X; public double Y; public PointD(double x, double y) { X = x; Y = y; } public static PointD operator +(PointD p1, PointD p2) { return new PointD(p1.X + p2.X, p1.Y + p2.Y); } public static PointD operator -(PointD p1, PointD p2) { return new PointD(p1.X - p2.X, p1.Y - p2.Y); } public static PointD operator *(PointD p1, double s) { return new PointD(p1.X * s, p1.Y * s); } public static PointD operator /(PointD p1, double s) { return new PointD(p1.X / s, p1.Y / s); } public static PointD Middle(PointD p1, PointD p2) { return new PointD((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2); } public static PointD FromPoint(PointD p1, double angle, double length) { return new PointD(p1.X + Math.Cos(angle) * length, p1.Y + Math.Sin(angle) * length); } public double Distance(PointD p) { return Math.Sqrt(Math.Pow(this.X - p.X, 2) + Math.Pow(this.Y - p.Y, 2)); } } public class Bipedal5Link { public delegate double YGroundDelegate(double x); private double[] Theta; private PointD[] P; private bool ROnGround; private bool LOnGround; private PointD RZero; private PointD LZero; private double[] F; private double Torque; private double I; private PointD CenterOfMass; private PointD Velocity; private PointD Acceleration; private double AngularVelocity; private double AngularAcceleration; private double[] Joints; private double M; private double M1; private double M2; private double G; private double KGX; private double KGY; private double BGX; private double BGY; private double L1; private double L2; private double ServoSpeed; private YGroundDelegate YGround; private bool HipFix; private double M1PlusM2; private double M1PlusM2TimesTwo; private double MTotal; private double PiOverTwo; private double PiOverFour; private double ThreePiOverTwo; private double StableUpperLimit; private double[] Feedback; private Pen PenLeft; private Brush BrushLeft; private Pen PenRight; private Brush BrushRight; private Pen PenGround; private ArrayList LSteps; private ArrayList RSteps; private SoundPlayer S; public Bipedal5Link(double m, double m1, double m2, double l1, double l2, double kg, double bg, double g, PointD hip, double[] theta, double servoSpeed, YGroundDelegate yGround) { M = m; M1 = m1; M2 = m2; G = g; KGX = kg; KGY = KGX * 10; BGX = bg; BGY = BGX * 10; YGround = yGround; L1 = l1; L2 = l2; F = new double[5]; Torque = 0; I = 1; Velocity = new PointD(0, 0); Acceleration = new PointD(0, 0); AngularVelocity = 0; AngularAcceleration = 0; Joints = new double[5]; ServoSpeed = servoSpeed; Theta = new double[theta.Length]; Array.Copy(theta, Theta, theta.Length); RZero = new PointD(0, 0); LZero = new PointD(0, 0); HipFix = false; Feedback = new double[9]; P = new PointD[5]; P[0] = hip; P[1] = PointD.FromPoint(P[0], Theta[0] - Theta[1], L1); P[2] = PointD.FromPoint(P[0], Theta[0] - Theta[2], L1); P[3] = PointD.FromPoint(P[1], Theta[0] - Theta[1] - Theta[3], L2); P[4] = PointD.FromPoint(P[2], Theta[0] - Theta[2] - Theta[4], L2); M1PlusM2 = M1 + M2; M1PlusM2TimesTwo = M1PlusM2 * 2; MTotal = M + 2 * M1 + 2 * M2; PiOverTwo = Math.PI / 2; PiOverFour = Math.PI / 4; ThreePiOverTwo = 3 * Math.PI / 2; StableUpperLimit = 1.3 * (L1 + L2); UpdateCenterOfMass(); PenLeft = new Pen(Brushes.DarkOrange, 3); BrushLeft = new SolidBrush(Color.DarkOrange); PenRight = new Pen(Brushes.Yellow, 3); BrushRight = new SolidBrush(Color.Yellow); PenGround = new Pen(Brushes.SaddleBrown, 2); LSteps = new ArrayList(100); RSteps = new ArrayList(100); System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); S = new SoundPlayer(a.GetManifestResourceStream("Bipedal5Link.step.wav")); } public double[] RunStep(double[] joints, double deltaTime) { Joints = joints; double j; j = Math.Min(Math.Max(joints[1], -1), 1) * ServoSpeed; Theta[1] += j * deltaTime; Theta[1] = Math.Min(Math.Max(Theta[1], PiOverTwo), ThreePiOverTwo); j = Math.Min(Math.Max(joints[2], -1), 1) * ServoSpeed; Theta[2] += j * deltaTime; Theta[2] = Math.Min(Math.Max(Theta[2], PiOverTwo), ThreePiOverTwo); j = Math.Min(Math.Max(joints[3], -1), 1) * ServoSpeed; Theta[3] += j * deltaTime; Theta[3] = Math.Min(Math.Max(Theta[3], 0), PiOverTwo); j = Math.Min(Math.Max(joints[4], -1), 1) * ServoSpeed; Theta[4] += j * deltaTime; Theta[4] = Math.Min(Math.Max(Theta[4], 0), PiOverTwo); // // Position propagation (top - down) // j = Theta[0] - Theta[1]; P[1] = PointD.FromPoint(P[0], j, L1); P[3] = PointD.FromPoint(P[1], j - Theta[3], L2); j = Theta[0] - Theta[2]; P[2] = PointD.FromPoint(P[0], j, L1); P[4] = PointD.FromPoint(P[2], j - Theta[4], L2); if (ROnGround) { if (P[3].Y > YGround(P[3].X)) ROnGround = false; } else { if (P[3].Y <= YGround(P[3].X)) { RZero = P[3]; ROnGround = true; //if (sound) // S.Play(); } } if (LOnGround) { if (P[4].Y > YGround(P[4].X)) LOnGround = false; } else { if (P[4].Y <= YGround(P[4].X)) { LZero = P[4]; LOnGround = true; //if (sound) // S.Play(); } } // // Force propagation (bottom - up) // if (ROnGround) { F[1] = -KGX * (P[3].X - RZero.X); F[2] = -KGY * (P[3].Y - RZero.Y); } else { F[1] = 0; F[2] = 0; } if (LOnGround) { F[3] = -KGX * (P[4].X - LZero.X); F[4] = -KGY * (P[4].Y - LZero.Y); } else { F[3] = 0; F[4] = 0; } // // Update accelerations & velocities & positions // UpdateCenterOfMass(); if (LOnGround || ROnGround) { if (ROnGround) { I = MTotal * Math.Pow(CenterOfMass.Distance(RZero), 2); } else { I = MTotal * Math.Pow(CenterOfMass.Distance(LZero), 2); } Torque = (P[3].X - CenterOfMass.X) * F[2] + (CenterOfMass.Y - P[3].Y) * F[1] + (P[4].X - CenterOfMass.X) * F[4] + (CenterOfMass.Y - P[4].Y) * F[3]; AngularAcceleration = Torque / I; AngularVelocity += AngularAcceleration * deltaTime; } Theta[0] += AngularVelocity * deltaTime; Acceleration.X = (F[1] + F[3]) / MTotal; Acceleration.Y = (F[2] + F[4]) / MTotal - G; if (!HipFix) P[0] += Velocity * deltaTime; Velocity += Acceleration * deltaTime; //Stabilize Velocity *= 0.9999; AngularVelocity *= 0.9999; //Hardware //UpdateHardware(); //Feedback double theta1v = PiOverTwo + (Theta[0] - Theta[1]); double theta2v = PiOverTwo + (Theta[0] - Theta[2]); double theta3v = PiOverTwo + (Theta[0] - Theta[1] - Theta[3]); double theta4v = PiOverTwo + (Theta[0] - Theta[2] - Theta[4]); Feedback[1] = theta1v; Feedback[2] = theta2v; Feedback[3] = theta3v; Feedback[4] = theta4v; if (ROnGround) Feedback[5] = 1; else Feedback[5] = 0; if (LOnGround) Feedback[6] = 1; else Feedback[6] = 0; return Feedback; } private void UpdateCenterOfMass() { PointD comr = (PointD.Middle(P[0], P[1]) * M1 + PointD.Middle(P[1], P[3]) * M2) / M1PlusM2; PointD coml = (PointD.Middle(P[0], P[2]) * M1 + PointD.Middle(P[2], P[4]) * M2) / M1PlusM2; CenterOfMass = (PointD.Middle(coml, comr) * M1PlusM2TimesTwo + P[0] * M) / MTotal; } public bool IsStable() { double ground = YGround(P[0].X); //return (P[0].Y > P[1].Y) && (P[0].Y > P[2].Y) && (P[0].Y > ground) && (P[0].Y < ground + StableUpperLimit); //return (P[0].Y > P[1].Y) && (P[0].Y > P[2].Y) && (P[0].Y > ground) && (P[0].Y < ground + StableUpperLimit); //return (P[0].Y > ground) && (P[1].Y > ground) && (P[2].Y > ground) && (P[0].Y < ground + StableUpperLimit); return (P[0].Y > ground) && (P[1].Y > ground) && (P[2].Y > ground); //return (P[0].Y > P[1].Y) && (P[0].Y > P[2].Y); //return (P[0].Y > ground); } public PointD BehindPosition() { int b = 0; for (int i = 1 ; i < 5 ; i++) if (P[i].X < P[b].X) b = i; return P[b]; } public PointD ForemostPosition() { int b = 0; for (int i = 1 ; i < 5 ; i++) if (P[i].X > P[b].X) b = i; return P[b]; } public double Theta1 { get { return Theta[1]; } } public double Theta2 { get { return Theta[2]; } } public PointD HipPosition { get { return P[0]; } } public bool HipFixed { get { return HipFix; } set { HipFix = value; } } public bool LeftFootOnTheGround { get { return LOnGround; } } public bool RightFootOnTheGround { get { return ROnGround; } } public void Draw(Graphics g, PointF p, float scale) { PointF g1 = new PointF(p.X, p.Y - (float)YGround(0) * scale); PointF g2; for (float x = 100 ; x < 1500 ; x += 100) { g2 = new PointF(p.X + x * scale, p.Y - (float)YGround(x) * scale); g.DrawLine(PenGround, g1, g2); g1 = g2; } PointF hip = new PointF(p.X + (float)P[0].X * scale, p.Y - (float)P[0].Y * scale); PointF kneel = new PointF(p.X + (float)P[2].X * scale, p.Y - (float)P[2].Y * scale); PointF kneer = new PointF(p.X + (float)P[1].X * scale, p.Y - (float)P[1].Y * scale); PointF anklel = new PointF(p.X + (float)P[4].X * scale, p.Y - (float)P[4].Y * scale); PointF ankler = new PointF(p.X + (float)P[3].X * scale, p.Y - (float)P[3].Y * scale); PointF centerofmass = new PointF(p.X + (float)CenterOfMass.X * scale, p.Y - (float)CenterOfMass.Y * scale); PointD h = PointD.FromPoint(P[0], Theta[0], 0.07); PointF head = new PointF(p.X + (float)h.X * scale, p.Y - (float)h.Y * scale); g.FillEllipse(Brushes.Blue, centerofmass.X - 3, centerofmass.Y - 3, 6, 6); g.DrawLine(PenGround, hip, head); g.DrawLine(PenLeft, hip, kneel); g.DrawLine(PenLeft, kneel, anklel); g.FillEllipse(BrushLeft, kneel.X - 5, kneel.Y - 5, 10, 10); g.FillEllipse(BrushRight, hip.X - 5, hip.Y - 5, 10, 10); g.DrawLine(PenRight, hip, kneer); g.DrawLine(PenRight, kneer, ankler); g.FillEllipse(BrushRight, kneer.X - 5, kneer.Y - 5, 10, 10); if (HipFix) g.DrawEllipse(PenRight, hip.X - 8, hip.Y - 8, 16, 16); if (LOnGround) LSteps.Add(new RectangleF(anklel.X, p.Y + 3, 1, 1)); if (ROnGround) RSteps.Add(new RectangleF(ankler.X, p.Y + 6, 1, 1)); RectangleF[] ls = new RectangleF[LSteps.Count]; LSteps.CopyTo(ls); if (ls.Length > 0) g.FillRectangles(BrushLeft, ls); RectangleF[] rs = new RectangleF[RSteps.Count]; RSteps.CopyTo(rs); if (rs.Length > 0) g.FillRectangles(BrushRight, rs); } public string Parameters() { string ret = "musculo - skeletal system parameters" + Environment.NewLine; ret += "M = " + M.ToString("f3") + " kg" + Environment.NewLine; ret += "m1 = " + M1.ToString("f3") + " kg" + Environment.NewLine; ret += "l1 = " + L1.ToString("f3") + " m" + Environment.NewLine; ret += "m2 = " + M2.ToString("f3") + " kg" + Environment.NewLine; ret += "l2 = " + L2.ToString("f3") + " m" + Environment.NewLine; ret += "kgx = " + KGX.ToString("f3") + Environment.NewLine; ret += "kgy = " + KGY.ToString("f3") + Environment.NewLine; ret += "g = " + G.ToString("f3") + " kg m / s2" + Environment.NewLine; return ret; } public string Status() { string ret = "musculo - skeletal system status" + Environment.NewLine; for (int i = 0 ; i < 5 ; i++) ret += "(P" + i.ToString() + ".X, P" + i.ToString() + ".Y) = (" + P[i].X.ToString("f3") + " m, " + P[i].Y.ToString("f3") + " m)" + Environment.NewLine; ret += "Torque = " + Torque.ToString("f3") + " Nm" + Environment.NewLine; ret += "I = " + I.ToString("f3") + " kgm2" + Environment.NewLine; ret += "Velocity = (" + Velocity.X.ToString("f3") + " m/s, " + Velocity.Y.ToString("f3") + " m/s)" + Environment.NewLine; ret += "AngularVelocity = " + AngularVelocity.ToString("f3") + " radian/s" + Environment.NewLine; if (LOnGround) ret += "left foot on the ground" + Environment.NewLine; else ret += "left foot above the ground" + Environment.NewLine; if (ROnGround) ret += "right foot on the ground" + Environment.NewLine; else ret += "right foot above the ground" + Environment.NewLine; return ret; } } public class Bipedal5LinkHardware { private double[] Theta; private PointD[] P; private bool ROnGround; private bool LOnGround; private double[] Joints; private double M; private double M1; private double M2; private double L1; private double L2; private double ServoSpeed; private bool HipFix; private double M1PlusM2; private double M1PlusM2TimesTwo; private double MTotal; private PointD CenterOfMass; private double PiOverTwo; private double PiOverFour; private double ThreePiOverTwo; private double[] Feedback; private Pen PenLeft; private Brush BrushLeft; private Pen PenRight; private Brush BrushRight; private Pen PenGround; private ArrayList LSteps; private ArrayList RSteps; private SoundPlayer S; private ServoController Hardware; public Bipedal5LinkHardware(double m, double m1, double m2, double l1, double l2, PointD hip, double[] theta, double servoSpeed, ServoController hardware) { M = m; M1 = m1; M2 = m2; L1 = l1; L2 = l2; Joints = new double[5]; ServoSpeed = servoSpeed; Theta = new double[theta.Length]; Array.Copy(theta, Theta, theta.Length); Feedback = new double[9]; P = new PointD[5]; P[0] = hip; P[1] = PointD.FromPoint(P[0], Theta[0] - Theta[1], L1); P[2] = PointD.FromPoint(P[0], Theta[0] - Theta[2], L1); P[3] = PointD.FromPoint(P[1], Theta[0] - Theta[1] - Theta[3], L2); P[4] = PointD.FromPoint(P[2], Theta[0] - Theta[2] - Theta[4], L2); M1PlusM2 = M1 + M2; M1PlusM2TimesTwo = M1PlusM2 * 2; MTotal = M + 2 * M1 + 2 * M2; PiOverTwo = Math.PI / 2; PiOverFour = Math.PI / 4; ThreePiOverTwo = 3 * Math.PI / 2; UpdateCenterOfMass(); PenLeft = new Pen(Brushes.DarkOrange, 3); BrushLeft = new SolidBrush(Color.DarkOrange); PenRight = new Pen(Brushes.Yellow, 3); BrushRight = new SolidBrush(Color.Yellow); PenGround = new Pen(Brushes.SaddleBrown, 2); LSteps = new ArrayList(100); RSteps = new ArrayList(100); System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); S = new SoundPlayer(a.GetManifestResourceStream("Bipedal5Link.step.wav")); Hardware = hardware; } public double[] RunStep(double[] joints, double deltaTime) { Joints = joints; double j; j = Math.Min(Math.Max(joints[1], -1), 1) * ServoSpeed; Theta[1] += j * deltaTime; Theta[1] = Math.Min(Math.Max(Theta[1], PiOverTwo), ThreePiOverTwo); j = Math.Min(Math.Max(joints[2], -1), 1) * ServoSpeed; Theta[2] += j * deltaTime; Theta[2] = Math.Min(Math.Max(Theta[2], PiOverTwo), ThreePiOverTwo); j = Math.Min(Math.Max(joints[3], -1), 1) * ServoSpeed; Theta[3] += j * deltaTime; Theta[3] = Math.Min(Math.Max(Theta[3], 0), PiOverTwo); j = Math.Min(Math.Max(joints[4], -1), 1) * ServoSpeed; Theta[4] += j * deltaTime; Theta[4] = Math.Min(Math.Max(Theta[4], 0), PiOverTwo); // // Position propagation (top - down) // j = Theta[0] - Theta[1]; P[1] = PointD.FromPoint(P[0], j, L1); P[3] = PointD.FromPoint(P[1], j - Theta[3], L2); j = Theta[0] - Theta[2]; P[2] = PointD.FromPoint(P[0], j, L1); P[4] = PointD.FromPoint(P[2], j - Theta[4], L2); UpdateCenterOfMass(); //Feedback Feedback[1] = Theta[1] - Math.PI; Feedback[2] = Theta[2] - Math.PI; //Feedback[3] = Theta[3] - PiOverFour; //Feedback[4] = Theta[4] - PiOverFour; return Feedback; } private void UpdateCenterOfMass() { PointD comr = (PointD.Middle(P[0], P[1]) * M1 + PointD.Middle(P[1], P[3]) * M2) / M1PlusM2; PointD coml = (PointD.Middle(P[0], P[2]) * M1 + PointD.Middle(P[2], P[4]) * M2) / M1PlusM2; CenterOfMass = (PointD.Middle(coml, comr) * M1PlusM2TimesTwo + P[0] * M) / MTotal; } public double Theta1 { get { return Theta[1]; } } public double Theta2 { get { return Theta[2]; } } public PointD HipPosition { get { return P[0]; } } public bool LeftFootOnTheGround { get { return LOnGround; } } public bool RightFootOnTheGround { get { return ROnGround; } } public void UpdateHardware() { if (Hardware != null) { byte j0 = (byte)Math.Min(((Theta[1] - PiOverTwo) / Math.PI) * 225, 225); byte j1 = (byte)Math.Min(225 - ((Theta[2] - PiOverTwo) / Math.PI) * 225, 225); byte j2 = (byte)Math.Min(112 - (Theta[3] / Math.PI) * 225, 225); byte j3 = (byte)Math.Min((Theta[4] / Math.PI) * 225, 225); Hardware.SetPositions(new byte[] { j0, j1, j2, j3 }); //Hardware.SetPosition(0, (byte)(((Theta[1] - PiOverTwo) / Math.PI) * 225)); //Hardware.SetPosition(1, (byte)(225 - ((Theta[2] - PiOverTwo) / Math.PI) * 225)); //Hardware.SetPosition(2, (byte)(112 - (Theta[3] / Math.PI) * 225)); //Hardware.SetPosition(3, (byte)((Theta[4] / Math.PI) * 225)); } } public void Draw(Graphics g, PointF p, float scale) { PointF hip = new PointF(p.X + (float)P[0].X * scale, p.Y - (float)P[0].Y * scale); PointF kneel = new PointF(p.X + (float)P[2].X * scale, p.Y - (float)P[2].Y * scale); PointF kneer = new PointF(p.X + (float)P[1].X * scale, p.Y - (float)P[1].Y * scale); PointF anklel = new PointF(p.X + (float)P[4].X * scale, p.Y - (float)P[4].Y * scale); PointF ankler = new PointF(p.X + (float)P[3].X * scale, p.Y - (float)P[3].Y * scale); PointF centerofmass = new PointF(p.X + (float)CenterOfMass.X * scale, p.Y - (float)CenterOfMass.Y * scale); PointD h = PointD.FromPoint(P[0], Theta[0], 0.07); PointF head = new PointF(p.X + (float)h.X * scale, p.Y - (float)h.Y * scale); g.FillEllipse(Brushes.Blue, centerofmass.X - 3, centerofmass.Y - 3, 6, 6); g.DrawLine(PenGround, hip, head); g.DrawLine(PenLeft, hip, kneel); g.DrawLine(PenLeft, kneel, anklel); g.FillEllipse(BrushLeft, kneel.X - 5, kneel.Y - 5, 10, 10); g.FillEllipse(BrushRight, hip.X - 5, hip.Y - 5, 10, 10); g.DrawLine(PenRight, hip, kneer); g.DrawLine(PenRight, kneer, ankler); g.FillEllipse(BrushRight, kneer.X - 5, kneer.Y - 5, 10, 10); if (HipFix) g.DrawEllipse(PenRight, hip.X - 8, hip.Y - 8, 16, 16); if (LOnGround) LSteps.Add(new RectangleF(anklel.X, p.Y + 3, 1, 1)); if (ROnGround) RSteps.Add(new RectangleF(ankler.X, p.Y + 6, 1, 1)); RectangleF[] ls = new RectangleF[LSteps.Count]; LSteps.CopyTo(ls); if (ls.Length > 0) g.FillRectangles(BrushLeft, ls); RectangleF[] rs = new RectangleF[RSteps.Count]; RSteps.CopyTo(rs); if (rs.Length > 0) g.FillRectangles(BrushRight, rs); } public string Parameters() { string ret = "musculo - skeletal system parameters" + Environment.NewLine; ret += "M = " + M.ToString("f3") + " kg" + Environment.NewLine; ret += "m1 = " + M1.ToString("f3") + " kg" + Environment.NewLine; ret += "l1 = " + L1.ToString("f3") + " m" + Environment.NewLine; ret += "m2 = " + M2.ToString("f3") + " kg" + Environment.NewLine; ret += "l2 = " + L2.ToString("f3") + " m" + Environment.NewLine; return ret; } public string Status() { string ret = "musculo - skeletal system status" + Environment.NewLine; for (int i = 0 ; i < 5 ; i++) ret += "(P" + i.ToString() + ".X, P" + i.ToString() + ".Y) = (" + P[i].X.ToString("f3") + " m, " + P[i].Y.ToString("f3") + " m)" + Environment.NewLine; if (LOnGround) ret += "left foot on the ground" + Environment.NewLine; else ret += "left foot above the ground" + Environment.NewLine; if (ROnGround) ret += "right foot on the ground" + Environment.NewLine; else ret += "right foot above the ground" + Environment.NewLine; return ret; } } public class CPGNeuron { public double TauU; public double TauV; public double Beta; public double U; public double V; public double Y; public CPGNeuron(double tauU, double tauV, double beta) { TauU = tauU; TauV = tauV; Beta = beta; Random rnd = new Random(); U = 0; V = 0; Y = 0; } public double RunStep(double activation, double u0, double feedback, double deltaTime) { double d = -U - Beta * V + activation + u0 + feedback; U += deltaTime * (d / TauU); V += deltaTime * (-V + Y) / TauV; Y = Math.Max(0, U); return Y; } } public class CentralPatternGenerator { private CPGNeuron[] Neuron; private double[,] Weights; private PointF[] DrawingCoordinates; private Font F1; public CentralPatternGenerator(double hipTauU, double hipTauV, double hipBeta, double kneeTauU, double kneeTauV, double kneeBeta, double wFlexorExtensor, double wHipKnee, double wLeftRight) { Neuron = new CPGNeuron[9]; Weights = new double[9, 9]; Weights[1, 2] = wFlexorExtensor; Weights[2, 1] = wFlexorExtensor; Weights[3, 4] = wFlexorExtensor; Weights[4, 3] = wFlexorExtensor; Weights[5, 6] = wFlexorExtensor; Weights[6, 5] = wFlexorExtensor; Weights[7, 8] = wFlexorExtensor; Weights[8, 7] = wFlexorExtensor; Weights[1, 3] = wLeftRight; Weights[3, 1] = wLeftRight; Weights[2, 4] = wLeftRight; Weights[4, 2] = wLeftRight; Weights[5, 2] = wHipKnee; Weights[6, 1] = wHipKnee; Weights[7, 4] = wHipKnee; Weights[8, 3] = wHipKnee; Neuron[1] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[1].U = 0.1; Neuron[2] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[5] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); Neuron[6] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); Neuron[3] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[4] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[7] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); Neuron[8] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); DrawingCoordinates = new PointF[9]; DrawingCoordinates[1] = new PointF(175, 30); DrawingCoordinates[2] = new PointF(200, 70); DrawingCoordinates[5] = new PointF(175, 160); DrawingCoordinates[6] = new PointF(200, 200); DrawingCoordinates[3] = new PointF(50, 30); DrawingCoordinates[4] = new PointF(25, 70); DrawingCoordinates[7] = new PointF(50, 160); DrawingCoordinates[8] = new PointF(25, 200); F1 = new Font("Arial", 8); } public CentralPatternGenerator(double hipTauU, double hipTauV, double hipBeta, double kneeTauU, double kneeTauV, double kneeBeta, double[,] weights) { Neuron = new CPGNeuron[9]; Weights = weights; Neuron[1] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[1].U = 0.1; Neuron[2] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[5] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); Neuron[6] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); Neuron[3] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[4] = new CPGNeuron(hipTauU, hipTauV, hipBeta); Neuron[7] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); Neuron[8] = new CPGNeuron(kneeTauU, kneeTauV, kneeBeta); DrawingCoordinates = new PointF[9]; DrawingCoordinates[1] = new PointF(175, 30); DrawingCoordinates[2] = new PointF(200, 70); DrawingCoordinates[5] = new PointF(175, 160); DrawingCoordinates[6] = new PointF(200, 200); DrawingCoordinates[3] = new PointF(50, 30); DrawingCoordinates[4] = new PointF(25, 70); DrawingCoordinates[7] = new PointF(50, 160); DrawingCoordinates[8] = new PointF(25, 200); F1 = new Font("Arial", 8); } public string Parameters() { string ret = "central pattern generator parameters" + Environment.NewLine; ret += "hTauU = " + Neuron[1].TauU.ToString("f3") + Environment.NewLine; ret += "hTauV = " + Neuron[1].TauV.ToString("f3") + Environment.NewLine; ret += "hBeta = " + Neuron[1].Beta.ToString("f3") + Environment.NewLine; ret += "kTauU = " + Neuron[5].TauU.ToString("f3") + Environment.NewLine; ret += "kTauV = " + Neuron[5].TauV.ToString("f3") + Environment.NewLine; ret += "kBeta = " + Neuron[5].Beta.ToString("f3") + Environment.NewLine; return ret; } public string Status() { string ret = "central pattern generator status" + Environment.NewLine; ret += "right hip flexor y = " + Neuron[1].Y.ToString("f3") + Environment.NewLine; ret += "right hip extensor y = " + Neuron[2].Y.ToString("f3") + Environment.NewLine; ret += "left hip flexor y = " + Neuron[3].Y.ToString("f3") + Environment.NewLine; ret += "left hip extensor y = " + Neuron[4].Y.ToString("f3") + Environment.NewLine; ret += "right knee flexor y = " + Neuron[5].Y.ToString("f3") + Environment.NewLine; ret += "right knee extensor y = " + Neuron[6].Y.ToString("f3") + Environment.NewLine; ret += "left knee flexor y = " + Neuron[7].Y.ToString("f3") + Environment.NewLine; ret += "left knee extensor y = " + Neuron[8].Y.ToString("f3") + Environment.NewLine; return ret; } public double[] RunStep(double u0, double[] feedback, double deltaTime) { double[] y = new double[9]; for (int i = 1 ; i < 9 ; i++) y[i] = Neuron[i].Y; double activation; for (int i = 1 ; i < 9 ; i++) { activation = 0; for (int j = 1 ; j < 9 ; j++) activation += Weights[i, j] * y[j]; Neuron[i].RunStep(activation, u0, feedback[i], deltaTime); } double[] ret = new double[5]; ret[1] = - Neuron[1].Y + Neuron[2].Y; ret[2] = - Neuron[3].Y + Neuron[4].Y; ret[3] = Neuron[5].Y - Neuron[6].Y; ret[4] = Neuron[7].Y - Neuron[8].Y; return ret; } public void Draw(Graphics g) { for (int i = 1 ; i < 9 ; i++) for (int j = 1 ; j < 9 ; j++) { if (Weights[i, j] != 0) g.DrawLine(Pens.SaddleBrown, DrawingCoordinates[j], DrawingCoordinates[i]); } double u; int c; Brush b = Brushes.Blue; for (int i = 1 ; i < 9 ; i++) { u = Math.Max(Math.Min(Neuron[i].U, 0.8), -0.8); if ((-0.8 <= u) && (u <= 0.8)) { c = (int)(318.0 * u); if (c > 0) b = new SolidBrush(Color.FromArgb(c, c, 0)); else b = new SolidBrush(Color.FromArgb(-c, 0, 0)); } g.FillEllipse(b, DrawingCoordinates[i].X - 18, DrawingCoordinates[i].Y - 18, 36, 36); g.DrawEllipse(Pens.SaddleBrown, DrawingCoordinates[i].X - 18, DrawingCoordinates[i].Y - 18, 36, 36); g.DrawString("U" + i.ToString(), F1, Brushes.DarkOrange, DrawingCoordinates[i].X + 25, DrawingCoordinates[i].Y + 2); } } } public class ServoController { private SerialPort Port; public bool Running; private byte[] Buffer; private byte Response; private const int CommandStart = 230; private const int CommandReset = 231; private const int CommandStop = 232; private const int ResponseOK = 253; public ServoController(string comPort) { Buffer = new byte[4]; Running = false; Port = new SerialPort(comPort, 9600, Parity.None, 8, StopBits.One); Port.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived); //Port.ReadTimeout = 20; } ~ServoController() { if (Port != null) if (Port.IsOpen) Port.Close(); } public void Start() { if (!Running) { try { Port.Open(); } catch { } if (Port.IsOpen) { //Buffer[0] = CommandStart; //Port.Write(Buffer, 0, 4); Running = true; } } } public void Stop() { //if (Running) //{ Running = false; //for (int i = 0 ; i < 10 ; i++) //{ // Buffer[0] = CommandStop; // Port.Write(Buffer, 0, 4); // Thread.Sleep(10); //} //} } public void Reset() { if (!Running) { //Buffer[0] = CommandReset; //Port.Write(Buffer, 0, 4); byte j0p = Buffer[0]; byte j1p = Buffer[1]; byte j2p = Buffer[2]; byte j3p = Buffer[3]; for (int st = 0 ; st < 50 ; st++) { Buffer[0] = (byte)(j0p + ((112 - j0p) * ((float)st + 1f) / 50)); Buffer[1] = (byte)(j1p + ((112 - j1p) * ((float)st + 1f) / 50)); Buffer[2] = (byte)(j2p + ((112 - j2p) * ((float)st + 1f) / 50)); Buffer[3] = (byte)(j3p + ((0 - j3p) * ((float)st + 1f) / 50)); Port.Write(Buffer, 0, 4); Thread.Sleep(20); } } } public void SetPosition(int index, byte position) { if (Running) { Buffer[index] = position; Port.Write(Buffer, 0, 4); } } public void SetPositions(byte[] positions) { if (Running) { Buffer[0] = positions[0]; Buffer[1] = positions[1]; Buffer[2] = positions[2]; Buffer[3] = positions[3]; Port.Write(Buffer, 0, 4); } } public void Port_DataReceived(Object sender, SerialDataReceivedEventArgs e) { Response = (byte)Port.ReadByte(); } } }
using System.Collections; using Spring.Globalization; using Spring.Validation; namespace Spring.DataBinding { /// <summary> /// Base implementation of the <see cref="IBindingContainer"/>. /// </summary> /// <author>Aleksandar Seovic</author> public class BaseBindingContainer : IBindingContainer { #region Fields private IList bindings = new ArrayList(); #endregion #region Constructor(s) /// <summary> /// Creates a new instance of <see cref="BaseBindingContainer"/>. /// </summary> public BaseBindingContainer() { } #endregion #region Properties /// <summary> /// Gets a list of bindings for this container. /// </summary> /// <value> /// A list of bindings for this container. /// </value> protected IList Bindings { get { return bindings; } } #endregion #region IBindingContainer Implementation /// <summary> /// Gets a value indicating whether this instance has bindings. /// </summary> /// <value> /// <c>true</c> if this instance has bindings; otherwise, <c>false</c>. /// </value> public bool HasBindings { get { return bindings.Count > 0; } } /// <summary> /// Adds the binding. /// </summary> /// <param name="binding"> /// Binding definition to add. /// </param> /// <returns> /// Added <see cref="IBinding"/> instance. /// </returns> public IBinding AddBinding(IBinding binding) { bindings.Add(binding); return binding; } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding with a default /// binding direction of <see cref="BindingDirection.Bidirectional"/>. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public IBinding AddBinding(string sourceExpression, string targetExpression) { return AddBinding(sourceExpression, targetExpression, BindingDirection.Bidirectional, null); } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <param name="direction"> /// Binding direction. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public IBinding AddBinding(string sourceExpression, string targetExpression, BindingDirection direction) { return AddBinding(sourceExpression, targetExpression, direction, null); } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding with a default /// binding direction of <see cref="BindingDirection.Bidirectional"/>. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <param name="formatter"> /// <see cref="IFormatter"/> to use for value formatting and parsing. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public IBinding AddBinding(string sourceExpression, string targetExpression, IFormatter formatter) { return AddBinding(sourceExpression, targetExpression, BindingDirection.Bidirectional, formatter); } /// <summary> /// Adds the <see cref="SimpleExpressionBinding"/> binding. /// </summary> /// <param name="sourceExpression"> /// The source expression. /// </param> /// <param name="targetExpression"> /// The target expression. /// </param> /// <param name="direction"> /// Binding direction. /// </param> /// <param name="formatter"> /// <see cref="IFormatter"/> to use for value formatting and parsing. /// </param> /// <returns> /// Added <see cref="SimpleExpressionBinding"/> instance. /// </returns> public virtual IBinding AddBinding(string sourceExpression, string targetExpression, BindingDirection direction, IFormatter formatter) { SimpleExpressionBinding binding = new SimpleExpressionBinding(sourceExpression, targetExpression); binding.Direction = direction; binding.Formatter = formatter; bindings.Add(binding); return binding; } #endregion #region IBinding Implementation /// <summary> /// Binds source object to target object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors) { BindSourceToTarget(source, target, validationErrors, null); } /// <summary> /// Binds source object to target object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> /// <param name="variables"> /// Variables that should be used during expression evaluation. /// </param> public virtual void BindSourceToTarget(object source, object target, IValidationErrors validationErrors, IDictionary variables) { foreach (IBinding binding in bindings) { binding.BindSourceToTarget(source, target, validationErrors); } } /// <summary> /// Binds target object to source object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors) { BindTargetToSource(source, target, validationErrors, null); } /// <summary> /// Binds target object to source object. /// </summary> /// <param name="source"> /// The source object. /// </param> /// <param name="target"> /// The target object. /// </param> /// <param name="validationErrors"> /// Validation errors collection that type conversion errors should be added to. /// </param> /// <param name="variables"> /// Variables that should be used during expression evaluation. /// </param> public virtual void BindTargetToSource(object source, object target, IValidationErrors validationErrors, IDictionary variables) { foreach (IBinding binding in bindings) { binding.BindTargetToSource(source, target, validationErrors); } } /// <summary> /// Implemented as a NOOP for containers. /// of a non-fatal binding error. /// </summary> /// <param name="messageId"> /// Resource ID of the error message. /// </param> /// <param name="errorProviders"> /// List of error providers message should be added to. /// </param> public virtual void SetErrorMessage(string messageId, params string[] errorProviders) { } #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. namespace System.Xml.Schema { using System.Collections; using System.Text; using System.Diagnostics; internal class NamespaceList { public enum ListType { Any, Other, Set }; private ListType _type = ListType.Any; private Hashtable _set = null; private string _targetNamespace; public NamespaceList() { } public NamespaceList(string namespaces, string targetNamespace) { Debug.Assert(targetNamespace != null); _targetNamespace = targetNamespace; namespaces = namespaces.Trim(); if (namespaces == "##any" || namespaces.Length == 0) { _type = ListType.Any; } else if (namespaces == "##other") { _type = ListType.Other; } else { _type = ListType.Set; _set = new Hashtable(); string[] splitString = XmlConvert.SplitString(namespaces); for (int i = 0; i < splitString.Length; ++i) { if (splitString[i] == "##local") { _set[string.Empty] = string.Empty; } else if (splitString[i] == "##targetNamespace") { _set[targetNamespace] = targetNamespace; } else { XmlConvert.ToUri(splitString[i]); // can throw _set[splitString[i]] = splitString[i]; } } } } public NamespaceList Clone() { NamespaceList nsl = (NamespaceList)MemberwiseClone(); if (_type == ListType.Set) { Debug.Assert(_set != null); nsl._set = (Hashtable)(_set.Clone()); } return nsl; } public ListType Type { get { return _type; } } public string Excluded { get { return _targetNamespace; } } public ICollection Enumerate { get { switch (_type) { case ListType.Set: return _set.Keys; case ListType.Other: case ListType.Any: default: throw new InvalidOperationException(); } } } public virtual bool Allows(string ns) { switch (_type) { case ListType.Any: return true; case ListType.Other: return ns != _targetNamespace && ns.Length != 0; case ListType.Set: return _set[ns] != null; } Debug.Fail($"Unexpected type {_type}"); return false; } public bool Allows(XmlQualifiedName qname) { return Allows(qname.Namespace); } public override string ToString() { switch (_type) { case ListType.Any: return "##any"; case ListType.Other: return "##other"; case ListType.Set: StringBuilder sb = new StringBuilder(); bool first = true; foreach (string s in _set.Keys) { if (first) { first = false; } else { sb.Append(" "); } if (s == _targetNamespace) { sb.Append("##targetNamespace"); } else if (s.Length == 0) { sb.Append("##local"); } else { sb.Append(s); } } return sb.ToString(); } Debug.Fail($"Unexpected type {_type}"); return string.Empty; } public static bool IsSubset(NamespaceList sub, NamespaceList super) { if (super._type == ListType.Any) { return true; } else if (sub._type == ListType.Other && super._type == ListType.Other) { return super._targetNamespace == sub._targetNamespace; } else if (sub._type == ListType.Set) { if (super._type == ListType.Other) { return !sub._set.Contains(super._targetNamespace); } else { Debug.Assert(super._type == ListType.Set); foreach (string ns in sub._set.Keys) { if (!super._set.Contains(ns)) { return false; } } return true; } } return false; } public static NamespaceList Union(NamespaceList o1, NamespaceList o2, bool v1Compat) { NamespaceList nslist = null; Debug.Assert(o1 != o2); if (o1._type == ListType.Any) { //clause 2 - o1 is Any nslist = new NamespaceList(); } else if (o2._type == ListType.Any) { //clause 2 - o2 is Any nslist = new NamespaceList(); } else if (o1._type == ListType.Set && o2._type == ListType.Set) { //clause 3 , both are sets nslist = o1.Clone(); foreach (string ns in o2._set.Keys) { nslist._set[ns] = ns; } } else if (o1._type == ListType.Other && o2._type == ListType.Other) { //clause 4, both are negations if (o1._targetNamespace == o2._targetNamespace) { //negation of same value nslist = o1.Clone(); } else { //Not a breaking change, going from not expressible to not(absent) nslist = new NamespaceList("##other", string.Empty); //clause 4, negations of different values, result is not(absent) } } else if (o1._type == ListType.Set && o2._type == ListType.Other) { if (v1Compat) { if (o1._set.Contains(o2._targetNamespace)) { nslist = new NamespaceList(); } else { //This was not there originally in V1, added for consistency since its not breaking nslist = o2.Clone(); } } else { if (o2._targetNamespace != string.Empty) { //clause 5, o1 is set S, o2 is not(tns) nslist = o1.CompareSetToOther(o2); } else if (o1._set.Contains(string.Empty)) { //clause 6.1 - set S includes absent, o2 is not(absent) nslist = new NamespaceList(); } else { //clause 6.2 - set S does not include absent, result is not(absent) nslist = new NamespaceList("##other", string.Empty); } } } else if (o2._type == ListType.Set && o1._type == ListType.Other) { if (v1Compat) { if (o2._set.Contains(o2._targetNamespace)) { nslist = new NamespaceList(); } else { nslist = o1.Clone(); } } else { //New rules if (o1._targetNamespace != string.Empty) { //clause 5, o1 is set S, o2 is not(tns) nslist = o2.CompareSetToOther(o1); } else if (o2._set.Contains(string.Empty)) { //clause 6.1 - set S includes absent, o2 is not(absent) nslist = new NamespaceList(); } else { //clause 6.2 - set S does not include absent, result is not(absent) nslist = new NamespaceList("##other", string.Empty); } } } return nslist; } private NamespaceList CompareSetToOther(NamespaceList other) { //clause 5.1 NamespaceList nslist = null; if (_set.Contains(other._targetNamespace)) { //S contains negated ns if (_set.Contains(string.Empty)) { // AND S contains absent nslist = new NamespaceList(); //any is the result } else { //clause 5.2 nslist = new NamespaceList("##other", string.Empty); } } else if (_set.Contains(string.Empty)) { //clause 5.3 - Not expressible nslist = null; } else { //clause 5.4 - Set S does not contain negated ns or absent nslist = other.Clone(); } return nslist; } public static NamespaceList Intersection(NamespaceList o1, NamespaceList o2, bool v1Compat) { NamespaceList nslist = null; Debug.Assert(o1 != o2); //clause 1 if (o1._type == ListType.Any) { //clause 2 - o1 is any nslist = o2.Clone(); } else if (o2._type == ListType.Any) { //clause 2 - o2 is any nslist = o1.Clone(); } else if (o1._type == ListType.Set && o2._type == ListType.Other) { //Clause 3 o2 is other nslist = o1.Clone(); nslist.RemoveNamespace(o2._targetNamespace); if (!v1Compat) { nslist.RemoveNamespace(string.Empty); //remove ##local } } else if (o1._type == ListType.Other && o2._type == ListType.Set) { //Clause 3 o1 is other nslist = o2.Clone(); nslist.RemoveNamespace(o1._targetNamespace); if (!v1Compat) { nslist.RemoveNamespace(string.Empty); //remove ##local } } else if (o1._type == ListType.Set && o2._type == ListType.Set) { //clause 4 nslist = o1.Clone(); nslist = new NamespaceList(); nslist._type = ListType.Set; nslist._set = new Hashtable(); foreach (string ns in o1._set.Keys) { if (o2._set.Contains(ns)) { nslist._set.Add(ns, ns); } } } else if (o1._type == ListType.Other && o2._type == ListType.Other) { if (o1._targetNamespace == o2._targetNamespace) { //negation of same namespace name nslist = o1.Clone(); return nslist; } if (!v1Compat) { if (o1._targetNamespace == string.Empty) { // clause 6 - o1 is negation of absent nslist = o2.Clone(); } else if (o2._targetNamespace == string.Empty) { //clause 6 - o1 is negation of absent nslist = o1.Clone(); } } //if it comes here, its not expressible //clause 5 } return nslist; } private void RemoveNamespace(string tns) { if (_set[tns] != null) { _set.Remove(tns); } } }; internal class NamespaceListV1Compat : NamespaceList { public NamespaceListV1Compat(string namespaces, string targetNamespace) : base(namespaces, targetNamespace) { } public override bool Allows(string ns) { if (this.Type == ListType.Other) { return ns != Excluded; } else { return base.Allows(ns); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Reflection { using System; using System.Reflection; ////using System.Reflection.Cache; ////using System.Reflection.Emit; using System.Globalization; ////using System.Threading; ////using System.Diagnostics; ////using System.Security.Permissions; ////using System.Collections; ////using System.Security; ////using System.Text; using System.Runtime.ConstrainedExecution; using System.Runtime.CompilerServices; ////using System.Runtime.InteropServices; ////using System.Runtime.Serialization; ////using System.Runtime.Versioning; ////using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; ////using CorElementType = System.Reflection.CorElementType; ////using MdToken = System.Reflection.MetadataToken; [Serializable] internal sealed class RuntimeConstructorInfo : ConstructorInfo /*, ISerializable*/ { #region Private Data Members #pragma warning disable 169 // The private field 'class member' is never used private RuntimeMethodHandle m_handle; #pragma warning restore 169 //// private RuntimeTypeCache m_reflectedTypeCache; //// private RuntimeType m_declaringType; //// private string m_toString; //// private MethodAttributes m_methodAttributes; //// private BindingFlags m_bindingFlags; //// private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. //// private uint m_invocationFlags; //// private Signature m_signature; #endregion #region Constructor //// internal RuntimeConstructorInfo() //// { //// // Used for dummy head node during population //// } //// //// internal RuntimeConstructorInfo( RuntimeMethodHandle handle , //// RuntimeTypeHandle declaringTypeHandle , //// RuntimeTypeCache reflectedTypeCache , //// MethodAttributes methodAttributes , //// BindingFlags bindingFlags ) //// { //// ASSERT.POSTCONDITION( methodAttributes == handle.GetAttributes() ); //// //// m_bindingFlags = bindingFlags; //// m_handle = handle; //// m_reflectedTypeCache = reflectedTypeCache; //// m_declaringType = declaringTypeHandle.GetRuntimeType(); //// m_parameters = null; // Created lazily when GetParameters() is called. //// m_toString = null; //// m_methodAttributes = methodAttributes; //// } #endregion #region NonPublic Methods //// [ReliabilityContract( Consistency.WillNotCorruptState, Cer.Success )] //// internal override bool CacheEquals( object o ) //// { //// RuntimeConstructorInfo m = o as RuntimeConstructorInfo; //// //// if(m == null) //// { //// return false; //// } //// //// return m.m_handle.Equals( m_handle ); //// } //// //// private Signature Signature //// { //// get //// { //// if(m_signature == null) //// { //// m_signature = new Signature( m_handle, m_declaringType.GetTypeHandleInternal() ); //// } //// //// return m_signature; //// } //// } //// //// private RuntimeTypeHandle ReflectedTypeHandle //// { //// get //// { //// return m_reflectedTypeCache.RuntimeTypeHandle; //// } //// } //// //// private void CheckConsistency( Object target ) //// { //// if(target == null && IsStatic) //// { //// return; //// } //// //// if(!m_declaringType.IsInstanceOfType( target )) //// { //// if(target == null) //// { //// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_StatMethReqTarg" ) ); //// } //// //// throw new TargetException( Environment.GetResourceString( "RFLCT.Targ_ITargMismatch" ) ); //// } //// } //// //// internal BindingFlags BindingFlags //// { //// get //// { //// return m_bindingFlags; //// } //// } //// //// internal override RuntimeMethodHandle GetMethodHandle() //// { //// return m_handle; //// } //// //// internal override bool IsOverloaded //// { //// get //// { //// return m_reflectedTypeCache.GetConstructorList( MemberListType.CaseSensitive, Name ).Count > 1; //// } //// } //// //// internal override uint GetOneTimeSpecificFlags() //// { //// uint invocationFlags = INVOCATION_FLAGS_IS_CTOR; // this is a given //// //// if( //// (DeclaringType != null && DeclaringType.IsAbstract) || //// (IsStatic) //// ) //// { //// invocationFlags |= INVOCATION_FLAGS_NO_CTOR_INVOKE; //// } //// else if(DeclaringType == typeof( void )) //// { //// invocationFlags |= INVOCATION_FLAGS_NO_INVOKE; //// } //// // Check for attempt to create a delegate class, we demand unmanaged //// // code permission for this since it's hard to validate the target address. //// else if(typeof( Delegate ).IsAssignableFrom( DeclaringType )) //// { //// invocationFlags |= INVOCATION_FLAGS_IS_DELEGATE_CTOR; //// } //// //// return invocationFlags; //// } #endregion #region Object Overrides //// public override String ToString() //// { //// if(m_toString == null) //// { //// m_toString = "Void " + RuntimeMethodInfo.ConstructName( this ); //// } //// //// return m_toString; //// } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes( bool inherit ) { throw new NotImplementedException(); //// return CustomAttribute.GetCustomAttributes( this, typeof( object ) as RuntimeType ); } public override Object[] GetCustomAttributes( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.GetCustomAttributes( this, attributeRuntimeType ); } public override bool IsDefined( Type attributeType, bool inherit ) { throw new NotImplementedException(); //// if(attributeType == null) //// { //// throw new ArgumentNullException( "attributeType" ); //// } //// //// RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; //// //// if(attributeRuntimeType == null) //// { //// throw new ArgumentException( Environment.GetResourceString( "Arg_MustBeType" ), "attributeType" ); //// } //// //// return CustomAttribute.IsDefined( this, attributeRuntimeType ); } #endregion #region MemberInfo Overrides public override String Name { //// [MethodImpl( MethodImplOptions.InternalCall )] get { throw new NotImplementedException(); //// return m_handle.GetName(); } } //// public override MemberTypes MemberType //// { //// get //// { //// return MemberTypes.Constructor; //// } //// } public override Type DeclaringType { get { throw new NotImplementedException(); //// return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } //// public override Type ReflectedType //// { //// get //// { //// return m_reflectedTypeCache.IsGlobal ? null : m_reflectedTypeCache.RuntimeType; //// } //// } //// //// public override int MetadataToken //// { //// get //// { //// return m_handle.GetMethodDef(); //// } //// } //// //// public override Module Module //// { //// get //// { //// return m_declaringType.GetTypeHandleInternal().GetModuleHandle().GetModule(); //// } //// } #endregion #region MethodBase Overrides //// internal override Type GetReturnType() //// { //// return Signature.ReturnTypeHandle.GetRuntimeType(); //// } //// //// internal override ParameterInfo[] GetParametersNoCopy() //// { //// if(m_parameters == null) //// { //// m_parameters = ParameterInfo.GetParameters( this, this, Signature ); //// } //// //// return m_parameters; //// } [MethodImpl( MethodImplOptions.InternalCall )] public extern override ParameterInfo[] GetParameters(); //// { //// ParameterInfo[] parameters = GetParametersNoCopy(); //// //// if(parameters.Length == 0) //// { //// return parameters; //// } //// //// ParameterInfo[] ret = new ParameterInfo[parameters.Length]; //// //// Array.Copy( parameters, ret, parameters.Length ); //// //// return ret; //// } //// //// public override MethodImplAttributes GetMethodImplementationFlags() //// { //// return m_handle.GetImplAttributes(); //// } //// //// public override RuntimeMethodHandle MethodHandle //// { //// get //// { //// Type declaringType = DeclaringType; //// if((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_NotAllowedInReflectionOnly" ) ); //// } //// //// return m_handle; //// } //// } //// //// public override MethodAttributes Attributes //// { //// get //// { //// return m_methodAttributes; //// } //// } //// //// public override CallingConventions CallingConvention //// { //// get //// { //// return Signature.CallingConvention; //// } //// } //// //// internal static void CheckCanCreateInstance( Type declaringType, bool isVarArg ) //// { //// if(declaringType == null) //// { //// throw new ArgumentNullException( "declaringType" ); //// } //// //// // ctor is ReflectOnly //// if(declaringType is ReflectionOnlyType) //// { //// throw new InvalidOperationException( Environment.GetResourceString( "Arg_ReflectionOnlyInvoke" ) ); //// } //// // ctor is declared on interface class //// else if(declaringType.IsInterface) //// { //// throw new MemberAccessException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Acc_CreateInterfaceEx" ), declaringType ) ); //// } //// // ctor is on an abstract class //// else if(declaringType.IsAbstract) //// { //// throw new MemberAccessException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Acc_CreateAbstEx" ), declaringType ) ); //// } //// // ctor is on a class that contains stack pointers //// else if(declaringType.GetRootElementType() == typeof( ArgIterator )) //// { //// throw new NotSupportedException(); //// } //// // ctor is vararg //// else if(isVarArg) //// { //// throw new NotSupportedException(); //// } //// // ctor is generic or on a generic class //// else if(declaringType.ContainsGenericParameters) //// { //// throw new MemberAccessException( String.Format( CultureInfo.CurrentUICulture, Environment.GetResourceString( "Acc_CreateGenericEx" ), declaringType ) ); //// } //// // ctor is declared on System.Void //// else if(declaringType == typeof( void )) //// { //// throw new MemberAccessException( Environment.GetResourceString( "Access_Void" ) ); //// } //// } //// //// internal void ThrowNoInvokeException() //// { //// CheckCanCreateInstance( DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs ); //// //// // ctor is .cctor //// if((Attributes & MethodAttributes.Static) == MethodAttributes.Static) //// { //// throw new MemberAccessException( Environment.GetResourceString( "Acc_NotClassInit" ) ); //// } //// //// throw new TargetException(); //// } //// //// [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImpl( MethodImplOptions.InternalCall )] public extern override Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ); //// { //// // set one time info for invocation //// if(m_invocationFlags == INVOCATION_FLAGS_UNKNOWN) //// { //// m_invocationFlags = GetOneTimeFlags(); //// } //// //// if((m_invocationFlags & INVOCATION_FLAGS_NO_INVOKE) != 0) //// { //// ThrowNoInvokeException(); //// } //// //// // check basic method consistency. This call will throw if there are problems in the target/method relationship //// CheckConsistency( obj ); //// //// if(obj != null) //// { //// new SecurityPermission( SecurityPermissionFlag.SkipVerification ).Demand(); //// } //// //// if((m_invocationFlags & (INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS_NEED_SECURITY)) != 0) //// { //// if((m_invocationFlags & INVOCATION_FLAGS_RISKY_METHOD) != 0) //// { //// CodeAccessPermission.DemandInternal( PermissionType.ReflectionMemberAccess ); //// } //// if((m_invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) != 0) //// { //// PerformSecurityCheck( obj, m_handle, m_declaringType.TypeHandle.Value, m_invocationFlags ); //// } //// } //// //// // get the signature //// int formalCount = Signature.Arguments.Length; //// int actualCount = (parameters != null) ? parameters.Length : 0; //// if(formalCount != actualCount) //// { //// throw new TargetParameterCountException( Environment.GetResourceString( "Arg_ParmCnt" ) ); //// } //// //// // if we are here we passed all the previous checks. Time to look at the arguments //// if(actualCount > 0) //// { //// Object[] arguments = CheckArguments( parameters, binder, invokeAttr, culture, Signature ); //// Object retValue = m_handle.InvokeMethodFast( obj, arguments, Signature, m_methodAttributes, (ReflectedType != null) ? ReflectedType.TypeHandle : RuntimeTypeHandle.EmptyHandle ); //// //// // copy out. This should be made only if ByRef are present. //// for(int index = 0; index < actualCount; index++) //// { //// parameters[index] = arguments[index]; //// } //// //// return retValue; //// } //// //// return m_handle.InvokeMethodFast( obj, null, Signature, m_methodAttributes, (DeclaringType != null) ? DeclaringType.TypeHandle : RuntimeTypeHandle.EmptyHandle ); //// } //// //// //// [ReflectionPermissionAttribute( SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess )] //// public override MethodBody GetMethodBody() //// { //// MethodBody mb = m_handle.GetMethodBody( ReflectedTypeHandle ); //// if(mb != null) //// { //// mb.m_methodBase = this; //// } //// return mb; //// } #endregion #region ConstructorInfo Overrides //// [DebuggerStepThroughAttribute] //// [Diagnostics.DebuggerHidden] //// public override Object Invoke( BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture ) //// { //// // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context //// RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle; //// //// // set one time info for invocation //// if(m_invocationFlags == INVOCATION_FLAGS_UNKNOWN) //// { //// m_invocationFlags = GetOneTimeFlags(); //// } //// //// if((m_invocationFlags & (INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0) //// { //// ThrowNoInvokeException(); //// } //// //// if((m_invocationFlags & (INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) //// { //// if((m_invocationFlags & INVOCATION_FLAGS_RISKY_METHOD) != 0) //// { //// CodeAccessPermission.DemandInternal( PermissionType.ReflectionMemberAccess ); //// } //// if((m_invocationFlags & INVOCATION_FLAGS_NEED_SECURITY) != 0) //// { //// PerformSecurityCheck( null, m_handle, m_declaringType.TypeHandle.Value, m_invocationFlags & INVOCATION_FLAGS_CONSTRUCTOR_INVOKE ); //// } //// if((m_invocationFlags & INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0) //// { //// new SecurityPermission( SecurityPermissionFlag.UnmanagedCode ).Demand(); //// } //// } //// //// // get the signature //// int formalCount = Signature.Arguments.Length; //// int actualCount = (parameters != null) ? parameters.Length : 0; //// if(formalCount != actualCount) //// { //// throw new TargetParameterCountException( Environment.GetResourceString( "Arg_ParmCnt" ) ); //// } //// //// // make sure the class ctor has been run //// RuntimeHelpers.RunClassConstructor( declaringTypeHandle ); //// //// // if we are here we passed all the previous checks. Time to look at the arguments //// if(actualCount > 0) //// { //// Object[] arguments = CheckArguments( parameters, binder, invokeAttr, culture, Signature ); //// Object retValue = m_handle.InvokeConstructor( arguments, Signature, declaringTypeHandle ); //// //// // copy out. This should be made only if ByRef are present. //// for(int index = 0; index < actualCount; index++) //// { //// parameters[index] = arguments[index]; //// } //// //// return retValue; //// } //// //// return m_handle.InvokeConstructor( null, Signature, declaringTypeHandle ); //// } #endregion #region ISerializable Implementation //// public void GetObjectData( SerializationInfo info, StreamingContext context ) //// { //// if(info == null) //// { //// throw new ArgumentNullException( "info" ); //// } //// //// MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeHandle.GetRuntimeType(), ToString(), MemberTypes.Constructor ); //// } //// //// internal void SerializationInvoke( Object target, SerializationInfo info, StreamingContext context ) //// { //// MethodHandle.SerializationInvoke( target, Signature, info, context ); //// } #endregion } }