context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Controls; using OpenLiveWriter.Interop.Windows; namespace OpenLiveWriter.ApplicationFramework { public interface IMainFrameWindow : IWin32Window, ISynchronizeInvoke, IMiniFormOwner { string Caption { set; } Point Location { get; } Size Size { get; } event EventHandler LocationChanged; event EventHandler SizeChanged; event EventHandler Deactivate; event LayoutEventHandler Layout; void Activate(); void Update(); void PerformLayout(); void Invalidate(); void Close(); void OnKeyboardLanguageChanged(); } public interface IStatusBar { void SetWordCountMessage(string msg); void PushStatusMessage(string msg); void PopStatusMessage(); void SetStatusMessage(string msg); } public class NullStatusBar : IStatusBar { private int msgCount; public void SetWordCountMessage(string msg) { } public void PushStatusMessage(string msg) { msgCount++; } public void PopStatusMessage() { msgCount--; Debug.Assert(msgCount >= 0); } public void SetStatusMessage(string msg) { } } public class StatusMessage { public StatusMessage(string blogPostStatus) : this(null, blogPostStatus, null) { } public StatusMessage(Image icon, string blogPostStatus, string wordCountValue) { Icon = icon; BlogPostStatus = blogPostStatus; WordCountValue = wordCountValue; } public void ConsumeValues(StatusMessage externalMessage) { if (BlogPostStatus == null) { BlogPostStatus = externalMessage.BlogPostStatus; Icon = externalMessage.Icon; } if (WordCountValue == null) WordCountValue = externalMessage.WordCountValue; } private Image _icon; public Image Icon { get { return _icon; } set { _icon = value; } } private string _blogPostStatus; public string BlogPostStatus { get { return _blogPostStatus; } set { _blogPostStatus = value; } } private string _wordCountValue; public string WordCountValue { get { return _wordCountValue; } set { _wordCountValue = value; } } } public class DesignModeMainFrameWindow : SameThreadSimpleInvokeTarget, IMainFrameWindow { public string Caption { get { return String.Empty; } set { } } public Point Location { get { return Point.Empty; } } public Size Size { get { return Size.Empty; } } public void Activate() { } public void Update() { } public void AddOwnedForm(Form form) { } public void RemoveOwnedForm(Form form) { } public void SetStatusBarMessage(StatusMessage message) { } public void PushStatusBarMessage(StatusMessage message) { } public void PopStatusBarMessage() { } public void PerformLayout() { } public void Invalidate() { } public void Close() { } public IntPtr Handle { get { return User32.GetForegroundWindow(); } } public event EventHandler SizeChanged; protected void OnSizeChanged() { // prevent compiler warnings if (SizeChanged != null) SizeChanged(this, EventArgs.Empty); } public event EventHandler LocationChanged; protected void OnLocationChanged() { // prevent compiler warnings if (LocationChanged != null) LocationChanged(this, EventArgs.Empty); } public event EventHandler Deactivate; protected void OnDeactivate() { // prevent compiler warnings if (Deactivate != null) Deactivate(this, EventArgs.Empty); } public event LayoutEventHandler Layout; protected void OnLayout(LayoutEventArgs ea) { if (Layout != null) Layout(this, ea); } public void OnKeyboardLanguageChanged() { } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/timestamp.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/timestamp.proto</summary> public static partial class TimestampReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/timestamp.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TimestampReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv", "dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY", "AiABKAVCfgoTY29tLmdvb2dsZS5wcm90b2J1ZkIOVGltZXN0YW1wUHJvdG9Q", "AVorZ2l0aHViLmNvbS9nb2xhbmcvcHJvdG9idWYvcHR5cGVzL3RpbWVzdGFt", "cPgBAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG", "cHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Timestamp), global::Google.Protobuf.WellKnownTypes.Timestamp.Parser, new[]{ "Seconds", "Nanos" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// A Timestamp represents a point in time independent of any time zone /// or calendar, represented as seconds and fractions of seconds at /// nanosecond resolution in UTC Epoch time. It is encoded using the /// Proleptic Gregorian Calendar which extends the Gregorian calendar /// backwards to year one. It is encoded assuming all minutes are 60 /// seconds long, i.e. leap seconds are "smeared" so that no leap second /// table is needed for interpretation. Range is from /// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. /// By restricting to that range, we ensure that we can convert to /// and from RFC 3339 date strings. /// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). /// /// # Examples /// /// Example 1: Compute Timestamp from POSIX `time()`. /// /// Timestamp timestamp; /// timestamp.set_seconds(time(NULL)); /// timestamp.set_nanos(0); /// /// Example 2: Compute Timestamp from POSIX `gettimeofday()`. /// /// struct timeval tv; /// gettimeofday(&amp;tv, NULL); /// /// Timestamp timestamp; /// timestamp.set_seconds(tv.tv_sec); /// timestamp.set_nanos(tv.tv_usec * 1000); /// /// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. /// /// FILETIME ft; /// GetSystemTimeAsFileTime(&amp;ft); /// UINT64 ticks = (((UINT64)ft.dwHighDateTime) &lt;&lt; 32) | ft.dwLowDateTime; /// /// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z /// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. /// Timestamp timestamp; /// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); /// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); /// /// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. /// /// long millis = System.currentTimeMillis(); /// /// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) /// .setNanos((int) ((millis % 1000) * 1000000)).build(); /// /// Example 5: Compute Timestamp from current time in Python. /// /// timestamp = Timestamp() /// timestamp.GetCurrentTime() /// /// # JSON Mapping /// /// In JSON format, the Timestamp type is encoded as a string in the /// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the /// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" /// where {year} is always expressed using four digits while {month}, {day}, /// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional /// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), /// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone /// is required, though only UTC (as indicated by "Z") is presently supported. /// /// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past /// 01:30 UTC on January 15, 2017. /// /// In JavaScript, one can convert a Date object to this format using the /// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString] /// method. In Python, a standard `datetime.datetime` object can be converted /// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) /// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one /// can use the Joda Time's [`ISODateTimeFormat.dateTime()`]( /// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()) /// to obtain a formatter capable of generating timestamps in this format. /// </summary> public sealed partial class Timestamp : pb::IMessage<Timestamp> { private static readonly pb::MessageParser<Timestamp> _parser = new pb::MessageParser<Timestamp>(() => new Timestamp()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Timestamp> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Timestamp() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Timestamp(Timestamp other) : this() { seconds_ = other.seconds_; nanos_ = other.nanos_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Timestamp Clone() { return new Timestamp(this); } /// <summary>Field number for the "seconds" field.</summary> public const int SecondsFieldNumber = 1; private long seconds_; /// <summary> /// Represents seconds of UTC time since Unix epoch /// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to /// 9999-12-31T23:59:59Z inclusive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Seconds { get { return seconds_; } set { seconds_ = value; } } /// <summary>Field number for the "nanos" field.</summary> public const int NanosFieldNumber = 2; private int nanos_; /// <summary> /// Non-negative fractions of a second at nanosecond resolution. Negative /// second values with fractions must still have non-negative nanos values /// that count forward in time. Must be from 0 to 999,999,999 /// inclusive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Nanos { get { return nanos_; } set { nanos_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Timestamp); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Timestamp other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Seconds != other.Seconds) return false; if (Nanos != other.Nanos) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Seconds != 0L) hash ^= Seconds.GetHashCode(); if (Nanos != 0) hash ^= Nanos.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Seconds != 0L) { output.WriteRawTag(8); output.WriteInt64(Seconds); } if (Nanos != 0) { output.WriteRawTag(16); output.WriteInt32(Nanos); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Seconds != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds); } if (Nanos != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Timestamp other) { if (other == null) { return; } if (other.Seconds != 0L) { Seconds = other.Seconds; } if (other.Nanos != 0) { Nanos = other.Nanos; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Seconds = input.ReadInt64(); break; } case 16: { Nanos = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using BLToolkit.Common; using BLToolkit.DataAccess; namespace BLToolkit.Reflection.MetadataProvider { using Extension; using Mapping; public delegate void OnCreateProvider(MetadataProviderBase parentProvider); public delegate MetadataProviderBase CreateProvider(); public delegate MemberMapper EnsureMapperHandler(string mapName, string origName); public abstract class MetadataProviderBase { #region Provider Support public virtual void AddProvider(MetadataProviderBase provider) { } public virtual void InsertProvider(int index, MetadataProviderBase provider) { } public virtual MetadataProviderBase[] GetProviders() { return new MetadataProviderBase[0]; } #endregion #region GetFieldName public virtual string GetFieldName(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return member.Name; } #endregion #region GetFieldStorage public virtual string GetFieldStorage(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return null; } #endregion #region GetInheritanceDiscriminator public virtual bool GetInheritanceDiscriminator(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return false; } #endregion #region EnsureMapper public virtual void EnsureMapper(TypeAccessor typeAccessor, MappingSchema mappingSchema, EnsureMapperHandler handler) { } #endregion #region GetMapIgnore public virtual bool GetMapIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return TypeHelper.IsScalar(member.Type) == false;// || //(member.MemberInfo is FieldInfo && ((FieldInfo)member.MemberInfo).IsLiteral); } #endregion #region GetTrimmable public virtual bool GetTrimmable(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = member.Type != typeof(string); return isSet? false: TrimmableAttribute.Default.IsTrimmable; } #endregion #region GetMapValues public virtual MapValue[] GetMapValues(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return null; } public virtual MapValue[] GetMapValues(TypeExtension typeExtension, Type type, out bool isSet) { isSet = false; return null; } #endregion #region GetDefaultValue public virtual object GetDefaultValue(MappingSchema mappingSchema, TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return null; } public virtual object GetDefaultValue(MappingSchema mappingSchema, TypeExtension typeExtension, Type type, out bool isSet) { isSet = false; return null; } #endregion #region GetNullable public virtual bool GetNullable(MappingSchema mappingSchema, TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return member.Type.IsGenericType && member.Type.GetGenericTypeDefinition() == typeof(Nullable<>) /*|| #if FW3 member.Type == typeof(System.Data.Linq.Binary) || #endif member.Type == typeof(byte[])*/; } #endregion #region GetNullValue public virtual object GetNullValue(MappingSchema mappingSchema, TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; if (member.Type.IsEnum) return null; object value = mappingSchema.GetNullValue(member.Type); if (value is Type && (Type)value == typeof(DBNull)) { value = DBNull.Value; if (member.Type == typeof(string)) value = null; } return value; } #endregion #region GetDbName public virtual string GetDatabaseName(Type type, ExtensionList extensions, out bool isSet) { isSet = false; return null; } #endregion #region GetOwnerName public virtual string GetOwnerName(Type type, ExtensionList extensions, out bool isSet) { isSet = false; return null; } #endregion #region GetTableName public virtual string GetTableName(Type type, ExtensionList extensions, out bool isSet) { isSet = false; return type.IsInterface && type.Name.StartsWith("I") ? type.Name.Substring(1) : type.Name; } #endregion #region GetPrimaryKeyOrder public virtual int GetPrimaryKeyOrder(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet) { isSet = false; return 0; } #endregion #region GetNonUpdatableAttribute public virtual NonUpdatableAttribute GetNonUpdatableAttribute(Type type, TypeExtension typeExt, MemberAccessor member, out bool isSet) { isSet = false; return null; } #endregion #region GetSqlIgnore public virtual bool GetSqlIgnore(TypeExtension typeExtension, MemberAccessor member, out bool isSet) { isSet = false; return false; } #endregion #region GetRelations public virtual List<MapRelationBase> GetRelations(MappingSchema schema, ExtensionList typeExt, Type master, Type slave, out bool isSet) { isSet = false; return new List<MapRelationBase>(); } protected static List<string> GetPrimaryKeyFields(MappingSchema schema, TypeAccessor ta, TypeExtension tex) { MetadataProviderBase mdp = schema.MetadataProvider; List<string> keys = new List<string>(); foreach (MemberAccessor sma in ta) { bool isSetFlag; mdp.GetPrimaryKeyOrder(ta.Type, tex, sma, out isSetFlag); if (isSetFlag) { string name = mdp.GetFieldName(tex, sma, out isSetFlag); keys.Add(name); } } return keys; } #endregion #region GetAssociation public virtual Association GetAssociation(TypeExtension typeExtension, MemberAccessor member) { return null; } #endregion #region GetInheritanceMapping public virtual InheritanceMappingAttribute[] GetInheritanceMapping(Type type, TypeExtension typeExtension) { return Array<InheritanceMappingAttribute>.Empty; } #endregion #region Static Members public static event OnCreateProvider OnCreateProvider; private static CreateProvider _createProvider = CreateInternal; public static CreateProvider CreateProvider { get { return _createProvider; } set { _createProvider = value ?? new CreateProvider(CreateInternal); } } private static MetadataProviderBase CreateInternal() { MetadataProviderList list = new MetadataProviderList(); if (OnCreateProvider != null) OnCreateProvider(list); return list; } #endregion } }
namespace Factotum { partial class SiteEdit { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SiteEdit)); this.btnOK = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.btnCancel = new System.Windows.Forms.Button(); this.cboCustomer = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.ckActive = new System.Windows.Forms.CheckBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.txtSiteFullName = new Factotum.TextBoxWithUndo(); this.txtName = new Factotum.TextBoxWithUndo(); this.label5 = new System.Windows.Forms.Label(); this.cboDefaultCalProcedure = new System.Windows.Forms.ComboBox(); this.label6 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(125, 156); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(64, 22); this.btnOK.TabIndex = 8; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(54, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(56, 13); this.label1.TabIndex = 0; this.label1.Text = "Site Name"; // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.Location = new System.Drawing.Point(195, 156); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(64, 22); this.btnCancel.TabIndex = 9; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // cboCustomer // this.cboCustomer.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboCustomer.FormattingEnabled = true; this.cboCustomer.Location = new System.Drawing.Point(111, 95); this.cboCustomer.Name = "cboCustomer"; this.cboCustomer.Size = new System.Drawing.Size(147, 21); this.cboCustomer.TabIndex = 5; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(54, 98); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(51, 13); this.label2.TabIndex = 4; this.label2.Text = "Customer"; // // ckActive // this.ckActive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.ckActive.AutoSize = true; this.ckActive.Location = new System.Drawing.Point(27, 156); this.ckActive.Name = "ckActive"; this.ckActive.Size = new System.Drawing.Size(56, 17); this.ckActive.TabIndex = 10; this.ckActive.TabStop = false; this.ckActive.Text = "Active"; this.ckActive.UseVisualStyleBackColor = true; this.ckActive.Click += new System.EventHandler(this.ckActive_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(56, 41); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(54, 13); this.label3.TabIndex = 2; this.label3.Text = "Full Name"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(48, 54); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(62, 13); this.label4.TabIndex = 3; this.label4.Text = "For Reports"; // // txtSiteFullName // this.txtSiteFullName.Location = new System.Drawing.Point(111, 39); this.txtSiteFullName.Multiline = true; this.txtSiteFullName.Name = "txtSiteFullName"; this.txtSiteFullName.Size = new System.Drawing.Size(147, 50); this.txtSiteFullName.TabIndex = 3; this.txtSiteFullName.TextChanged += new System.EventHandler(this.txtSiteFullName_TextChanged); // // txtName // this.txtName.Location = new System.Drawing.Point(111, 12); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(147, 20); this.txtName.TabIndex = 1; this.txtName.TextChanged += new System.EventHandler(this.txtName_TextChanged); this.txtName.Validating += new System.ComponentModel.CancelEventHandler(this.txtName_Validating); // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(12, 119); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(93, 13); this.label5.TabIndex = 6; this.label5.Text = "Default Calibration"; // // cboDefaultCalProcedure // this.cboDefaultCalProcedure.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboDefaultCalProcedure.FormattingEnabled = true; this.cboDefaultCalProcedure.Location = new System.Drawing.Point(111, 122); this.cboDefaultCalProcedure.Name = "cboDefaultCalProcedure"; this.cboDefaultCalProcedure.Size = new System.Drawing.Size(147, 21); this.cboDefaultCalProcedure.TabIndex = 7; // // label6 // this.label6.AutoSize = true; this.label6.Location = new System.Drawing.Point(49, 132); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(56, 13); this.label6.TabIndex = 12; this.label6.Text = "Procedure"; // // SiteEdit // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(271, 190); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.cboDefaultCalProcedure); this.Controls.Add(this.label4); this.Controls.Add(this.txtSiteFullName); this.Controls.Add(this.label3); this.Controls.Add(this.txtName); this.Controls.Add(this.ckActive); this.Controls.Add(this.label2); this.Controls.Add(this.cboCustomer); this.Controls.Add(this.btnCancel); this.Controls.Add(this.label1); this.Controls.Add(this.btnOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(279, 224); this.Name = "SiteEdit"; this.Text = "Edit Site"; ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Label label1; private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.CheckBox ckActive; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cboCustomer; private TextBoxWithUndo txtName; private System.Windows.Forms.Label label4; private TextBoxWithUndo txtSiteFullName; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.ComboBox cboDefaultCalProcedure; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client.Cache { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Event; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Client.Cache.Query.Continuous; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Interop; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Compute; using NUnit.Framework; /// <summary> /// Tests for thin client continuous queries. /// </summary> public class ContinuousQueryTest : ClientTestBase { /** */ private const int MaxCursors = 20; /// <summary> /// Initializes a new instance of <see cref="ContinuousQueryTest"/>. /// </summary> public ContinuousQueryTest() : base(2) { // No-op. } /// <summary> /// Executes after every test. /// </summary> [TearDown] public void TestTearDown() { Assert.IsEmpty(Client.GetActiveNotificationListeners()); } /// <summary> /// Basic continuous query test. /// /// - Start the query /// - Add cache entry, verify query event /// - Update cache entry, verify query event /// - Remove cache entry, verify query event /// </summary> [Test] public void TestContinuousQueryCallsLocalListenerWithCorrectEvent() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var events = new List<ICacheEntryEvent<int, int>>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(events.Add)); using (cache.QueryContinuous(qry)) { // Create. cache.Put(1, 1); TestUtils.WaitForTrueCondition(() => events.Count == 1); var evt = events.Single(); Assert.AreEqual(CacheEntryEventType.Created, evt.EventType); Assert.IsFalse(evt.HasOldValue); Assert.IsTrue(evt.HasValue); Assert.AreEqual(1, evt.Key); Assert.AreEqual(1, evt.Value); // Update. cache.Put(1, 2); TestUtils.WaitForTrueCondition(() => events.Count == 2); evt = events.Last(); Assert.AreEqual(CacheEntryEventType.Updated, evt.EventType); Assert.IsTrue(evt.HasOldValue); Assert.IsTrue(evt.HasValue); Assert.AreEqual(1, evt.Key); Assert.AreEqual(2, evt.Value); Assert.AreEqual(1, evt.OldValue); // Remove. cache.Remove(1); TestUtils.WaitForTrueCondition(() => events.Count == 3); evt = events.Last(); Assert.AreEqual(CacheEntryEventType.Removed, evt.EventType); Assert.IsTrue(evt.HasOldValue); Assert.IsTrue(evt.HasValue); Assert.AreEqual(1, evt.Key); Assert.AreEqual(2, evt.Value); Assert.AreEqual(2, evt.OldValue); } } /// <summary> /// Tests that default query settings have correct values. /// </summary> [Test] public void TestDefaultSettings() { var qry = new ContinuousQueryClient<int, int>(); Assert.AreEqual(ContinuousQueryClient.DefaultBufferSize, qry.BufferSize); Assert.AreEqual(TimeSpan.Zero, qry.TimeInterval); } /// <summary> /// Tests that Compute notifications and Continuous Query notifications work together correctly. /// Compute and Continuous Queries use the same server -> client notification mechanism, /// we ensure that there are no conflicts when both are used in parallel. /// /// - Start a new thread that runs Compute tasks in background /// - Start two continuous queries, with and without filter, using same thin client connection /// - Update cache and verify that continuous query listeners receive correct events /// </summary> [Test] public void TestComputeWorksWhenContinuousQueryIsActive() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var receivedKeysAll = new ConcurrentBag<int>(); var receivedKeysOdd = new ConcurrentBag<int>(); var qry1 = new ContinuousQueryClient<int, int> { Listener = new DelegateListener<int, int>(e => receivedKeysOdd.Add(e.Key)), Filter = new OddKeyFilter() }; var qry2 = new ContinuousQueryClient<int, int> { Listener = new DelegateListener<int, int>(e => receivedKeysAll.Add(e.Key)), }; var cts = new CancellationTokenSource(); var computeRunnerTask = Task.Factory.StartNew(() => { while (!cts.IsCancellationRequested) { var res = Client.GetCompute().ExecuteJavaTask<int>( ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeInt); Assert.AreEqual(1, res); } }, cts.Token); var keys = Enumerable.Range(1, 10000).ToArray(); using (cache.QueryContinuous(qry1)) using (cache.QueryContinuous(qry2)) { foreach (var key in keys) { cache[key] = key; } } cts.Cancel(); computeRunnerTask.Wait(); TestUtils.WaitForTrueCondition(() => receivedKeysAll.Count == keys.Length); Assert.AreEqual(keys.Length / 2, receivedKeysOdd.Count); CollectionAssert.AreEquivalent(keys, receivedKeysAll); CollectionAssert.AreEquivalent(keys.Where(k => k % 2 == 1), receivedKeysOdd); } /// <summary> /// Tests that continuous query with filter receives only matching events. /// /// - Start a continuous query with filter /// - Verify that filter receives all events /// - Verify that listener receives filtered events /// </summary> [Test] public void TestContinuousQueryWithFilterReceivesOnlyMatchingEvents() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); ICacheEntryEvent<int, int> lastEvt = null; var listener = new DelegateListener<int, int>(e => lastEvt = e); var qry = new ContinuousQueryClient<int,int>(listener) { Filter = new OddKeyFilter() }; using (cache.QueryContinuous(qry)) { cache.Put(0, 0); TestUtils.WaitForTrueCondition(() => OddKeyFilter.LastKey == 0); Assert.IsNull(lastEvt); cache.Put(5, 5); TestUtils.WaitForTrueCondition(() => OddKeyFilter.LastKey == 5); TestUtils.WaitForTrueCondition(() => lastEvt != null); Assert.IsNotNull(lastEvt); Assert.AreEqual(5, lastEvt.Key); cache.Put(8, 8); TestUtils.WaitForTrueCondition(() => OddKeyFilter.LastKey == 8); Assert.AreEqual(5, lastEvt.Key); } } /// <summary> /// Tests that continuous query with a Java filter receives only matching events. /// /// - Start a continuous query with a Java filter /// - Check that .NET listener receives filtered events /// </summary> [Test] public void TestContinuousQueryWithJavaFilterReceivesOnlyMatchingEvents() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var evts = new ConcurrentBag<int>(); var listener = new DelegateListener<int, int>(e => evts.Add(e.Key)); var qry = new ContinuousQueryClient<int, int>(listener) { Filter = new JavaObject("org.apache.ignite.platform.PlatformCacheEntryEvenKeyEventFilter", null) .ToCacheEntryEventFilter<int, int>() }; using (cache.QueryContinuous(qry)) { cache.PutAll(Enumerable.Range(1, 5).ToDictionary(x => x, x => x)); } TestUtils.WaitForTrueCondition(() => evts.Count == 2); CollectionAssert.AreEquivalent(new[] {2, 4}, evts); } /// <summary> /// Tests that server-side updates are sent to the client. /// /// - Start a thin client continuous query /// - Update cache from server node /// - Check that thin client receives events /// </summary> [Test] public void TestClientContinuousQueryReceivesEventsFromServerCache() { const int count = 10000; var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var receiveCount = 0; var listener = new DelegateListener<int, int>(e => { Interlocked.Increment(ref receiveCount); }); using (cache.QueryContinuous(new ContinuousQueryClient<int, int>(listener))) { var serverCache = Ignition.GetIgnite("1").GetCache<int, int>(cache.Name); for (var i = 0; i < count; i++) { serverCache.Put(i, i); } TestUtils.WaitForTrueCondition(() => receiveCount == count); } } /// <summary> /// Tests that when cache is in binary mode (<see cref="ICacheClient{TK,TV}.WithKeepBinary{K1,V1}"/>, /// continuous query listener and filter receive binary objects. /// /// - Get a cache in binary mode (WithKeepBinary) /// - Start a continuous query /// - Check that both filter and listener receive objects in binary form /// </summary> [Test] public void TestContinuousQueryWithKeepBinaryPassesBinaryObjectsToListenerAndFilter() { var cache = Client.GetOrCreateCache<int, Person>(TestUtils.TestName); var binCache = cache.WithKeepBinary<int, IBinaryObject>(); var evts = new ConcurrentBag<IBinaryObject>(); var qry = new ContinuousQueryClient<int, IBinaryObject> { Listener = new DelegateListener<int, IBinaryObject>(e => evts.Add(e.Value)), Filter = new EvenIdBinaryFilter() }; using (binCache.QueryContinuous(qry)) { cache[2] = new Person(2); cache[3] = new Person(3); TestUtils.WaitForTrueCondition(() => !evts.IsEmpty); } // Listener should receive one event with an even id. var binObj = evts.Single(); Assert.IsNotNull(binObj); Assert.AreEqual(2, binObj.GetField<int>("Id")); Assert.AreEqual("Person 2", binObj.GetField<string>("Name")); // Filter has received both events, last one was filtered out. binObj = EvenIdBinaryFilter.LastValue; Assert.IsNotNull(binObj); Assert.AreEqual(3, binObj.GetField<int>("Id")); Assert.AreEqual("Person 3", binObj.GetField<string>("Name")); } /// <summary> /// Tests that custom key / value objects can be used in Continuous Query filter and listener. /// /// - Create a cache with a custom class value (Person) /// - Run a continuous query with filter and listener /// </summary> [Test] public void TestContinuousQueryWithCustomObjects() { var cache = Client.GetOrCreateCache<int, Person>(TestUtils.TestName); var evts = new ConcurrentBag<Person>(); var qry = new ContinuousQueryClient<int, Person> { Listener = new DelegateListener<int, Person>(e => evts.Add(e.Value)), Filter = new EvenIdFilter() }; using (cache.QueryContinuous(qry)) { cache[2] = new Person(2); cache[3] = new Person(3); TestUtils.WaitForTrueCondition(() => !evts.IsEmpty); } // Listener should receive one event with an even id. var obj = evts.Single(); Assert.IsNotNull(obj); Assert.AreEqual(2, obj.Id); Assert.AreEqual("Person 2", obj.Name); // Filter has received both events, last one was filtered out. obj = EvenIdFilter.LastValue; Assert.IsNotNull(obj); Assert.AreEqual(3, obj.Id); Assert.AreEqual("Person 3", obj.Name); } /// <summary> /// Tests that exception in continuous query remote filter is logged and event is delivered anyway. /// /// - Run a continuous query with a filter that throws an exception /// - Verify that exception is logged /// - Verify that the client receives an event /// </summary> [Test] public void TestExceptionInFilterIsLoggedAndFilterIsIgnored() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var evts = new ConcurrentBag<int>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(e => evts.Add(e.Key))) { Filter = new ExceptionalFilter() }; using (cache.QueryContinuous(qry)) { cache[1] = 1; } Assert.AreEqual(1, cache[1]); // Assert: error is logged. var error = GetLoggers() .SelectMany(x => x.Entries) .Where(e => e.Level >= LogLevel.Warn) .Select(e => e.Message) .LastOrDefault(); Assert.AreEqual( "CacheEntryEventFilter failed: javax.cache.event.CacheEntryListenerException: " + ExceptionalFilter.Error, error); // Assert: continuous query event is delivered. Assert.AreEqual(new[] {1}, evts); } /// <summary> /// Tests that continuous query disconnected event (<see cref="IContinuousQueryHandleClient.Disconnected"/>) /// is raised when thin client connection is lost. /// /// - Start a continuous query /// - Disconnect the client /// - Verify that the Disconnected event is raised /// </summary> [Test] public void TestClientDisconnectRaisesDisconnectedEventOnQueryHandle() { ICacheEntryEvent<int, int> lastEvt = null; var qry = new ContinuousQueryClient<int,int>( new DelegateListener<int, int>(e => lastEvt = e)); var client = GetClient(); var cache = client.GetOrCreateCache<int, int>(TestUtils.TestName); var handle = cache.QueryContinuous(qry); ContinuousQueryClientDisconnectedEventArgs disconnectedEventArgs = null; handle.Disconnected += (sender, args) => { disconnectedEventArgs = args; // ReSharper disable once AccessToDisposedClosure (disposed state does not matter) Assert.AreEqual(handle, sender); }; cache[1] = 1; TestUtils.WaitForTrueCondition(() => lastEvt != null); client.Dispose(); // Assert: disconnected event has been raised. TestUtils.WaitForTrueCondition(() => disconnectedEventArgs != null); Assert.IsNotNull(disconnectedEventArgs.Exception); StringAssert.StartsWith("Cannot access a disposed object", disconnectedEventArgs.Exception.Message); // Multiple dispose is allowed. handle.Dispose(); handle.Dispose(); } /// <summary> /// Tests that continuous query disconnected event is not raised on a disposed handle. /// /// - Start a continuous query /// - Subscribe to the Disconnected event /// - Stop the continuous query /// - Stop the client /// - Check that the Disconnected event did not occur /// </summary> [Test] public void TestClientDisconnectDoesNotRaiseDisconnectedEventOnDisposedQueryHandle() { var qry = new ContinuousQueryClient<int,int>(new DelegateListener<int, int>()); var client = GetClient(); var cache = client.GetOrCreateCache<int, int>(TestUtils.TestName); ContinuousQueryClientDisconnectedEventArgs disconnectedEventArgs = null; using (var handle = cache.QueryContinuous(qry)) { handle.Disconnected += (sender, args) => disconnectedEventArgs = args; } client.Dispose(); // Assert: disconnected event has NOT been raised. Assert.IsNull(disconnectedEventArgs); } /// <summary> /// Tests that client does not receive updates for a stopped continuous query. /// /// - Start a continuous query with the TimeInterval set to 1 second and the BufferSize to 10 /// - Put 1 entry to the cache /// - Stop the continuous query /// - Check that the client does not receive any continuous query events after the query has been stopped /// </summary> [Test] public void TestDisposedQueryHandleDoesNotReceiveUpdates() { // Stop the query before the batch is sent out by time interval. var interval = TimeSpan.FromSeconds(1); TestBatches(1, 10, interval, (keys, res) => { }); Thread.Sleep(interval); // Check that socket has no dangling notifications. Assert.IsEmpty(Client.GetActiveNotificationListeners()); } /// <summary> /// Tests that <see cref="ClientConnectorConfiguration.MaxOpenCursorsPerConnection"/> controls /// maximum continuous query count. /// /// - Set MaxOpenCursorsPerConnection /// - Try to start more queries than that /// - Check that correct exception is returned /// </summary> [Test] public void TestContinuousQueryCountIsLimitedByMaxCursors() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var qry = new ContinuousQueryClient<int, int>( new DelegateListener<int, int>()); var queries = Enumerable.Range(1, MaxCursors).Select(_ => cache.QueryContinuous(qry)).ToList(); var ex = Assert.Throws<IgniteClientException>(() => cache.QueryContinuous(qry)); queries.ForEach(q => q.Dispose()); StringAssert.StartsWith("Too many open cursors", ex.Message); Assert.AreEqual(ClientStatusCode.TooManyCursors, ex.StatusCode); } /// <summary> /// Tests that multiple queries can be started from multiple threads. /// /// - Run multiple continuous queries from different threads using the same thin client connection /// - Versify that results are correct /// </summary> [Test] public void TestMultipleQueriesMultithreaded() { var cache = Ignition.GetIgnite().GetOrCreateCache<int, int>(TestUtils.TestName); cache.Put(1, 0); var cts = new CancellationTokenSource(); var updaterThread = Task.Factory.StartNew(() => { for (long i = 0; i < long.MaxValue && !cts.IsCancellationRequested; i++) { cache.Put(1, (int) i); } }); var clientCache = Client.GetCache<int, int>(cache.Name); TestUtils.RunMultiThreaded(() => { var evt = new ManualResetEventSlim(); var qry = new ContinuousQueryClient<int, int> { Listener = new DelegateListener<int, int>(e => { Assert.AreEqual(1, e.Key); Assert.AreEqual(CacheEntryEventType.Updated, e.EventType); evt.Set(); }) }; for (var i = 0; i < 200; i++) { evt.Reset(); using (clientCache.QueryContinuous(qry)) { evt.Wait(); } } }, 16); cts.Cancel(); updaterThread.Wait(); } /// <summary> /// Tests that Listener presence is validated before starting the continuous query. /// </summary> [Test] public void TestContinuousQueryWithoutListenerThrowsException() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var ex = Assert.Throws<ArgumentNullException>(() => cache.QueryContinuous(new ContinuousQueryClient<int, int>())); Assert.AreEqual("continuousQuery.Listener", ex.ParamName); } /// <summary> /// Tests that when custom <see cref="ContinuousQueryClient{TK,TV}.BufferSize"/> is set, /// events are sent in batches, not 1 by 1. /// /// - Start a continuous query with the BufferSize set to 3 /// - Put 8 entries to the cache /// - Check that 2 batches of 3 entries has been received, and last 2 keys has not been received. /// </summary> [Test] public void TestCustomBufferSizeResultsInBatchedUpdates() { TestBatches(8, 3, TimeSpan.Zero, (keys, res) => { TestUtils.WaitForTrueCondition(() => res.Count == 2, () => res.Count.ToString()); var resOrdered = res.OrderBy(x => x.FirstOrDefault()).ToList(); CollectionAssert.AreEquivalent(keys.Take(3), resOrdered.First()); CollectionAssert.AreEquivalent(keys.Skip(3).Take(3), resOrdered.Last()); }); } /// <summary> /// Tests that when custom <see cref="ContinuousQueryClient{TK,TV}.TimeInterval"/> is set, /// and <see cref="ContinuousQueryClient{TK,TV}.BufferSize"/> is greater than 1, /// batches are sent out before buffer is full when the time interval passes. /// /// - Start a continuous query with the BufferSize set to 4 and TimeInterval set to 1 second /// - Put 2 entries to the cache /// - Wait and check that clint has received one batch of 2 entries /// </summary> [Test] public void TestCustomTimeIntervalCausesIncompleteBatches() { TestBatches(2, 4, TimeSpan.FromSeconds(1), (keys, res) => { TestUtils.WaitForTrueCondition(() => res.Count == 1, () => res.Count.ToString(), 2000); CollectionAssert.AreEquivalent(keys.Take(2), res.Single()); }); } /// <summary> /// Tests that <see cref="ContinuousQueryClient{TK,TV}.IncludeExpired"/> is false by default /// and expiration events are not delivered. /// /// - Create a cache with expiry policy /// - Start a continuous query with default settings /// - Check that Created events are delivered, but Expired events are not /// </summary> [Test] public void TestIncludeExpiredIsFalseByDefaultAndExpiredEventsAreSkipped() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName) .WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(100), null, null)); var events = new ConcurrentQueue<ICacheEntryEvent<int, int>>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(events.Enqueue)); Assert.IsFalse(qry.IncludeExpired); using (cache.QueryContinuous(qry)) { cache[1] = 2; TestUtils.WaitForTrueCondition(() => !cache.ContainsKey(1), 5000); cache[2] = 3; } Assert.AreEqual(2, events.Count); Assert.AreEqual(CacheEntryEventType.Created, events.First().EventType); Assert.AreEqual(CacheEntryEventType.Created, events.Last().EventType); } /// <summary> /// Tests that enabling <see cref="ContinuousQueryClient{TK,TV}.IncludeExpired"/> causes /// <see cref="CacheEntryEventType.Expired"/> events to be delivered. /// /// - Create a cache with expiry policy /// - Start a continuous query with <see cref="ContinuousQueryClient{TK,TV}.IncludeExpired"/> set to <c>true</c> /// - Check that Expired events are delivered /// </summary> [Test] public void TestExpiredEventsAreDeliveredWhenIncludeExpiredIsTrue() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName) .WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(100), null, null)); var events = new ConcurrentQueue<ICacheEntryEvent<int, int>>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(events.Enqueue)) { IncludeExpired = true }; using (cache.QueryContinuous(qry)) { cache[1] = 2; TestUtils.WaitForTrueCondition(() => events.Count == 2, 5000); } Assert.AreEqual(2, events.Count); Assert.AreEqual(CacheEntryEventType.Created, events.First().EventType); Assert.AreEqual(CacheEntryEventType.Expired, events.Last().EventType); Assert.IsTrue(events.Last().HasValue); Assert.IsTrue(events.Last().HasOldValue); Assert.AreEqual(2, events.Last().Value); Assert.AreEqual(2, events.Last().OldValue); Assert.AreEqual(1, events.Last().Key); } /// <summary> /// Tests batching behavior. /// </summary> private void TestBatches(int keyCount, int bufferSize, TimeSpan interval, Action<List<int>, ConcurrentQueue<List<int>>> assert) { var res = new ConcurrentQueue<List<int>>(); var qry = new ContinuousQueryClient<int, int> { Listener = new DelegateBatchListener<int, int>(evts => res.Enqueue(evts.Select(e => e.Key).ToList())), BufferSize = bufferSize, TimeInterval = interval }; var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var server = Ignition.GetIgnite("1"); var serverCache = server.GetCache<int, int>(cache.Name); // Use primary keys for "remote" node to ensure batching. // Client is connected to another server node, so it will receive batches as expected. var keys = TestUtils.GetPrimaryKeys(server, cache.Name).Take(keyCount).ToList(); using (cache.QueryContinuous(qry)) { keys.ForEach(k => serverCache.Put(k, k)); assert(keys, res); } } /** <inheritdoc /> */ protected override IgniteConfiguration GetIgniteConfiguration() { return new IgniteConfiguration(base.GetIgniteConfiguration()) { ClientConnectorConfiguration = new ClientConnectorConfiguration { MaxOpenCursorsPerConnection = MaxCursors, ThinClientConfiguration = new ThinClientConfiguration { MaxActiveComputeTasksPerConnection = 100, } } }; } /** */ private class DelegateListener<TK, TV> : ICacheEntryEventListener<TK, TV> { /** */ private readonly Action<ICacheEntryEvent<TK, TV>> _action; /** */ public DelegateListener(Action<ICacheEntryEvent<TK, TV>> action = null) { _action = action ?? (_ => {}); } /** <inheritdoc /> */ public void OnEvent(IEnumerable<ICacheEntryEvent<TK, TV>> evts) { foreach (var evt in evts) { _action(evt); } } } /** */ private class DelegateBatchListener<TK, TV> : ICacheEntryEventListener<TK, TV> { /** */ private readonly Action<IEnumerable<ICacheEntryEvent<TK, TV>>> _action; /** */ public DelegateBatchListener(Action<IEnumerable<ICacheEntryEvent<TK, TV>>> action = null) { _action = action ?? (_ => {}); } /** <inheritdoc /> */ public void OnEvent(IEnumerable<ICacheEntryEvent<TK, TV>> evts) { _action(evts); } } /** */ private class OddKeyFilter : ICacheEntryEventFilter<int, int>, ICacheEntryFilter<int, int> { /** */ public static int LastKey; /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, int> evt) { LastKey = evt.Key; return evt.Key % 2 == 1; } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, int> entry) { LastKey = entry.Key; return entry.Key % 2 == 1; } } /** */ private class ExceptionalFilter : ICacheEntryEventFilter<int, int>, ICacheEntryFilter<int, int> { /** */ public const string Error = "Foo failed because of bar"; /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, int> evt) { throw new Exception(Error); } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, int> entry) { throw new Exception(Error); } } /** */ private class EvenIdFilter : ICacheEntryEventFilter<int, Person> { /** */ public static Person LastValue { get; set; } /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, Person> evt) { LastValue = evt.Value; return evt.Value.Id % 2 == 0; } } /** */ private class EvenIdBinaryFilter : ICacheEntryEventFilter<int, IBinaryObject> { /** */ public static IBinaryObject LastValue { get; set; } /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, IBinaryObject> evt) { LastValue = evt.Value; return evt.Value.GetField<int>("Id") % 2 == 0; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace ColourList.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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class FindTests { private static void RunTest(Action<X509Certificate2Collection> test) { RunTest((msCer, pfxCer, col1) => test(col1)); } private static void RunTest(Action<X509Certificate2, X509Certificate2, X509Certificate2Collection> test) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection col1 = new X509Certificate2Collection(new[] { msCer, pfxCer }); test(msCer, pfxCer, col1); } } private static void RunExceptionTest<TException>(X509FindType findType, object findValue) where TException : Exception { RunTest( (msCer, pfxCer, col1) => { Assert.Throws<TException>(() => col1.Find(findType, findValue, validOnly: false)); }); } private static void RunZeroMatchTest(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } private static void RunSingleMatchTest_MsCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(msCer, col1, findType, findValue); }); } private static void RunSingleMatchTest_PfxCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(pfxCer, col1, findType, findValue); }); } private static void EvaluateSingleMatch( X509Certificate2 expected, X509Certificate2Collection col1, X509FindType findType, object findValue) { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); byte[] serialNumber; using (X509Certificate2 match = col2[0]) { Assert.Equal(expected, match); Assert.NotSame(expected, match); // FriendlyName is Windows-only. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Verify that the find result and original are linked, not just equal. match.FriendlyName = "HAHA"; Assert.Equal("HAHA", expected.FriendlyName); } serialNumber = match.GetSerialNumber(); } // Check that disposing match didn't dispose expected Assert.Equal(serialNumber, expected.GetSerialNumber()); } } [Theory] [MemberData(nameof(GenerateInvalidInputs))] public static void FindWithWrongTypeValue(X509FindType findType, Type badValueType) { object badValue; if (badValueType == typeof(object)) { badValue = new object(); } else if (badValueType == typeof(DateTime)) { badValue = DateTime.Now; } else if (badValueType == typeof(byte[])) { badValue = Array.Empty<byte>(); } else if (badValueType == typeof(string)) { badValue = "Hello, world"; } else { throw new InvalidOperationException("No creator exists for type " + badValueType); } RunExceptionTest<CryptographicException>(findType, badValue); } [Theory] [MemberData(nameof(GenerateInvalidOidInputs))] public static void FindWithBadOids(X509FindType findType, string badOid) { RunExceptionTest<ArgumentException>(findType, badOid); } [Fact] public static void FindByNullName() { RunExceptionTest<ArgumentNullException>(X509FindType.FindBySubjectName, null); } [Fact] public static void FindByInvalidThumbprint() { RunZeroMatchTest(X509FindType.FindByThumbprint, "Nothing"); } [Fact] public static void FindByInvalidThumbprint_RightLength() { RunZeroMatchTest(X509FindType.FindByThumbprint, "ffffffffffffffffffffffffffffffffffffffff"); } [Fact] public static void FindByValidThumbprint() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( pfxCer, col1, X509FindType.FindByThumbprint, pfxCer.Thumbprint); }); } [Theory] [InlineData(false)] [InlineData(true)] public static void FindByValidThumbprint_ValidOnly(bool validOnly) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { var col1 = new X509Certificate2Collection(msCer); X509Certificate2Collection col2 = col1.Find(X509FindType.FindByThumbprint, msCer.Thumbprint, validOnly); using (new ImportedCollection(col2)) { // The certificate is expired. Unless we invent time travel // (or roll the computer clock back significantly), the validOnly // criteria should filter it out. // // This test runs both ways to make sure that the precondition of // "would match otherwise" is met (in the validOnly=false case it is // effectively the same as FindByValidThumbprint, but does less inspection) int expectedMatchCount = validOnly ? 0 : 1; Assert.Equal(expectedMatchCount, col2.Count); if (!validOnly) { // Double check that turning on validOnly doesn't prevent the cloning // behavior of Find. using (X509Certificate2 match = col2[0]) { Assert.Equal(msCer, match); Assert.NotSame(msCer, match); } } } } } [Fact] public static void FindByValidThumbprint_RootCert() { using (X509Store machineRoot = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { machineRoot.Open(OpenFlags.ReadOnly); using (var watchedStoreCerts = new ImportedCollection(machineRoot.Certificates)) { X509Certificate2Collection storeCerts = watchedStoreCerts.Collection; X509Certificate2 rootCert = null; TimeSpan tolerance = TimeSpan.FromHours(12); // These APIs use local time, so use DateTime.Now, not DateTime.UtcNow. DateTime notBefore = DateTime.Now; DateTime notAfter = DateTime.Now.Subtract(tolerance); foreach (X509Certificate2 cert in storeCerts) { if (cert.NotBefore >= notBefore || cert.NotAfter <= notAfter) { // Not (safely) valid, skip. continue; } X509KeyUsageExtension keyUsageExtension = null; foreach (X509Extension extension in cert.Extensions) { keyUsageExtension = extension as X509KeyUsageExtension; if (keyUsageExtension != null) { break; } } // Some tool is putting the com.apple.systemdefault utility cert in the // LM\Root store on OSX machines; but it gets rejected by OpenSSL as an // invalid root for not having the Certificate Signing key usage value. // // While the real problem seems to be with whatever tool is putting it // in the bundle; we can work around it here. const X509KeyUsageFlags RequiredFlags = X509KeyUsageFlags.KeyCertSign; // No key usage extension means "good for all usages" if (keyUsageExtension != null && (keyUsageExtension.KeyUsages & RequiredFlags) != RequiredFlags) { // Not a valid KeyUsage, skip. continue; } using (ChainHolder chainHolder = new ChainHolder()) { chainHolder.Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; if (!chainHolder.Chain.Build(cert)) { // Despite being not expired and having a valid KeyUsage, it's // not considered a valid root/chain. continue; } } rootCert = cert; break; } // Just in case someone has a system with no valid trusted root certs whatsoever. if (rootCert != null) { X509Certificate2Collection matches = storeCerts.Find(X509FindType.FindByThumbprint, rootCert.Thumbprint, true); using (new ImportedCollection(matches)) { // Improve the debuggability, since the root cert found on each // machine might be different if (matches.Count == 0) { Assert.True( false, $"Root certificate '{rootCert.Subject}' ({rootCert.NotBefore} - {rootCert.NotAfter}) is findable with thumbprint '{rootCert.Thumbprint}' and validOnly=true"); } Assert.NotSame(rootCert, matches[0]); Assert.Equal(rootCert, matches[0]); } } } } } [Theory] [InlineData("Nothing")] [InlineData("US, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] public static void TestSubjectName_NoMatch(string subjectQualifier) { RunZeroMatchTest(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("Microsoft Corporation")] [InlineData("MOPR")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] [InlineData("us, washington, redmond, microsoft corporation, mopr, microsoft corporation")] public static void TestSubjectName_Match(string subjectQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("ou=mopr, o=microsoft corporation")] [InlineData("CN=Microsoft Corporation")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedSubjectName_NoMatch(string distinguishedSubjectName) { RunZeroMatchTest(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Theory] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft corporation, ou=mopr, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedSubjectName_Match(string distinguishedSubjectName) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Fact] public static void TestIssuerName_NoMatch() { RunZeroMatchTest(X509FindType.FindByIssuerName, "Nothing"); } [Theory] [InlineData("Microsoft Code Signing PCA")] [InlineData("Microsoft Corporation")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, Microsoft Code Signing PCA")] [InlineData("us, washington, redmond, microsoft corporation, microsoft code signing pca")] public static void TestIssuerName_Match(string issuerQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerName, issuerQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("CN=Microsoft Code Signing PCA")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedIssuerName_NoMatch(string issuerDistinguishedName) { RunZeroMatchTest(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Theory] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft Code signing pca, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft code signing pca, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedIssuerName_Match(string issuerDistinguishedName) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Fact] public static void TestByTimeValid_Before() { RunTest( (msCer, pfxCer, col1) => { DateTime earliest = new[] { msCer.NotBefore, pfxCer.NotBefore }.Min(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, earliest - TimeSpan.FromSeconds(1), validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_After() { RunTest( (msCer, pfxCer, col1) => { DateTime latest = new[] { msCer.NotAfter, pfxCer.NotAfter }.Max(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, latest + TimeSpan.FromSeconds(1), validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_Between() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); DateTime noMatchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestByTimeValid_Match() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( msCer, col1, X509FindType.FindByTimeValid, msCer.NotBefore + TimeSpan.FromSeconds(1)); }); } [Fact] public static void TestFindByTimeNotYetValid_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the latest NotBefore, so one is valid, the other is not yet valid. DateTime matchTime = latestNotBefore - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, matchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); } }); } [Fact] public static void TestFindByTimeNotYetValid_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the latest NotBefore, both certificates are time-valid DateTime noMatchTime = latestNotBefore + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestFindByTimeExpired_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the earliest NotAfter, so one is valid, the other is no longer valid. DateTime matchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, matchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(1, col2.Count); } }); } [Fact] public static void TestFindByTimeExpired_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisfied Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the earliest NotAfter, so both certificates are valid DateTime noMatchTime = earliestNotAfter - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, noMatchTime, validOnly: false); using (new ImportedCollection(col2)) { Assert.Equal(0, col2.Count); } }); } [Fact] public static void TestBySerialNumber_Decimal() { // Decimal string is an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "284069184166497622998429950103047369500"); } [Fact] public static void TestBySerialNumber_DecimalLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "000" + "284069184166497622998429950103047369500"); } [Theory] [InlineData("1137338006039264696476027508428304567989436592")] // Leading zeroes are fine/ignored [InlineData("0001137338006039264696476027508428304567989436592")] // Compat: Minus signs are ignored [InlineData("-1137338006039264696476027508428304567989436592")] public static void TestBySerialNumber_Decimal_CertB(string serialNumber) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, serialNumber); } [Fact] public static void TestBySerialNumber_Hex() { // Hex string is also an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_HexIgnoreCase() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "d5b5bc1c458a558845bff51cb4dff31c"); } [Fact] public static void TestBySerialNumber_HexLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "0000" + "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_NoMatch() { RunZeroMatchTest( X509FindType.FindBySerialNumber, "23000000B011AF0A8BD03B9FDD0001000000B0"); } [Theory] [MemberData(nameof(GenerateWorkingFauxSerialNumbers))] public static void TestBySerialNumber_Match_NonDecimalInput(string input) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, input); } [Fact] public static void TestByExtension_FriendlyName() { // Cannot just say "Enhanced Key Usage" here because the extension name is localized. // Instead, look it up via the OID. RunSingleMatchTest_MsCer(X509FindType.FindByExtension, new Oid("2.5.29.37").FriendlyName); } [Fact] public static void TestByExtension_OidValue() { RunSingleMatchTest_MsCer(X509FindType.FindByExtension, "2.5.29.37"); } [Fact] // Compat: Non-ASCII digits don't throw, but don't match. public static void TestByExtension_OidValue_ArabicNumericChar() { // This uses the same OID as TestByExtension_OidValue, but uses "Arabic-Indic Digit Two" instead // of "Digit Two" in the third segment. This value can't possibly ever match, but it doesn't throw // as an illegal OID value. RunZeroMatchTest(X509FindType.FindByExtension, "2.5.\u06629.37"); } [Fact] public static void TestByExtension_UnknownFriendlyName() { RunExceptionTest<ArgumentException>(X509FindType.FindByExtension, "BOGUS"); } [Fact] public static void TestByExtension_NoMatch() { RunZeroMatchTest(X509FindType.FindByExtension, "2.9"); } [Fact] public static void TestBySubjectKeyIdentifier_UsingFallback() { RunSingleMatchTest_PfxCer( X509FindType.FindBySubjectKeyIdentifier, "B4D738B2D4978AFF290A0B02987BABD114FEE9C7"); } [Theory] [InlineData("5971A65A334DDA980780FF841EBE87F9723241F2")] // Whitespace is allowed [InlineData("59 71\tA6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")] // Lots of kinds of whitespace (does not include \u000b or \u000c, because those // produce a build warning (which becomes an error): // EXEC : warning : '(not included here)', hexadecimal value 0x0C, is an invalid character. [InlineData( "59\u000971\u000aA6\u30005A\u205f33\u000d4D\u0020DA\u008598\u00a007\u1680" + "80\u2000FF\u200184\u20021E\u2003BE\u200487\u2005F9\u200672\u200732\u2008" + "4\u20091\u200aF\u20282\u2029\u202f")] // Non-byte-aligned whitespace is allowed [InlineData("597 1A6 5A3 34D DA9 807 80F F84 1EB E87 F97 232 41F 2")] // Non-symmetric whitespace is allowed [InlineData(" 5971A65 A334DDA980780FF84 1EBE87F97 23241F 2")] public static void TestBySubjectKeyIdentifier_ExtensionPresent(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Theory] // Compat: Lone trailing nybbles are ignored [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")] // Compat: Lone trailing nybbles are ignored, even if not hex [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")] // Compat: A non-hex character as the high nybble makes that nybble be F [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 p9 72 32 41 F2")] // Compat: A non-hex character as the low nybble makes the whole byte FF. [InlineData("59 71 A6 5A 33 4D DA 98 07 80 0p 84 1E BE 87 F9 72 32 41 F2")] public static void TestBySubjectKeyIdentifier_Compat(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch() { RunZeroMatchTest(X509FindType.FindBySubjectKeyIdentifier, ""); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch_RightLength() { RunZeroMatchTest( X509FindType.FindBySubjectKeyIdentifier, "5971A65A334DDA980780FF841EBE87F9723241F0"); } [Fact] public static void TestByApplicationPolicy_MatchAll() { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", false); using (new ImportedCollection(results)) { Assert.Equal(2, results.Count); Assert.True(results.Contains(msCer)); Assert.True(results.Contains(pfxCer)); } }); } [Fact] public static void TestByApplicationPolicy_NoPolicyAlwaysMatches() { // PfxCer doesn't have any application policies which means it's good for all usages (even nonsensical ones.) RunSingleMatchTest_PfxCer(X509FindType.FindByApplicationPolicy, "2.2"); } [Fact] public static void TestByApplicationPolicy_NoMatch() { RunTest( (msCer, pfxCer, col1) => { // Per TestByApplicationPolicy_NoPolicyAlwaysMatches we know that pfxCer will match, so remove it. col1.Remove(pfxCer); X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "2.2", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } }); } [Fact] public static void TestByCertificatePolicies_MatchA() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.18.19"); } } [Fact] public static void TestByCertificatePolicies_MatchB() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.32.33"); } } [Fact] public static void TestByCertificatePolicies_NoMatch() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { X509Certificate2Collection col1 = new X509Certificate2Collection(policyCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByCertificatePolicy, "2.999", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } } } [Fact] public static void TestByTemplate_MatchA() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "Hello"); } } [Fact] public static void TestByTemplate_MatchB() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "2.7.8.9"); } } [Fact] public static void TestByTemplate_NoMatch() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { X509Certificate2Collection col1 = new X509Certificate2Collection(templatedCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByTemplateName, "2.999", false); using (new ImportedCollection(results)) { Assert.Equal(0, results.Count); } } } [Theory] [InlineData((int)0x80)] [InlineData((uint)0x80)] [InlineData(X509KeyUsageFlags.DigitalSignature)] [InlineData("DigitalSignature")] [InlineData("digitalSignature")] public static void TestFindByKeyUsage_Match(object matchCriteria) { TestFindByKeyUsage(true, matchCriteria); } [Theory] [InlineData((int)0x20)] [InlineData((uint)0x20)] [InlineData(X509KeyUsageFlags.KeyEncipherment)] [InlineData("KeyEncipherment")] [InlineData("KEYEncipherment")] public static void TestFindByKeyUsage_NoMatch(object matchCriteria) { TestFindByKeyUsage(false, matchCriteria); } private static void TestFindByKeyUsage(bool shouldMatch, object matchCriteria) { using (var noKeyUsages = new X509Certificate2(TestData.MsCertificate)) using (var noKeyUsages2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) using (var keyUsages = new X509Certificate2(Path.Combine("TestData", "microsoft.cer"))) { var coll = new X509Certificate2Collection { noKeyUsages, noKeyUsages2, keyUsages, }; X509Certificate2Collection results = coll.Find(X509FindType.FindByKeyUsage, matchCriteria, false); using (new ImportedCollection(results)) { // The two certificates with no KeyUsages extension will always match, // the real question is about the third. int matchCount = shouldMatch ? 3 : 2; Assert.Equal(matchCount, results.Count); if (shouldMatch) { bool found = false; foreach (X509Certificate2 cert in results) { if (keyUsages.Equals(cert)) { Assert.NotSame(cert, keyUsages); found = true; break; } } Assert.True(found, "Certificate with key usages was found in the collection"); } else { Assert.False( results.Contains(keyUsages), "KeyUsages certificate is not present in the collection"); } } } } public static IEnumerable<object[]> GenerateWorkingFauxSerialNumbers { get { const string seedDec = "1137338006039264696476027508428304567989436592"; string[] nonHexWords = { "wow", "its", "tough", "using", "only", "high", "lttr", "vlus" }; string gluedTogether = string.Join("", nonHexWords); string withSpaces = string.Join(" ", nonHexWords); yield return new object[] { gluedTogether + seedDec }; yield return new object[] { seedDec + gluedTogether }; yield return new object[] { withSpaces + seedDec }; yield return new object[] { seedDec + withSpaces }; StringBuilder builderDec = new StringBuilder(512); int offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; } builderDec.Append(nonHexWords[i]); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; builderDec.Length = 0; offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; builderDec.Append(' '); } builderDec.Append(nonHexWords[i]); builderDec.Append(' '); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; } } public static IEnumerable<object[]> GenerateInvalidOidInputs { get { X509FindType[] oidTypes = { X509FindType.FindByApplicationPolicy, }; string[] invalidOids = { "", "This Is Not An Oid", "1", "95.22", ".1", "1..1", "1.", "1.2.", }; List<object[]> combinations = new List<object[]>(oidTypes.Length * invalidOids.Length); for (int findTypeIndex = 0; findTypeIndex < oidTypes.Length; findTypeIndex++) { for (int oidIndex = 0; oidIndex < invalidOids.Length; oidIndex++) { combinations.Add(new object[] { oidTypes[findTypeIndex], invalidOids[oidIndex] }); } } return combinations; } } public static IEnumerable<object[]> GenerateInvalidInputs { get { Type[] allTypes = { typeof(object), typeof(DateTime), typeof(byte[]), typeof(string), }; Tuple<X509FindType, Type>[] legalInputs = { Tuple.Create(X509FindType.FindByThumbprint, typeof(string)), Tuple.Create(X509FindType.FindBySubjectName, typeof(string)), Tuple.Create(X509FindType.FindBySubjectDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindBySerialNumber, typeof(string)), Tuple.Create(X509FindType.FindByTimeValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeNotYetValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeExpired, typeof(DateTime)), Tuple.Create(X509FindType.FindByTemplateName, typeof(string)), Tuple.Create(X509FindType.FindByApplicationPolicy, typeof(string)), Tuple.Create(X509FindType.FindByCertificatePolicy, typeof(string)), Tuple.Create(X509FindType.FindByExtension, typeof(string)), // KeyUsage supports int/uint/KeyUsage/string, but only one of those is in allTypes. Tuple.Create(X509FindType.FindByKeyUsage, typeof(string)), Tuple.Create(X509FindType.FindBySubjectKeyIdentifier, typeof(string)), }; List<object[]> invalidCombinations = new List<object[]>(); for (int findTypesIndex = 0; findTypesIndex < legalInputs.Length; findTypesIndex++) { Tuple<X509FindType, Type> tuple = legalInputs[findTypesIndex]; for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) { Type t = allTypes[typeIndex]; if (t != tuple.Item2) { invalidCombinations.Add(new object[] { tuple.Item1, t }); } } } return invalidCombinations; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Tests.TestHelpers; using Xunit; namespace LibGit2Sharp.Tests { public class CommitFixture : BaseFixture { private const string sha = "8496071c1b46c854b31185ea97743be6a8774479"; private readonly List<string> expectedShas = new List<string> { "a4a7d", "c4780", "9fd73", "4a202", "5b5b0", "84960" }; [Fact] public void CanCountCommits() { using (var repo = new Repository(BareTestRepoPath)) { Assert.Equal(7, repo.Commits.Count()); } } [Fact] public void CanCorrectlyCountCommitsWhenSwitchingToAnotherBranch() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { // Hard reset and then remove untracked files repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); repo.Checkout("test"); Assert.Equal(2, repo.Commits.Count()); Assert.Equal("e90810b8df3e80c413d903f631643c716887138d", repo.Commits.First().Id.Sha); repo.Checkout("master"); Assert.Equal(9, repo.Commits.Count()); Assert.Equal("32eab9cb1f450b5fe7ab663462b77d7f4b703344", repo.Commits.First().Id.Sha); } } [Fact] public void CanEnumerateCommits() { int count = 0; using (var repo = new Repository(BareTestRepoPath)) { foreach (Commit commit in repo.Commits) { Assert.NotNull(commit); count++; } } Assert.Equal(7, count); } [Fact] public void CanEnumerateCommitsInDetachedHeadState() { string path = CloneBareTestRepo(); using (var repo = new Repository(path)) { ObjectId parentOfHead = repo.Head.Tip.Parents.First().Id; repo.Refs.Add("HEAD", parentOfHead.Sha, true); Assert.Equal(true, repo.Info.IsHeadDetached); Assert.Equal(6, repo.Commits.Count()); } } [Fact] public void DefaultOrderingWhenEnumeratingCommitsIsTimeBased() { using (var repo = new Repository(BareTestRepoPath)) { Assert.Equal(CommitSortStrategies.Time, repo.Commits.SortedBy); } } [Fact] public void CanEnumerateCommitsFromSha() { int count = 0; using (var repo = new Repository(BareTestRepoPath)) { foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f" })) { Assert.NotNull(commit); count++; } } Assert.Equal(6, count); } [Fact] public void QueryingTheCommitHistoryWithUnknownShaOrInvalidEntryPointThrows() { using (var repo = new Repository(BareTestRepoPath)) { Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = Constants.UnknownSha }).Count()); Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = "refs/heads/deadbeef" }).Count()); Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null }).Count()); } } [Fact] public void QueryingTheCommitHistoryFromACorruptedReferenceThrows() { string path = CloneBareTestRepo(); using (var repo = new Repository(path)) { CreateCorruptedDeadBeefHead(repo.Info.Path); Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Branches["deadbeef"] }).Count()); Assert.Throws<LibGit2SharpException>(() => repo.Commits.QueryBy(new CommitFilter { Since = repo.Refs["refs/heads/deadbeef"] }).Count()); } } [Fact] public void QueryingTheCommitHistoryWithBadParamsThrows() { using (var repo = new Repository(BareTestRepoPath)) { Assert.Throws<ArgumentException>(() => repo.Commits.QueryBy(new CommitFilter { Since = string.Empty })); Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(new CommitFilter { Since = null })); Assert.Throws<ArgumentNullException>(() => repo.Commits.QueryBy(default(CommitFilter))); } } [Fact] public void CanEnumerateCommitsWithReverseTimeSorting() { var reversedShas = new List<string>(expectedShas); reversedShas.Reverse(); int count = 0; using (var repo = new Repository(BareTestRepoPath)) { foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse })) { Assert.NotNull(commit); Assert.True(commit.Sha.StartsWith(reversedShas[count])); count++; } } Assert.Equal(6, count); } [Fact] public void CanEnumerateCommitsWithReverseTopoSorting() { using (var repo = new Repository(BareTestRepoPath)) { List<Commit> commits = repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Time | CommitSortStrategies.Reverse }).ToList(); foreach (Commit commit in commits) { Assert.NotNull(commit); foreach (Commit p in commit.Parents) { Commit parent = commits.Single(x => x.Id == p.Id); Assert.True(commits.IndexOf(commit) > commits.IndexOf(parent)); } } } } [Fact] public void CanSimplifyByFirstParent() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Head, FirstParentOnly = true }, new[] { "4c062a6", "be3563a", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanGetParentsCount() { using (var repo = new Repository(BareTestRepoPath)) { Assert.Equal(1, repo.Commits.First().Parents.Count()); } } [Fact] public void CanEnumerateCommitsWithTimeSorting() { int count = 0; using (var repo = new Repository(BareTestRepoPath)) { foreach (Commit commit in repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Time })) { Assert.NotNull(commit); Assert.True(commit.Sha.StartsWith(expectedShas[count])); count++; } } Assert.Equal(6, count); } [Fact] public void CanEnumerateCommitsWithTopoSorting() { using (var repo = new Repository(BareTestRepoPath)) { List<Commit> commits = repo.Commits.QueryBy(new CommitFilter { Since = "a4a7dce85cf63874e984719f4fdd239f5145052f", SortBy = CommitSortStrategies.Topological }).ToList(); foreach (Commit commit in commits) { Assert.NotNull(commit); foreach (Commit p in commit.Parents) { Commit parent = commits.Single(x => x.Id == p.Id); Assert.True(commits.IndexOf(commit) < commits.IndexOf(parent)); } } } } [Fact] public void CanEnumerateFromHead() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Head }, new[] { "4c062a6", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateFromDetachedHead() { string path = CloneStandardTestRepo(); using (var repoClone = new Repository(path)) { // Hard reset and then remove untracked files repoClone.Reset(ResetMode.Hard); repoClone.RemoveUntrackedFiles(); string headSha = repoClone.Head.Tip.Sha; repoClone.Checkout(headSha); AssertEnumerationOfCommitsInRepo(repoClone, repo => new CommitFilter { Since = repo.Head }, new[] { "32eab9c", "592d3c8", "4c062a6", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } } [Fact] public void CanEnumerateUsingTwoHeadsAsBoundaries() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = "HEAD", Until = "refs/heads/br2" }, new[] { "4c062a6", "be3563a" } ); } [Fact] public void CanEnumerateUsingImplicitHeadAsSinceBoundary() { AssertEnumerationOfCommits( repo => new CommitFilter { Until = "refs/heads/br2" }, new[] { "4c062a6", "be3563a" } ); } [Fact] public void CanEnumerateUsingTwoAbbreviatedShasAsBoundaries() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = "a4a7dce", Until = "4a202b3" }, new[] { "a4a7dce", "c47800c", "9fd738e" } ); } [Fact] public void CanEnumerateCommitsFromTwoHeads() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = new[] { "refs/heads/br2", "refs/heads/master" } }, new[] { "4c062a6", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateCommitsFromMixedStartingPoints() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = new object[] { repo.Branches["br2"], "refs/heads/master", new ObjectId("e90810b8df3e80c413d903f631643c716887138d") } }, new[] { "4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateCommitsUsingGlob() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Refs.FromGlob("refs/heads/*") }, new[] { "4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071" }); } [Fact] public void CanHideCommitsUsingGlob() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = "refs/heads/packed-test", Until = repo.Refs.FromGlob("*/packed") }, new[] { "4a202b3", "5b5b025", "8496071" }); } [Fact] public void CanEnumerateCommitsFromAnAnnotatedTag() { CanEnumerateCommitsFromATag(t => t); } [Fact] public void CanEnumerateCommitsFromATagAnnotation() { CanEnumerateCommitsFromATag(t => t.Annotation); } private static void CanEnumerateCommitsFromATag(Func<Tag, object> transformer) { AssertEnumerationOfCommits( repo => new CommitFilter { Since = transformer(repo.Tags["test"]) }, new[] { "e90810b", "6dcf9bf", } ); } [Fact] public void CanEnumerateAllCommits() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Refs.OrderBy(r => r.CanonicalName, StringComparer.Ordinal), }, new[] { "44d5d18", "bb65291", "532740a", "503a16f", "3dfd6fd", "4409de1", "902c60b", "4c062a6", "e90810b", "6dcf9bf", "a4a7dce", "be3563a", "c47800c", "9fd738e", "4a202b3", "41bc8c6", "5001298", "5b5b025", "8496071", }); } [Fact] public void CanEnumerateCommitsFromATagWhichPointsToABlob() { AssertEnumerationOfCommits( repo => new CommitFilter { Since = repo.Tags["point_to_blob"] }, new string[] { }); } [Fact] public void CanEnumerateCommitsFromATagWhichPointsToATree() { string path = CloneBareTestRepo(); using (var repo = new Repository(path)) { string headTreeSha = repo.Head.Tip.Tree.Sha; Tag tag = repo.ApplyTag("point_to_tree", headTreeSha); AssertEnumerationOfCommitsInRepo(repo, r => new CommitFilter { Since = tag }, new string[] { }); } } private static void AssertEnumerationOfCommits(Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds) { using (var repo = new Repository(BareTestRepoPath)) { AssertEnumerationOfCommitsInRepo(repo, filterBuilder, abbrevIds); } } private static void AssertEnumerationOfCommitsInRepo(IRepository repo, Func<IRepository, CommitFilter> filterBuilder, IEnumerable<string> abbrevIds) { ICommitLog commits = repo.Commits.QueryBy(filterBuilder(repo)); IEnumerable<string> commitShas = commits.Select(c => c.Id.ToString(7)).ToArray(); Assert.Equal(abbrevIds, commitShas); } [Fact] public void CanLookupCommitGeneric() { using (var repo = new Repository(BareTestRepoPath)) { var commit = repo.Lookup<Commit>(sha); Assert.Equal("testing\n", commit.Message); Assert.Equal("testing", commit.MessageShort); Assert.Equal(sha, commit.Sha); } } [Fact] public void CanReadCommitData() { using (var repo = new Repository(BareTestRepoPath)) { GitObject obj = repo.Lookup(sha); Assert.NotNull(obj); Assert.Equal(typeof(Commit), obj.GetType()); var commit = (Commit)obj; Assert.Equal("testing\n", commit.Message); Assert.Equal("testing", commit.MessageShort); Assert.Equal("UTF-8", commit.Encoding); Assert.Equal(sha, commit.Sha); Assert.NotNull(commit.Author); Assert.Equal("Scott Chacon", commit.Author.Name); Assert.Equal("[email protected]", commit.Author.Email); Assert.Equal(1273360386, commit.Author.When.ToSecondsSinceEpoch()); Assert.NotNull(commit.Committer); Assert.Equal("Scott Chacon", commit.Committer.Name); Assert.Equal("[email protected]", commit.Committer.Email); Assert.Equal(1273360386, commit.Committer.When.ToSecondsSinceEpoch()); Assert.Equal("181037049a54a1eb5fab404658a3a250b44335d7", commit.Tree.Sha); Assert.Equal(0, commit.Parents.Count()); } } [Fact] public void CanReadCommitWithMultipleParents() { using (var repo = new Repository(BareTestRepoPath)) { var commit = repo.Lookup<Commit>("a4a7dce85cf63874e984719f4fdd239f5145052f"); Assert.Equal(2, commit.Parents.Count()); } } [Fact] public void CanDirectlyAccessABlobOfTheCommit() { using (var repo = new Repository(BareTestRepoPath)) { var commit = repo.Lookup<Commit>("4c062a6"); var blob = commit["1/branch_file.txt"].Target as Blob; Assert.NotNull(blob); Assert.Equal("hi\n", blob.GetContentText()); } } [Fact] public void CanDirectlyAccessATreeOfTheCommit() { using (var repo = new Repository(BareTestRepoPath)) { var commit = repo.Lookup<Commit>("4c062a6"); var tree1 = commit["1"].Target as Tree; Assert.NotNull(tree1); } } [Fact] public void DirectlyAccessingAnUnknownTreeEntryOfTheCommitReturnsNull() { using (var repo = new Repository(BareTestRepoPath)) { var commit = repo.Lookup<Commit>("4c062a6"); Assert.Null(commit["I-am-not-here"]); } } [Fact] public void CanCommitWithSignatureFromConfig() { string repoPath = InitNewRepository(); string configPath = CreateConfigurationWithDummyUser(Constants.Signature); var options = new RepositoryOptions { GlobalConfigurationLocation = configPath }; using (var repo = new Repository(repoPath, options)) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null"); repo.Index.Stage(relativeFilepath); File.AppendAllText(filePath, "token\n"); repo.Index.Stage(relativeFilepath); Assert.Null(repo.Head[relativeFilepath]); Commit commit = repo.Commit("Initial egotistic commit"); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n"); AssertBlobContent(commit[relativeFilepath], "nulltoken\n"); AssertCommitSignaturesAre(commit, Constants.Signature); } } [Fact] public void CommitParentsAreMergeHeads() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard, "c47800"); CreateAndStageANewFile(repo); Touch(repo.Info.Path, "MERGE_HEAD", "9fd738e8f7967c078dceed8190330fc8648ee56a\n"); Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation); Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature); Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation); Assert.Equal(2, newMergedCommit.Parents.Count()); Assert.Equal(newMergedCommit.Parents.First().Sha, "c47800c7266a2be04c571c04d5a6614691ea99bd"); Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "9fd738e8f7967c078dceed8190330fc8648ee56a"); // Assert reflog entry is created var reflogEntry = repo.Refs.Log(repo.Refs.Head).First(); Assert.Equal(repo.Head.Tip.Id, reflogEntry.To); Assert.NotNull(reflogEntry.Commiter.Email); Assert.NotNull(reflogEntry.Commiter.Name); Assert.Equal(string.Format("commit (merge): {0}", newMergedCommit.MessageShort), reflogEntry.Message); } } [Fact] public void CommitCleansUpMergeMetadata() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "this is a new file"); repo.Index.Stage(relativeFilepath); string mergeHeadPath = Touch(repo.Info.Path, "MERGE_HEAD", "abcdefabcdefabcdefabcdefabcdefabcdefabcd"); string mergeMsgPath = Touch(repo.Info.Path, "MERGE_MSG", "This is a dummy merge.\n"); string mergeModePath = Touch(repo.Info.Path, "MERGE_MODE", "no-ff"); string origHeadPath = Touch(repo.Info.Path, "ORIG_HEAD", "beefbeefbeefbeefbeefbeefbeefbeefbeefbeef"); Assert.True(File.Exists(mergeHeadPath)); Assert.True(File.Exists(mergeMsgPath)); Assert.True(File.Exists(mergeModePath)); Assert.True(File.Exists(origHeadPath)); var author = Constants.Signature; repo.Commit("Initial egotistic commit", author, author); Assert.False(File.Exists(mergeHeadPath)); Assert.False(File.Exists(mergeMsgPath)); Assert.False(File.Exists(mergeModePath)); Assert.True(File.Exists(origHeadPath)); } } [Fact] public void CanCommitALittleBit() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { string dir = repo.Info.Path; Assert.True(Path.IsPathRooted(dir)); Assert.True(Directory.Exists(dir)); const string relativeFilepath = "new.txt"; string filePath = Touch(repo.Info.WorkingDirectory, relativeFilepath, "null"); repo.Index.Stage(relativeFilepath); File.AppendAllText(filePath, "token\n"); repo.Index.Stage(relativeFilepath); Assert.Null(repo.Head[relativeFilepath]); var author = Constants.Signature; const string shortMessage = "Initial egotistic commit"; const string commitMessage = shortMessage + "\n\nOnly the coolest commits from us"; Commit commit = repo.Commit(commitMessage, author, author); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken\n"); AssertBlobContent(commit[relativeFilepath], "nulltoken\n"); Assert.Equal(0, commit.Parents.Count()); Assert.False(repo.Info.IsHeadUnborn); // Assert a reflog entry is created on HEAD Assert.Equal(1, repo.Refs.Log("HEAD").Count()); var reflogEntry = repo.Refs.Log("HEAD").First(); Assert.Equal(author, reflogEntry.Commiter); Assert.Equal(commit.Id, reflogEntry.To); Assert.Equal(ObjectId.Zero, reflogEntry.From); Assert.Equal(string.Format("commit (initial): {0}", shortMessage), reflogEntry.Message); // Assert a reflog entry is created on HEAD target var targetCanonicalName = repo.Refs.Head.TargetIdentifier; Assert.Equal(1, repo.Refs.Log(targetCanonicalName).Count()); Assert.Equal(commit.Id, repo.Refs.Log(targetCanonicalName).First().To); File.WriteAllText(filePath, "nulltoken commits!\n"); repo.Index.Stage(relativeFilepath); var author2 = new Signature(author.Name, author.Email, author.When.AddSeconds(5)); Commit commit2 = repo.Commit("Are you trying to fork me?", author2, author2); AssertBlobContent(repo.Head[relativeFilepath], "nulltoken commits!\n"); AssertBlobContent(commit2[relativeFilepath], "nulltoken commits!\n"); Assert.Equal(1, commit2.Parents.Count()); Assert.Equal(commit.Id, commit2.Parents.First().Id); // Assert the reflog is shifted Assert.Equal(2, repo.Refs.Log("HEAD").Count()); Assert.Equal(reflogEntry.To, repo.Refs.Log("HEAD").First().From); Branch firstCommitBranch = repo.CreateBranch("davidfowl-rules", commit); repo.Checkout(firstCommitBranch); File.WriteAllText(filePath, "davidfowl commits!\n"); var author3 = new Signature("David Fowler", "[email protected]", author.When.AddSeconds(2)); repo.Index.Stage(relativeFilepath); Commit commit3 = repo.Commit("I'm going to branch you backwards in time!", author3, author3); AssertBlobContent(repo.Head[relativeFilepath], "davidfowl commits!\n"); AssertBlobContent(commit3[relativeFilepath], "davidfowl commits!\n"); Assert.Equal(1, commit3.Parents.Count()); Assert.Equal(commit.Id, commit3.Parents.First().Id); AssertBlobContent(firstCommitBranch[relativeFilepath], "nulltoken\n"); } } private static void AssertBlobContent(TreeEntry entry, string expectedContent) { Assert.Equal(TreeEntryTargetType.Blob, entry.TargetType); Assert.Equal(expectedContent, ((Blob)(entry.Target)).GetContentText()); } private static void AddCommitToRepo(string path) { using (var repo = new Repository(path)) { const string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n"); repo.Index.Stage(relativeFilepath); var author = new Signature("nulltoken", "[email protected]", DateTimeOffset.Parse("Wed, Dec 14 2011 08:29:03 +0100")); repo.Commit("Initial commit", author, author); } } [Fact] public void CanGeneratePredictableObjectShas() { string repoPath = InitNewRepository(); AddCommitToRepo(repoPath); using (var repo = new Repository(repoPath)) { Commit commit = repo.Commits.Single(); Assert.Equal("1fe3126578fc4eca68c193e4a3a0a14a0704624d", commit.Sha); Tree tree = commit.Tree; Assert.Equal("2b297e643c551e76cfa1f93810c50811382f9117", tree.Sha); GitObject blob = tree.Single().Target; Assert.IsAssignableFrom<Blob>(blob); Assert.Equal("9daeafb9864cf43055ae93beb0afd6c7d144bfa4", blob.Sha); } } [Fact] public void CanAmendARootCommit() { string repoPath = InitNewRepository(); AddCommitToRepo(repoPath); using (var repo = new Repository(repoPath)) { Assert.Equal(1, repo.Head.Commits.Count()); Commit originalCommit = repo.Head.Tip; Assert.Equal(0, originalCommit.Parents.Count()); CreateAndStageANewFile(repo); Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }); Assert.Equal(1, repo.Head.Commits.Count()); AssertCommitHasBeenAmended(repo, amendedCommit, originalCommit); } } [Fact] public void CanAmendACommitWithMoreThanOneParent() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { var mergedCommit = repo.Lookup<Commit>("be3563a"); Assert.NotNull(mergedCommit); Assert.Equal(2, mergedCommit.Parents.Count()); repo.Reset(ResetMode.Soft, mergedCommit.Sha); CreateAndStageANewFile(repo); const string commitMessage = "I'm rewriting the history!"; Commit amendedCommit = repo.Commit(commitMessage, Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }); AssertCommitHasBeenAmended(repo, amendedCommit, mergedCommit); AssertRefLogEntry(repo, "HEAD", amendedCommit.Id, string.Format("commit (amend): {0}", commitMessage), mergedCommit.Id, amendedCommit.Committer); } } private static void CreateAndStageANewFile(IRepository repo) { string relativeFilepath = string.Format("new-file-{0}.txt", Guid.NewGuid()); Touch(repo.Info.WorkingDirectory, relativeFilepath, "brand new content\n"); repo.Index.Stage(relativeFilepath); } private static void AssertCommitHasBeenAmended(IRepository repo, Commit amendedCommit, Commit originalCommit) { Commit headCommit = repo.Head.Tip; Assert.Equal(amendedCommit, headCommit); Assert.NotEqual(originalCommit.Sha, amendedCommit.Sha); Assert.Equal(originalCommit.Parents, amendedCommit.Parents); } [Fact] public void CanNotAmendAnEmptyRepository() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { Assert.Throws<UnbornBranchException>(() => repo.Commit("I can not amend anything !:(", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true })); } } [Fact] public void CanRetrieveChildrenOfASpecificCommit() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { const string parentSha = "5b5b025afb0b4c913b4c338a42934a3863bf3644"; var filter = new CommitFilter { /* Revwalk from all the refs (git log --all) ... */ Since = repo.Refs, /* ... and stop when the parent is reached */ Until = parentSha }; var commits = repo.Commits.QueryBy(filter); var children = from c in commits from p in c.Parents let pId = p.Id where pId.Sha == parentSha select c; var expectedChildren = new[] { "c47800c7266a2be04c571c04d5a6614691ea99bd", "4a202b346bb0fb0db7eff3cffeb3c70babbd2045" }; Assert.Equal(expectedChildren, children.Select(c => c.Id.Sha)); } } [Fact] public void CanCorrectlyDistinguishAuthorFromCommitter() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { var author = new Signature("Wilbert van Dolleweerd", "[email protected]", Epoch.ToDateTimeOffset(1244187936, 120)); var committer = new Signature("Henk Westhuis", "[email protected]", Epoch.ToDateTimeOffset(1244286496, 120)); Commit c = repo.Commit("I can haz an author and a committer!", author, committer); Assert.Equal(author, c.Author); Assert.Equal(committer, c.Committer); } } [Fact] public void CanCommitOnOrphanedBranch() { string newBranchName = "refs/heads/newBranch"; string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { // Set Head to point to branch other than master repo.Refs.UpdateTarget("HEAD", newBranchName); Assert.Equal(newBranchName, repo.Head.CanonicalName); const string relativeFilepath = "test.txt"; Touch(repo.Info.WorkingDirectory, relativeFilepath, "test\n"); repo.Index.Stage(relativeFilepath); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); Assert.Equal(1, repo.Head.Commits.Count()); } } [Fact] public void CanNotCommitAnEmptyCommit() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature)); } } [Fact] public void CanCommitAnEmptyCommitWhenForced() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AllowEmptyCommit = true }); } } [Fact] public void CanNotAmendAnEmptyCommit() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AllowEmptyCommit = true }); Assert.Throws<EmptyCommitException>(() => repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true })); } } [Fact] public void CanAmendAnEmptyCommitWhenForced() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Commit emptyCommit = repo.Commit("Empty commit!", Constants.Signature, Constants.Signature, new CommitOptions { AllowEmptyCommit = true }); Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true, AllowEmptyCommit = true }); AssertCommitHasBeenAmended(repo, amendedCommit, emptyCommit); } } [Fact] public void CanCommitAnEmptyCommitWhenMerging() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n"); Assert.Equal(CurrentOperation.Merge, repo.Info.CurrentOperation); Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature); Assert.Equal(2, newMergedCommit.Parents.Count()); Assert.Equal(newMergedCommit.Parents.First().Sha, "32eab9cb1f450b5fe7ab663462b77d7f4b703344"); Assert.Equal(newMergedCommit.Parents.Skip(1).First().Sha, "f705abffe7015f2beacf2abe7a36583ebee3487e"); } } [Fact] public void CanAmendAnEmptyMergeCommit() { string path = CloneStandardTestRepo(); using (var repo = new Repository(path)) { repo.Reset(ResetMode.Hard); repo.RemoveUntrackedFiles(); Touch(repo.Info.Path, "MERGE_HEAD", "f705abffe7015f2beacf2abe7a36583ebee3487e\n"); Commit newMergedCommit = repo.Commit("Merge commit", Constants.Signature, Constants.Signature); Commit amendedCommit = repo.Commit("I'm rewriting the history!", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true }); AssertCommitHasBeenAmended(repo, amendedCommit, newMergedCommit); } } [Fact] public void CanNotAmendACommitInAWayThatWouldLeadTheNewCommitToBecomeEmpty() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { Touch(repo.Info.WorkingDirectory, "test.txt", "test\n"); repo.Index.Stage("test.txt"); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); Touch(repo.Info.WorkingDirectory, "new.txt", "content\n"); repo.Index.Stage("new.txt"); repo.Commit("One commit", Constants.Signature, Constants.Signature); repo.Index.Remove("new.txt"); Assert.Throws<EmptyCommitException>(() => repo.Commit("Oops", Constants.Signature, Constants.Signature, new CommitOptions { AmendPreviousCommit = true })); } } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using SharpDX.Mathematics; using Factory = SharpDX.DirectWrite.Factory; namespace SharpDX.Toolkit.Graphics { using System.Drawing; using System.Drawing.Imaging; // This code was originally taken from DirectXTk but rewritten with DirectWrite // for more accuracy in font rendering internal class TrueTypeImporter : IFontImporter { // Properties hold the imported font data. public IEnumerable<Glyph> Glyphs { get; private set; } public float LineSpacing { get; private set; } public void Import(FontDescription options) { var factory = new DirectWrite.Factory(); DirectWrite.Font font = null; using (var fontCollection = factory.GetSystemFontCollection(false)) { int index; if(!fontCollection.FindFamilyName(options.FontName, out index)) { // Lets try to import System.Drawing for old system bitmap fonts (like MS Sans Serif) throw new FontException(string.Format("Can't find font '{0}'.", options.FontName)); } using(var fontFamily = fontCollection.GetFontFamily(index)) { var weight = FontWeight.Regular; var style = DirectWrite.FontStyle.Normal; switch(options.Style) { case FontStyle.Bold: weight = FontWeight.Bold; break; case FontStyle.Italic: weight = FontWeight.Regular; style = DirectWrite.FontStyle.Italic; break; case FontStyle.Regular: weight = FontWeight.Regular; break; } font = fontFamily.GetFirstMatchingFont(weight, DirectWrite.FontStretch.Normal, style); } } var fontFace = new FontFace(font); var fontMetrics = fontFace.Metrics; // Create a bunch of GDI+ objects. var fontSize = PointsToPixels(options.Size); // Which characters do we want to include? var characters = CharacterRegion.Flatten(options.CharacterRegions); var glyphList = new List<Glyph>(); // Store the font height. LineSpacing = (float)(fontMetrics.LineGap + fontMetrics.Ascent + fontMetrics.Descent) / fontMetrics.DesignUnitsPerEm * fontSize; var baseLine = (float)(fontMetrics.LineGap + fontMetrics.Ascent) / fontMetrics.DesignUnitsPerEm * fontSize; // Rasterize each character in turn. foreach (char character in characters) { var glyph = ImportGlyph(factory, fontFace, character, fontMetrics, fontSize, options.AntiAlias); glyph.YOffset += baseLine; glyphList.Add(glyph); } Glyphs = glyphList; factory.Dispose(); } private Glyph ImportGlyph(Factory factory, FontFace fontFace, char character, FontMetrics fontMetrics, float fontSize, FontAntiAliasMode antiAliasMode) { var indices = fontFace.GetGlyphIndices(new int[] {character}); var metrics = fontFace.GetDesignGlyphMetrics(indices, false); var metric = metrics[0]; var width = (float)(metric.AdvanceWidth - metric.LeftSideBearing - metric.RightSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize; var height = (float)(metric.AdvanceHeight - metric.TopSideBearing - metric.BottomSideBearing) / fontMetrics.DesignUnitsPerEm * fontSize; var xOffset = (float)metric.LeftSideBearing / fontMetrics.DesignUnitsPerEm * fontSize; var yOffset = (float)(metric.TopSideBearing - metric.VerticalOriginY) / fontMetrics.DesignUnitsPerEm * fontSize; var advanceWidth = (float)metric.AdvanceWidth / fontMetrics.DesignUnitsPerEm * fontSize; var advanceHeight = (float)metric.AdvanceHeight / fontMetrics.DesignUnitsPerEm * fontSize; var pixelWidth = (int)Math.Ceiling(width + 4); var pixelHeight = (int)Math.Ceiling(height + 4); var matrix = Matrix.Identity; matrix.M41 = -(float)Math.Floor(xOffset) + 1; matrix.M42 = -(float)Math.Floor(yOffset) + 1; Bitmap bitmap; if(char.IsWhiteSpace(character)) { bitmap = new Bitmap(1, 1, PixelFormat.Format32bppArgb); } else { var glyphRun = new GlyphRun() { FontFace = fontFace, Advances = new[] { (float)Math.Ceiling(advanceWidth) }, FontSize = fontSize, BidiLevel = 0, Indices = indices, IsSideways = false, Offsets = new[] {new GlyphOffset()} }; RenderingMode renderingMode; if (antiAliasMode != FontAntiAliasMode.Aliased) { var rtParams = new RenderingParams(factory); renderingMode = fontFace.GetRecommendedRenderingMode(fontSize, 1.0f, MeasuringMode.Natural, rtParams); rtParams.Dispose(); } else { renderingMode = RenderingMode.Aliased; } using(var runAnalysis = new GlyphRunAnalysis(factory, glyphRun, 1.0f, (Matrix3x2)matrix, renderingMode, MeasuringMode.Natural, 0.0f, 0.0f)) { var bounds = new SharpDX.Rectangle(0, 0, pixelWidth, pixelHeight); bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); if (renderingMode == RenderingMode.Aliased) { var texture = new byte[bounds.Width * bounds.Height]; runAnalysis.CreateAlphaTexture(TextureType.Aliased1x1, bounds, texture, texture.Length); for (int y = 0; y < bounds.Height; y++) { for (int x = 0; x < bounds.Width; x++) { int pixelX = y * bounds.Width + x; var grey = texture[pixelX]; var color = Color.FromArgb(grey, grey, grey); bitmap.SetPixel(x, y, color); } } } else { var texture = new byte[bounds.Width * bounds.Height * 3]; runAnalysis.CreateAlphaTexture(TextureType.Cleartype3x1, bounds, texture, texture.Length); for (int y = 0; y < bounds.Height; y++) { for (int x = 0; x < bounds.Width; x++) { int pixelX = (y * bounds.Width + x) * 3; var red = LinearToGamma(texture[pixelX]); var green = LinearToGamma(texture[pixelX + 1]); var blue = LinearToGamma(texture[pixelX + 2]); var color = Color.FromArgb(red, green, blue); bitmap.SetPixel(x, y, color); } } } } } var glyph = new Glyph(character, bitmap) { XOffset = -matrix.M41, XAdvance = advanceWidth, YOffset = -matrix.M42, }; return glyph; } private static byte LinearToGamma(byte color) { return (byte)(Math.Pow(color / 255.0f, 1 / 2.2f) * 255.0f); } // Converts a font size from points to pixels. Can't just let GDI+ do this for us, // because we want identical results on every machine regardless of system DPI settings. static float PointsToPixels(float points) { return points * 96 / 72; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq.Expressions; namespace LinqToDB.DataProvider.DB2 { using Data; using Mapping; using SchemaProvider; using SqlProvider; public class DB2DataProvider : DynamicDataProviderBase { public DB2DataProvider(string name, DB2Version version) : base(name, null) { Version = version; SqlProviderFlags.AcceptsTakeAsParameter = false; SqlProviderFlags.AcceptsTakeAsParameterIfSkip = true; SqlProviderFlags.IsDistinctOrderBySupported = version != DB2Version.zOS; SetCharField("CHAR", (r,i) => r.GetString(i).TrimEnd()); _sqlOptimizer = new DB2SqlOptimizer(SqlProviderFlags); } protected override void OnConnectionTypeCreated(Type connectionType) { DB2Types.ConnectionType = connectionType; DB2Types.DB2Int64. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Int64", true); DB2Types.DB2Int32. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Int32", true); DB2Types.DB2Int16. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Int16", true); DB2Types.DB2Decimal. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Decimal", true); DB2Types.DB2DecimalFloat.Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2DecimalFloat", true); DB2Types.DB2Real. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Real", true); DB2Types.DB2Real370. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Real370", true); DB2Types.DB2Double. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Double", true); DB2Types.DB2String. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2String", true); DB2Types.DB2Clob. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Clob", true); DB2Types.DB2Binary. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Binary", true); DB2Types.DB2Blob. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Blob", true); DB2Types.DB2Date. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Date", true); DB2Types.DB2Time. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Time", true); DB2Types.DB2TimeStamp. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2TimeStamp", true); DB2Types.DB2Xml = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Xml", true); DB2Types.DB2RowId. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2RowId", true); DB2Types.DB2DateTime. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2DateTime", false); SetProviderField(DB2Types.DB2Int64, typeof(Int64), "GetDB2Int64"); SetProviderField(DB2Types.DB2Int32, typeof(Int32), "GetDB2Int32"); SetProviderField(DB2Types.DB2Int16, typeof(Int16), "GetDB2Int16"); SetProviderField(DB2Types.DB2Decimal, typeof(Decimal), "GetDB2Decimal"); SetProviderField(DB2Types.DB2DecimalFloat, typeof(Decimal), "GetDB2DecimalFloat"); SetProviderField(DB2Types.DB2Real, typeof(Single), "GetDB2Real"); SetProviderField(DB2Types.DB2Real370, typeof(Single), "GetDB2Real370"); SetProviderField(DB2Types.DB2Double, typeof(Double), "GetDB2Double"); SetProviderField(DB2Types.DB2String, typeof(String), "GetDB2String"); SetProviderField(DB2Types.DB2Clob, typeof(String), "GetDB2Clob"); SetProviderField(DB2Types.DB2Binary, typeof(byte[]), "GetDB2Binary"); SetProviderField(DB2Types.DB2Blob, typeof(byte[]), "GetDB2Blob"); SetProviderField(DB2Types.DB2Date, typeof(DateTime), "GetDB2Date"); SetProviderField(DB2Types.DB2Time, typeof(TimeSpan), "GetDB2Time"); SetProviderField(DB2Types.DB2TimeStamp, typeof(DateTime), "GetDB2TimeStamp"); SetProviderField(DB2Types.DB2Xml, typeof(string), "GetDB2Xml"); SetProviderField(DB2Types.DB2RowId, typeof(byte[]), "GetDB2RowId"); MappingSchema.AddScalarType(DB2Types.DB2Int64, GetNullValue(DB2Types.DB2Int64), true, DataType.Int64); MappingSchema.AddScalarType(DB2Types.DB2Int32, GetNullValue(DB2Types.DB2Int32), true, DataType.Int32); MappingSchema.AddScalarType(DB2Types.DB2Int16, GetNullValue(DB2Types.DB2Int16), true, DataType.Int16); MappingSchema.AddScalarType(DB2Types.DB2Decimal, GetNullValue(DB2Types.DB2Decimal), true, DataType.Decimal); MappingSchema.AddScalarType(DB2Types.DB2DecimalFloat, GetNullValue(DB2Types.DB2DecimalFloat), true, DataType.Decimal); MappingSchema.AddScalarType(DB2Types.DB2Real, GetNullValue(DB2Types.DB2Real), true, DataType.Single); MappingSchema.AddScalarType(DB2Types.DB2Real370, GetNullValue(DB2Types.DB2Real370), true, DataType.Single); MappingSchema.AddScalarType(DB2Types.DB2Double, GetNullValue(DB2Types.DB2Double), true, DataType.Double); MappingSchema.AddScalarType(DB2Types.DB2String, GetNullValue(DB2Types.DB2String), true, DataType.NVarChar); MappingSchema.AddScalarType(DB2Types.DB2Clob, GetNullValue(DB2Types.DB2Clob), true, DataType.NText); MappingSchema.AddScalarType(DB2Types.DB2Binary, GetNullValue(DB2Types.DB2Binary), true, DataType.VarBinary); MappingSchema.AddScalarType(DB2Types.DB2Blob, GetNullValue(DB2Types.DB2Blob), true, DataType.Blob); MappingSchema.AddScalarType(DB2Types.DB2Date, GetNullValue(DB2Types.DB2Date), true, DataType.Date); MappingSchema.AddScalarType(DB2Types.DB2Time, GetNullValue(DB2Types.DB2Time), true, DataType.Time); MappingSchema.AddScalarType(DB2Types.DB2TimeStamp, GetNullValue(DB2Types.DB2TimeStamp), true, DataType.DateTime2); MappingSchema.AddScalarType(DB2Types.DB2Xml, GetNullValue(DB2Types.DB2Xml), true, DataType.Xml); MappingSchema.AddScalarType(DB2Types.DB2RowId, GetNullValue(DB2Types.DB2RowId), true, DataType.VarBinary); _setBlob = GetSetParameter(connectionType, "DB2Parameter", "DB2Type", "DB2Type", "Blob"); if (DB2Types.DB2DateTime.IsSupported) { SetProviderField(DB2Types.DB2DateTime, typeof(DateTime), "GetDB2DateTime"); MappingSchema.AddScalarType(DB2Types.DB2DateTime, GetNullValue(DB2Types.DB2DateTime), true, DataType.DateTime); } if (DataConnection.TraceSwitch.TraceInfo) { DataConnection.WriteTraceLine( DataReaderType.Assembly.FullName, DataConnection.TraceSwitch.DisplayName); DataConnection.WriteTraceLine( DB2Types.DB2DateTime.IsSupported ? "DB2DateTime is supported." : "DB2DateTime is not supported.", DataConnection.TraceSwitch.DisplayName); } DB2Tools.Initialized(); } static object GetNullValue(Type type) { var getValue = Expression.Lambda<Func<object>>(Expression.Convert(Expression.Field(null, type, "Null"), typeof(object))); return getValue.Compile()(); } public override string ConnectionNamespace { get { return "IBM.Data.DB2"; } } protected override string ConnectionTypeName { get { return "IBM.Data.DB2.DB2Connection, IBM.Data.DB2"; } } protected override string DataReaderTypeName { get { return "IBM.Data.DB2.DB2DataReader, IBM.Data.DB2"; } } public DB2Version Version { get; private set; } static class MappingSchemaInstance { public static readonly DB2LUWMappingSchema DB2LUWMappingSchema = new DB2LUWMappingSchema(); public static readonly DB2zOSMappingSchema DB2zOSMappingSchema = new DB2zOSMappingSchema(); } public override MappingSchema MappingSchema { get { switch (Version) { case DB2Version.LUW : return MappingSchemaInstance.DB2LUWMappingSchema; case DB2Version.zOS : return MappingSchemaInstance.DB2zOSMappingSchema; } return base.MappingSchema; } } public override ISchemaProvider GetSchemaProvider() { return Version == DB2Version.zOS ? new DB2zOSSchemaProvider() : new DB2LUWSchemaProvider(); } public override ISqlBuilder CreateSqlBuilder() { return Version == DB2Version.zOS ? new DB2zOSSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter) as ISqlBuilder: new DB2LUWSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter); } readonly DB2SqlOptimizer _sqlOptimizer; public override ISqlOptimizer GetSqlOptimizer() { return _sqlOptimizer; } public override void InitCommand(DataConnection dataConnection, CommandType commandType, string commandText, DataParameter[] parameters) { dataConnection.DisposeCommand(); base.InitCommand(dataConnection, commandType, commandText, parameters); } static Action<IDbDataParameter> _setBlob; public override void SetParameter(IDbDataParameter parameter, string name, DataType dataType, object value) { if (value is sbyte) { value = (short)(sbyte)value; dataType = DataType.Int16; } else if (value is byte) { value = (short)(byte)value; dataType = DataType.Int16; } switch (dataType) { case DataType.UInt16 : dataType = DataType.Int32; break; case DataType.UInt32 : dataType = DataType.Int64; break; case DataType.UInt64 : dataType = DataType.Decimal; break; case DataType.VarNumeric : dataType = DataType.Decimal; break; case DataType.DateTime2 : dataType = DataType.DateTime; break; case DataType.Char : case DataType.VarChar : case DataType.NChar : case DataType.NVarChar : if (value is Guid) value = ((Guid)value).ToString(); else if (value is bool) value = Common.ConvertTo<char>.From((bool)value); break; case DataType.Boolean : case DataType.Int16 : if (value is bool) { value = (bool)value ? 1 : 0; dataType = DataType.Int16; } break; case DataType.Guid : if (value is Guid) { value = ((Guid)value).ToByteArray(); dataType = DataType.VarBinary; } break; case DataType.Binary : case DataType.VarBinary : if (value is Guid) value = ((Guid)value).ToByteArray(); break; case DataType.Blob : base.SetParameter(parameter, "@" + name, dataType, value); _setBlob(parameter); return; } base.SetParameter(parameter, "@" + name, dataType, value); } #region BulkCopy DB2BulkCopy _bulkCopy; public override BulkCopyRowsCopied BulkCopy<T>(DataConnection dataConnection, BulkCopyOptions options, IEnumerable<T> source) { if (_bulkCopy == null) _bulkCopy = new DB2BulkCopy(GetConnectionType()); return _bulkCopy.BulkCopy( options.BulkCopyType == BulkCopyType.Default ? DB2Tools.DefaultBulkCopyType : options.BulkCopyType, dataConnection, options, source); } #endregion #region Merge public override int Merge<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source, string tableName, string databaseName, string schemaName) { if (delete) throw new LinqToDBException("DB2 MERGE statement does not support DELETE by source."); return new DB2Merge().Merge(dataConnection, deletePredicate, delete, source, tableName, databaseName, schemaName); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) Lead Pipe Software. All rights reserved. // Licensed under the MIT License. Please see the LICENSE file in the project root for full license information. // -------------------------------------------------------------------------------------------------------------------- using LeadPipe.Net.Extensions; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace LeadPipe.Net.Validation { /// <summary> /// A set of validatable object extension methods. /// </summary> public static class ValidatableObjectExtensions { /// <summary> /// Determines whether the type has validation attributes on each field that match a specified type. /// </summary> /// <param name="t"> /// The t. /// </param> /// <param name="typeToCompare"> /// The type to compare. /// </param> /// <returns> /// <c>true</c> if the type has validation attributes on each field that match the specified type; otherwise, <c>false</c>. /// </returns> public static bool FieldValidationAttributesMatch(this Type t, Type typeToCompare) { // Get all the properties from each type... var leftSide = t.GetProperties().ToList(); var rightSide = typeToCompare.GetProperties().ToList(); return !(from rightSideField in rightSide let leftSideField = leftSide.Find(p => p.Name == rightSideField.Name) where leftSideField.IsNotNull() let leftSideAttributes = leftSideField.GetCustomAttributes(false).Where( a => a.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute))) let rightSideAttributes = rightSideField.GetCustomAttributes(false).Where( a => a.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute))) where leftSideAttributes.Any(attribute => !rightSideAttributes.Contains(attribute)) select leftSideAttributes).Any(); } /// <summary> /// Gets the Validation attributes. /// </summary> /// <remarks> /// <para> /// This particular extension method is fairly useless since it strips away context. /// </para> /// </remarks> /// <param name="t"> /// The type. /// </param> /// <returns> /// The ValidationAttribute. /// </returns> public static List<object> GetValidationAttributes(this Type t) { List<object> validationAttributes = (from property in t.GetProperties() from attribute in property.GetCustomAttributes(false) where attribute.GetType().IsSubclassOf(typeof(ValidationAttribute)) || attribute.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute)) select attribute).ToList(); return validationAttributes; } /// <summary> /// Determines whether a type has one or more Validation attribute. /// </summary> /// <param name="t"> /// The Type to inspect. /// </param> /// <returns> /// <c>true</c> if the type has the Validation attribute; otherwise, <c>false</c>. /// </returns> public static bool HasValidationAttributes(this Type t) { return t.GetValidationAttributes().Count() > 0; } /// <summary> /// Determines whether the specified validatable object is valid. /// </summary> /// <param name="validatableObject"> /// The validatable object. /// </param> /// <returns> /// <c>true</c> if the specified validatable object is valid; otherwise, <c>false</c>. /// </returns> public static bool IsValid(this IValidatableObject validatableObject) { return validatableObject.Validate().Count == 0; } /// <summary> /// Determines whether the type has validation attributes on each method that match a specified type. /// </summary> /// <param name="t"> /// The t. /// </param> /// <param name="typeToCompare"> /// The type to compare. /// </param> /// <returns> /// <c>true</c> if the type has validation attributes on each method that match the specified type; otherwise, <c>false</c>. /// </returns> public static bool MethodValidationAttributesMatch(this Type t, Type typeToCompare) { // Get all the methods from each type... var leftSide = t.GetMethods().ToList(); var rightSide = typeToCompare.GetMethods().ToList(); return !(from rightSideMethod in rightSide let leftSideMethod = leftSide.Find(p => p.Name == rightSideMethod.Name) where leftSideMethod.IsNotNull() let leftSideAttributes = leftSideMethod.GetCustomAttributes(false).Where( a => a.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute))) let rightSideAttributes = rightSideMethod.GetCustomAttributes(false).Where( a => a.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute))) where leftSideAttributes.Any(attribute => !rightSideAttributes.Contains(attribute)) select leftSideAttributes).Any(); } /// <summary> /// Determines whether the type has validation attributes on each property that match a specified type. /// </summary> /// <param name="t"> /// The t. /// </param> /// <param name="typeToCompare"> /// The type to compare. /// </param> /// <returns> /// <c>true</c> if the type has validation attributes on each property that match the specified type; otherwise, <c>false</c>. /// </returns> public static bool PropertyValidationAttributesMatch(this Type t, Type typeToCompare) { // Get all the properties from each type... var leftSide = t.GetProperties().ToList(); var rightSide = typeToCompare.GetProperties().ToList(); return !(from rightSideProperty in rightSide let leftSideProperty = leftSide.Find(p => p.Name == rightSideProperty.Name) where leftSideProperty.IsNotNull() let leftSideAttributes = leftSideProperty.GetCustomAttributes(false).Where( a => a.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute))) let rightSideAttributes = rightSideProperty.GetCustomAttributes(false).Where( a => a.GetType().IsSubclassOf(typeof(LeadPipeValidationAttribute))) where leftSideAttributes.Any(attribute => !rightSideAttributes.Contains(attribute)) select leftSideAttributes).Any(); } /// <summary> /// Validates a validatable object. /// </summary> /// <param name="validatableObject"> /// The validatable object. /// </param> /// <returns> /// A list of validation results. /// </returns> public static List<ValidationResult> Validate(this IValidatableObject validatableObject) { var validationResult = new List<ValidationResult>(); System.ComponentModel.DataAnnotations.Validator.TryValidateObject( validatableObject, new ValidationContext(validatableObject, null, null), validationResult, true); return validationResult; } /// <summary> /// Determines whether the type has validation attributes that match a specified type. /// </summary> /// <param name="t"> /// The t. /// </param> /// <param name="typeToCompare"> /// The type to compare. /// </param> /// <returns> /// <c>true</c> if the type has validation attributes that match the specified type; otherwise, <c>false</c>. /// </returns> public static bool ValidationAttributesMatch(this Type t, Type typeToCompare) { return t.FieldValidationAttributesMatch(typeToCompare) && t.PropertyValidationAttributesMatch(typeToCompare) && t.MethodValidationAttributesMatch(typeToCompare); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedPacketMirroringsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetPacketMirroringRequest request = new GetPacketMirroringRequest { PacketMirroring = "packet_mirroringf2de2a5f", Region = "regionedb20d96", Project = "projectaa6ff846", }; PacketMirroring expectedResponse = new PacketMirroring { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", MirroredResources = new PacketMirroringMirroredResourceInfo(), Region = "regionedb20d96", Network = new PacketMirroringNetworkInfo(), Enable = "enable6d158f20", Filter = new PacketMirroringFilter(), Description = "description2cf9da67", CollectorIlb = new PacketMirroringForwardingRuleInfo(), Priority = 1546225849U, SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); PacketMirroring response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetPacketMirroringRequest request = new GetPacketMirroringRequest { PacketMirroring = "packet_mirroringf2de2a5f", Region = "regionedb20d96", Project = "projectaa6ff846", }; PacketMirroring expectedResponse = new PacketMirroring { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", MirroredResources = new PacketMirroringMirroredResourceInfo(), Region = "regionedb20d96", Network = new PacketMirroringNetworkInfo(), Enable = "enable6d158f20", Filter = new PacketMirroringFilter(), Description = "description2cf9da67", CollectorIlb = new PacketMirroringForwardingRuleInfo(), Priority = 1546225849U, SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PacketMirroring>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); PacketMirroring responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PacketMirroring responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetPacketMirroringRequest request = new GetPacketMirroringRequest { PacketMirroring = "packet_mirroringf2de2a5f", Region = "regionedb20d96", Project = "projectaa6ff846", }; PacketMirroring expectedResponse = new PacketMirroring { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", MirroredResources = new PacketMirroringMirroredResourceInfo(), Region = "regionedb20d96", Network = new PacketMirroringNetworkInfo(), Enable = "enable6d158f20", Filter = new PacketMirroringFilter(), Description = "description2cf9da67", CollectorIlb = new PacketMirroringForwardingRuleInfo(), Priority = 1546225849U, SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); PacketMirroring response = client.Get(request.Project, request.Region, request.PacketMirroring); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetPacketMirroringRequest request = new GetPacketMirroringRequest { PacketMirroring = "packet_mirroringf2de2a5f", Region = "regionedb20d96", Project = "projectaa6ff846", }; PacketMirroring expectedResponse = new PacketMirroring { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", MirroredResources = new PacketMirroringMirroredResourceInfo(), Region = "regionedb20d96", Network = new PacketMirroringNetworkInfo(), Enable = "enable6d158f20", Filter = new PacketMirroringFilter(), Description = "description2cf9da67", CollectorIlb = new PacketMirroringForwardingRuleInfo(), Priority = 1546225849U, SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PacketMirroring>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); PacketMirroring responseCallSettings = await client.GetAsync(request.Project, request.Region, request.PacketMirroring, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PacketMirroring responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.PacketMirroring, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsPacketMirroringRequest request = new TestIamPermissionsPacketMirroringRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsPacketMirroringRequest request = new TestIamPermissionsPacketMirroringRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsPacketMirroringRequest request = new TestIamPermissionsPacketMirroringRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<PacketMirrorings.PacketMirroringsClient> mockGrpcClient = new moq::Mock<PacketMirrorings.PacketMirroringsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsPacketMirroringRequest request = new TestIamPermissionsPacketMirroringRequest { Region = "regionedb20d96", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PacketMirroringsClient client = new PacketMirroringsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Region, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using GenFx.Validation; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Threading.Tasks; namespace GenFx { /// <summary> /// Provides the abstract base class for a type of genetic algorithm. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] [DataContract] public abstract class GeneticAlgorithm : GeneticComponent { private const int DefaultEnvironmentSize = 1; [DataMember] private int currentGeneration; [DataMember] private GeneticEnvironment? environment; [DataMember] private readonly List<Metric> metrics = new List<Metric>(); [DataMember] private List<Metric> sortedMetrics = new List<Metric>(); [DataMember] private readonly List<Plugin> plugins = new List<Plugin>(); [DataMember] private bool isInitialized; [DataMember] private FitnessEvaluator? fitnessEvaluator; [DataMember] private Terminator terminator = new DefaultTerminator(); [DataMember] private FitnessScalingStrategy? fitnessScalingStrategy; [DataMember] private SelectionOperator? selectionOperator; [DataMember] private MutationOperator? mutationOperator; [DataMember] private CrossoverOperator? crossoverOperator; [DataMember] private ElitismStrategy? elitismStrategy; [DataMember] private GeneticEntity? geneticEntitySeed; [DataMember] private Population? populationSeed; [DataMember] private int minimumEnvironmentSize = DefaultEnvironmentSize; // Mapping of component properties to Validator objects as described by external components private Dictionary<PropertyInfo, List<PropertyValidator>> externalValidationMapping = new Dictionary<PropertyInfo, List<PropertyValidator>>(); /// <summary> /// Initializes a new instance of this class. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] protected GeneticAlgorithm() { } /// <summary> /// Occurs when the fitness of an environment has been evaluated. /// </summary> public event EventHandler<EnvironmentFitnessEvaluatedEventArgs>? FitnessEvaluated; /// <summary> /// Occurs when a new generation has been created (but its fitness has not yet been evaluated). /// </summary> public event EventHandler? GenerationCreated; /// <summary> /// Occurs when execution of the algorithm completes. /// </summary> public event EventHandler? AlgorithmCompleted; /// <summary> /// Occurs when the algorithm is about to begin execution. /// </summary> /// <remarks> /// This event only occurs when the algorithm is first started after having been initialized. /// It does not occur when resuming execution after a pause. /// </remarks> public event EventHandler? AlgorithmStarting; /// <summary> /// Gets or sets the minimum number of <see cref="Population"/> objects that are contained by the <see cref="GeneticEnvironment"/>. /// </summary> /// <value> /// The number of populations that are contained by the <see cref="GeneticEnvironment"/>. /// This value is defaulted to 1 and must be greater or equal to 1. /// </value> /// <exception cref="ValidationException">Value is not valid.</exception> [ConfigurationProperty] [IntegerValidator(MinValue = 1)] public int MinimumEnvironmentSize { get { return this.minimumEnvironmentSize; } set { this.SetProperty(ref this.minimumEnvironmentSize, value); } } /// <summary> /// Gets the <see cref="FitnessEvaluator"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] [RequiredValidator] public FitnessEvaluator? FitnessEvaluator { get { return this.fitnessEvaluator; } set { this.SetProperty(ref this.fitnessEvaluator, value); } } /// <summary> /// Gets the <see cref="GenFx.Terminator"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] public Terminator Terminator { get { return this.terminator; } set { if (value is null) { throw new ArgumentNullException(nameof(value)); } this.SetProperty(ref this.terminator, value); } } /// <summary> /// Gets the <see cref="GenFx.FitnessScalingStrategy"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] public FitnessScalingStrategy? FitnessScalingStrategy { get { return this.fitnessScalingStrategy; } set { this.SetProperty(ref this.fitnessScalingStrategy, value); } } /// <summary> /// Gets the <see cref="GenFx.SelectionOperator"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] [RequiredValidator] public SelectionOperator? SelectionOperator { get { return this.selectionOperator; } set { this.SetProperty(ref this.selectionOperator, value); } } /// <summary> /// Gets the <see cref="GenFx.MutationOperator"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] public MutationOperator? MutationOperator { get { return this.mutationOperator; } set { this.SetProperty(ref this.mutationOperator, value); } } /// <summary> /// Gets the <see cref="GenFx.CrossoverOperator"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] public CrossoverOperator? CrossoverOperator { get { return this.crossoverOperator; } set { this.SetProperty(ref this.crossoverOperator, value); } } /// <summary> /// Gets the <see cref="GenFx.ElitismStrategy"/> to be used by the algorithm. /// </summary> [ConfigurationProperty] public ElitismStrategy? ElitismStrategy { get { return this.elitismStrategy; } set { this.SetProperty(ref this.elitismStrategy, value); } } /// <summary> /// Gets the <see cref="GeneticEntity"/> to be used by the algorithm. /// </summary> /// <remarks> /// This instance is only used for its configuration property values and to generate /// additional genetic entities. /// </remarks> [ConfigurationProperty] [RequiredValidator] public GeneticEntity? GeneticEntitySeed { get { return this.geneticEntitySeed; } set { this.SetProperty(ref this.geneticEntitySeed, value); } } /// <summary> /// Gets the <see cref="Population"/> to be used by the algorithm. /// </summary> /// <remarks> /// This instance is only used for its configuration property values and to generate /// additional populations. /// </remarks> [ConfigurationProperty] [RequiredValidator] public Population? PopulationSeed { get { return this.populationSeed; } set { this.SetProperty(ref this.populationSeed, value); } } /// <summary> /// Gets the collection of metrics to be calculated for the genetic algorithm. /// </summary> [ConfigurationProperty] public IList<Metric> Metrics { get { return this.metrics; } } /// <summary> /// Gets the collection of plugins to be used by the genetic algorithm. /// </summary> [ConfigurationProperty] public IList<Plugin> Plugins { get { return this.plugins; } } /// <summary> /// Gets the <see cref="GeneticEnvironment"/> being used by this object. /// </summary> public GeneticEnvironment? Environment { get { return this.environment; } private set { this.SetProperty(ref this.environment, value); } } /// <summary> /// Gets the index of the generation reached so far during execution of the genetic algorithm. /// </summary> /// <value> /// The index of the generation reached so far during execution of the genetic algorithm. /// </value> public int CurrentGeneration { get { return this.currentGeneration; } private set { this.SetProperty(ref this.currentGeneration, value); } } /// <summary> /// Gets a value indicating whether the algorithm is initialized. /// </summary> public bool IsInitialized { get { return this.isInitialized; } } /// <summary> /// Initializes the genetic algorithm with a starting <see cref="GeneticEnvironment"/>. /// </summary> /// <exception cref="ValidationException">The state of a component's configuration is invalid.</exception> /// <exception cref="InvalidOperationException">The configuration for a required component has not been set.</exception> /// <exception cref="InvalidOperationException">An exception occured while instantiating a component.</exception> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public async Task InitializeAsync() { this.Environment = new GeneticEnvironment(this); this.CompileExternalValidatorMapping(); this.Validate(this); foreach (GeneticComponentWithAlgorithm component in this.GetAllComponents()) { component.Initialize(this); this.Validate(component); } this.SortMetrics(); this.Environment.Populations.Clear(); this.CurrentGeneration = 0; await this.Environment.InitializeAsync(); this.isInitialized = true; this.OnGenerationCreated(); await this.Environment.EvaluateFitnessAsync(); this.RaiseFitnessEvaluatedEvent(); } internal void AssertIsInitialized() { if (!this.IsInitialized) { throw new InvalidOperationException(Resources.ComponentNotInitialized); } } /// <summary> /// Executes the genetic algorithm. /// </summary> /// <remarks> /// The execution will continue until the <see cref="Terminator.IsComplete()"/> method returns /// true or <see cref="CancelEventArgs.Cancel"/> property is set to true. /// </remarks> /// <exception cref="InvalidOperationException">The algorithm has not been initialized.</exception> public async Task RunAsync() { this.CheckAlgorithmIsInitialized(); bool cancelRun = false; while (!cancelRun) { cancelRun = await this.StepCoreAsync(); } } /// <summary> /// Executes one generation of the genetic algorithm. /// </summary> /// <returns>True if the genetic algorithm has completed its execution; otherwise, false.</returns> /// <remarks> /// Subsequent calls to either <see cref="RunAsync()"/> or <see cref="StepAsync()"/> will resume execution from /// where the previous <see cref="StepAsync()"/> call left off. /// </remarks> /// <exception cref="InvalidOperationException">The algorithm has not been initialized.</exception> public Task<bool> StepAsync() { this.CheckAlgorithmIsInitialized(); return this.StepCoreAsync(); } /// <summary> /// Completes the execution of the algorithm. /// </summary> public void Complete() { this.OnAlgorithmCompleted(); } /// <summary> /// When overriden in a derived class, modifies <paramref name="population"/> to become the next generation /// of entities. /// </summary> /// <param name="population">The current <see cref="Population"/> to be modified.</param> protected abstract Task CreateNextGenerationAsync(Population population); /// <summary> /// Helper method used to apply the <see cref="GenFx.SelectionOperator"/>. /// </summary> /// <param name="entityCount">Number of <see cref="GeneticEntity"/> objects to select from the population.</param> /// <param name="currentPopulation"><see cref="Population"/> containing the <see cref="GeneticEntity"/> objects from which to select.</param> /// <returns>The selected <see cref="GeneticEntity"/> objects.</returns> protected IList<GeneticEntity> ApplySelection(int entityCount, Population currentPopulation) { return this.SelectionOperator?.SelectEntities(entityCount, currentPopulation) ?? Enumerable.Empty<GeneticEntity>().ToList(); } /// <summary> /// Helper method used to apply the <see cref="GenFx.ElitismStrategy"/>, if one is set, to the <paramref name="currentPopulation"/>. /// </summary> /// <param name="currentPopulation"><see cref="Population"/> from which to select the /// elite entities.</param> /// <returns>The collection of entities, if any, that are elite.</returns> /// <exception cref="ArgumentNullException"><paramref name="currentPopulation"/> is null.</exception> protected IList<GeneticEntity> ApplyElitism(Population currentPopulation) { if (currentPopulation == null) { throw new ArgumentNullException(nameof(currentPopulation)); } if (this.ElitismStrategy != null) { return this.ElitismStrategy.GetEliteEntities(currentPopulation); } else { return new List<GeneticEntity>(); } } /// <summary> /// Applies the <see cref="GenFx.CrossoverOperator"/>, if one is set, to the genetic entities. /// </summary> /// <param name="population">Current population.</param> /// <param name="parents">Parents to which to apply the crossover operation.</param> /// <returns>List of entities after the crossover was applied.</returns> protected IList<GeneticEntity> ApplyCrossover(Population population, IList<GeneticEntity> parents) { if (population == null) { throw new ArgumentNullException(nameof(population)); } if (parents == null) { throw new ArgumentNullException(nameof(parents)); } IList<GeneticEntity> childEntities = new List<GeneticEntity>(); if (this.CrossoverOperator != null) { Queue<GeneticEntity> parentQueue = new Queue<GeneticEntity>(parents); while (childEntities.Count < population.MinimumPopulationSize) { // If there are not enough parents left to perform a crossover with, then // just skip the crossover and add the parents to the child list. if (this.CrossoverOperator.RequiredParentCount > parentQueue.Count) { childEntities.AddRange(parentQueue); parentQueue.Clear(); break; } else { List<GeneticEntity> parentSubset = new List<GeneticEntity>(); for (int i = 0; i < this.CrossoverOperator.RequiredParentCount; i++) { parentSubset.Add(parentQueue.Dequeue()); } childEntities.AddRange(this.CrossoverOperator.Crossover(parentSubset)); } } } else { childEntities = parents; } return childEntities; } /// <summary> /// Applies the <see cref="GenFx.MutationOperator"/>, if one is set, to the <paramref name="entities"/>. /// </summary> /// <param name="entities">List of entities to be potentially mutated.</param> /// <returns>List of entities after the mutation was applied.</returns> /// <exception cref="ArgumentNullException"><paramref name="entities"/> is null.</exception> protected IList<GeneticEntity> ApplyMutation(IList<GeneticEntity> entities) { if (entities == null) { throw new ArgumentNullException(nameof(entities)); } if (this.MutationOperator == null) { return entities; } List<GeneticEntity> mutants = new List<GeneticEntity>(); foreach (GeneticEntity entity in entities) { GeneticEntity newEntity = this.MutationOperator.Mutate(entity); mutants.Add(newEntity); } return mutants; } /// <summary> /// Returns all <see cref="GeneticComponent"/> instances contained by this algorithm. /// </summary> /// <returns>All <see cref="GeneticComponent"/> instances contained by this algorithm.</returns> internal IEnumerable<GeneticComponent> GetAllComponents() { if (this.CrossoverOperator != null) { yield return this.CrossoverOperator; } if (this.ElitismStrategy != null) { yield return this.ElitismStrategy; } if (this.FitnessScalingStrategy != null) { yield return this.FitnessScalingStrategy; } if (this.MutationOperator != null) { yield return this.MutationOperator; } foreach (Metric metric in this.Metrics) { yield return metric; } foreach (Plugin pluginConfig in this.Plugins) { yield return pluginConfig; } if (this.Terminator != null) { yield return terminator; } yield return this.FitnessEvaluator!; yield return this.SelectionOperator!; yield return this.GeneticEntitySeed!; yield return this.PopulationSeed!; } /// <summary> /// Sorts the metrics according to their dependencies. /// </summary> private void SortMetrics() { this.sortedMetrics = new List<Metric>(); List<MetricNode> roots = new List<MetricNode>(); Dictionary<Type, MetricNode> collectedMetricTypes = new Dictionary<Type, GenFx.GeneticAlgorithm.MetricNode>(); foreach (Type metricType in this.metrics.Select(m => m.GetType())) { CollectMetricTypeGraphs(metricType, roots, collectedMetricTypes); } // Iterate through the nodes in the graphs, breadth first, and add them to the list // of sorted metric. Since we're iterating them in this way, they are inherently sorted. Queue<MetricNode> nodesToIterate = new Queue<MetricNode>(roots); while (nodesToIterate.Any()) { MetricNode node = nodesToIterate.Dequeue(); Metric metric = this.metrics.First(m => m.GetType() == node.MetricType); this.sortedMetrics.Add(metric); foreach (MetricNode dependentNode in node.Dependencies) { nodesToIterate.Enqueue(dependentNode); } } } /// <summary> /// Collects the roots of the set of graphs that make up the metric type dependencies. /// </summary> /// <param name="metricType">Type of <see cref="Metric"/> to process.</param> /// <param name="roots">List of collected root nodes.</param> /// <param name="collectedMetricTypes">Mapping of metric types and their nodes that have been collected so far.</param> /// <returns>The <see cref="MetricNode"/> associated with <paramref name="metricType"/>.</returns> private static MetricNode CollectMetricTypeGraphs(Type metricType, List<MetricNode> roots, Dictionary<Type, MetricNode> collectedMetricTypes) { if (collectedMetricTypes.TryGetValue(metricType, out MetricNode metricNode)) { // We've encountered a type that we've processed already. Ensure that this isn't // the result of a cycle in the graph. DetectMetricTypeDependencyCycle(metricNode, metricNode); return metricNode; } List<Type> metricTypeDependencies = GetMetricTypeDependencies(metricType); if (!metricTypeDependencies.Any()) { MetricNode root = new MetricNode(metricType); roots.Add(root); metricNode = root; collectedMetricTypes.Add(metricType, metricNode); } else { MetricNode node = new MetricNode(metricType); collectedMetricTypes.Add(metricType, node); foreach (Type dependency in metricTypeDependencies) { MetricNode dependencyNode = CollectMetricTypeGraphs(dependency, roots, collectedMetricTypes); dependencyNode.Dependencies.Add(node); } metricNode = node; } return metricNode; } /// <summary> /// Detects whether there's a cycle in the metric type dependency graph and throws an exception /// if there is. /// </summary> /// <param name="currentNode">The node to search dependencies of.</param> /// <param name="nodeToSearch">The node to search for a match of.</param> private static void DetectMetricTypeDependencyCycle(MetricNode currentNode, MetricNode nodeToSearch) { foreach (MetricNode dependentNode in currentNode.Dependencies) { if (dependentNode.MetricType == nodeToSearch.MetricType) { throw new InvalidOperationException( StringUtil.GetFormattedString(Resources.ErrorMsg_CycleInMetricDependencyGraph, nodeToSearch.MetricType)); } DetectMetricTypeDependencyCycle(dependentNode, nodeToSearch); } } /// <summary> /// Returns the list of <see cref="Metric"/> types that the <paramref name="metricType"/> /// is dependent upon. /// </summary> /// <param name="metricType">A type of <see cref="Metric"/> to search dependencies for.</param> /// <returns></returns> private static List<Type> GetMetricTypeDependencies(Type metricType) { RequiredMetricAttribute[] attribs = (RequiredMetricAttribute[])metricType .GetCustomAttributes(typeof(RequiredMetricAttribute), true); return attribs.Select(a => a.RequiredType).ToList(); } /// <summary> /// Throws an exception if the algorithm is not initialized. /// </summary> private void CheckAlgorithmIsInitialized() { if (!this.isInitialized) { throw new InvalidOperationException( StringUtil.GetFormattedString(Resources.ErrorMsg_AlgorithmNotInitialized, "Initialize")); } } /// <summary> /// Raises the <see cref="FitnessEvaluated"/> event. /// </summary> /// <returns>True if the user has canceled continued execution of the genetic algorithm; otherwise, false.</returns> private bool RaiseFitnessEvaluatedEvent() { this.CalculateStats(this.environment!, this.currentGeneration); EnvironmentFitnessEvaluatedEventArgs e = new EnvironmentFitnessEvaluatedEventArgs(this.environment!, this.currentGeneration); this.OnFitnessEvaluated(e); return e.Cancel; } /// <summary> /// Raises the <see cref="FitnessEvaluated"/> event. /// </summary> /// <param name="e"><see cref="EnvironmentFitnessEvaluatedEventArgs"/> to be passed to the <see cref="FitnessEvaluated"/> event.</param> private void OnFitnessEvaluated(EnvironmentFitnessEvaluatedEventArgs e) { this.FitnessEvaluated?.Invoke(this, e); } private void OnGenerationCreated() { this.GenerationCreated?.Invoke(this, EventArgs.Empty); } /// <summary> /// Raises the <see cref="AlgorithmStarting"/> event. /// </summary> private void OnAlgorithmStarting() { this.AlgorithmStarting?.Invoke(this, EventArgs.Empty); } /// <summary> /// Executes the genetic algorithm until the <see cref="Terminator.IsComplete()"/> method returns /// true or <see cref="CancelEventArgs.Cancel"/> property is set to true. /// </summary> /// <returns>true if the genetic algorithm has completed its execution; otherwise, false.</returns> private async Task<bool> StepCoreAsync() { if (this.currentGeneration == 0) { this.OnAlgorithmStarting(); } bool isAlgorithmComplete = false; bool isCanceled = false; if (!this.Terminator.IsComplete()) { isCanceled = await this.CreateNextGenerationAsync(); if (!isCanceled) { isAlgorithmComplete = this.Terminator.IsComplete(); if (isAlgorithmComplete) { this.isInitialized = false; } } } else { isAlgorithmComplete = true; } if (isAlgorithmComplete) { this.Complete(); } return isAlgorithmComplete || isCanceled; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { this.CompileExternalValidatorMapping(); } private void OnAlgorithmCompleted() { this.AlgorithmCompleted?.Invoke(this, EventArgs.Empty); } /// <summary> /// Calculates the metrics for a generation. /// </summary> private void CalculateStats(GeneticEnvironment geneticEnvironment, int generationIndex) { foreach (Metric metric in this.sortedMetrics) { metric.Calculate(geneticEnvironment, generationIndex); } } /// <summary> /// Creates the next generation. /// </summary> private async Task<bool> CreateNextGenerationAsync() { List<Task> createGenerationTasks = new List<Task>(); for (int i = 0; i < this.environment!.Populations.Count; i++) { Population population = this.environment.Populations[i]; // Increment the age of all the genetic entities in the population. Parallel.ForEach(population.Entities, e => e.Age++); createGenerationTasks.Add(this.CreateNextGenerationAsync(population)); } await Task.WhenAll(createGenerationTasks); this.CurrentGeneration++; this.OnGenerationCreated(); await this.environment.EvaluateFitnessAsync(); return this.RaiseFitnessEvaluatedEvent(); } /// <summary> /// Validates the component. /// </summary> /// <param name="component">The <see cref="GeneticComponent"/> to validate.</param> private void Validate(GeneticComponent component) { component.Validate(); Type currentType = component.GetType(); while (currentType != typeof(GeneticComponent)) { IEnumerable<PropertyInfo> properties = currentType .GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo propertyInfo in properties) { // Check that the property is valid using the validators described by external components. if (externalValidationMapping.TryGetValue(propertyInfo, out List<PropertyValidator> externalValidators)) { object propValue = propertyInfo.GetValue(component, null); foreach (PropertyValidator validator in externalValidators) { validator.EnsureIsValid(component.GetType().Name + Type.Delimiter + propertyInfo.Name, propValue, component); } } } currentType = currentType.BaseType; } } /// <summary> /// Compiles the mapping of component configuration properties to <see cref="PropertyValidator"/> objects as described by external components. /// </summary> private void CompileExternalValidatorMapping() { foreach (GeneticComponent component in this.GetAllComponents()) { this.CompileExternalValidatorMapping(component); } this.CompileExternalValidatorMapping(this); } /// <summary> /// Compiles the mapping of component configuration properties to <see cref="PropertyValidator"/> objects as described by the specified component. /// </summary> /// <param name="component">The component to check whether it has defined validators for a configuration property.</param> private void CompileExternalValidatorMapping(GeneticComponent component) { if (component == null) { return; } IExternalConfigurationPropertyValidatorAttribute[] attribs = (IExternalConfigurationPropertyValidatorAttribute[])component.GetType().GetCustomAttributes(typeof(IExternalConfigurationPropertyValidatorAttribute), true); foreach (IExternalConfigurationPropertyValidatorAttribute attrib in attribs) { PropertyInfo prop = ExternalValidatorAttributeHelper.GetTargetPropertyInfo(attrib.TargetComponentType, attrib.TargetPropertyName); if (!this.externalValidationMapping.TryGetValue(prop, out List<PropertyValidator> validators)) { validators = new List<PropertyValidator>(); this.externalValidationMapping.Add(prop, validators); } validators.Add(attrib.Validator); } } /// <summary> /// Represents a node within the dependency graph of <see cref="Metric"/> types used by /// algorithm. /// </summary> private class MetricNode { public Type MetricType { get; private set; } public List<MetricNode> Dependencies { get; private set; } public MetricNode(Type metricType) { this.MetricType = metricType; this.Dependencies = new List<MetricNode>(); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections; using System.ComponentModel; using System.Windows; using System.Windows.Data; using System.Windows.Threading; using System.Windows.Media; using MS.Utility; using MS.Internal; using MS.Internal.Controls; using MS.Internal.Data; using MS.Internal.KnownBoxes; using MS.Internal.PresentationFramework; namespace System.Windows.Controls { /// <summary> /// The base class for all controls that contain single content and have a header. /// </summary> /// <remarks> /// HeaderedContentControl adds Header, HasHeader, HeaderTemplate, and HeaderTemplateSelector features to a ContentControl. /// </remarks> [Localizability(LocalizationCategory.Text)] // can contain localizable text public class HeaderedContentControl : ContentControl { #region Constructors static HeaderedContentControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(HeaderedContentControl), new FrameworkPropertyMetadata(typeof(HeaderedContentControl))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(HeaderedContentControl)); } /// <summary> /// Default DependencyObject constructor /// </summary> public HeaderedContentControl() : base() { } #endregion #region Properties /// <summary> /// The DependencyProperty for the Header property. /// Flags: None /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register( "Header", typeof(object), typeof(HeaderedContentControl), new FrameworkPropertyMetadata( (object) null, new PropertyChangedCallback(OnHeaderChanged))); /// <summary> /// Header is the data used to for the header of each item in the control. /// </summary> [Bindable(true), Category("Content")] [Localizability(LocalizationCategory.Label)] public object Header { get { return GetValue(HeaderProperty); } set { SetValue(HeaderProperty, value); } } /// <summary> /// Called when HeaderProperty is invalidated on "d." /// </summary> private static void OnHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedContentControl ctrl = (HeaderedContentControl) d; ctrl.SetValue(HasHeaderPropertyKey, (e.NewValue != null) ? BooleanBoxes.TrueBox : BooleanBoxes.FalseBox); ctrl.OnHeaderChanged(e.OldValue, e.NewValue); } /// <summary> /// This method is invoked when the Header property changes. /// </summary> /// <param name="oldHeader">The old value of the Header property.</param> /// <param name="newHeader">The new value of the Header property.</param> protected virtual void OnHeaderChanged(object oldHeader, object newHeader) { RemoveLogicalChild(oldHeader); AddLogicalChild(newHeader); } /// <summary> /// The key needed set a read-only property. /// </summary> internal static readonly DependencyPropertyKey HasHeaderPropertyKey = DependencyProperty.RegisterReadOnly( "HasHeader", typeof(bool), typeof(HeaderedContentControl), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// The DependencyProperty for the HasHeader property. /// Flags: None /// Other: Read-Only /// Default Value: false /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty HasHeaderProperty = HasHeaderPropertyKey.DependencyProperty; /// <summary> /// True if Header is non-null, false otherwise. /// </summary> [Bindable(false), Browsable(false)] public bool HasHeader { get { return (bool) GetValue(HasHeaderProperty); } } /// <summary> /// The DependencyProperty for the HeaderTemplate property. /// Flags: Can be used in style rules /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.Register( "HeaderTemplate", typeof(DataTemplate), typeof(HeaderedContentControl), new FrameworkPropertyMetadata( (DataTemplate) null, new PropertyChangedCallback(OnHeaderTemplateChanged))); /// <summary> /// HeaderTemplate is the template used to display the <seealso cref="Header"/>. /// </summary> [Bindable(true), Category("Content")] public DataTemplate HeaderTemplate { get { return (DataTemplate) GetValue(HeaderTemplateProperty); } set { SetValue(HeaderTemplateProperty, value); } } /// <summary> /// Called when HeaderTemplateProperty is invalidated on "d." /// </summary> private static void OnHeaderTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedContentControl ctrl = (HeaderedContentControl)d; ctrl.OnHeaderTemplateChanged((DataTemplate) e.OldValue, (DataTemplate) e.NewValue); } /// <summary> /// This method is invoked when the HeaderTemplate property changes. /// </summary> /// <param name="oldHeaderTemplate">The old value of the HeaderTemplate property.</param> /// <param name="newHeaderTemplate">The new value of the HeaderTemplate property.</param> protected virtual void OnHeaderTemplateChanged(DataTemplate oldHeaderTemplate, DataTemplate newHeaderTemplate) { Helper.CheckTemplateAndTemplateSelector("Header", HeaderTemplateProperty, HeaderTemplateSelectorProperty, this); } /// <summary> /// The DependencyProperty for the HeaderTemplateSelector property. /// Flags: none /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty HeaderTemplateSelectorProperty = DependencyProperty.Register( "HeaderTemplateSelector", typeof(DataTemplateSelector), typeof(HeaderedContentControl), new FrameworkPropertyMetadata( (DataTemplateSelector) null, new PropertyChangedCallback(OnHeaderTemplateSelectorChanged))); /// <summary> /// HeaderTemplateSelector allows the application writer to provide custom logic /// for choosing the template used to display the <seealso cref="Header"/>. /// </summary> /// <remarks> /// This property is ignored if <seealso cref="HeaderTemplate"/> is set. /// </remarks> [Bindable(true), Category("Content")] public DataTemplateSelector HeaderTemplateSelector { get { return (DataTemplateSelector) GetValue(HeaderTemplateSelectorProperty); } set { SetValue(HeaderTemplateSelectorProperty, value); } } /// <summary> /// Called when HeaderTemplateSelectorProperty is invalidated on "d." /// </summary> private static void OnHeaderTemplateSelectorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedContentControl ctrl = (HeaderedContentControl) d; ctrl.OnHeaderTemplateSelectorChanged((DataTemplateSelector) e.OldValue, (DataTemplateSelector) e.NewValue); } /// <summary> /// This method is invoked when the HeaderTemplateSelector property changes. /// </summary> /// <param name="oldHeaderTemplateSelector">The old value of the HeaderTemplateSelector property.</param> /// <param name="newHeaderTemplateSelector">The new value of the HeaderTemplateSelector property.</param> protected virtual void OnHeaderTemplateSelectorChanged(DataTemplateSelector oldHeaderTemplateSelector, DataTemplateSelector newHeaderTemplateSelector) { Helper.CheckTemplateAndTemplateSelector("Header", HeaderTemplateProperty, HeaderTemplateSelectorProperty, this); } /// <summary> /// The DependencyProperty for the HeaderStringFormat property. /// Flags: None /// Default Value: null /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty HeaderStringFormatProperty = DependencyProperty.Register( "HeaderStringFormat", typeof(String), typeof(HeaderedContentControl), new FrameworkPropertyMetadata( (String) null, new PropertyChangedCallback(OnHeaderStringFormatChanged))); /// <summary> /// HeaderStringFormat is the format used to display the header content as a string. /// This arises only when no template is available. /// </summary> [Bindable(true), CustomCategory("Content")] public String HeaderStringFormat { get { return (String) GetValue(HeaderStringFormatProperty); } set { SetValue(HeaderStringFormatProperty, value); } } /// <summary> /// Called when HeaderStringFormatProperty is invalidated on "d." /// </summary> private static void OnHeaderStringFormatChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedContentControl ctrl = (HeaderedContentControl)d; ctrl.OnHeaderStringFormatChanged((String) e.OldValue, (String) e.NewValue); } /// <summary> /// This method is invoked when the HeaderStringFormat property changes. /// </summary> /// <param name="oldHeaderStringFormat">The old value of the HeaderStringFormat property.</param> /// <param name="newHeaderStringFormat">The new value of the HeaderStringFormat property.</param> protected virtual void OnHeaderStringFormatChanged(String oldHeaderStringFormat, String newHeaderStringFormat) { } #endregion #region LogicalTree /// <summary> /// Returns enumerator to logical children /// </summary> protected internal override IEnumerator LogicalChildren { get { object header = Header; if (HeaderIsNotLogical || header == null) { return base.LogicalChildren; } return new HeaderedContentModelTreeEnumerator(this, ContentIsNotLogical ? null : Content, header); } } #endregion #region Internal Methods /// <summary> /// Gives a string representation of this object. /// </summary> /// <returns></returns> internal override string GetPlainText() { return ContentControl.ContentObjectToString(Header); } /// <summary> /// Indicates whether Header should be a logical child or not. /// </summary> internal bool HeaderIsNotLogical { get { return ReadControlFlag(ControlBoolFlags.HeaderIsNotLogical); } set { WriteControlFlag(ControlBoolFlags.HeaderIsNotLogical, value); } } /// <summary> /// Indicates whether Header is a data item /// </summary> internal bool HeaderIsItem { get { return ReadControlFlag(ControlBoolFlags.HeaderIsItem); } set { WriteControlFlag(ControlBoolFlags.HeaderIsItem, value); } } /// <summary> /// Prepare to display the item. /// </summary> internal void PrepareHeaderedContentControl(object item, DataTemplate itemTemplate, DataTemplateSelector itemTemplateSelector, string stringFormat) { if (item != this) { // don't treat Content as a logical child ContentIsNotLogical = true; HeaderIsNotLogical = true; if (ContentIsItem || !HasNonDefaultValue(ContentProperty)) { Content = item; ContentIsItem = true; } // Visuals can't be placed in both Header and Content, but data can if (!(item is Visual) && (HeaderIsItem || !HasNonDefaultValue(HeaderProperty))) { Header = item; HeaderIsItem = true; } if (itemTemplate != null) SetValue(HeaderTemplateProperty, itemTemplate); if (itemTemplateSelector != null) SetValue(HeaderTemplateSelectorProperty, itemTemplateSelector); if (stringFormat != null) SetValue(HeaderStringFormatProperty, stringFormat); } else { ContentIsNotLogical = false; } } /// <summary> /// Undo the effect of PrepareHeaderedContentControl. /// </summary> internal void ClearHeaderedContentControl(object item) { if (item != this) { if (ContentIsItem) { Content = BindingExpressionBase.DisconnectedItem; } if (HeaderIsItem) { Header = BindingExpressionBase.DisconnectedItem; } } } #endregion #region Method Overrides /// <summary> /// Gives a string representation of this object. /// </summary> public override string ToString() { string typeText = this.GetType().ToString(); string headerText = String.Empty; string contentText = String.Empty; bool valuesDefined = false; // Accessing Header's content may be thread sensitive if (CheckAccess()) { headerText = ContentControl.ContentObjectToString(Header); contentText = ContentControl.ContentObjectToString(Content); valuesDefined = true; } else { //Not on dispatcher, try posting to the dispatcher with 20ms timeout Dispatcher.Invoke(DispatcherPriority.Send, new TimeSpan(0, 0, 0, 0, 20), new DispatcherOperationCallback(delegate(object o) { headerText = ContentControl.ContentObjectToString(Header); contentText = ContentControl.ContentObjectToString(Content); valuesDefined = true; return null; }), null); } // If header and content text are defined if (valuesDefined) { return SR.Get(SRID.ToStringFormatString_HeaderedContentControl, typeText, headerText, contentText); } // Not able to access the dispatcher return typeText; } #endregion #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered DefaultStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Xunit; internal class Outside { public class Inside { } } internal class Outside<T> { public class Inside<U> { } } namespace System.Tests { public class TypeTests { [Theory] [InlineData(typeof(int), null)] [InlineData(typeof(int[]), null)] [InlineData(typeof(Outside.Inside), typeof(Outside))] [InlineData(typeof(Outside.Inside[]), null)] [InlineData(typeof(Outside<int>), null)] [InlineData(typeof(Outside<int>.Inside<double>), typeof(Outside<>))] public static void DeclaringType(Type t, Type expected) { Assert.Equal(expected, t.DeclaringType); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(int[]))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public static void GenericParameterPosition_Invalid(Type t) { Assert.Throws<InvalidOperationException>(() => t.GenericParameterPosition); } [Theory] [InlineData(typeof(int), new Type[0])] [InlineData(typeof(IDictionary<int, string>), new[] { typeof(int), typeof(string) })] [InlineData(typeof(IList<int>), new[] { typeof(int) })] [InlineData(typeof(IList<>), new Type[0])] public static void GenericTypeArguments(Type t, Type[] expected) { Type[] result = t.GenericTypeArguments; Assert.Equal(expected.Length, result.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], result[i]); } } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), true)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void HasElementType(Type t, bool expected) { Assert.Equal(expected, t.HasElementType); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), true)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void IsArray(Type t, bool expected) { Assert.Equal(expected, t.IsArray); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void IsByRef(Type t, bool expected) { Assert.Equal(expected, t.IsByRef); Assert.True(t.MakeByRefType().IsByRef); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] [InlineData(typeof(int*), true)] public static void IsPointer(Type t, bool expected) { Assert.Equal(expected, t.IsPointer); Assert.True(t.MakePointerType().IsPointer); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), true)] [InlineData(typeof(IList<>), false)] public static void IsConstructedGenericType(Type t, bool expected) { Assert.Equal(expected, t.IsConstructedGenericType); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(IList<int>), false)] [InlineData(typeof(IList<>), false)] public static void IsGenericParameter(Type t, bool expected) { Assert.Equal(expected, t.IsGenericParameter); } [Theory] [InlineData(typeof(int), false)] [InlineData(typeof(int[]), false)] [InlineData(typeof(Outside.Inside), true)] [InlineData(typeof(Outside.Inside[]), false)] [InlineData(typeof(Outside<int>), false)] [InlineData(typeof(Outside<int>.Inside<double>), true)] public static void IsNested(Type t, bool expected) { Assert.Equal(expected, t.IsNested); } [Theory] [InlineData(typeof(int), typeof(int))] [InlineData(typeof(int[]), typeof(int[]))] [InlineData(typeof(Outside<int>), typeof(Outside<int>))] public static void TypeHandle(Type t1, Type t2) { RuntimeTypeHandle r1 = t1.TypeHandle; RuntimeTypeHandle r2 = t2.TypeHandle; Assert.Equal(r1, r2); Assert.Equal(t1, Type.GetTypeFromHandle(r1)); Assert.Equal(t1, Type.GetTypeFromHandle(r2)); } [Fact] public static void GetTypeFromDefaultHandle() { Assert.Null(Type.GetTypeFromHandle(default(RuntimeTypeHandle))); } [Theory] [InlineData(typeof(int[]), 1)] [InlineData(typeof(int[,,]), 3)] public static void GetArrayRank(Type t, int expected) { Assert.Equal(expected, t.GetArrayRank()); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public static void GetArrayRank_Invalid(Type t) { AssertExtensions.Throws<ArgumentException>(null, () => t.GetArrayRank()); } [Theory] [InlineData(typeof(int), null)] [InlineData(typeof(Outside.Inside), null)] [InlineData(typeof(int[]), typeof(int))] [InlineData(typeof(Outside<int>.Inside<double>[]), typeof(Outside<int>.Inside<double>))] [InlineData(typeof(Outside<int>), null)] [InlineData(typeof(Outside<int>.Inside<double>), null)] public static void GetElementType(Type t, Type expected) { Assert.Equal(expected, t.GetElementType()); } [Theory] [InlineData(typeof(int), typeof(int[]))] public static void MakeArrayType(Type t, Type tArrayExpected) { Type tArray = t.MakeArrayType(); Assert.Equal(tArrayExpected, tArray); Assert.Equal(t, tArray.GetElementType()); Assert.True(tArray.IsArray); Assert.True(tArray.HasElementType); string s1 = t.ToString(); string s2 = tArray.ToString(); Assert.Equal(s2, s1 + "[]"); } [Theory] [InlineData(typeof(int))] public static void MakeByRefType(Type t) { Type tRef1 = t.MakeByRefType(); Type tRef2 = t.MakeByRefType(); Assert.Equal(tRef1, tRef2); Assert.True(tRef1.IsByRef); Assert.True(tRef1.HasElementType); Assert.Equal(t, tRef1.GetElementType()); string s1 = t.ToString(); string s2 = tRef1.ToString(); Assert.Equal(s2, s1 + "&"); } [Theory] [InlineData("System.Nullable`1[System.Int32]", typeof(int?))] [InlineData("System.Int32*", typeof(int*))] [InlineData("System.Int32**", typeof(int**))] [InlineData("Outside`1", typeof(Outside<>))] [InlineData("Outside`1+Inside`1", typeof(Outside<>.Inside<>))] [InlineData("Outside[]", typeof(Outside[]))] [InlineData("Outside[,,]", typeof(Outside[,,]))] [InlineData("Outside[][]", typeof(Outside[][]))] [InlineData("Outside`1[System.Nullable`1[System.Boolean]]", typeof(Outside<bool?>))] public static void GetTypeByName(string typeName, Type expectedType) { Type t = Type.GetType(typeName, throwOnError: false, ignoreCase: false); Assert.Equal(expectedType, t); t = Type.GetType(typeName.ToLower(), throwOnError: false, ignoreCase: true); Assert.Equal(expectedType, t); } [Theory] [InlineData("system.nullable`1[system.int32]", typeof(TypeLoadException), false)] [InlineData("System.NonExistingType", typeof(TypeLoadException), false)] [InlineData("", typeof(TypeLoadException), false)] [InlineData("System.Int32[,*,]", typeof(ArgumentException), false)] [InlineData("Outside`2", typeof(TypeLoadException), false)] [InlineData("Outside`1[System.Boolean, System.Int32]", typeof(ArgumentException), true)] public static void GetTypeByName_Invalid(string typeName, Type expectedException, bool alwaysThrowsException) { if (!alwaysThrowsException) { Type t = Type.GetType(typeName, throwOnError: false, ignoreCase: false); Assert.Null(t); } Assert.Throws(expectedException, () => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Stackwalking is not supported on UaoAot")] public static void GetTypeByName_ViaReflection() { MethodInfo method = typeof(Type).GetMethod("GetType", new[] { typeof(string) }); object result = method.Invoke(null, new object[] { "System.Tests.TypeTests" }); Assert.Equal(typeof(TypeTests), result); } [Fact] public static void Delimiter() { Assert.NotNull(Type.Delimiter); } [Theory] [InlineData(typeof(bool), TypeCode.Boolean)] [InlineData(typeof(byte), TypeCode.Byte)] [InlineData(typeof(char), TypeCode.Char)] [InlineData(typeof(DateTime), TypeCode.DateTime)] [InlineData(typeof(decimal), TypeCode.Decimal)] [InlineData(typeof(double), TypeCode.Double)] [InlineData(null, TypeCode.Empty)] [InlineData(typeof(short), TypeCode.Int16)] [InlineData(typeof(int), TypeCode.Int32)] [InlineData(typeof(long), TypeCode.Int64)] [InlineData(typeof(object), TypeCode.Object)] [InlineData(typeof(System.Nullable), TypeCode.Object)] [InlineData(typeof(Nullable<int>), TypeCode.Object)] [InlineData(typeof(Dictionary<,>), TypeCode.Object)] [InlineData(typeof(Exception), TypeCode.Object)] [InlineData(typeof(sbyte), TypeCode.SByte)] [InlineData(typeof(float), TypeCode.Single)] [InlineData(typeof(string), TypeCode.String)] [InlineData(typeof(ushort), TypeCode.UInt16)] [InlineData(typeof(uint), TypeCode.UInt32)] [InlineData(typeof(ulong), TypeCode.UInt64)] public static void GetTypeCode(Type t, TypeCode typeCode) { Assert.Equal(typeCode, Type.GetTypeCode(t)); } public static void ReflectionOnlyGetType() { AssertExtensions.Throws<ArgumentNullException>("typeName", () => Type.ReflectionOnlyGetType(null, true, false)); Assert.Throws<TypeLoadException>(() => Type.ReflectionOnlyGetType("", true, true)); Assert.Throws<NotSupportedException>(() => Type.ReflectionOnlyGetType("System.Tests.TypeTests", false, true)); } } public class TypeTestsExtended : RemoteExecutorTestBase { public class ContextBoundClass : ContextBoundObject { public string Value = "The Value property."; } static string s_testAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestLoadAssembly.dll"); static string testtype = "System.Collections.Generic.Dictionary`2[[Program, Foo], [Program, Foo]]"; private static Func<AssemblyName, Assembly> assemblyloader = (aName) => aName.Name == "TestLoadAssembly" ? Assembly.LoadFrom(@".\TestLoadAssembly.dll") : null; private static Func<Assembly, String, Boolean, Type> typeloader = (assem, name, ignore) => assem == null ? Type.GetType(name, false, ignore) : assem.GetType(name, false, ignore); [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() is not supported on UapAot")] public static void GetTypeByName() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteInvoke(() => { string test1 = testtype; Type t1 = Type.GetType(test1, (aName) => aName.Name == "Foo" ? Assembly.LoadFrom(s_testAssemblyPath) : null, typeloader, true ); Assert.NotNull(t1); string test2 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program, TestLoadAssembly]]"; Type t2 = Type.GetType(test2, assemblyloader, typeloader, true); Assert.NotNull(t2); Assert.Equal(t1, t2); return SuccessExitCode; }, options).Dispose(); } [Theory] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() is not supported on UapAot")] [InlineData("System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program2, TestLoadAssembly]]")] [InlineData("")] public void GetTypeByName_NoSuchType_ThrowsTypeLoadException(string typeName) { RemoteInvoke(marshalledTypeName => { Assert.Throws<TypeLoadException>(() => Type.GetType(marshalledTypeName, assemblyloader, typeloader, true)); Assert.Null(Type.GetType(marshalledTypeName, assemblyloader, typeloader, false)); return SuccessExitCode; }, typeName).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() is not supported on UapAot")] public static void GetTypeByNameCaseSensitiveTypeloadFailure() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteInvoke(() => { //Type load failure due to case sensitive search of type Ptogram string test3 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [program, TestLoadAssembly]]"; Assert.Throws<TypeLoadException>(() => Type.GetType(test3, assemblyloader, typeloader, true, false //case sensitive )); //non throwing version Type t2 = Type.GetType(test3, assemblyloader, typeloader, false, //no throw false ); Assert.Null(t2); return SuccessExitCode; }, options).Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void IsContextful() { Assert.True(!typeof(TypeTestsExtended).IsContextful); Assert.True(!typeof(ContextBoundClass).IsContextful); } #region GetInterfaceMap tests public static IEnumerable<object[]> GetInterfaceMap_TestData() { yield return new object[] { typeof(ISimpleInterface), typeof(SimpleType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("Method"), typeof(SimpleType).GetMethod("Method")), new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("GenericMethod"), typeof(SimpleType).GetMethod("GenericMethod")) } }; yield return new object[] { typeof(IGenericInterface<object>), typeof(DerivedType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<object>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(object) })), } }; yield return new object[] { typeof(IGenericInterface<string>), typeof(DerivedType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<string>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(string) })), } }; } [Theory] [MemberData(nameof(GetInterfaceMap_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Type.GetInterfaceMap() is not supported on UapAot")] public static void GetInterfaceMap(Type interfaceType, Type classType, Tuple<MethodInfo, MethodInfo>[] expectedMap) { InterfaceMapping actualMapping = classType.GetInterfaceMap(interfaceType); Assert.Equal(interfaceType, actualMapping.InterfaceType); Assert.Equal(classType, actualMapping.TargetType); Assert.Equal(expectedMap.Length, actualMapping.InterfaceMethods.Length); Assert.Equal(expectedMap.Length, actualMapping.TargetMethods.Length); for (int i = 0; i < expectedMap.Length; i++) { Assert.Contains(expectedMap[i].Item1, actualMapping.InterfaceMethods); int index = Array.IndexOf(actualMapping.InterfaceMethods, expectedMap[i].Item1); Assert.Equal(expectedMap[i].Item2, actualMapping.TargetMethods[index]); } } interface ISimpleInterface { void Method(); void GenericMethod<T>(); } class SimpleType : ISimpleInterface { public void Method() { } public void GenericMethod<T>() { } } interface IGenericInterface<T> { void Method(T arg); } class GenericBaseType<T> : IGenericInterface<T> { public void Method(T arg) { } } class DerivedType : GenericBaseType<object>, IGenericInterface<string> { public void Method(string arg) { } } #endregion } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using FarseerPhysics.Common; using FarseerPhysics.Common.ConvexHull; using Microsoft.Xna.Framework; namespace FarseerPhysics.Collision.Shapes { /// <summary> /// Represents a simple non-selfintersecting convex polygon. /// Create a convex hull from the given array of points. /// </summary> public class PolygonShape : Shape { private Vertices _vertices; private Vertices _normals; public PolygonShape(Vertices vertices) : this(vertices, 1) { } /// <summary> /// Initializes a new instance of the <see cref="PolygonShape"/> class. /// </summary> /// <param name="vertices">The vertices.</param> /// <param name="density">The density.</param> public PolygonShape(Vertices vertices, float density) : base(density) { ShapeType = ShapeType.Polygon; _radius = Settings.PolygonRadius; Vertices = vertices; } /// <summary> /// Create a new PolygonShape with the specified density. /// </summary> /// <param name="density">The density.</param> public PolygonShape(float density) : base(density) { Debug.Assert(density >= 0f); ShapeType = ShapeType.Polygon; _radius = Settings.PolygonRadius; _vertices = new Vertices(Settings.MaxPolygonVertices); _normals = new Vertices(Settings.MaxPolygonVertices); } internal PolygonShape() : base(0) { ShapeType = ShapeType.Polygon; _radius = Settings.PolygonRadius; _vertices = new Vertices(Settings.MaxPolygonVertices); _normals = new Vertices(Settings.MaxPolygonVertices); } /// <summary> /// Create a convex hull from the given array of local points. /// The number of vertices must be in the range [3, Settings.MaxPolygonVertices]. /// Warning: the points may be re-ordered, even if they form a convex polygon /// Warning: collinear points are handled but not removed. Collinear points may lead to poor stacking behavior. /// </summary> public Vertices Vertices { get { return _vertices; } set { _vertices = new Vertices(value); Debug.Assert(_vertices.Count >= 3 && _vertices.Count <= Settings.MaxPolygonVertices); if (Settings.UseConvexHullPolygons) { //FPE note: This check is required as the GiftWrap algorithm early exits on triangles //So instead of giftwrapping a triangle, we just force it to be clock wise. if (_vertices.Count <= 3) _vertices.ForceCounterClockWise(); else _vertices = GiftWrap.GetConvexHull(_vertices); } _normals = new Vertices(_vertices.Count); // Compute normals. Ensure the edges have non-zero length. for (int i = 0; i < _vertices.Count; ++i) { int next = i + 1 < _vertices.Count ? i + 1 : 0; Vector2 edge = _vertices[next] - _vertices[i]; Debug.Assert(edge.LengthSquared() > Settings.Epsilon * Settings.Epsilon); //FPE optimization: Normals.Add(MathHelper.Cross(edge, 1.0f)); Vector2 temp = new Vector2(edge.Y, -edge.X); temp.Normalize(); _normals.Add(temp); } // Compute the polygon mass data ComputeProperties(); } } public Vertices Normals { get { return _normals; } } public override int ChildCount { get { return 1; } } protected override void ComputeProperties() { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.X = (1/mass) * rho * int(x * dA) // centroid.Y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. Debug.Assert(Vertices.Count >= 3); //FPE optimization: Early exit as polygons with 0 density does not have any properties. if (_density <= 0) return; //FPE optimization: Consolidated the calculate centroid and mass code to a single method. Vector2 center = Vector2.Zero; float area = 0.0f; float I = 0.0f; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). Vector2 s = Vector2.Zero; // This code would put the reference point inside the polygon. for (int i = 0; i < Vertices.Count; ++i) { s += Vertices[i]; } s *= 1.0f / Vertices.Count; const float k_inv3 = 1.0f / 3.0f; for (int i = 0; i < Vertices.Count; ++i) { // Triangle vertices. Vector2 e1 = Vertices[i] - s; Vector2 e2 = i + 1 < Vertices.Count ? Vertices[i + 1] - s : Vertices[0] - s; float D = MathUtils.Cross(e1, e2); float triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid center += triangleArea * k_inv3 * (e1 + e2); float ex1 = e1.X, ey1 = e1.Y; float ex2 = e2.X, ey2 = e2.Y; float intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; float inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += (0.25f * k_inv3 * D) * (intx2 + inty2); } //The area is too small for the engine to handle. Debug.Assert(area > Settings.Epsilon); // We save the area MassData.Area = area; // Total mass MassData.Mass = _density * area; // Center of mass center *= 1.0f / area; MassData.Centroid = center + s; // Inertia tensor relative to the local origin (point s). MassData.Inertia = _density * I; // Shift to center of mass then to original body origin. MassData.Inertia += MassData.Mass * (Vector2.Dot(MassData.Centroid, MassData.Centroid) - Vector2.Dot(center, center)); } public override bool TestPoint(ref Transform transform, ref Vector2 point) { Vector2 pLocal = MathUtils.MulT(transform.q, point - transform.p); for (int i = 0; i < Vertices.Count; ++i) { float dot = Vector2.Dot(Normals[i], pLocal - Vertices[i]); if (dot > 0.0f) { return false; } } return true; } public override bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform, int childIndex) { output = new RayCastOutput(); // Put the ray into the polygon's frame of reference. Vector2 p1 = MathUtils.MulT(transform.q, input.Point1 - transform.p); Vector2 p2 = MathUtils.MulT(transform.q, input.Point2 - transform.p); Vector2 d = p2 - p1; float lower = 0.0f, upper = input.MaxFraction; int index = -1; for (int i = 0; i < Vertices.Count; ++i) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 float numerator = Vector2.Dot(Normals[i], Vertices[i] - p1); float denominator = Vector2.Dot(Normals[i], d); if (denominator == 0.0f) { if (numerator < 0.0f) { return false; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if (denominator < 0.0f && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0.0f && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } // The use of epsilon here causes the assert on lower to trip // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. //if (upper < lower - b2_epsilon) if (upper < lower) { return false; } } Debug.Assert(0.0f <= lower && lower <= input.MaxFraction); if (index >= 0) { output.Fraction = lower; output.Normal = MathUtils.Mul(transform.q, Normals[index]); return true; } return false; } /// <summary> /// Given a transform, compute the associated axis aligned bounding box for a child shape. /// </summary> /// <param name="aabb">The aabb results.</param> /// <param name="transform">The world transform of the shape.</param> /// <param name="childIndex">The child shape index.</param> public override void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex) { Vector2 lower = MathUtils.Mul(ref transform, Vertices[0]); Vector2 upper = lower; for (int i = 1; i < Vertices.Count; ++i) { Vector2 v = MathUtils.Mul(ref transform, Vertices[i]); lower = Vector2.Min(lower, v); upper = Vector2.Max(upper, v); } Vector2 r = new Vector2(Radius, Radius); aabb.LowerBound = lower - r; aabb.UpperBound = upper + r; } public override float ComputeSubmergedArea(ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc) { sc = Vector2.Zero; //Transform plane into shape co-ordinates Vector2 normalL = MathUtils.MulT(xf.q, normal); float offsetL = offset - Vector2.Dot(normal, xf.p); float[] depths = new float[Settings.MaxPolygonVertices]; int diveCount = 0; int intoIndex = -1; int outoIndex = -1; bool lastSubmerged = false; int i; for (i = 0; i < Vertices.Count; i++) { depths[i] = Vector2.Dot(normalL, Vertices[i]) - offsetL; bool isSubmerged = depths[i] < -Settings.Epsilon; if (i > 0) { if (isSubmerged) { if (!lastSubmerged) { intoIndex = i - 1; diveCount++; } } else { if (lastSubmerged) { outoIndex = i - 1; diveCount++; } } } lastSubmerged = isSubmerged; } switch (diveCount) { case 0: if (lastSubmerged) { //Completely submerged sc = MathUtils.Mul(ref xf, MassData.Centroid); return MassData.Mass / Density; } //Completely dry return 0; case 1: if (intoIndex == -1) { intoIndex = Vertices.Count - 1; } else { outoIndex = Vertices.Count - 1; } break; } int intoIndex2 = (intoIndex + 1) % Vertices.Count; int outoIndex2 = (outoIndex + 1) % Vertices.Count; float intoLambda = (0 - depths[intoIndex]) / (depths[intoIndex2] - depths[intoIndex]); float outoLambda = (0 - depths[outoIndex]) / (depths[outoIndex2] - depths[outoIndex]); Vector2 intoVec = new Vector2(Vertices[intoIndex].X * (1 - intoLambda) + Vertices[intoIndex2].X * intoLambda, Vertices[intoIndex].Y * (1 - intoLambda) + Vertices[intoIndex2].Y * intoLambda); Vector2 outoVec = new Vector2(Vertices[outoIndex].X * (1 - outoLambda) + Vertices[outoIndex2].X * outoLambda, Vertices[outoIndex].Y * (1 - outoLambda) + Vertices[outoIndex2].Y * outoLambda); //Initialize accumulator float area = 0; Vector2 center = new Vector2(0, 0); Vector2 p2 = Vertices[intoIndex2]; const float k_inv3 = 1.0f / 3.0f; //An awkward loop from intoIndex2+1 to outIndex2 i = intoIndex2; while (i != outoIndex2) { i = (i + 1) % Vertices.Count; Vector2 p3; if (i == outoIndex2) p3 = outoVec; else p3 = Vertices[i]; //Add the triangle formed by intoVec,p2,p3 { Vector2 e1 = p2 - intoVec; Vector2 e2 = p3 - intoVec; float D = MathUtils.Cross(e1, e2); float triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid center += triangleArea * k_inv3 * (intoVec + p2 + p3); } p2 = p3; } //Normalize and transform centroid center *= 1.0f / area; sc = MathUtils.Mul(ref xf, center); return area; } public bool CompareTo(PolygonShape shape) { if (Vertices.Count != shape.Vertices.Count) return false; for (int i = 0; i < Vertices.Count; i++) { if (Vertices[i] != shape.Vertices[i]) return false; } return (Radius == shape.Radius && MassData == shape.MassData); } public override Shape Clone() { PolygonShape clone = new PolygonShape(); clone.ShapeType = ShapeType; clone._radius = _radius; clone._density = _density; clone._vertices = new Vertices(_vertices); clone._normals = new Vertices(_normals); clone.MassData = MassData; return clone; } } }
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 Apress.Recipes.WebApi.WebHost.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 file="ReflectPropertyDescriptor.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ namespace System.ComponentModel { using Microsoft.Win32; using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters; using System.Security; using System.Security.Permissions; /// <internalonly/> /// <devdoc> /// <para> /// ReflectPropertyDescriptor defines a property. Properties are the main way that a user can /// set up the state of a component. /// The ReflectPropertyDescriptor class takes a component class that the property lives on, /// a property name, the type of the property, and various attributes for the /// property. /// For a property named XXX of type YYY, the associated component class is /// required to implement two methods of the following /// form: /// </para> /// <code> /// public YYY GetXXX(); /// public void SetXXX(YYY value); /// </code> /// The component class can optionally implement two additional methods of /// the following form: /// <code> /// public boolean ShouldSerializeXXX(); /// public void ResetXXX(); /// </code> /// These methods deal with a property's default value. The ShouldSerializeXXX() /// method returns true if the current value of the XXX property is different /// than it's default value, so that it should be persisted out. The ResetXXX() /// method resets the XXX property to its default value. If the ReflectPropertyDescriptor /// includes the default value of the property (using the DefaultValueAttribute), /// the ShouldSerializeXXX() and ResetXXX() methods are ignored. /// If the ReflectPropertyDescriptor includes a reference to an editor /// then that value editor will be used to /// edit the property. Otherwise, a system-provided editor will be used. /// Various attributes can be passed to the ReflectPropertyDescriptor, as are described in /// Attribute. /// ReflectPropertyDescriptors can be obtained by a user programmatically through the /// ComponentManager. /// </devdoc> [HostProtection(SharedState = true)] internal sealed class ReflectPropertyDescriptor : PropertyDescriptor { private static readonly Type[] argsNone = new Type[0]; private static readonly object noValue = new object(); private static TraceSwitch PropDescCreateSwitch = new TraceSwitch("PropDescCreate", "ReflectPropertyDescriptor: Dump errors when creating property info"); private static TraceSwitch PropDescUsageSwitch = new TraceSwitch("PropDescUsage", "ReflectPropertyDescriptor: Debug propertydescriptor usage"); private static TraceSwitch PropDescSwitch = new TraceSwitch("PropDesc", "ReflectPropertyDescriptor: Debug property descriptor"); private static readonly int BitDefaultValueQueried = BitVector32.CreateMask(); private static readonly int BitGetQueried = BitVector32.CreateMask(BitDefaultValueQueried); private static readonly int BitSetQueried = BitVector32.CreateMask(BitGetQueried); private static readonly int BitShouldSerializeQueried = BitVector32.CreateMask(BitSetQueried); private static readonly int BitResetQueried = BitVector32.CreateMask(BitShouldSerializeQueried); private static readonly int BitChangedQueried = BitVector32.CreateMask(BitResetQueried); private static readonly int BitIPropChangedQueried = BitVector32.CreateMask(BitChangedQueried); private static readonly int BitReadOnlyChecked = BitVector32.CreateMask(BitIPropChangedQueried); private static readonly int BitAmbientValueQueried = BitVector32.CreateMask(BitReadOnlyChecked); private static readonly int BitSetOnDemand = BitVector32.CreateMask(BitAmbientValueQueried); BitVector32 state = new BitVector32(); // Contains the state bits for this proeprty descriptor. Type componentClass; // used to determine if we should all on us or on the designer Type type; // the data type of the property object defaultValue; // the default value of the property (or noValue) object ambientValue; // the ambient value of the property (or noValue) PropertyInfo propInfo; // the property info MethodInfo getMethod; // the property get method MethodInfo setMethod; // the property set method MethodInfo shouldSerializeMethod; // the should serialize method MethodInfo resetMethod; // the reset property method EventDescriptor realChangedEvent; // <propertyname>Changed event handler on object EventDescriptor realIPropChangedEvent; // INotifyPropertyChanged.PropertyChanged event handler on object Type receiverType; // Only set if we are an extender /// <devdoc> /// The main constructor for ReflectPropertyDescriptors. /// </devdoc> public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Attribute[] attributes) : base(name, attributes) { Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "Creating ReflectPropertyDescriptor for " + componentClass.FullName + "." + name); try { if (type == null) { Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "type == null, name == " + name); throw new ArgumentException(SR.GetString(SR.ErrorInvalidPropertyType, name)); } if (componentClass == null) { Debug.WriteLineIf(PropDescCreateSwitch.TraceVerbose, "componentClass == null, name == " + name); throw new ArgumentException(SR.GetString(SR.InvalidNullArgument, "componentClass")); } this.type = type; this.componentClass = componentClass; } catch (Exception t) { Debug.Fail("Property '" + name + "' on component " + componentClass.FullName + " failed to init."); Debug.Fail(t.ToString()); throw t; } } /// <devdoc> /// A constructor for ReflectPropertyDescriptors that have no attributes. /// </devdoc> public ReflectPropertyDescriptor(Type componentClass, string name, Type type, PropertyInfo propInfo, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) { this.propInfo = propInfo; this.getMethod = getMethod; this.setMethod = setMethod; if (getMethod != null && propInfo != null && setMethod == null ) state[BitGetQueried | BitSetOnDemand] = true; else state[BitGetQueried | BitSetQueried] = true; } /// <devdoc> /// A constructor for ReflectPropertyDescriptors that creates an extender property. /// </devdoc> public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Type receiverType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs) { this.receiverType = receiverType; this.getMethod = getMethod; this.setMethod = setMethod; state[BitGetQueried | BitSetQueried] = true; } /// <devdoc> /// This constructor takes an existing ReflectPropertyDescriptor and modifies it by merging in the /// passed-in attributes. /// </devdoc> public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldReflectPropertyDescriptor, Attribute[] attributes) : base(oldReflectPropertyDescriptor, attributes) { this.componentClass = componentClass; this.type = oldReflectPropertyDescriptor.PropertyType; if (componentClass == null) { throw new ArgumentException(SR.GetString(SR.InvalidNullArgument, "componentClass")); } // If the classes are the same, we can potentially optimize the method fetch because // the old property descriptor may already have it. // ReflectPropertyDescriptor oldProp = oldReflectPropertyDescriptor as ReflectPropertyDescriptor; if (oldProp != null) { if (oldProp.ComponentType == componentClass) { propInfo = oldProp.propInfo; getMethod = oldProp.getMethod; setMethod = oldProp.setMethod; shouldSerializeMethod = oldProp.shouldSerializeMethod; resetMethod = oldProp.resetMethod; defaultValue = oldProp.defaultValue; ambientValue = oldProp.ambientValue; state = oldProp.state; } // Now we must figure out what to do with our default value. First, check to see // if the caller has provided an new default value attribute. If so, use it. Otherwise, // just let it be and it will be picked up on demand. // if (attributes != null) { foreach(Attribute a in attributes) { DefaultValueAttribute dva = a as DefaultValueAttribute; if (dva != null) { defaultValue = dva.Value; // Default values for enums are often stored as their underlying integer type: if (defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType()) { defaultValue = Enum.ToObject(PropertyType, defaultValue); } state[BitDefaultValueQueried] = true; } else { AmbientValueAttribute ava = a as AmbientValueAttribute; if (ava != null) { ambientValue = ava.Value; state[BitAmbientValueQueried] = true; } } } } } #if DEBUG else if (oldReflectPropertyDescriptor is DebugReflectPropertyDescriptor) { DebugReflectPropertyDescriptor oldProp1 = (DebugReflectPropertyDescriptor)oldReflectPropertyDescriptor; if (oldProp1.ComponentType == componentClass) { propInfo = oldProp1.propInfo; getMethod = oldProp1.getMethod; setMethod = oldProp1.setMethod; shouldSerializeMethod = oldProp1.shouldSerializeMethod; resetMethod = oldProp1.resetMethod; defaultValue = oldProp1.defaultValue; ambientValue = oldProp1.ambientValue; state = oldProp1.state; } // Now we must figure out what to do with our default value. First, check to see // if the caller has provided an new default value attribute. If so, use it. Otherwise, // just let it be and it will be picked up on demand. // if (attributes != null) { foreach(Attribute a in attributes) { if (a is DefaultValueAttribute) { defaultValue = ((DefaultValueAttribute)a).Value; state[BitDefaultValueQueried] = true; } else if (a is AmbientValueAttribute) { ambientValue = ((AmbientValueAttribute)a).Value; state[BitAmbientValueQueried] = true; } } } } #endif } /// <devdoc> /// Retrieves the ambient value for this property. /// </devdoc> private object AmbientValue { get { if (!state[BitAmbientValueQueried]) { state[BitAmbientValueQueried] = true; Attribute a = Attributes[typeof(AmbientValueAttribute)]; if (a != null) { ambientValue = ((AmbientValueAttribute)a).Value; } else { ambientValue = noValue; } } return ambientValue; } } /// <devdoc> /// The EventDescriptor for the "{propertyname}Changed" event on the component, or null if there isn't one for this property. /// </devdoc> private EventDescriptor ChangedEventValue { get { if (!state[BitChangedQueried]) { state[BitChangedQueried] = true; realChangedEvent = TypeDescriptor.GetEvents(ComponentType)[string.Format(CultureInfo.InvariantCulture, "{0}Changed", Name)]; } return realChangedEvent; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { realChangedEvent = value; state[BitChangedQueried] = true; } */ } /// <devdoc> /// The EventDescriptor for the INotifyPropertyChanged.PropertyChanged event on the component, or null if there isn't one for this property. /// </devdoc> private EventDescriptor IPropChangedEventValue { get { if (!state[BitIPropChangedQueried]) { state[BitIPropChangedQueried] = true; if (typeof(INotifyPropertyChanged).IsAssignableFrom(ComponentType)) { realIPropChangedEvent = TypeDescriptor.GetEvents(typeof(INotifyPropertyChanged))["PropertyChanged"]; } } return realIPropChangedEvent; } set { realIPropChangedEvent = value; state[BitIPropChangedQueried] = true; } } /// <devdoc> /// Retrieves the type of the component this PropertyDescriptor is bound to. /// </devdoc> public override Type ComponentType { get { return componentClass; } } /// <devdoc> /// Retrieves the default value for this property. /// </devdoc> private object DefaultValue { get { if (!state[BitDefaultValueQueried]) { state[BitDefaultValueQueried] = true; Attribute a = Attributes[typeof(DefaultValueAttribute)]; if (a != null) { defaultValue = ((DefaultValueAttribute)a).Value; // Default values for enums are often stored as their underlying integer type: if (defaultValue != null && PropertyType.IsEnum && PropertyType.GetEnumUnderlyingType() == defaultValue.GetType()) { defaultValue = Enum.ToObject(PropertyType, defaultValue); } } else { defaultValue = noValue; } } return defaultValue; } } /// <devdoc> /// The GetMethod for this property /// </devdoc> private MethodInfo GetMethodValue { get { if (!state[BitGetQueried]) { state[BitGetQueried] = true; if (receiverType == null) { if (propInfo == null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; propInfo = componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]); } if (propInfo != null) { getMethod = propInfo.GetGetMethod(true); } if (getMethod == null) { throw new InvalidOperationException(SR.GetString(SR.ErrorMissingPropertyAccessors, componentClass.FullName + "." + Name)); } } else { getMethod = FindMethod(componentClass, "Get" + Name, new Type[] { receiverType }, type); if (getMethod == null) { throw new ArgumentException(SR.GetString(SR.ErrorMissingPropertyAccessors, Name)); } } } return getMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitGetQueried] = true; getMethod = value; } */ } /// <devdoc> /// Determines if this property is an extender property. /// </devdoc> private bool IsExtender { get { return (receiverType != null); } } /// <devdoc> /// Indicates whether this property is read only. /// </devdoc> public override bool IsReadOnly { get { return SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly; } } /// <devdoc> /// Retrieves the type of the property. /// </devdoc> public override Type PropertyType { get { return type; } } /// <devdoc> /// Access to the reset method, if one exists for this property. /// </devdoc> private MethodInfo ResetMethodValue { get { if (!state[BitResetQueried]) { state[BitResetQueried] = true; Type[] args; if (receiverType == null) { args = argsNone; } else { args = new Type[] {receiverType}; } IntSecurity.FullReflection.Assert(); try { resetMethod = FindMethod(componentClass, "Reset" + Name, args, typeof(void), /* publicOnly= */ false); } finally { CodeAccessPermission.RevertAssert(); } } return resetMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitResetQueried] = true; resetMethod = value; } */ } /// <devdoc> /// Accessor for the set method /// </devdoc> private MethodInfo SetMethodValue { get { if (!state[BitSetQueried] && state[BitSetOnDemand]) { state[BitSetQueried] = true; BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; string name = propInfo.Name; if (setMethod == null) { for (Type t = ComponentType.BaseType; t != null && t != typeof(object); t = t.BaseType) { if (t == null) { break; } PropertyInfo p = t.GetProperty(name, bindingFlags, null, PropertyType, new Type[0], null); if (p != null) { setMethod = p.GetSetMethod(); if (setMethod != null) { break; } } } } } if (!state[BitSetQueried]) { state[BitSetQueried] = true; if (receiverType == null) { if (propInfo == null) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty; propInfo = componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]); } if (propInfo != null) { setMethod = propInfo.GetSetMethod(true); } } else { setMethod = FindMethod(componentClass, "Set" + Name, new Type[] { receiverType, type}, typeof(void)); } } return setMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitSetQueried] = true; setMethod = value; } */ } /// <devdoc> /// Accessor for the ShouldSerialize method. /// </devdoc> private MethodInfo ShouldSerializeMethodValue { get { if (!state[BitShouldSerializeQueried]) { state[BitShouldSerializeQueried] = true; Type[] args; if (receiverType == null) { args = argsNone; } else { args = new Type[] {receiverType}; } IntSecurity.FullReflection.Assert(); try { shouldSerializeMethod = FindMethod(componentClass, "ShouldSerialize" + Name, args, typeof(Boolean), /* publicOnly= */ false); } finally { CodeAccessPermission.RevertAssert(); } } return shouldSerializeMethod; } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. set { state[BitShouldSerializeQueried] = true; shouldSerializeMethod = value; } */ } /// <devdoc> /// Allows interested objects to be notified when this property changes. /// </devdoc> public override void AddValueChanged(object component, EventHandler handler) { if (component == null) throw new ArgumentNullException("component"); if (handler == null) throw new ArgumentNullException("handler"); // If there's an event called <propertyname>Changed, hook the caller's handler directly up to that on the component EventDescriptor changedEvent = ChangedEventValue; if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) { changedEvent.AddEventHandler(component, handler); } // Otherwise let the base class add the handler to its ValueChanged event for this component else { // Special case: If this will be the FIRST handler added for this component, and the component implements // INotifyPropertyChanged, the property descriptor must START listening to the generic PropertyChanged event if (GetValueChangedHandler(component) == null) { EventDescriptor iPropChangedEvent = IPropChangedEventValue; if (iPropChangedEvent != null) { iPropChangedEvent.AddEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged)); } } base.AddValueChanged(component, handler); } } internal bool ExtenderCanResetValue(IExtenderProvider provider, object component) { if (DefaultValue != noValue) { return !object.Equals(ExtenderGetValue(provider, component),defaultValue); } MethodInfo reset = ResetMethodValue; if (reset != null) { MethodInfo shouldSerialize = ShouldSerializeMethodValue; if (shouldSerialize != null) { try { provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider); return (bool)shouldSerialize.Invoke(provider, new object[] { component}); } catch {} } return true; } return false; } internal Type ExtenderGetReceiverType() { return receiverType; } internal Type ExtenderGetType(IExtenderProvider provider) { return PropertyType; } internal object ExtenderGetValue(IExtenderProvider provider, object component) { if (provider != null) { provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider); return GetMethodValue.Invoke(provider, new object[] { component}); } return null; } internal void ExtenderResetValue(IExtenderProvider provider, object component, PropertyDescriptor notifyDesc) { if (DefaultValue != noValue) { ExtenderSetValue(provider, component, DefaultValue, notifyDesc); } else if (AmbientValue != noValue) { ExtenderSetValue(provider, component, AmbientValue, notifyDesc); } else if (ResetMethodValue != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object newValue; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = ExtenderGetValue(provider, component); try { changeService.OnComponentChanging(component, notifyDesc); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider); if (ResetMethodValue != null) { ResetMethodValue.Invoke(provider, new object[] { component}); // Now notify the change service that the change was successful. // if (changeService != null) { newValue = ExtenderGetValue(provider, component); changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue); } } } } internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc) { if (provider != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = ExtenderGetValue(provider, component); try { changeService.OnComponentChanging(component, notifyDesc); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider); if (SetMethodValue != null) { SetMethodValue.Invoke(provider, new object[] { component, value}); // Now notify the change service that the change was successful. // if (changeService != null) { changeService.OnComponentChanged(component, notifyDesc, oldValue, value); } } } } internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object component) { provider = (IExtenderProvider)GetInvocationTarget(componentClass, provider); if (IsReadOnly) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] {component}); } catch {} } return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); } else if (DefaultValue == noValue) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] {component}); } catch {} } return true; } return !object.Equals(DefaultValue, ExtenderGetValue(provider, component)); } /// <devdoc> /// Indicates whether reset will change the value of the component. If there /// is a DefaultValueAttribute, then this will return true if getValue returns /// something different than the default value. If there is a reset method and /// a ShouldSerialize method, this will return what ShouldSerialize returns. /// If there is just a reset method, this always returns true. If none of these /// cases apply, this returns false. /// </devdoc> public override bool CanResetValue(object component) { if (IsExtender || IsReadOnly) { return false; } if (DefaultValue != noValue) { return !object.Equals(GetValue(component),DefaultValue); } if (ResetMethodValue != null) { if (ShouldSerializeMethodValue != null) { component = GetInvocationTarget(componentClass, component); try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch {} } return true; } if (AmbientValue != noValue) { return ShouldSerializeValue(component); } return false; } protected override void FillAttributes(IList attributes) { Debug.Assert(componentClass != null, "Must have a component class for FillAttributes"); // // The order that we fill in attributes is critical. The list of attributes will be // filtered so that matching attributes at the end of the list replace earlier matches // (last one in wins). Therefore, the four categories of attributes we add must be // added as follows: // // 1. Attributes of the property type. These are the lowest level and should be // overwritten by any newer attributes. // // 2. Attributes obtained from any SpecificTypeAttribute. These supercede attributes // for the property type. // // 3. Attributes of the property itself, from base class to most derived. This way // derived class attributes replace base class attributes. // // 4. Attributes from our base MemberDescriptor. While this seems opposite of what // we want, MemberDescriptor only has attributes if someone passed in a new // set in the constructor. Therefore, these attributes always // supercede existing values. // // We need to include attributes from the type of the property. // foreach (Attribute typeAttr in TypeDescriptor.GetAttributes(PropertyType)) { attributes.Add(typeAttr); } // NOTE : Must look at method OR property, to handle the case of Extender properties... // // Note : Because we are using BindingFlags.DeclaredOnly it is more effcient to re-aquire // : the property info, rather than use the one we have cached. The one we have cached // : may ave come from a base class, meaning we will request custom metadata for this // : class twice. BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly; Type currentReflectType = componentClass; int depth = 0; // First, calculate the depth of the object hierarchy. We do this so we can do a single // object create for an array of attributes. // while(currentReflectType != null && currentReflectType != typeof(object)) { depth++; currentReflectType = currentReflectType.BaseType; } // Now build up an array in reverse order // if (depth > 0) { currentReflectType = componentClass; Attribute[][] attributeStack = new Attribute[depth][]; while(currentReflectType != null && currentReflectType != typeof(object)) { MemberInfo memberInfo = null; // Fill in our member info so we can get at the custom attributes. // if (IsExtender) { //receiverType is used to avoid ambitiousness when there are overloads for the get method. memberInfo = currentReflectType.GetMethod("Get" + Name, bindingFlags, null, new Type[] { receiverType }, null); } else { memberInfo = currentReflectType.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]); } // Get custom attributes for the member info. // if (memberInfo != null) { attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo); } // Ready for the next loop iteration. // currentReflectType = currentReflectType.BaseType; } // Look in the attribute stack for AttributeProviders // foreach(Attribute[] attributeArray in attributeStack) { if (attributeArray != null) { foreach(Attribute attr in attributeArray) { AttributeProviderAttribute sta = attr as AttributeProviderAttribute; if (sta != null) { Type specificType = Type.GetType(sta.TypeName); if (specificType != null) { Attribute[] stAttrs = null; if (!String.IsNullOrEmpty(sta.PropertyName)) { MemberInfo[] milist = specificType.GetMember(sta.PropertyName); if (milist.Length > 0 && milist[0] != null) { stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(milist[0]); } } else { stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(specificType); } if (stAttrs != null) { foreach(Attribute stAttr in stAttrs) { attributes.Add(stAttr); } } } } } } } // Now trawl the attribute stack so that we add attributes // from base class to most derived. // foreach(Attribute[] attributeArray in attributeStack) { if (attributeArray != null) { foreach(Attribute attr in attributeArray) { attributes.Add(attr); } } } } // Include the base attributes. These override all attributes on the actual // property, so we want to add them last. // base.FillAttributes(attributes); // Finally, override any form of ReadOnlyAttribute. // if (SetMethodValue == null) { attributes.Add(ReadOnlyAttribute.Yes); } } /// <devdoc> /// Retrieves the current value of the property on component, /// invoking the getXXX method. An exception in the getXXX /// method will pass through. /// </devdoc> public override object GetValue(object component) { #if DEBUG if (PropDescUsageSwitch.TraceVerbose) { string compName = "(null)"; if (component != null) compName = component.ToString(); Debug.WriteLine("[" + Name + "]: GetValue(" + compName + ")"); } #endif if (IsExtender) { Debug.WriteLineIf(PropDescUsageSwitch.TraceVerbose, "[" + Name + "]: ---> returning: null"); return null; } Debug.Assert(component != null, "GetValue must be given a component"); if (component != null) { component = GetInvocationTarget(componentClass, component); try { return SecurityUtils.MethodInfoInvoke(GetMethodValue, component, null); } catch (Exception t) { string name = null; IComponent comp = component as IComponent; if (comp != null) { ISite site = comp.Site; if (site != null && site.Name != null) { name = site.Name; } } if (name == null) { name = component.GetType().FullName; } if (t is TargetInvocationException) { t = t.InnerException; } string message = t.Message; if (message == null) { message = t.GetType().Name; } throw new TargetInvocationException(SR.GetString(SR.ErrorPropertyAccessorException, Name, name, message), t); } } Debug.WriteLineIf(PropDescUsageSwitch.TraceVerbose, "[" + Name + "]: ---> returning: null"); return null; } /// <devdoc> /// Handles INotifyPropertyChanged.PropertyChange events from components. /// If event pertains to this property, issue a ValueChanged event. /// </devdoc> /// </internalonly> internal void OnINotifyPropertyChanged(object component, PropertyChangedEventArgs e) { if (String.IsNullOrEmpty(e.PropertyName) || String.Compare(e.PropertyName, Name, true, System.Globalization.CultureInfo.InvariantCulture) == 0) { OnValueChanged(component, e); } } /// <devdoc> /// This should be called by your property descriptor implementation /// when the property value has changed. /// </devdoc> protected override void OnValueChanged(object component, EventArgs e) { if (state[BitChangedQueried] && realChangedEvent == null) { base.OnValueChanged(component, e); } } /// <devdoc> /// Allows interested objects to be notified when this property changes. /// </devdoc> public override void RemoveValueChanged(object component, EventHandler handler) { if (component == null) throw new ArgumentNullException("component"); if (handler == null) throw new ArgumentNullException("handler"); // If there's an event called <propertyname>Changed, we hooked the caller's // handler directly up to that on the component, so remove it now. EventDescriptor changedEvent = ChangedEventValue; if (changedEvent != null && changedEvent.EventType.IsInstanceOfType(handler)) { changedEvent.RemoveEventHandler(component, handler); } // Otherwise the base class added the handler to its ValueChanged // event for this component, so let the base class remove it now. else { base.RemoveValueChanged(component, handler); // Special case: If that was the LAST handler removed for this component, and the component implements // INotifyPropertyChanged, the property descriptor must STOP listening to the generic PropertyChanged event if (GetValueChangedHandler(component) == null) { EventDescriptor iPropChangedEvent = IPropChangedEventValue; if (iPropChangedEvent != null) { iPropChangedEvent.RemoveEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged)); } } } } /// <devdoc> /// Will reset the default value for this property on the component. If /// there was a default value passed in as a DefaultValueAttribute, that /// value will be set as the value of the property on the component. If /// there was no default value passed in, a ResetXXX method will be looked /// for. If one is found, it will be invoked. If one is not found, this /// is a nop. /// </devdoc> public override void ResetValue(object component) { object invokee = GetInvocationTarget(componentClass, component); if (DefaultValue != noValue) { SetValue(component, DefaultValue); } else if (AmbientValue != noValue) { SetValue(component, AmbientValue); } else if (ResetMethodValue != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object newValue; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { // invokee might be a type from mscorlib or system, GetMethodValue might return a NonPublic method oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } if (ResetMethodValue != null) { SecurityUtils.MethodInfoInvoke(ResetMethodValue, invokee, (object[])null); // Now notify the change service that the change was successful. // if (changeService != null) { newValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null); changeService.OnComponentChanged(component, this, oldValue, newValue); } } } } /// <devdoc> /// This will set value to be the new value of this property on the /// component by invoking the setXXX method on the component. If the /// value specified is invalid, the component should throw an exception /// which will be passed up. The component designer should design the /// property so that getXXX following a setXXX should return the value /// passed in if no exception was thrown in the setXXX call. /// </devdoc> public override void SetValue(object component, object value) { #if DEBUG if (PropDescUsageSwitch.TraceVerbose) { string compName = "(null)"; string valName = "(null)"; if (component != null) compName = component.ToString(); if (value != null) valName = value.ToString(); Debug.WriteLine("[" + Name + "]: SetValue(" + compName + ", " + valName + ")"); } #endif if (component != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; object oldValue = null; object invokee = GetInvocationTarget(componentClass, component); Debug.Assert(!IsReadOnly, "SetValue attempted on read-only property [" + Name + "]"); if (!IsReadOnly) { // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } // Make sure that it is ok to send the onchange events // if (changeService != null) { oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null); try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } try { try { SecurityUtils.MethodInfoInvoke(SetMethodValue, invokee, new object[] { value }); OnValueChanged(invokee, EventArgs.Empty); } catch (Exception t) { // Give ourselves a chance to unwind properly before rethrowing the exception. // value = oldValue; // If there was a problem setting the controls property then we get: // ArgumentException (from properties set method) // ==> Becomes inner exception of TargetInvocationException // ==> caught here if (t is TargetInvocationException && t.InnerException != null) { // Propagate the original exception up throw t.InnerException; } else { throw t; } } } finally { // Now notify the change service that the change was successful. // if (changeService != null) { changeService.OnComponentChanged(component, this, oldValue, value); } } } } } /// <devdoc> /// Indicates whether the value of this property needs to be persisted. In /// other words, it indicates whether the state of the property is distinct /// from when the component is first instantiated. If there is a default /// value specified in this ReflectPropertyDescriptor, it will be compared against the /// property's current value to determine this. If there is't, the /// ShouldSerializeXXX method is looked for and invoked if found. If both /// these routes fail, true will be returned. /// /// If this returns false, a tool should not persist this property's value. /// </devdoc> public override bool ShouldSerializeValue(object component) { component = GetInvocationTarget(componentClass, component); if (IsReadOnly) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch {} } return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content); } else if (DefaultValue == noValue) { if (ShouldSerializeMethodValue != null) { try { return (bool)ShouldSerializeMethodValue.Invoke(component, null); } catch {} } return true; } return !object.Equals(DefaultValue, GetValue(component)); } /// <devdoc> /// Indicates whether value change notifications for this property may originate from outside the property /// descriptor, such as from the component itself (value=true), or whether notifications will only originate /// from direct calls made to PropertyDescriptor.SetValue (value=false). For example, the component may /// implement the INotifyPropertyChanged interface, or may have an explicit '{name}Changed' event for this property. /// </devdoc> public override bool SupportsChangeEvents { get { return IPropChangedEventValue != null || ChangedEventValue != null; } } /* The following code has been removed to fix FXCOP violations. The code is left here incase it needs to be resurrected in the future. /// <devdoc> /// A constructor for ReflectPropertyDescriptors that have no attributes. /// </devdoc> public ReflectPropertyDescriptor(Type componentClass, string name, Type type) : this(componentClass, name, type, (Attribute[])null) { } */ } }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils { using System; using System.IO; /// <summary> /// Common interface for all file systems. /// </summary> public interface IFileSystem { /// <summary> /// Gets a value indicating whether the file system is read-only or read-write. /// </summary> /// <returns>true if the file system is read-write.</returns> bool CanWrite { get; } /// <summary> /// Gets the root directory of the file system. /// </summary> DiscDirectoryInfo Root { get; } /// <summary> /// Gets a value indicating whether the file system is thread-safe. /// </summary> bool IsThreadSafe { get; } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file</param> /// <param name="destinationFile">The destination file</param> void CopyFile(string sourceFile, string destinationFile); /// <summary> /// Copies an existing file to a new file, allowing overwriting of an existing file. /// </summary> /// <param name="sourceFile">The source file</param> /// <param name="destinationFile">The destination file</param> /// <param name="overwrite">Whether to permit over-writing of an existing file.</param> void CopyFile(string sourceFile, string destinationFile, bool overwrite); /// <summary> /// Creates a directory. /// </summary> /// <param name="path">The path of the new directory</param> void CreateDirectory(string path); /// <summary> /// Deletes a directory. /// </summary> /// <param name="path">The path of the directory to delete.</param> void DeleteDirectory(string path); /// <summary> /// Deletes a directory, optionally with all descendants. /// </summary> /// <param name="path">The path of the directory to delete.</param> /// <param name="recursive">Determines if the all descendants should be deleted</param> void DeleteDirectory(string path, bool recursive); /// <summary> /// Deletes a file. /// </summary> /// <param name="path">The path of the file to delete.</param> void DeleteFile(string path); /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test</param> /// <returns>true if the directory exists</returns> bool DirectoryExists(string path); /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test</param> /// <returns>true if the file exists</returns> bool FileExists(string path); /// <summary> /// Indicates if a file or directory exists. /// </summary> /// <param name="path">The path to test</param> /// <returns>true if the file or directory exists</returns> bool Exists(string path); /// <summary> /// Gets the names of subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of directories.</returns> string[] GetDirectories(string path); /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of directories matching the search pattern.</returns> string[] GetDirectories(string path, string searchPattern); /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> string[] GetDirectories(string path, string searchPattern, SearchOption searchOption); /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files.</returns> string[] GetFiles(string path); /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files matching the search pattern.</returns> string[] GetFiles(string path, string searchPattern); /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> string[] GetFiles(string path, string searchPattern, SearchOption searchOption); /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> string[] GetFileSystemEntries(string path); /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> string[] GetFileSystemEntries(string path, string searchPattern); /// <summary> /// Moves a directory. /// </summary> /// <param name="sourceDirectoryName">The directory to move.</param> /// <param name="destinationDirectoryName">The target directory name.</param> void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName); /// <summary> /// Moves a file. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> void MoveFile(string sourceName, string destinationName); /// <summary> /// Moves a file, allowing an existing file to be overwritten. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> /// <param name="overwrite">Whether to permit a destination file to be overwritten</param> void MoveFile(string sourceName, string destinationName, bool overwrite); /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <returns>The new stream.</returns> SparseStream OpenFile(string path, FileMode mode); /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> SparseStream OpenFile(string path, FileMode mode, FileAccess access); /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect</param> /// <returns>The attributes of the file or directory</returns> FileAttributes GetAttributes(string path); /// <summary> /// Sets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to change</param> /// <param name="newValue">The new attributes of the file or directory</param> void SetAttributes(string path, FileAttributes newValue); /// <summary> /// Gets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The creation time.</returns> DateTime GetCreationTime(string path); /// <summary> /// Sets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetCreationTime(string path, DateTime newTime); /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> DateTime GetCreationTimeUtc(string path); /// <summary> /// Sets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetCreationTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last access time</returns> DateTime GetLastAccessTime(string path); /// <summary> /// Sets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastAccessTime(string path, DateTime newTime); /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last access time</returns> DateTime GetLastAccessTimeUtc(string path); /// <summary> /// Sets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastAccessTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last write time</returns> DateTime GetLastWriteTime(string path); /// <summary> /// Sets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastWriteTime(string path, DateTime newTime); /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory</param> /// <returns>The last write time</returns> DateTime GetLastWriteTimeUtc(string path); /// <summary> /// Sets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> void SetLastWriteTimeUtc(string path, DateTime newTime); /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file</param> /// <returns>The length in bytes</returns> long GetFileLength(string path); /// <summary> /// Gets an object representing a possible file. /// </summary> /// <param name="path">The file path</param> /// <returns>The representing object</returns> /// <remarks>The file does not need to exist</remarks> DiscFileInfo GetFileInfo(string path); /// <summary> /// Gets an object representing a possible directory. /// </summary> /// <param name="path">The directory path</param> /// <returns>The representing object</returns> /// <remarks>The directory does not need to exist</remarks> DiscDirectoryInfo GetDirectoryInfo(string path); /// <summary> /// Gets an object representing a possible file system object (file or directory). /// </summary> /// <param name="path">The file system path</param> /// <returns>The representing object</returns> /// <remarks>The file system object does not need to exist</remarks> DiscFileSystemInfo GetFileSystemInfo(string path); /// <summary> /// Reads the boot code of the file system into a byte array. /// </summary> /// <returns>The boot code, or <c>null</c> if not available</returns> byte[] ReadBootCode(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class CastTests { public class Helper { // Helper Method for Test15 and Test16 public static void GenericTest<T>(object o) { byte? i = 10; Object[] source = { -1, 0, o, i }; IEnumerable<int?> source1 = source.Cast<int?>(); IEnumerable<T> actual = source1.Cast<T>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast019 { [Fact] public void Cast001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.Cast<long>(); var rst2 = q.Cast<long>(); Assert.Throws<InvalidCastException>(() => { foreach (var t in rst1) ; }); } [Fact] public void Cast002() { var q = from x in new byte[] { 0, 255, 127, 128, 1, 33, 99 } select x; var rst1 = q.Cast<ushort>(); var rst2 = q.Cast<ushort>(); Assert.Throws<InvalidCastException>(() => { foreach (var t in rst1) ; }); } } public class Cast1 { // source is empty public static int Test1() { Object[] source = { }; int[] expected = { }; IEnumerable<int> actual = source.Cast<int>(); return Verification.Allequal(expected, actual); } public static int Main() { return Test1(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Cast10 { [Fact] // source of type int? to object and IEnumerable<int?> Cast to type long // DDB: 137558 public void Test10() { int? i = 10; Object[] source = { -4, 1, 2, 3, 9, i }; IEnumerable<int?> source1 = source.Cast<int?>(); IEnumerable<long> actual = source1.Cast<long>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast11 { [Fact] // source of type int? to object and IEnumerable<int?> Cast to type long? // DDB: 137558 public void Test11() { int? i = 10; Object[] source = { -4, 1, 2, 3, 9, null, i }; IEnumerable<int?> source1 = source.Cast<int?>(); IEnumerable<long?> actual = source1.Cast<long?>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast12 { // source of type int? to object cast to IEnumerable<int?> // DDB: 137558 public static int Test12() { int? i = 10; Object[] source = { -4, 1, 2, 3, 9, null, i }; int?[] expected = { -4, 1, 2, 3, 9, null, i }; IEnumerable<int?> actual = source.Cast<int?>(); return Verification.Allequal(expected, actual); } public static int Main() { return Test12(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Cast13 { [Fact] // source of type object cast to IEnumerable<int> // DDB: 137558 public void Test() { Object[] source = { -4, 1, 2, 3, 9, "45" }; IEnumerable<int> actual = source.Cast<int>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast14 { [Fact] // source of type int Cast to type double // DDB: 137558 public void Test() { int[] source = new int[] { -4, 1, 2, 9 }; IEnumerable<double> actual = source.Cast<double>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast15 { [Fact] // Cast involving Generic types // DDB: 137558 public void Test() { Helper.GenericTest<long?>(null); } } public class Cast16 { [Fact] // Cast involving Generic types // DDB: 137558 public void Test() { Helper.GenericTest<long>(9L); } } public class Cast17 { // source of type object Cast to type string // DDB: 137558 public static int Test17() { object[] source = { "Test1", "4.5", null, "Test2" }; string[] expected = { "Test1", "4.5", null, "Test2" }; IEnumerable<string> actual = source.Cast<string>(); return Verification.Allequal(expected, actual); } public static int Main() { return Test17(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Cast18 { [Fact] //testing array conversion using .Cast() // From Silverlight testing public void Test() { Assert.Throws<InvalidCastException>(() => new[] { -4 }.Cast<long>().ToList()); } } public class Cast2 { [Fact] // first element cannot be cast to type int: Test for InvalidCastException public void Test() { Object[] source = { "Test", 3, 5, 10 }; IEnumerable<int> actual = source.Cast<int>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast3 { [Fact] // last element cannot be cast to type int: Test for InvalidCastException public void Test() { Object[] source = { -5, 9, 0, 5, 9, "Test" }; IEnumerable<int> actual = source.Cast<int>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast4 { // All elements in source can be cast to int? public static int Test4() { Object[] source = { 3, null, 5, -4, 0, null, 9 }; int?[] expected = { 3, null, 5, -4, 0, null, 9 }; IEnumerable<int?> actual = source.Cast<int?>(); return Verification.Allequal(expected, actual); } public static int Main() { return Test4(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class Cast5 { [Fact] // source of type int Cast to type long // DDB: 137558 public void Test() { int[] source = new int[] { -4, 1, 2, 3, 9 }; IEnumerable<long> actual = source.Cast<long>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast6 { [Fact] // source of type int Cast to type long? // DDB: 137558 public void Test() { int[] source = new int[] { -4, 1, 2, 3, 9 }; IEnumerable<long?> actual = source.Cast<long?>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast7 { [Fact] // source of type int? Cast to type long // DDB: 137558 public static void Test() { int?[] source = new int?[] { -4, 1, 2, 3, 9 }; IEnumerable<long> actual = source.Cast<long>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast8 { // source of type int? Cast to type long with null value // DDB: 137558 public void Test() { int?[] source = new int?[] { -4, 1, 2, 3, 9 }; IEnumerable<long> actual = source.Cast<long>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } public class Cast9 { [Fact] // source of type int? Cast to type long? // DDB: 137558 public void Test() { int?[] source = new int?[] { -4, 1, 2, 3, 9, null }; IEnumerable<long?> actual = source.Cast<long?>(); Assert.Throws<InvalidCastException>(() => actual.ToList()); } } } }
using System; using Avalonia.Utilities; using Xunit; namespace Avalonia.Base.UnitTests.Utilities { public class MathUtilitiesTests { private const double AnyValue = 42.42; private readonly double _calculatedAnyValue; private readonly double _one; private readonly double _zero; public MathUtilitiesTests() { _calculatedAnyValue = 0.0; _one = 0.0; _zero = 1.0; const int N = 10; var dxAny = AnyValue / N; var dxOne = 1.0 / N; var dxZero = _zero / N; for (var i = 0; i < N; ++i) { _calculatedAnyValue += dxAny; _one += dxOne; _zero -= dxZero; } } [Fact] public void Two_Equivalent_Double_Values_Are_Close() { var actual = MathUtilities.AreClose(AnyValue, _calculatedAnyValue); Assert.True(actual); Assert.Equal(AnyValue, Math.Round(_calculatedAnyValue, 14)); } [Fact] public void Two_Equivalent_Single_Values_Are_Close() { var expectedValue = (float)AnyValue; var actualValue = (float)_calculatedAnyValue; var actual = MathUtilities.AreClose(expectedValue, actualValue); Assert.True(actual); Assert.Equal((float) Math.Round(expectedValue, 5), (float) Math.Round(actualValue, 4)); } [Fact] public void Calculated_Double_One_Is_One() { var actual = MathUtilities.IsOne(_one); Assert.True(actual); Assert.Equal(1.0, Math.Round(_one, 15)); } [Fact] public void Calculated_Single_One_Is_One() { var actualValue = (float)_one; var actual = MathUtilities.IsOne(actualValue); Assert.True(actual); Assert.Equal(1.0f, (float) Math.Round(actualValue, 7)); } [Fact] public void Calculated_Double_Zero_Is_Zero() { var actual = MathUtilities.IsZero(_zero); Assert.True(actual); Assert.Equal(0.0, Math.Round(_zero, 15)); } [Fact] public void Calculated_Single_Zero_Is_Zero() { var actualValue = (float)_zero; var actual = MathUtilities.IsZero(actualValue); Assert.True(actual); Assert.Equal(0.0f, (float) Math.Round(actualValue, 7)); } [Fact] public void Float_Clamp_Input_NaN_Return_NaN() { var clamp = MathUtilities.Clamp(double.NaN, 0.0, 1.0); Assert.True(double.IsNaN(clamp)); } [Fact] public void Float_Clamp_Input_NegativeInfinity_Return_Min() { const double min = 0.0; const double max = 1.0; var actual = MathUtilities.Clamp(double.NegativeInfinity, min, max); Assert.Equal(min, actual); } [Fact] public void Float_Clamp_Input_PositiveInfinity_Return_Max() { const double min = 0.0; const double max = 1.0; var actual = MathUtilities.Clamp(double.PositiveInfinity, min, max); Assert.Equal(max, actual); } [Fact] public void Double_Float_Zero_Less_Than_One() { var actual = MathUtilities.LessThan(0d, 1d); Assert.True(actual); } [Fact] public void Single_Float_Zero_Less_Than_One() { var actual = MathUtilities.LessThan(0f, 1f); Assert.True(actual); } [Fact] public void Double_Float_One_Not_Less_Than_Zero() { var actual = MathUtilities.LessThan(1d, 0d); Assert.False(actual); } [Fact] public void Single_Float_One_Not_Less_Than_Zero() { var actual = MathUtilities.LessThan(1f, 0f); Assert.False(actual); } [Fact] public void Double_Float_Zero_Not_Greater_Than_One() { var actual = MathUtilities.GreaterThan(0d, 1d); Assert.False(actual); } [Fact] public void Single_Float_Zero_Not_Greater_Than_One() { var actual = MathUtilities.GreaterThan(0f, 1f); Assert.False(actual); } [Fact] public void Double_Float_One_Greater_Than_Zero() { var actual = MathUtilities.GreaterThan(1d, 0d); Assert.True(actual); } [Fact] public void Single_Float_One_Greater_Than_Zero() { var actual = MathUtilities.GreaterThan(1f, 0f); Assert.True(actual); } [Fact] public void Double_Float_One_Less_Than_Or_Close_One() { var actual = MathUtilities.LessThanOrClose(1d, 1d); Assert.True(actual); } [Fact] public void Single_Float_One_Less_Than_Or_Close_One() { var actual = MathUtilities.LessThanOrClose(1f, 1f); Assert.True(actual); } [Fact] public void Double_Float_One_Greater_Than_Or_Close_One() { var actual = MathUtilities.GreaterThanOrClose(1d, 1d); Assert.True(actual); } [Fact] public void Single_Float_One_Greater_Than_Or_Close_One() { var actual = MathUtilities.GreaterThanOrClose(1f, 1f); Assert.True(actual); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.Extensions.Localization; using Orchard.ContentManagement; using Orchard.ContentManagement.Display; using Orchard.DisplayManagement.ModelBinding; using Orchard.DisplayManagement.Notify; using Orchard.Entities; using Orchard.Environment.Cache; using Orchard.Layers.Handlers; using Orchard.Layers.Models; using Orchard.Layers.Services; using Orchard.Layers.ViewModels; using Orchard.Settings; using YesSql; namespace Orchard.Layers.Controllers { public class AdminController : Controller, IUpdateModel { private readonly IContentManager _contentManager; private readonly IContentItemDisplayManager _contentItemDisplayManager; private readonly ISiteService _siteService; private readonly ILayerService _layerService; private readonly IAuthorizationService _authorizationService; private readonly ISession _session; private readonly ISignal _signal; private readonly INotifier _notifier; public AdminController( ISignal signal, IAuthorizationService authorizationService, ISession session, ILayerService layerService, IContentManager contentManager, IContentItemDisplayManager contentItemDisplayManager, ISiteService siteService, IStringLocalizer<AdminController> s, IHtmlLocalizer<AdminController> h, INotifier notifier ) { _signal = signal; _authorizationService = authorizationService; _session = session; _layerService = layerService; _contentManager = contentManager; _contentItemDisplayManager = contentItemDisplayManager; _siteService = siteService; S = s; H = h; _notifier = notifier; } public IStringLocalizer S { get; } public IHtmlLocalizer H { get; } public async Task<IActionResult> Index() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } var layers = await _layerService.GetLayersAsync(); var widgets = await _layerService.GetLayerWidgetsAsync(c => c.Latest == true); var model = new LayersIndexViewModel { Layers = layers.Layers }; var siteSettings = await _siteService.GetSiteSettingsAsync(); model.Zones = siteSettings.As<LayerSettings>()?.Zones ?? Array.Empty<string>(); model.Widgets = new Dictionary<string, List<dynamic>>(); foreach (var widget in widgets.OrderBy(x => x.Position)) { var zone = widget.Zone; List <dynamic> list; if (!model.Widgets.TryGetValue(zone, out list)) { model.Widgets.Add(zone, list = new List<dynamic>()); } list.Add(await _contentItemDisplayManager.BuildDisplayAsync(widget.ContentItem, this, "SummaryAdmin")); } return View(model); } [HttpPost] public async Task<IActionResult> Index(LayersIndexViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } return RedirectToAction("Index"); } public async Task<IActionResult> Create() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } return View(); } [HttpPost, ActionName("Create")] public async Task<IActionResult> CreatePost(LayerEditViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } var layers = await _layerService.GetLayersAsync(); ValidateViewModel(model, layers, isNew: true); if (ModelState.IsValid) { layers.Layers.Add(new Layer { Name = model.Name, Rule = model.Rule, Description = model.Description }); await _layerService.UpdateAsync(layers); return RedirectToAction("Index"); } return View(model); } public async Task<IActionResult> Edit(string name) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } var layers = await _layerService.GetLayersAsync(); var layer = layers.Layers.FirstOrDefault(x => String.Equals(x.Name, name)); if (layer == null) { return NotFound(); } var model = new LayerEditViewModel { Name = layer.Name, Rule = layer.Rule, Description = layer.Description }; return View(model); } [HttpPost, ActionName("Edit")] public async Task<IActionResult> EditPost(LayerEditViewModel model) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } var layers = await _layerService.GetLayersAsync(); ValidateViewModel(model, layers, isNew: false); if (ModelState.IsValid) { var layer = layers.Layers.FirstOrDefault(x => String.Equals(x.Name, model.Name)); if (layer == null) { return NotFound(); } layer.Name = model.Name; layer.Rule = model.Rule; layer.Description = model.Description; await _layerService.UpdateAsync(layers); return RedirectToAction("Index"); } return View(model); } [HttpPost] public async Task<IActionResult> Delete(string name) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return Unauthorized(); } var layers = await _layerService.GetLayersAsync(); var layer = layers.Layers.FirstOrDefault(x => String.Equals(x.Name, name)); if (layer == null) { return NotFound(); } var widgets = await _layerService.GetLayerWidgetsAsync(c => c.Latest == true); if (!widgets.Any(x => String.Equals(x.Layer, name, StringComparison.OrdinalIgnoreCase))) { layers.Layers.Remove(layer); _notifier.Success(H["Layer deleted successfully."]); } else { _notifier.Error(H["The layer couldn't be deleted: you must remove any associated widgets first."]); } return RedirectToAction("Index"); } [HttpPost] public async Task<IActionResult> UpdatePosition(string contentItemId, double position, string zone) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageLayers)) { return StatusCode(401); } // Load the latest version first if any var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest); if (contentItem == null) { return StatusCode(404); } var layerMetadata = contentItem.As<LayerMetadata>(); if (layerMetadata == null) { return StatusCode(403); } layerMetadata.Position = position; layerMetadata.Zone = zone; contentItem.Apply(layerMetadata); _session.Save(contentItem); // In case the moved contentItem is the draft for a published contentItem we update it's position too. // We do that because we want the position of published and draft version to be the same. if (contentItem.IsPublished() == false) { var publishedContentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Published); if (publishedContentItem != null) { layerMetadata = contentItem.As<LayerMetadata>(); if (layerMetadata == null) { return StatusCode(403); } layerMetadata.Position = position; layerMetadata.Zone = zone; publishedContentItem.Apply(layerMetadata); _session.Save(publishedContentItem); } } // Clear the cache _signal.SignalToken(LayerMetadataHandler.LayerChangeToken); if (Request.Headers != null && Request.Headers["X-Requested-With"] == "XMLHttpRequest") { return StatusCode(200); } else { return RedirectToAction("Index"); } } private void ValidateViewModel(LayerEditViewModel model, LayersDocument layers, bool isNew) { if (String.IsNullOrWhiteSpace(model.Name)) { ModelState.AddModelError(nameof(LayerEditViewModel.Name), S["The layer name is required."]); } else if (isNew && layers.Layers.Any(x => String.Equals(x.Name, model.Name, StringComparison.OrdinalIgnoreCase))) { ModelState.AddModelError(nameof(LayerEditViewModel.Name), S["The layer name already exists."]); } if (String.IsNullOrWhiteSpace(model.Rule)) { ModelState.AddModelError(nameof(LayerEditViewModel.Rule), S["The rule is required."]); } } } }
using System; using System.Xml; using System.Globalization; using SharpVectors.Dom.Css; namespace SharpVectors.Dom.Svg { public sealed class SvgUseElement : SvgTransformableElement, ISvgUseElement { #region Private Fields private ISvgAnimatedLength x; private ISvgAnimatedLength y; private ISvgAnimatedLength width; private ISvgAnimatedLength height; private ISvgElementInstance instanceRoot; private SvgTests svgTests; private SvgUriReference svgURIReference; private SvgExternalResourcesRequired svgExternalResourcesRequired; // For rendering support... private string saveTransform; private string saveWidth; private string saveHeight; #endregion #region Constructors and Destructor public SvgUseElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgURIReference = new SvgUriReference(this); svgURIReference.NodeChanged += new NodeChangeHandler(ReferencedNodeChange); svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgTests = new SvgTests(this); } #endregion #region ISvgUseElement Members public ISvgAnimatedLength X { get { if (x == null) { x = new SvgAnimatedLength(this, "x", SvgLengthDirection.Horizontal, "0"); } return x; } } public ISvgAnimatedLength Y { get { if (y == null) { y = new SvgAnimatedLength(this, "y", SvgLengthDirection.Vertical, "0"); } return y; } } public ISvgAnimatedLength Width { get { if (width == null) { width = new SvgAnimatedLength(this, "width", SvgLengthDirection.Horizontal, String.Empty); } return width; } } public ISvgAnimatedLength Height { get { if (height == null) { height = new SvgAnimatedLength(this, "height", SvgLengthDirection.Vertical, String.Empty); } return height; } } public ISvgElementInstance InstanceRoot { get { if (instanceRoot == null) { instanceRoot = new SvgElementInstance(ReferencedElement, this, null); } return instanceRoot; } } public ISvgElementInstance AnimatedInstanceRoot { get { return InstanceRoot; } } #endregion #region ISvgURIReference Members public ISvgAnimatedString Href { get { return svgURIReference.Href; } } public XmlElement ReferencedElement { get { return svgURIReference.ReferencedNode as XmlElement; } } #endregion #region ISvgExternalResourcesRequired Members public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region ISvgTests Members public ISvgStringList RequiredFeatures { get { return svgTests.RequiredFeatures; } } public ISvgStringList RequiredExtensions { get { return svgTests.RequiredExtensions; } } public ISvgStringList SystemLanguage { get { return svgTests.SystemLanguage; } } public bool HasExtension(string extension) { return svgTests.HasExtension(extension); } #endregion #region Update Handling public override void HandleAttributeChange(XmlAttribute attribute) { if (attribute.NamespaceURI.Length == 0) { switch (attribute.LocalName) { case "x": x = null; return; case "y": y = null; return; case "width": width = null; return; case "height": height = null; return; } } else if (attribute.NamespaceURI == SvgDocument.XLinkNamespace) { switch (attribute.LocalName) { case "href": instanceRoot = null; break; } } base.HandleAttributeChange(attribute); } public void ReferencedNodeChange(Object src, XmlNodeChangedEventArgs args) { //TODO - This is getting called too often! //instanceRoot = null; } #endregion #region Rendering public void CopyToReferencedElement(XmlElement refEl) { // X and Y become a translate portion of any transform, width and height may get passed on if (X.AnimVal.Value != 0 || Y.AnimVal.Value != 0) { saveTransform = this.GetAttribute("transform"); //this.SetAttribute("transform", saveTransform + " translate(" // + X.AnimVal.Value + "," + Y.AnimVal.Value + ")"); string transform = String.Format(CultureInfo.InvariantCulture, "{0} translate({1},{2})", saveTransform, X.AnimVal.Value, Y.AnimVal.Value); this.SetAttribute("transform", transform); } // if (refEl is SvgSymbolElement) if (String.Equals(refEl.Name, "symbol", StringComparison.OrdinalIgnoreCase)) { refEl.SetAttribute("width", (HasAttribute("width")) ? GetAttribute("width") : "100%"); refEl.SetAttribute("height", (HasAttribute("height")) ? GetAttribute("height") : "100%"); } // if (refEl is SvgSymbolElement) if (String.Equals(refEl.Name, "symbol", StringComparison.OrdinalIgnoreCase)) { saveWidth = refEl.GetAttribute("width"); saveHeight = refEl.GetAttribute("height"); if (HasAttribute("width")) refEl.SetAttribute("width", GetAttribute("width")); if (HasAttribute("height")) refEl.SetAttribute("height", GetAttribute("height")); } } public void RestoreReferencedElement(XmlElement refEl) { if (saveTransform != null) this.SetAttribute("transform", saveTransform); if (saveWidth != null) { refEl.SetAttribute("width", saveWidth); refEl.SetAttribute("height", saveHeight); } } #endregion } }
#region Header //////////////////////////////////////////////////////////////////////////////////// // // File Description: TemplateBase // --------------------------------------------------------------------------------- // Date Created : May 14, 2014 // Author : Rob van Oostenrijk // //////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using TcmTemplating.Extensions; using TcmTemplating.Helpers; using Tridion.ContentManager; using Tridion.ContentManager.CommunicationManagement; using Tridion.ContentManager.ContentManagement; using Tridion.ContentManager.Publishing; using Tridion.ContentManager.Publishing.Rendering; using Tridion.ContentManager.Security; using Tridion.ContentManager.Templating; using Tridion.ContentManager.Templating.Assembly; namespace TcmTemplating { /// <summary> /// <see cref="TemplateBase" /> is the abstract base class for all Tridion template transformations. /// </summary> public abstract class TemplateBase : ITemplate { #region Private Members private long mTicksStart; private Engine mEngine; private Package mPackage; private TemplatingLogger mLogger; private static XmlNamespaceManager mNSM; // Cache local Tridion objects if requested private Publication mPublication = null; private StructureGroup mRootStructureGroup = null; private Page mPage = null; private PageTemplate mPageTemplate = null; private Component mComponent = null; private ComponentTemplate mComponentTemplate = null; private PublishTransaction mPublishTransaction = null; private User mPublishingUser = null; private PublicationTarget mPublicationTarget = null; private Lazy<Dictionary<String, String>> mPublishedBinaries = new Lazy<Dictionary<String, String>>(() => new Dictionary<String, String>()); #region Constants private const String THUMBNAIL_SUFFIX = "thumb"; private const String THUMBNAIL_VARIANT = "thumbnail"; // Output Format constants public const String OF_ASPJSCRIPT = "ASP JScript"; public const String OF_ASPVBSCRIPT = "ASP VBScript"; public const String OF_ASCX = "ASCX WebControl"; public const String OF_JSP = "JSP Scripting"; // Target Language constants public const String TL_ASPJSCRIPT = "ASP/JavaScript"; public const String TL_ASPVBSCRIPT = "ASP/VBScript"; public const String TL_ASPDOTNET = "ASP.NET"; public const String TL_JSP = "JSP"; #endregion #endregion #region Properties /// <summary> /// An XmlNameSpaceManager already initialized with several XML namespaces such as: tcm, xlink and xhtml /// </summary> public static XmlNamespaceManager NSManager { get { if (mNSM == null) { mNSM = new XmlNamespaceManager(new NameTable()); mNSM.AddNamespace(Tridion.Constants.TcmPrefix, Tridion.Constants.TcmNamespace); mNSM.AddNamespace(Tridion.Constants.XlinkPrefix, Tridion.Constants.XlinkNamespace); mNSM.AddNamespace(Tridion.Constants.XhtmlPrefix, Tridion.Constants.XhtmlNamespace); } return mNSM; } } /// <summary> /// Gets default <see cref="T:System.Xml.XmlWriterSettings" /> to use for writing Xml templates. /// </summary> /// <value> /// Template <see cref="T:System.Xml.XmlWriterSettings" /> /// </value> public virtual XmlWriterSettings TemplateXmlWriterSettings { get { return new XmlWriterSettings() { CheckCharacters = true, ConformanceLevel = ConformanceLevel.Fragment, Encoding = Encoding.UTF8, Indent = false, NamespaceHandling = NamespaceHandling.OmitDuplicates, NewLineHandling = NewLineHandling.None }; } } /// <summary> /// Get the tridion <see cref="T:Tridion.ContentManager.Templating.TemplatingLogger" /> /// </summary> /// <value> /// <see cref="T:Tridion.ContentManager.Templating.TemplatingLogger" /> /// </value> public TemplatingLogger Logger { get { if (mLogger == null) mLogger = TemplatingLogger.GetLogger(this.GetType()); return mLogger; } } /// <summary> /// Gets a value indicating whether this instance is in preview mode. /// </summary> /// <value> /// <c>true</c> if this instance is in preview mode; otherwise, <c>false</c>. /// </value> public bool IsPreview { get { return mEngine.RenderMode == RenderMode.PreviewDynamic || mEngine.RenderMode == RenderMode.PreviewStatic; } } /// <summary> /// Returns true if the current render mode is Publish /// </summary> public bool IsPublishing { get { return (mEngine.RenderMode == RenderMode.Publish); } } /// <summary> /// Checks whether there is an item in the package of type tridion/page /// </summary> /// <returns>True if there is a page item in the package</returns> public bool IsPage { get { return (Page != null); } } /// <summary> /// Checks whether there is an item in the package of type tridion/component /// </summary> /// <returns>True if there is a component item in the package</returns> public bool IsComponent { get { return (Component != null); } } /// <summary> /// Gets a value indicating whether this publishing instance is publishing to live/production. /// </summary> /// <value> /// <c>true</c> if publishing to production; otherwise, <c>false</c>. /// </value> public bool IsProduction { get { // For publication targets which are named 'Live' or 'Production' we indicate the Production environment return (PublicationTarget != null && (PublicationTarget.Title.Contains("live", StringComparison.OrdinalIgnoreCase) || PublicationTarget.Title.Contains("production", StringComparison.OrdinalIgnoreCase))); } } /// <summary> /// Obtains the <see cref="T:TcmTemplating.Helpers.FormatTextResolver" /> used to expand Format Text Fields (RTF). /// </summary> /// <value> /// <see cref="T:TcmTemplating.Helpers.FormatTextResolver" /> /// </value> protected virtual FormatTextResolver FormatTextResolver { get { return new FormatTextResolver(this); } } #endregion /// <summary> /// Performs the actual transformation logic of this <see cref="TemplateBase"/>. /// </summary> /// <remarks>Transform is the main entry-point for template functionality.</remarks> protected abstract void Transform(); /// <summary> /// Allow templates to provide a PreTransform hook /// </summary> protected virtual void PreTransform() { } /// <summary> /// Allow templates to provide a PostTransform hook /// </summary> protected virtual void PostTransform() { } /// <summary> /// Execute the transformation for the specified template /// </summary> /// <param name="Engine"><see cref="T:Tridion.ContentManager.Templating.Engine"/>.</param> /// <param name="Package"><see cref="T:Tridion.ContentManager.Templating.Package"/></param> public void Transform(Engine Engine, Package Package) { try { mTicksStart = Environment.TickCount; mEngine = Engine; mPackage = Package; // Actual template transformation PreTransform(); Transform(); PostTransform(); } catch (Exception ex) { String exceptionStack = LoggerExtensions.TraceException(ex); Logger.Error("TemplateBase.Transform Exception\n" + exceptionStack); StringBuilder sb = new StringBuilder(); sb.AppendLine(ex.Message); sb.AppendFormat("Publisher: {0}\n", Environment.MachineName); sb.Append(exceptionStack); // Re-throw to ensure Tridion knows what happened throw new Exception(sb.ToString(), ex); } // Ensure we always clean up, no matter what happens during the template transformation finally { Logger.Info("{0}: Render time {1:0.00000} seconds @ {2:dd/MM/yyyy hh:mm:ss tt} ", this.GetType().FullName, ProcessedTime / 1000.0, DateTime.Now); // Do not cache objects across template transformations ItemFieldsFactory.ClearCache(); // Clear published binaries list if it was used if (mPublishedBinaries.IsValueCreated) mPublishedBinaries.Value.Clear(); mPackage = null; mEngine = null; mLogger = null; mComponent = null; mComponentTemplate = null; mPage = null; mPageTemplate = null; mRootStructureGroup = null; mPublication = null; mPublishTransaction = null; mPublishingUser = null; mPublicationTarget = null; } } /// <summary> /// Initializes the specified <see cref="T:Tridion.ContentManager.Templating.Engine"/> and <see cref="T:Tridion.ContentManager.Templating.Package"/>. /// </summary> /// <param name="engine">The <see cref="T:Tridion.ContentManager.Templating.Engine"/>.</param> /// <param name="package">The <see cref="T:Tridion.ContentManager.Templating.Package"/>.</param> internal void Initialize(Engine engine, Package package) { mEngine = engine; mPackage = package; } #region Base Functionality /// <summary> /// Gets the amount of time in milliseconds this current template has been processing. /// </summary> /// <value> /// Processing time in milliseconds /// </value> public long ProcessedTime { get { return (Environment.TickCount - mTicksStart); } } /// <summary> /// Returns the current <see cref="T:Tridion.ContentManager.Templating.Engine"/> /// </summary> /// <value> /// <see cref="T:Tridion.ContentManager.Templating.Engine"/> /// </value> public Engine Engine { get { return mEngine; } } /// <summary> /// Returns the current <see cref="T:Tridion.ContentManager.Templating.Package"/> /// </summary> /// <value> /// <see cref="T:Tridion.ContentManager.Templating.Package"/> /// </value> public Package Package { get { return mPackage; } } /// <summary> /// Returns the component object that is defined in the package for this template. /// </summary> /// <remarks> /// This method should only be called when there is an actual Component item in the package. /// It does not currently handle the situation where no such item is available. /// </remarks> /// <returns>the component object that is defined in the package for this template.</returns> public Component Component { get { if (mComponent == null) { Item component = mPackage.GetByType(ContentType.Component); if (component != null) mComponent = GetComponent(component.GetAsSource().GetValue("ID")); } return mComponent; } } /// <summary> /// Returns the Template from the resolved item if it's a Component Template /// </summary> /// <returns>A Component Template or null</returns> public ComponentTemplate ComponentTemplate { get { if (mComponentTemplate == null) { Template template = mEngine.PublishingContext.ResolvedItem.Template; if (template is ComponentTemplate) { mComponentTemplate = (ComponentTemplate)template; } } return mComponentTemplate; } } /// <summary> /// Returns the Template from the resolved item if it's a Page Template /// </summary> /// <returns>A Page Template or null</returns> public PageTemplate PageTemplate { get { if (mPageTemplate == null) { Template template = mEngine.PublishingContext.ResolvedItem.Template; if (template is PageTemplate) { mPageTemplate = (PageTemplate)template; } } return mPageTemplate; } } /// <summary> /// Returns the page object that is defined in the package for this template. /// </summary> /// <remarks> /// This method should only be called when there is an actual Page item in the package. /// It does not currently handle the situation where no such item is available. /// </remarks> /// <returns>the page object that is defined in the package for this template.</returns> public Page Page { get { if (mPage == null) { Item pageItem = mPackage.GetByType(ContentType.Page); if (pageItem != null) mPage = mEngine.GetObject(pageItem.GetAsSource().GetValue("ID")) as Page; if (Engine.PublishingContext.RenderContext.ContextItem is Page) mPage = Engine.PublishingContext.RenderContext.ContextItem as Page; } return mPage; } } /// <summary> /// Returns the page object that is defined in the package for this template. /// </summary> /// <remarks> /// This method should only be called when there is an actual Page item in the package. /// It does not currently handle the situation where no such item is available. /// </remarks> /// <returns>the page object that is defined in the package for this template.</returns> public StructureGroup RootStructureGroup { get { if (mRootStructureGroup == null) { Publication publication = Publication; if (publication != null) { mRootStructureGroup = publication.RootStructureGroup; } } return mRootStructureGroup; } } /// <summary> /// Returns the publication object that can be determined from the package for this template. /// </summary> /// <remarks> /// This method currently depends on a Page item being available in the package, meaning that /// it will only work when invoked from a Page Template. /// /// Updated by Kah Tan ([email protected]) /// </remarks> /// <returns>the Publication object that can be determined from the package for this template.</returns> public Publication Publication { get { if (mPublication == null) { RepositoryLocalObject pubItem = null; Repository repository = null; pubItem = Page; if (pubItem == null) pubItem = Component; if (pubItem != null) { repository = pubItem.ContextRepository; mPublication = repository as Publication; } } return mPublication; } } /// <summary> /// Returns the currently executing PublishTransaction. /// Note that Tridion does not easily expose this data, so use this with care. /// </summary> /// <value> /// Active <see cref="T:Tridion.ContentManager.Publishing.PublishTransaction" /> or null /// </value> public PublishTransaction PublishTransaction { get { if (mPublishTransaction == null) { String binaryPath = mEngine.PublishingContext.PublishInstruction.RenderInstruction.BinaryStoragePath; Regex tcmRegex = new Regex(@"tcm_\d+-\d+-66560"); Match match = tcmRegex.Match(binaryPath); if (match.Success) { String transactionId = match.Value.Replace('_', ':'); TcmUri transactionUri = new TcmUri(transactionId); mPublishTransaction = new PublishTransaction(transactionUri, mEngine.GetSession()); } } return mPublishTransaction; } } /// <summary> /// Gets the current publishing user (user that initiated the publishing action). /// </summary> /// <value> /// Active <see cref="T:Tridion.ContentManager.Security.User"/> or Null /// </value> public User PublishingUser { get { if (mPublishingUser == null) { PublishTransaction transaction = PublishTransaction; if (transaction != null) { mPublishingUser = transaction.Creator; } } return mPublishingUser; } } /// <summary> /// Gets the current <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget" /> /// </summary> /// <value> /// <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget" /> /// </value> public PublicationTarget PublicationTarget { get { if (mPublicationTarget == null) { mPublicationTarget = Engine.PublishingContext.PublicationTarget; } return mPublicationTarget; } } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.ContentManagement.IdentifiableObject"/> object specified by the ID /// </summary> /// <param name="ID">IdentifiableObject ID</param> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.IdentifiableObject"/></returns> public T GetObject<T>(String ID) where T : IdentifiableObject { return mEngine.GetObject(ID) as T; } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.ContentManagement.IdentifiableObject"/> object specified by the ID /// </summary> /// <param name="ID">IdentifiableObject ID</param> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.IdentifiableObject"/></returns> public T GetObject<T>(TcmUri ID) where T : IdentifiableObject { return mEngine.GetObject(ID) as T; } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.ContentManagement.Component"/> component specified by the ID /// </summary> /// <param name="ID"><see cref="T:Tridion.ContentManager.TcmUri"/></param> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></returns> public Component GetComponent(TcmUri ID) { return GetObject<Component>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.ContentManagement.Component"/> component specified by the ID /// </summary> /// <param name="ID">Component ID</param> /// <returns><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></returns> public Component GetComponent(String ID) { return GetObject<Component>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.CommunicationManagement.StructureGroup"/> sepecified by the ID /// </summary> /// <param name="ID">Structure Group ID.</param> /// <returns><see cref="T:Tridion.ContentManager.CommunicationManagement.StructureGroup"/></returns> public StructureGroup GetStructureGroup(String ID) { return GetObject<StructureGroup>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.CommunicationManagement.StructureGroup"/> specified by the ID /// </summary> /// <param name="ID"><see cref="T:Tridion.ContentManager.TcmUri"/></param> /// <returns><see cref="T:Tridion.ContentManager.CommunicationManagement.StructureGroup"/></returns> public StructureGroup GetStructureGroup(TcmUri ID) { return GetObject<StructureGroup>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.CommunicationManagement.Page"/> specified by the ID /// </summary> /// <param name="ID">Page ID.</param> /// <returns><see cref="T:Tridion.ContentManager.CommunicationManagement.Page"/></returns> public Page GetPage(String ID) { return GetObject<Page>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.CommunicationManagement.Page"/> specified by the ID /// </summary> /// <param name="ID"><see cref="T:Tridion.ContentManager.TcmUri"/></param> /// <returns><see cref="T:Tridion.ContentManager.CommunicationManagement.Page"/></returns> public Page GetPage(TcmUri ID) { return GetObject<Page>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentTemplate"/> specified by the ID /// </summary> /// <param name="ID">Component Template ID.</param> /// <returns><see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentTemplate"/></returns> public ComponentTemplate GetComponentTemplate(String ID) { return GetObject<ComponentTemplate>(ID); } /// <summary> /// Gets the <see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentTemplate"/> specified by the ID /// </summary> /// <param name="ID"><see cref="T:Tridion.ContentManager.TcmUri"/></param> /// <returns><see cref="T:Tridion.ContentManager.CommunicationManagement.ComponentTemplate"/></returns> public ComponentTemplate GetComponentTemplate(TcmUri ID) { return GetObject<ComponentTemplate>(ID); } /// <summary> /// Checks whether a Target Type URI is associated with the current publication target being published to /// </summary> public bool IsTTInPublicationContext(String ttURI) { if (IsPublishing && mEngine.PublishingContext.PublicationTarget != null) // not null only during publishing { foreach (TargetType tt in mEngine.PublishingContext.PublicationTarget.TargetTypes) { if (tt.Id == ttURI) return true; } } return false; } /// <summary> /// Checks whether at least one of a list of Target Type URIs is associated with the current publication target being published to /// </summary> public bool IsTTInPublicationContext(IEnumerable<String> ttURIs) { if (mEngine.PublishingContext.PublicationTarget != null)// not null only during publishing { foreach (String uri in ttURIs) { foreach (TargetType tt in mEngine.PublishingContext.PublicationTarget.TargetTypes) { if (tt.Id == uri) return true; } } } return false; } #endregion #region Utilities /// <summary> /// Obtains the Tridion standard name for a published binary /// </summary> /// <param name="Binary">The binary.</param> /// <returns></returns> public String BinaryFileName(Component Binary) { if (Binary.BinaryContent != null) { return String.Format("{0}_tcm{1}-{2}{3}", Uri.EscapeDataString(Path.GetFileNameWithoutExtension(Binary.BinaryContent.Filename)), Binary.Id.PublicationId, Binary.Id.ItemId, Path.GetExtension(Binary.BinaryContent.Filename)); } return String.Empty; } /// <summary> /// Publishes the multi-media component binary /// </summary> /// <param name="Component"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param> /// <returns>Published binary path</returns> public string PublishBinary(Component Component) { return PublishBinary(Component, String.Empty); } /// <summary> /// Publishes the multi-media component binary /// </summary> /// <param name="Component"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param> /// <param name="variantId">Binary Variant Id.</param> /// <returns>Published binary path</returns> public string PublishBinary(Component Component, String variantId) { if (Component != null && Component.ComponentType == ComponentType.Multimedia && Component.BinaryContent != null) { Binary pubBinary = null; if (!String.IsNullOrEmpty(variantId)) { String key = Component.Id.ToString() + "-" + variantId; String value; if (mPublishedBinaries.Value.TryGetValue(key, out value)) { // Return the previous published binary path return value; } else { pubBinary = mEngine.PublishingContext.RenderedItem.AddBinary(Component, variantId); mPublishedBinaries.Value.Add(key, pubBinary.Url); return pubBinary.Url; } } else { String key = Component.Id.ToString(); String value; if (mPublishedBinaries.Value.TryGetValue(key, out value)) { // Return the previous published binary path return value; } else { pubBinary = mEngine.PublishingContext.RenderedItem.AddBinary(Component); mPublishedBinaries.Value.Add(key, pubBinary.Url); return pubBinary.Url; } } } else { Logger.Warning("PublishBinary: {0} is not a multimedia component.", Component != null ? Component.Id : "(null)"); } return String.Empty; } /// <summary> /// Publishes the given binary component, while associating it with the relatedComponent. /// </summary> /// <param name="Component"><see cref="T:Tridion.ContentManager.ContentManagement.Component" /></param> /// <param name="relatedComponent"><see cref="T:Tridion.ContentManager.ContentManagement.Component" /></param> /// <returns> /// Binary publish path /// </returns> public String PublishBinary(Component Component, Component relatedComponent) { return PublishBinary(Component, relatedComponent, String.Empty); } /// <summary> /// Publishes the given binary component, while associating it with the relatedComponent. /// </summary> /// <param name="Component"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param> /// <param name="relatedComponent"><see cref="T:Tridion.ContentManager.ContentManagement.Component"/></param> /// <param name="variantId">variant id.</param> /// <returns>Binary publish path</returns> public String PublishBinary(Component Component, Component relatedComponent, String variantId) { if (Component != null && Component.ComponentType == ComponentType.Multimedia && Component.BinaryContent != null && relatedComponent != null) { using (MemoryStream binaryStream = new MemoryStream()) { Component.BinaryContent.WriteToStream(binaryStream); binaryStream.Seek(0, SeekOrigin.Begin); String fileName = BinaryFileName(Component); mEngine.PublishingContext.RenderedItem.AddBinary(binaryStream, fileName, variantId, relatedComponent, Component.BinaryContent.MultimediaType.MimeType); return VirtualPathUtility.AppendTrailingSlash(Publication.MultimediaUrl) + fileName; } } return String.Empty; } /// <summary> /// Publishes a <see cref="T:Tridion.ContentManager.IdentifiableObject"/> to a given <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget"/> and /// with <see cref="T:Tridion.ContentManager.Publishing.PublishPriority"/> /// </summary> /// <param name="PublishUser"><see cref="T:Tridion.ContentManager.Security.User"/></param> /// <param name="Item"><see cref="T:Tridion.ContentManager.IdentifiableObject"/></param> /// <param name="Target"><see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget"/></param> /// <param name="Priority"><see cref="T:Tridion.ContentManager.Publishing.PublishPriority"/></param> public void PublishItem(User PublishUser, IdentifiableObject Item, PublicationTarget Target, PublishPriority Priority) { PublishItem(PublishingUser, Item, Engine.PublishingContext.PublicationTarget, PublishTransaction.Priority, DateTime.Now); } /// <summary> /// Publishes a <see cref="T:Tridion.ContentManager.IdentifiableObject"/> to a given <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget"/> and /// with <see cref="T:Tridion.ContentManager.Publishing.PublishPriority"/> /// </summary> /// <param name="PublishUser"><see cref="T:Tridion.ContentManager.Security.User"/></param> /// <param name="Item"><see cref="T:Tridion.ContentManager.IdentifiableObject"/></param> /// <param name="Target"><see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget"/></param> /// <param name="Priority"><see cref="T:Tridion.ContentManager.Publishing.PublishPriority"/></param> /// <param name="startDate"><see cref="T:System.DateTime"/></param> public void PublishItem(User PublishUser, IdentifiableObject Item, PublicationTarget Target, PublishPriority Priority, DateTime startDate) { if (Engine.RenderMode == RenderMode.Publish) { if (startDate == null) startDate = DateTime.Now; using (Session session = new Session(PublishUser.Title)) { PublishInstruction publishInstruction = new PublishInstruction(session) { StartAt = startDate, DeployAt = startDate }; RenderInstruction renderInstruction = new RenderInstruction(session); renderInstruction.RenderMode = RenderMode.Publish; publishInstruction.RenderInstruction = renderInstruction; PublishEngine.Publish(new IdentifiableObject[] { session.GetObject(Item.Id) }, publishInstruction, new PublicationTarget[] { Target }, Priority); } } } /// <summary> /// Publishes a <see cref="T:Tridion.ContentManager.IdentifiableObject" /> to the current <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget" /> and /// with <see cref="T:Tridion.ContentManager.Publishing.PublishPriority" /> /// </summary> /// <param name="PublishUser"><see cref="T:Tridion.ContentManager.Security.User" /></param> /// <param name="Item"><see cref="T:Tridion.ContentManager.IdentifiableObject" /></param> /// <param name="Priority"><see cref="T:Tridion.ContentManager.Publishing.PublishPriority" /></param> public void PublishItem(User PublishUser, IdentifiableObject Item, PublishPriority Priority) { PublishItem(PublishUser, Item, Engine.PublishingContext.PublicationTarget, Priority); } /// <summary> /// Publishes a <see cref="T:Tridion.ContentManager.IdentifiableObject" /> to the current <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget" /> and /// with <see cref="T:Tridion.ContentManager.Publishing.PublishPriority" /> using the current <see cref="P:PublishingUser"/> /// </summary> /// <param name="Item"><see cref="T:Tridion.ContentManager.IdentifiableObject" /></param> /// <param name="Priority"><see cref="T:Tridion.ContentManager.Publishing.PublishPriority" /></param> public void PublishItem(IdentifiableObject Item, PublishPriority Priority) { PublishItem(PublishingUser, Item, Priority); } /// <summary> /// Publishes a <see cref="T:Tridion.ContentManager.IdentifiableObject" /> to the current <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget" /> and /// with the publish transactions <see cref="T:Tridion.ContentManager.Publishing.PublishPriority" /> using the current <see cref="P:PublishingUser"/> /// </summary> /// <param name="Item"><see cref="T:Tridion.ContentManager.IdentifiableObject" /></param> /// <param name="startDate"><see cref="T:System.DateTime"/></param> public void PublishItem(IdentifiableObject Item, DateTime startDate) { PublishItem(PublishingUser, Item, Engine.PublishingContext.PublicationTarget, PublishTransaction.Priority, startDate); } /// <summary> /// Publishes a <see cref="T:Tridion.ContentManager.IdentifiableObject" /> to the current <see cref="T:Tridion.ContentManager.CommunicationManagement.PublicationTarget" /> and /// with the publish transactions <see cref="T:Tridion.ContentManager.Publishing.PublishPriority" /> using the current <see cref="P:PublishingUser"/> /// </summary> /// <param name="Item"><see cref="T:Tridion.ContentManager.IdentifiableObject" /></param> public void PublishItem(IdentifiableObject Item) { PublishItem(PublishingUser, Item, Engine.PublishingContext.PublicationTarget, PublishTransaction.Priority); } /// <summary> /// Generates a scaled image (thumbnail) from the given binary image. /// </summary> /// <param name="Binary">Binary Multimedia Component</param> /// <param name="ThumbnailWidth">Result image Width</param> /// <param name="ThumbnailHeight">Result image Height</param> /// <returns></returns> public String GenerateThumbnail(Component Binary, int ThumbnailWidth, int ThumbnailHeight) { if (Binary != null && Binary.BinaryContent != null) { try { // Output the existing image to a memory stream using (MemoryStream stream = new MemoryStream()) { Binary.BinaryContent.WriteToStream(stream); using (Image image = Image.FromStream(stream)) { double aspectRatio = (double)image.Width / (double)image.Height; double boxRatio = (double)ThumbnailWidth / (double)ThumbnailHeight; double scaleFactor = 0; if (boxRatio > aspectRatio) // Use height, since that is the most restrictive dimension of box. scaleFactor = (double)ThumbnailHeight / (double)image.Height; else scaleFactor = (double)ThumbnailWidth / (double)image.Width; double newWidth = (double)image.Width * scaleFactor; double newHeight = (double)image.Height * scaleFactor; using (Bitmap bitmap = new Bitmap((int)newWidth, (int)newHeight)) { using (Graphics graphic = Graphics.FromImage(bitmap)) { graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; graphic.CompositingMode = CompositingMode.SourceOver; graphic.DrawImage(image, 0, 0, bitmap.Width, bitmap.Height); } using (MemoryStream streamOut = new MemoryStream()) { String extension = String.Empty; String mimeType = String.Empty; // Determine if the input image has transparency if ((image.Flags & (int)ImageFlags.HasAlpha) == (int)ImageFlags.HasAlpha) { // Save as transparent PNG (Portable Network Graphics) bitmap.Save(streamOut, ImageFormat.Png); extension = "png"; mimeType = "image/png"; } else { // Save as optimized non-transparent JPEG (Joint Photo Experts Group) ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => String.Equals(e.MimeType, "image/jpeg", StringComparison.OrdinalIgnoreCase)); if (imageCodecInfo != null) { System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(encoder, 90L); bitmap.Save(streamOut, imageCodecInfo, parameters); extension = "jpg"; mimeType = "image/jpeg"; } } if (!String.IsNullOrEmpty(extension) && !String.IsNullOrEmpty(mimeType)) { String fileName = String.Format("{0}-{1}_tcm{2}_{3}.{4}", Path.GetFileNameWithoutExtension(Binary.BinaryContent.Filename), THUMBNAIL_SUFFIX, Binary.Id.PublicationId, Binary.Id.ItemId, extension); Binary binary = Engine.PublishingContext.RenderedItem.AddBinary(streamOut, fileName, THUMBNAIL_VARIANT, Binary, mimeType); return binary.Url; } } } } } } catch (Exception ex) { Logger.Error("GenerateThumbnail", ex); } } return String.Empty; } /// <summary> /// Publishes an <see cref="T:Tridion.ContentManager.IdentifiableObject" /> intelligently if and only if, <see cref="T:Tridion.ContentManager.IdentifiableObject" /> is not in /// "Waiting For Publish" state or "Scheduled For Publish" state within the scheduleDateFilter <see cref="T:System.DateTime" /> /// </summary> /// <param name="identifiableObject">The <see cref="T:Tridion.ContentManager.IdentifiableObject" />.</param> /// <param name="startDateFilter">The start <see cref="T:System.DateTime"/> filter.</param> /// <param name="scheduleDateFilter">The schedule <see cref="T:System.DateTime"/> filter.</param> /// <param name="publishStartDate">The publish start <see cref="T:System.DateTime"/>.</param> public void PublishIntelligently(IdentifiableObject identifiableObject, DateTime startDateFilter, DateTime scheduleDateFilter, DateTime publishStartDate) { PublishTransactionsFilter filter = new PublishTransactionsFilter(Engine.GetSession()) { StartDate = startDateFilter, PublicationTarget = PublicationTarget, ForRepository = GetObject<Repository>(Publication.Id) }; PublishTransaction publishTransaction = PublishEngine.GetPublishTransactions(filter) .FirstOrDefault(t => t.Items.Count > 0 && t.Items.First().Id == identifiableObject.Id && (t.State == PublishTransactionState.WaitingForPublish || (t.State == PublishTransactionState.ScheduledForPublish && scheduleDateFilter >= t.Instruction.StartAt))); if (publishTransaction == null) PublishItem(identifiableObject, publishStartDate); } #endregion } }
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 SocialApi.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; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.DurableInstancing { using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Runtime; using System.Transactions; using System.Runtime.Diagnostics; sealed class SqlCommandAsyncResult : TransactedAsyncResult { static readonly TimeSpan MaximumOpenTimeout = TimeSpan.FromMinutes(2); static readonly RetryErrorCode[] retryErrorCodes = { new RetryErrorCode(-2, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SqlError: Timeout new RetryErrorCode(20, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - a connection failed early in the login process. to SQL Server. new RetryErrorCode(53, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), //A network-related or instance-specific error occurred while establishing a connection to SQL Server. new RetryErrorCode(64, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), //A transport-level error has occurred when receiving results from the server (TCP Provider, error: 0 - The specified network name is no longer available). new RetryErrorCode(121, RetryErrorOptions.RetryBeginOrEnd), // A transport-level error has occurred new RetryErrorCode(233, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Severed shared memory/named pipe connection drawn from the pool new RetryErrorCode(1205, RetryErrorOptions.RetryBeginOrEnd), // Deadlock new RetryErrorCode(1222, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Lock Request Timeout new RetryErrorCode(3910, RetryErrorOptions.RetryOnBegin | RetryErrorOptions.RetryWhenTransaction), // Transaction context in use by another session. new RetryErrorCode(4060, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Database not online new RetryErrorCode(8645, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // A timeout occurred while waiting for memory resources new RetryErrorCode(8641, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Could not perform the operation because the requested memory grant was not available new RetryErrorCode(10053, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // A transport-level error has occurred when receiving results from the server new RetryErrorCode(10054, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Severed tcp connection drawn from the pool new RetryErrorCode(10060, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // The server was not found or was not accessible. new RetryErrorCode(10061, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Server not started new RetryErrorCode(10928, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - The limit for the database resource has been reached. new RetryErrorCode(10929, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - The server is currently too busy to support requests up to the maximum limit. new RetryErrorCode(40143, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server encountered error processing the request. new RetryErrorCode(40197, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server encountered error processing the request. new RetryErrorCode(40501, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server is currently busy. new RetryErrorCode(40549, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - transaction blocking system calls new RetryErrorCode(40553, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - excessive memory usage new RetryErrorCode(40613, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction) // SQL Azure error - database on server is not available. }; static AsyncCompletion onExecuteReaderCallback = new AsyncCompletion(OnExecuteReader); static AsyncCompletion onRetryCommandCallback = new AsyncCompletion(OnRetryCommand); string connectionString; DependentTransaction dependentTransaction; int maximumRetries; int retryCount; EventTraceActivity eventTraceActivity; SqlCommand sqlCommand; SqlDataReader sqlDataReader; TimeoutHelper timeoutHelper; public SqlCommandAsyncResult(SqlCommand sqlCommand, string connectionString, EventTraceActivity eventTraceActivity, DependentTransaction dependentTransaction, TimeSpan timeout, int retryCount, int maximumRetries, AsyncCallback callback, object state) : base(callback, state) { long openTimeout = Math.Min(timeout.Ticks, SqlCommandAsyncResult.MaximumOpenTimeout.Ticks); this.sqlCommand = sqlCommand; this.connectionString = connectionString; this.eventTraceActivity = eventTraceActivity; this.dependentTransaction = dependentTransaction; this.timeoutHelper = new TimeoutHelper(TimeSpan.FromTicks(openTimeout)); this.retryCount = retryCount; this.maximumRetries = maximumRetries; } [Flags] enum RetryErrorOptions { RetryOnBegin = 1, RetryOnEnd = 2, RetryWhenTransaction = 4, RetryBeginOrEnd = RetryOnBegin | RetryOnEnd } public static SqlDataReader End(IAsyncResult result) { SqlCommandAsyncResult SqlCommandAsyncResult = AsyncResult.End<SqlCommandAsyncResult>(result); return SqlCommandAsyncResult.sqlDataReader; } public void StartCommand() { StartCommandInternal(true); } static bool OnExecuteReader(IAsyncResult result) { SqlCommandAsyncResult thisPtr = (SqlCommandAsyncResult)(result.AsyncState); return thisPtr.CompleteExecuteReader(result); } static bool OnRetryCommand(IAsyncResult childPtr) { SqlCommandAsyncResult parentPtr = (SqlCommandAsyncResult)(childPtr.AsyncState); parentPtr.sqlDataReader = SqlCommandAsyncResult.End(childPtr); return true; } static bool ShouldRetryForSqlError(int error, RetryErrorOptions retryErrorOptions) { if (Transaction.Current != null) { retryErrorOptions |= RetryErrorOptions.RetryWhenTransaction; } return SqlCommandAsyncResult.retryErrorCodes.Any(x => x.ErrorCode == error && (x.RetryErrorOptions & retryErrorOptions) == retryErrorOptions); } static void StartCommandCallback(object state) { SqlCommandAsyncResult thisPtr = (SqlCommandAsyncResult) state; try { // this can throw on the [....] path - we need to signal the callback thisPtr.StartCommandInternal(false); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (thisPtr.sqlCommand.Connection != null) { thisPtr.sqlCommand.Connection.Close(); } thisPtr.Complete(false, e); } } bool CheckRetryCount() { return (++this.retryCount < maximumRetries); } bool CheckRetryCountAndTimer() { return (this.CheckRetryCount() && !this.HasOperationTimedOut()); } bool CompleteExecuteReader(IAsyncResult result) { bool completeSelf = true; try { this.sqlDataReader = this.sqlCommand.EndExecuteReader(result); } catch (SqlException exception) { if (TD.SqlExceptionCaughtIsEnabled()) { TD.SqlExceptionCaught(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture), exception.Message); } if (this.sqlDataReader != null) { this.sqlDataReader.Close(); } if (this.sqlCommand.Connection != null) { this.sqlCommand.Connection.Close(); } // If we completed [....] then any retry is done by the original caller. if (!result.CompletedSynchronously) { if (this.CheckRetryCountAndTimer() && ShouldRetryForSqlError(exception.Number, RetryErrorOptions.RetryOnEnd)) { if (this.EnqueueRetry()) { if (TD.RetryingSqlCommandDueToSqlErrorIsEnabled()) { TD.RetryingSqlCommandDueToSqlError(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture)); } completeSelf = false; } } } if (completeSelf) { if (this.retryCount == maximumRetries && TD.MaximumRetriesExceededForSqlCommandIsEnabled()) { TD.MaximumRetriesExceededForSqlCommand(this.eventTraceActivity); } throw; } } return completeSelf; } bool EnqueueRetry() { bool result = false; int delay = this.GetRetryDelay(); if (this.timeoutHelper.RemainingTime().TotalMilliseconds > delay) { this.sqlCommand.Dispose(); IOThreadTimer iott = new IOThreadTimer(StartCommandCallback, new SqlCommandAsyncResult(CloneSqlCommand(this.sqlCommand), this.connectionString, this.eventTraceActivity, this.dependentTransaction, this.timeoutHelper.RemainingTime(), this.retryCount, this.maximumRetries, this.PrepareAsyncCompletion(onRetryCommandCallback), this), false); iott.Set(delay); if (TD.QueuingSqlRetryIsEnabled()) { TD.QueuingSqlRetry(this.eventTraceActivity, delay.ToString(CultureInfo.InvariantCulture)); } result = true; } return result; } static SqlCommand CloneSqlCommand(SqlCommand command) { //We do not want to use SqlCommand.Clone here because we do not want to replicate the parameters SqlCommand newCommand = new SqlCommand() { CommandType = command.CommandType, CommandText = command.CommandText, }; SqlParameter[] tempParameterList = new SqlParameter[command.Parameters.Count]; for (int i = 0; i < command.Parameters.Count; i++) { tempParameterList[i] = command.Parameters[i]; } command.Parameters.Clear(); newCommand.Parameters.AddRange(tempParameterList); return newCommand; } int GetRetryDelay() { return 1000; } bool HasOperationTimedOut() { return (this.timeoutHelper.RemainingTime() <= TimeSpan.Zero); } void StartCommandInternal(bool synchronous) { if (!this.HasOperationTimedOut()) { try { IAsyncResult result; using (this.PrepareTransactionalCall(this.dependentTransaction)) { AsyncCallback wrappedCallback = this.PrepareAsyncCompletion(onExecuteReaderCallback); this.sqlCommand.Connection = StoreUtilities.CreateConnection(this.connectionString); if (!this.HasOperationTimedOut()) { result = this.sqlCommand.BeginExecuteReader(wrappedCallback, this, CommandBehavior.CloseConnection); } else { this.sqlCommand.Connection.Close(); this.Complete(synchronous, new TimeoutException(SR.TimeoutOnSqlOperation(this.timeoutHelper.OriginalTimeout.ToString()))); return; } } if (this.CheckSyncContinue(result)) { if (this.CompleteExecuteReader(result)) { this.Complete(synchronous); } } return; } catch (SqlException exception) { if (TD.SqlExceptionCaughtIsEnabled()) { TD.SqlExceptionCaught(this.eventTraceActivity, exception.Number.ToString(null, CultureInfo.InvariantCulture), exception.Message); } if (this.sqlCommand.Connection != null) { this.sqlCommand.Connection.Close(); } if (!this.CheckRetryCount() || !ShouldRetryForSqlError(exception.Number, RetryErrorOptions.RetryOnBegin)) { throw; } if (TD.RetryingSqlCommandDueToSqlErrorIsEnabled()) { TD.RetryingSqlCommandDueToSqlError(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture)); } } catch (InvalidOperationException) { if (!this.CheckRetryCount()) { throw; } } if (this.EnqueueRetry()) { return; } } if (this.HasOperationTimedOut()) { if (TD.TimeoutOpeningSqlConnectionIsEnabled()) { TD.TimeoutOpeningSqlConnection(this.eventTraceActivity, this.timeoutHelper.OriginalTimeout.ToString()); } } else { if (TD.MaximumRetriesExceededForSqlCommandIsEnabled()) { TD.MaximumRetriesExceededForSqlCommand(this.eventTraceActivity); } } this.Complete(synchronous, new TimeoutException(SR.TimeoutOnSqlOperation(this.timeoutHelper.OriginalTimeout.ToString()))); } class RetryErrorCode { public RetryErrorCode(int code, RetryErrorOptions retryErrorOptions) { this.ErrorCode = code; this.RetryErrorOptions = retryErrorOptions; } public int ErrorCode { get; private set; } public RetryErrorOptions RetryErrorOptions { get; private set; } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System.Runtime; class QueryTreeBuilder { Diverger diverger; Opcode lastOpcode; internal QueryTreeBuilder() { } internal Opcode LastOpcode { get { return this.lastOpcode; } } internal Opcode Build(Opcode tree, OpcodeBlock newBlock) { if (null == tree) { this.lastOpcode = newBlock.Last; return newBlock.First; } this.diverger = new Diverger(tree, newBlock.First); if (!this.diverger.Find()) { // The opcodes in newBlock already have equivalents or identical opcodes // in the query tree that can do the job Fx.Assert(this.diverger.TreePath.Count > 0, ""); this.lastOpcode = this.diverger.TreePath[this.diverger.TreePath.Count - 1]; return tree; } Fx.Assert(this.diverger.TreePath.Count == this.diverger.InsertPath.Count, ""); // We can reuse opcodes upto this.diverger.TreePath[this.diverger.TreePath.Count - 1] // The remainder of the code in newBlock must be executed as is... if (null == this.diverger.TreeOpcode) { // We reached a leaf in the query tree // Simply add the remainder of the inserted code to the end of the tree path.. this.diverger.TreePath[this.diverger.TreePath.Count - 1].Attach(this.diverger.InsertOpcode); } else { // Merge in the remaider of the new code block into the query tree // The first diverging opcodes follow the last entry in each path this.diverger.TreeOpcode.Add(this.diverger.InsertOpcode); } this.lastOpcode = newBlock.Last; if (this.diverger.InsertOpcode.IsMultipleResult()) { // The complete new block was merged in, except for the the actual result opcode, which never // automatically merges. This means that the new block found all of its opcodes in common with // the tree if (OpcodeID.Branch == this.diverger.TreeOpcode.ID) { OpcodeList branches = (((BranchOpcode) this.diverger.TreeOpcode).Branches); for (int i = 0, count = branches.Count; i < count; ++i) { if (branches[i].IsMultipleResult()) { this.lastOpcode = branches[i]; break; } } } else if (this.diverger.TreeOpcode.IsMultipleResult()) { this.lastOpcode = this.diverger.TreeOpcode; } } // Since we'll be diverging, any jumps that preceeded and leapt past the divergence point // will have to be branched this.FixupJumps(); return tree; } void FixupJumps() { QueryBuffer<Opcode> treePath = this.diverger.TreePath; QueryBuffer<Opcode> insertPath = this.diverger.InsertPath; for (int i = 0; i < insertPath.Count; ++i) { if (insertPath[i].TestFlag(OpcodeFlags.Jump)) { Fx.Assert(treePath[i].ID == insertPath[i].ID, ""); JumpOpcode insertJump = (JumpOpcode) insertPath[i]; // Opcodes in 'insertPath' have equivalent opcodes in the query tree: i.e. the query tree contains an // an equivalent execution path (upto the point of divergence naturally) that will produce in an identical // result. The remainder of the query tree (anything that lies beyond the point of divergence) represents // a distinct execution path and is grafted onto the tree as a new branch. In fact, we simply break off // the remainder from the query being inserted and graft it onto the query tree. // If there are jumps on the insert path that jump to opcodes NOT in the insert path, then the jumps // will reach opcodes in the new branch we will add(see above). However, because the actual jump opcodes // are shared (used as is from the query tree), the actual jump must also be branched. One jump will // continue to jump to the original opcode and the second new one will jump to an opcode in the grafted branch. if (-1 == insertPath.IndexOf(insertJump.Jump, i + 1)) { Fx.Assert(insertJump.Jump.ID == OpcodeID.BlockEnd, ""); BlockEndOpcode jumpTo = (BlockEndOpcode) insertJump.Jump; // no longer jumping from insertJump to jumpTo insertJump.RemoveJump(jumpTo); // Instead, jumping from treePath[i] to jumpTo JumpOpcode treeJump = (JumpOpcode) treePath[i]; treeJump.AddJump(jumpTo); } } } } // Can handle queries being merged into trees but not trees merged into trees. // In other words, no branch opcodes in the query being inserted internal struct Diverger { Opcode treeOpcode; QueryBuffer<Opcode> treePath; QueryBuffer<Opcode> insertPath; Opcode insertOpcode; internal Diverger(Opcode tree, Opcode insert) { this.treePath = new QueryBuffer<Opcode>(16); this.insertPath = new QueryBuffer<Opcode>(16); this.treeOpcode = tree; this.insertOpcode = insert; } internal Opcode InsertOpcode { get { return this.insertOpcode; } } internal QueryBuffer<Opcode> InsertPath { get { return this.insertPath; } } internal Opcode TreeOpcode { get { return this.treeOpcode; } } internal QueryBuffer<Opcode> TreePath { get { return this.treePath; } } // Stops at the last common node on each internal bool Find() { Opcode treeNext = null; while (true) { if (null == this.treeOpcode && null == this.insertOpcode) { return false; // no diverge. both ran out at the same time } if (null == this.insertOpcode) { return false; // Ran out before tree did. No divergence. } if (null == this.treeOpcode) { return true; // tree ran out before insert. Divergence } if (this.treeOpcode.TestFlag(OpcodeFlags.Branch)) { treeNext = this.treeOpcode.Locate(this.insertOpcode); if (null == treeNext) { return true; // divergence } this.treeOpcode = treeNext; treeNext = treeNext.Next; } else { if (!this.treeOpcode.Equals(this.insertOpcode)) { return true; // divergence, obviously } treeNext = this.treeOpcode.Next; } // No divergence. Add to paths this.treePath.Add(this.treeOpcode); this.insertPath.Add(this.insertOpcode); this.insertOpcode = this.insertOpcode.Next; this.treeOpcode = treeNext; } } } } }
#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; using System.Collections.Generic; using System.Reflection; using System.Collections; using System.Linq; using System.Globalization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Text.RegularExpressions; namespace Newtonsoft.Json.Utilities { internal static class ReflectionUtils { public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat) { switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return GetSimpleTypeName(t); case FormatterAssemblyStyle.Full: return t.AssemblyQualifiedName; default: throw new ArgumentOutOfRangeException(); } } private static string GetSimpleTypeName(Type type) { #if !SILVERLIGHT string fullyQualifiedTypeName = type.FullName + ", " + type.Assembly.GetName().Name; // for type names with no nested type names then return if (!type.IsGenericType || type.IsGenericTypeDefinition) return fullyQualifiedTypeName; #else // Assembly.GetName() is marked SecurityCritical string fullyQualifiedTypeName = type.AssemblyQualifiedName; #endif StringBuilder builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool IsInstantiatableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsAbstract || t.IsInterface || t.IsArray || t.IsGenericTypeDefinition || t == typeof(void)) return false; if (!HasDefaultConstructor(t)) return false; return true; } public static bool HasDefaultConstructor(Type t) { return HasDefaultConstructor(t, false); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags accessModifier = BindingFlags.Public; if (nonPublic) accessModifier = accessModifier | BindingFlags.NonPublic; return t.GetConstructor(accessModifier | BindingFlags.Instance, null, new Type[0], null); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } //public static bool IsValueTypeUnitializedValue(ValueType value) //{ // if (value == null) // return true; // return value.Equals(CreateUnitializedValue(value.GetType())); //} public static bool IsUnitializedValue(object value) { if (value == null) { return true; } else { object unitializedValue = CreateUnitializedValue(value.GetType()); return value.Equals(unitializedValue); } } public static object CreateUnitializedValue(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); if (type.IsGenericTypeDefinition) throw new ArgumentException("Type {0} is a generic type definition and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); if (type.IsClass || type.IsInterface || type == typeof(void)) return null; else if (type.IsValueType) return Activator.CreateInstance(type); else throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); } public static bool IsPropertyIndexed(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return !CollectionUtils.IsNullOrEmpty<ParameterInfo>(property.GetIndexParameters()); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface) { if (type.IsGenericType) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (Type i in type.GetInterfaces()) { if (i.IsGenericType) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) { Type current = type; while (current != null) { if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) { match = current; return true; } current = current.BaseType; } foreach (Type i in type.GetInterfaces()) { if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) { match = type; return true; } } match = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName) { Type match; return type.AssignableToTypeName(fullTypeName, out match); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass || !genericClassDefinition.IsGenericTypeDefinition) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType, genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } else if (typeof(IEnumerable).IsAssignableFrom(type)) { return null; } else { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } else if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } else { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } } public static Type GetDictionaryValueType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return valueType; } public static Type GetDictionaryKeyType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return keyType; } /// <summary> /// Tests whether the list's items are their unitialized value. /// </summary> /// <param name="list">The list.</param> /// <returns>Whether the list's items are their unitialized value</returns> public static bool ItemsUnitializedValue<T>(IList<T> list) { ValidationUtils.ArgumentNotNull(list, "list"); Type elementType = GetCollectionItemType(list.GetType()); if (elementType.IsValueType) { object unitializedValue = CreateUnitializedValue(elementType); for (int i = 0; i < list.Count; i++) { if (!list[i].Equals(unitializedValue)) return false; } } else if (elementType.IsClass) { for (int i = 0; i < list.Count; i++) { object value = list[i]; if (value != null) return false; } } else { throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType)); } return true; } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { return ((PropertyInfo)member).GetValue(target, null); } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsInitOnly) return false; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties<T>(BindingFlags bindingAttr) { return GetFieldsAndProperties(typeof(T), bindingAttr); } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List<MemberInfo> targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/ // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count); var groupedMembers = targetMembers.GroupBy(m => m.Name).Select(g => new { Count = g.Count(), Members = g.Cast<MemberInfo>() }); foreach (var groupedMember in groupedMembers) { if (groupedMember.Count == 1) { distinctMembers.Add(groupedMember.Members.First()); } else { var members = groupedMember.Members.Where(m => !IsOverridenGenericMember(m, bindingAttr) || m.Name == "Item"); distinctMembers.AddRange(members); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Member must be a field or property."); Type declaringType = memberInfo.DeclaringType; if (!declaringType.IsGenericType) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return CollectionUtils.GetSingleItem(attributes, true); } public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (attributeProvider is Assembly) return (T[])Attribute.GetCustomAttributes((Assembly)attributeProvider, typeof(T), inherit); if (attributeProvider is MemberInfo) return (T[])Attribute.GetCustomAttributes((MemberInfo)attributeProvider, typeof(T), inherit); if (attributeProvider is Module) return (T[])Attribute.GetCustomAttributes((Module)attributeProvider, typeof(T), inherit); if (attributeProvider is ParameterInfo) return (T[])Attribute.GetCustomAttributes((ParameterInfo)attributeProvider, typeof(T), inherit); return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } public static string GetNameAndAssessmblyName(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return t.FullName + ", " + t.Assembly.GetName().Name; } public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes"); ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition)); return genericTypeDefinition.MakeGenericType(innerTypes); } public static object CreateGeneric(Type genericTypeDefinition, Type innerType, params object[] args) { return CreateGeneric(genericTypeDefinition, new [] { innerType }, args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, params object[] args) { return CreateGeneric(genericTypeDefinition, innerTypes, (t, a) => CreateInstance(t, a.ToArray()), args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, Func<Type, IList<object>, object> instanceCreator, params object[] args) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes"); ValidationUtils.ArgumentNotNull(instanceCreator, "createInstance"); Type specificType = MakeGenericType(genericTypeDefinition, innerTypes.ToArray()); return instanceCreator(specificType, args); } public static bool IsCompatibleValue(object value, Type type) { if (value == null) return IsNullable(type); if (type.IsAssignableFrom(value.GetType())) return true; return false; } public static object CreateInstance(Type type, params object[] args) { ValidationUtils.ArgumentNotNull(type, "type"); #if !PocketPC return Activator.CreateInstance(type, args); #else // CF doesn't have a Activator.CreateInstance overload that takes args // lame if (type.IsValueType && CollectionUtils.IsNullOrEmpty<object>(args)) return Activator.CreateInstance(type); ConstructorInfo[] constructors = type.GetConstructors(); ConstructorInfo match = constructors.Where(c => { ParameterInfo[] parameters = c.GetParameters(); if (parameters.Length != args.Length) return false; for (int i = 0; i < parameters.Length; i++) { ParameterInfo parameter = parameters[i]; object value = args[i]; if (!IsCompatibleValue(value, parameter.ParameterType)) return false; } return true; }).FirstOrDefault(); if (match == null) throw new Exception("Could not create '{0}' with given parameters.".FormatWith(CultureInfo.InvariantCulture, type)); return match.Invoke(args); #endif } public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); return fieldInfos.Cast<FieldInfo>(); } private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> propertyInfos = new List<MemberInfo>(targetType.GetProperties(bindingAttr)); GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); return propertyInfos.Cast<PropertyInfo>(); } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<MemberInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(nonPublicBindingAttr)) { PropertyInfo nonPublicProperty = propertyInfo; // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == nonPublicProperty.Name); if (index == -1) { initialProperties.Add(nonPublicProperty); } else { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = nonPublicProperty; } } } } } } }
// 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.IdentityModel.Claims; using System.Security.Principal; using System.ServiceModel; namespace System.IdentityModel.Policy { internal interface IIdentityInfo { IIdentity Identity { get; } } internal class UnconditionalPolicy : IAuthorizationPolicy, IDisposable { private SecurityUniqueId _id; private ClaimSet _issuance; private ReadOnlyCollection<ClaimSet> _issuances; private IIdentity _primaryIdentity; private bool _disposed = false; public UnconditionalPolicy(ClaimSet issuance) : this(issuance, SecurityUtils.MaxUtcDateTime) { } public UnconditionalPolicy(ClaimSet issuance, DateTime expirationTime) { if (issuance == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(issuance)); } Initialize(ClaimSet.System, issuance, null, expirationTime); } public UnconditionalPolicy(ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime) { if (issuances == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(issuances)); } Initialize(ClaimSet.System, null, issuances, expirationTime); } internal UnconditionalPolicy(IIdentity primaryIdentity, ClaimSet issuance) : this(issuance) { _primaryIdentity = primaryIdentity; } internal UnconditionalPolicy(IIdentity primaryIdentity, ClaimSet issuance, DateTime expirationTime) : this(issuance, expirationTime) { _primaryIdentity = primaryIdentity; } internal UnconditionalPolicy(IIdentity primaryIdentity, ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime) : this(issuances, expirationTime) { _primaryIdentity = primaryIdentity; } private UnconditionalPolicy(UnconditionalPolicy from) { IsDisposable = from.IsDisposable; _primaryIdentity = from.IsDisposable ? SecurityUtils.CloneIdentityIfNecessary(from._primaryIdentity) : from._primaryIdentity; if (from._issuance != null) { _issuance = from.IsDisposable ? SecurityUtils.CloneClaimSetIfNecessary(from._issuance) : from._issuance; } else { _issuances = from.IsDisposable ? SecurityUtils.CloneClaimSetsIfNecessary(from._issuances) : from._issuances; } Issuer = from.Issuer; ExpirationTime = from.ExpirationTime; } private void Initialize(ClaimSet issuer, ClaimSet issuance, ReadOnlyCollection<ClaimSet> issuances, DateTime expirationTime) { Issuer = issuer; _issuance = issuance; _issuances = issuances; ExpirationTime = expirationTime; if (issuance != null) { IsDisposable = issuance is WindowsClaimSet; } else { for (int i = 0; i < issuances.Count; ++i) { if (issuances[i] is WindowsClaimSet) { IsDisposable = true; break; } } } } public string Id { get { if (_id == null) { _id = SecurityUniqueId.Create(); } return _id.Value; } } public ClaimSet Issuer { get; private set; } internal IIdentity PrimaryIdentity { get { ThrowIfDisposed(); if (_primaryIdentity == null) { IIdentity identity = null; if (_issuance != null) { if (_issuance is IIdentityInfo) { identity = ((IIdentityInfo)_issuance).Identity; } } else { for (int i = 0; i < _issuances.Count; ++i) { ClaimSet issuance = _issuances[i]; if (issuance is IIdentityInfo) { identity = ((IIdentityInfo)issuance).Identity; // Preferably Non-Anonymous if (identity != null && identity != SecurityUtils.AnonymousIdentity) { break; } } } } _primaryIdentity = identity ?? SecurityUtils.AnonymousIdentity; } return _primaryIdentity; } } internal ReadOnlyCollection<ClaimSet> Issuances { get { ThrowIfDisposed(); if (_issuances == null) { List<ClaimSet> issuances = new List<ClaimSet>(1); issuances.Add(_issuance); _issuances = new ReadOnlyCollection<ClaimSet>(issuances); } return _issuances; } } public DateTime ExpirationTime { get; private set; } internal bool IsDisposable { get; private set; } = false; internal UnconditionalPolicy Clone() { ThrowIfDisposed(); return (IsDisposable) ? new UnconditionalPolicy(this) : this; } public virtual void Dispose() { if (IsDisposable && !_disposed) { _disposed = true; SecurityUtils.DisposeIfNecessary(_primaryIdentity as IDisposable); SecurityUtils.DisposeClaimSetIfNecessary(_issuance); SecurityUtils.DisposeClaimSetsIfNecessary(_issuances); } } private void ThrowIfDisposed() { if (_disposed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(GetType().FullName)); } } public virtual bool Evaluate(EvaluationContext evaluationContext, ref object state) { ThrowIfDisposed(); if (_issuance != null) { evaluationContext.AddClaimSet(this, _issuance); } else { for (int i = 0; i < _issuances.Count; ++i) { if (_issuances[i] != null) { evaluationContext.AddClaimSet(this, _issuances[i]); } } } // Preferably Non-Anonymous if (PrimaryIdentity != null && PrimaryIdentity != SecurityUtils.AnonymousIdentity) { IList<IIdentity> identities; object obj; if (!evaluationContext.Properties.TryGetValue(SecurityUtils.Identities, out obj)) { identities = new List<IIdentity>(1); evaluationContext.Properties.Add(SecurityUtils.Identities, identities); } else { // null if other overrides the property with something else identities = obj as IList<IIdentity>; } if (identities != null) { identities.Add(PrimaryIdentity); } } evaluationContext.RecordExpirationTime(ExpirationTime); return true; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.SchemaTokenCreator.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using System.IO; namespace Novell.Directory.Ldap.Utilclass { public class SchemaTokenCreator { private string basestring; private readonly bool cppcomments = false; // C++ style comments enabled private readonly bool ccomments = false; // C style comments enabled private readonly bool iseolsig = false; private bool cidtolower; private bool pushedback; private int peekchar; private sbyte[] ctype; private int linenumber = 1; private int ichar = 1; private char[] buf; private readonly StreamReader reader; private readonly StringReader sreader; private readonly Stream input; public string StringValue; public double NumberValue; public int lastttype; private void Initialise() { ctype = new sbyte[256]; buf = new char[20]; peekchar = int.MaxValue; WordCharacters('a', 'z'); WordCharacters('A', 'Z'); WordCharacters(128 + 32, 255); WhitespaceCharacters(0, ' '); CommentCharacter('/'); QuoteCharacter('"'); QuoteCharacter('\''); parseNumbers(); } public SchemaTokenCreator(Stream instream) { Initialise(); if (instream == null) { throw new NullReferenceException(); } input = instream; } public SchemaTokenCreator(StreamReader r) { Initialise(); if (r == null) { throw new NullReferenceException(); } reader = r; } public SchemaTokenCreator(StringReader r) { Initialise(); if (r == null) { throw new NullReferenceException(); } sreader = r; } public void pushBack() { pushedback = true; } public int CurrentLine { get { return linenumber; } } public string ToStringValue() { string strval; switch (lastttype) { case (int) TokenTypes.EOF: strval = "EOF"; break; case (int) TokenTypes.EOL: strval = "EOL"; break; case (int) TokenTypes.WORD: strval = StringValue; break; case (int) TokenTypes.STRING: strval = StringValue; break; case (int) TokenTypes.NUMBER: case (int) TokenTypes.REAL: strval = "n=" + NumberValue; break; default: { if (lastttype < 256 && (ctype[lastttype] & (sbyte) CharacterTypes.STRINGQUOTE) != 0) { strval = StringValue; break; } var s = new char[3]; s[0] = s[2] = '\''; s[1] = (char) lastttype; strval = new string(s); break; } } return strval; } public void WordCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] |= (sbyte) CharacterTypes.ALPHABETIC; } public void WhitespaceCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] = (sbyte) CharacterTypes.WHITESPACE; } public void OrdinaryCharacters(int min, int max) { if (min < 0) min = 0; if (max >= ctype.Length) max = ctype.Length - 1; while (min <= max) ctype[min++] = 0; } public void OrdinaryCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = 0; } public void CommentCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = (sbyte) CharacterTypes.COMMENTCHAR; } public void InitTable() { for (var i = ctype.Length; --i >= 0;) ctype[i] = 0; } public void QuoteCharacter(int ch) { if (ch >= 0 && ch < ctype.Length) ctype[ch] = (sbyte) CharacterTypes.STRINGQUOTE; } public void parseNumbers() { for (int i = '0'; i <= '9'; i++) ctype[i] |= (sbyte) CharacterTypes.NUMERIC; ctype['.'] |= (sbyte) CharacterTypes.NUMERIC; ctype['-'] |= (sbyte) CharacterTypes.NUMERIC; } private int read() { if (sreader != null) { return sreader.Read(); } if (reader != null) { return reader.Read(); } if (input != null) return input.ReadByte(); throw new Exception(); } public int nextToken() { if (pushedback) { pushedback = false; return lastttype; } StringValue = null; var curc = peekchar; if (curc < 0) curc = int.MaxValue; if (curc == int.MaxValue - 1) { curc = read(); if (curc < 0) return lastttype = (int) TokenTypes.EOF; if (curc == '\n') curc = int.MaxValue; } if (curc == int.MaxValue) { curc = read(); if (curc < 0) return lastttype = (int) TokenTypes.EOF; } lastttype = curc; peekchar = int.MaxValue; int ctype = curc < 256 ? this.ctype[curc] : (sbyte) CharacterTypes.ALPHABETIC; while ((ctype & (sbyte) CharacterTypes.WHITESPACE) != 0) { if (curc == '\r') { linenumber++; if (iseolsig) { peekchar = int.MaxValue - 1; return lastttype = (int) TokenTypes.EOL; } curc = read(); if (curc == '\n') curc = read(); } else { if (curc == '\n') { linenumber++; if (iseolsig) { return lastttype = (int) TokenTypes.EOL; } } curc = read(); } if (curc < 0) return lastttype = (int) TokenTypes.EOF; ctype = curc < 256 ? this.ctype[curc] : (sbyte) CharacterTypes.ALPHABETIC; } if ((ctype & (sbyte) CharacterTypes.NUMERIC) != 0) { var checkb = false; if (curc == '-') { curc = read(); if (curc != '.' && (curc < '0' || curc > '9')) { peekchar = curc; return lastttype = '-'; } checkb = true; } double dvar = 0; var tempvar = 0; var checkdec = 0; while (true) { if (curc == '.' && checkdec == 0) checkdec = 1; else if ('0' <= curc && curc <= '9') { dvar = dvar * 10 + (curc - '0'); tempvar += checkdec; } else break; curc = read(); } peekchar = curc; if (tempvar != 0) { double divby = 10; tempvar--; while (tempvar > 0) { divby *= 10; tempvar--; } dvar = dvar / divby; } NumberValue = checkb ? -dvar : dvar; return lastttype = (int) TokenTypes.NUMBER; } if ((ctype & (sbyte) CharacterTypes.ALPHABETIC) != 0) { var i = 0; do { if (i >= buf.Length) { var nb = new char[buf.Length * 2]; Array.Copy(buf, 0, nb, 0, buf.Length); buf = nb; } buf[i++] = (char) curc; curc = read(); ctype = curc < 0 ? (sbyte) CharacterTypes.WHITESPACE : curc < 256 ? this.ctype[curc] : (sbyte) CharacterTypes.ALPHABETIC; } while ((ctype & ((sbyte) CharacterTypes.ALPHABETIC | (sbyte) CharacterTypes.NUMERIC)) != 0); peekchar = curc; StringValue = new string(buf, 0, i); if (cidtolower) StringValue = StringValue.ToLower(); return lastttype = (int) TokenTypes.WORD; } if ((ctype & (sbyte) CharacterTypes.STRINGQUOTE) != 0) { lastttype = curc; var i = 0; var rc = read(); while (rc >= 0 && rc != lastttype && rc != '\n' && rc != '\r') { if (rc == '\\') { curc = read(); var first = curc; if (curc >= '0' && curc <= '7') { curc = curc - '0'; var loopchar = read(); if ('0' <= loopchar && loopchar <= '7') { curc = (curc << 3) + (loopchar - '0'); loopchar = read(); if ('0' <= loopchar && loopchar <= '7' && first <= '3') { curc = (curc << 3) + (loopchar - '0'); rc = read(); } else rc = loopchar; } else rc = loopchar; } else { switch (curc) { case 'f': curc = 0xC; break; case 'a': curc = 0x7; break; case 'b': curc = '\b'; break; case 'v': curc = 0xB; break; case 'n': curc = '\n'; break; case 'r': curc = '\r'; break; case 't': curc = '\t'; break; default: break; } rc = read(); } } else { curc = rc; rc = read(); } if (i >= buf.Length) { var nb = new char[buf.Length * 2]; Array.Copy(buf, 0, nb, 0, buf.Length); buf = nb; } buf[i++] = (char) curc; } peekchar = rc == lastttype ? int.MaxValue : rc; StringValue = new string(buf, 0, i); return lastttype; } if (curc == '/' && (cppcomments || ccomments)) { curc = read(); if (curc == '*' && ccomments) { var prevc = 0; while ((curc = read()) != '/' || prevc != '*') { if (curc == '\r') { linenumber++; curc = read(); if (curc == '\n') { curc = read(); } } else { if (curc == '\n') { linenumber++; curc = read(); } } if (curc < 0) return lastttype = (int) TokenTypes.EOF; prevc = curc; } return nextToken(); } if (curc == '/' && cppcomments) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } if ((this.ctype['/'] & (sbyte) CharacterTypes.COMMENTCHAR) != 0) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } peekchar = curc; return lastttype = '/'; } if ((ctype & (sbyte) CharacterTypes.COMMENTCHAR) != 0) { while ((curc = read()) != '\n' && curc != '\r' && curc >= 0) ; peekchar = curc; return nextToken(); } return lastttype = curc; } } }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BitCoinSharp.Store; using NUnit.Framework; namespace BitCoinSharp.Test { [TestFixture] public class ChainSplitTests { private NetworkParameters _unitTestParams; private Wallet _wallet; private BlockChain _chain; private IBlockStore _chainBlockStore; private Address _coinbaseTo; private Address _someOtherGuy; [SetUp] public void SetUp() { _unitTestParams = NetworkParameters.UnitTests(); _wallet = new Wallet(_unitTestParams); _wallet.AddKey(new EcKey()); _chainBlockStore = new MemoryBlockStore(_unitTestParams); _chain = new BlockChain(_unitTestParams, _wallet, _chainBlockStore); _coinbaseTo = _wallet.Keychain[0].ToAddress(_unitTestParams); _someOtherGuy = new EcKey().ToAddress(_unitTestParams); } [TearDown] public void TearDown() { _chainBlockStore.Dispose(); } [Test] public void TestForking1() { // Check that if the block chain forks, we end up using the right chain. Only tests inbound transactions // (receiving coins). Checking that we understand reversed spends is in testForking2. // TODO: Change this test to not use coinbase transactions as they are special (maturity rules). var reorgHappened = false; _wallet.Reorganized += (sender, e) => reorgHappened = true; // Start by building a couple of blocks on top of the genesis block. var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); var b2 = b1.CreateNextBlock(_coinbaseTo); Assert.IsTrue(_chain.Add(b1)); Assert.IsTrue(_chain.Add(b2)); Assert.IsFalse(reorgHappened); // We got two blocks which generated 50 coins each, to us. Assert.AreEqual("100.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); // We now have the following chain: // genesis -> b1 -> b2 // // so fork like this: // // genesis -> b1 -> b2 // \-> b3 // // Nothing should happen at this point. We saw b2 first so it takes priority. var b3 = b1.CreateNextBlock(_someOtherGuy); Assert.IsTrue(_chain.Add(b3)); Assert.IsFalse(reorgHappened); // No re-org took place. Assert.AreEqual("100.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); // Now we add another block to make the alternative chain longer. Assert.IsTrue(_chain.Add(b3.CreateNextBlock(_someOtherGuy))); Assert.IsTrue(reorgHappened); // Re-org took place. reorgHappened = false; // // genesis -> b1 -> b2 // \-> b3 -> b4 // // We lost some coins! b2 is no longer a part of the best chain so our available balance should drop to 50. Assert.AreEqual("50.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); // ... and back to the first chain. var b5 = b2.CreateNextBlock(_coinbaseTo); var b6 = b5.CreateNextBlock(_coinbaseTo); Assert.IsTrue(_chain.Add(b5)); Assert.IsTrue(_chain.Add(b6)); // // genesis -> b1 -> b2 -> b5 -> b6 // \-> b3 -> b4 // Assert.IsTrue(reorgHappened); Assert.AreEqual("200.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); } [Test] public void TestForking2() { // Check that if the chain forks and new coins are received in the alternate chain our balance goes up // after the re-org takes place. var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_someOtherGuy); var b2 = b1.CreateNextBlock(_someOtherGuy); Assert.IsTrue(_chain.Add(b1)); Assert.IsTrue(_chain.Add(b2)); // genesis -> b1 -> b2 // \-> b3 -> b4 Assert.AreEqual(0UL, _wallet.GetBalance()); var b3 = b1.CreateNextBlock(_coinbaseTo); var b4 = b3.CreateNextBlock(_someOtherGuy); Assert.IsTrue(_chain.Add(b3)); Assert.AreEqual(0UL, _wallet.GetBalance()); Assert.IsTrue(_chain.Add(b4)); Assert.AreEqual("50.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); } [Test] public void TestForking3() { // Check that we can handle our own spends being rolled back by a fork. var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); _chain.Add(b1); Assert.AreEqual("50.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); var dest = new EcKey().ToAddress(_unitTestParams); var spend = _wallet.CreateSend(dest, Utils.ToNanoCoins(10, 0)); _wallet.ConfirmSend(spend); // Waiting for confirmation ... Assert.AreEqual(0UL, _wallet.GetBalance()); var b2 = b1.CreateNextBlock(_someOtherGuy); b2.AddTransaction(spend); b2.Solve(); _chain.Add(b2); Assert.AreEqual(Utils.ToNanoCoins(40, 0), _wallet.GetBalance()); // genesis -> b1 (receive coins) -> b2 (spend coins) // \-> b3 -> b4 var b3 = b1.CreateNextBlock(_someOtherGuy); var b4 = b3.CreateNextBlock(_someOtherGuy); _chain.Add(b3); _chain.Add(b4); // b4 causes a re-org that should make our spend go inactive. Because the inputs are already spent our // available balance drops to zero again. Assert.AreEqual(0UL, _wallet.GetBalance(Wallet.BalanceType.Available)); // We estimate that it'll make it back into the block chain (we know we won't double spend). // assertEquals(Utils.toNanoCoins(40, 0), wallet.getBalance(Wallet.BalanceType.ESTIMATED)); } [Test] public void TestForking4() { // Check that we can handle external spends on an inactive chain becoming active. An external spend is where // we see a transaction that spends our own coins but we did not broadcast it ourselves. This happens when // keys are being shared between wallets. var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); _chain.Add(b1); Assert.AreEqual("50.00", Utils.BitcoinValueToFriendlyString(_wallet.GetBalance())); var dest = new EcKey().ToAddress(_unitTestParams); var spend = _wallet.CreateSend(dest, Utils.ToNanoCoins(50, 0)); // We do NOT confirm the spend here. That means it's not considered to be pending because createSend is // stateless. For our purposes it is as if some other program with our keys created the tx. // // genesis -> b1 (receive 50) --> b2 // \-> b3 (external spend) -> b4 var b2 = b1.CreateNextBlock(_someOtherGuy); _chain.Add(b2); var b3 = b1.CreateNextBlock(_someOtherGuy); b3.AddTransaction(spend); b3.Solve(); _chain.Add(b3); // The external spend is not active yet. Assert.AreEqual(Utils.ToNanoCoins(50, 0), _wallet.GetBalance()); var b4 = b3.CreateNextBlock(_someOtherGuy); _chain.Add(b4); // The external spend is now active. Assert.AreEqual(Utils.ToNanoCoins(0, 0), _wallet.GetBalance()); } [Test] public void TestDoubleSpendOnFork() { // Check what happens when a re-org happens and one of our confirmed transactions becomes invalidated by a // double spend on the new best chain. var eventCalled = false; _wallet.DeadTransaction += (sender, e) => eventCalled = true; var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); _chain.Add(b1); var t1 = _wallet.CreateSend(_someOtherGuy, Utils.ToNanoCoins(10, 0)); var yetAnotherGuy = new EcKey().ToAddress(_unitTestParams); var t2 = _wallet.CreateSend(yetAnotherGuy, Utils.ToNanoCoins(20, 0)); _wallet.ConfirmSend(t1); // Receive t1 as confirmed by the network. var b2 = b1.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); b2.AddTransaction(t1); b2.Solve(); _chain.Add(b2); // Now we make a double spend become active after a re-org. var b3 = b1.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); b3.AddTransaction(t2); b3.Solve(); _chain.Add(b3); // Side chain. var b4 = b3.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); _chain.Add(b4); // New best chain. // Should have seen a double spend. Assert.IsTrue(eventCalled); Assert.AreEqual(Utils.ToNanoCoins(30, 0), _wallet.GetBalance()); } [Test] public void TestDoubleSpendOnForkPending() { // Check what happens when a re-org happens and one of our UNconfirmed transactions becomes invalidated by a // double spend on the new best chain. Transaction eventDead = null; Transaction eventReplacement = null; _wallet.DeadTransaction += (sender, e) => { eventDead = e.DeadTx; eventReplacement = e.ReplacementTx; }; // Start with 50 coins. var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); _chain.Add(b1); var t1 = _wallet.CreateSend(_someOtherGuy, Utils.ToNanoCoins(10, 0)); var yetAnotherGuy = new EcKey().ToAddress(_unitTestParams); var t2 = _wallet.CreateSend(yetAnotherGuy, Utils.ToNanoCoins(20, 0)); _wallet.ConfirmSend(t1); // t1 is still pending ... var b2 = b1.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); _chain.Add(b2); Assert.AreEqual(Utils.ToNanoCoins(0, 0), _wallet.GetBalance()); Assert.AreEqual(Utils.ToNanoCoins(40, 0), _wallet.GetBalance(Wallet.BalanceType.Estimated)); // Now we make a double spend become active after a re-org. // genesis -> b1 -> b2 [t1 pending] // \-> b3 (t2) -> b4 var b3 = b1.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); b3.AddTransaction(t2); b3.Solve(); _chain.Add(b3); // Side chain. var b4 = b3.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); _chain.Add(b4); // New best chain. // Should have seen a double spend against the pending pool. Assert.AreEqual(t1, eventDead); Assert.AreEqual(t2, eventReplacement); Assert.AreEqual(Utils.ToNanoCoins(30, 0), _wallet.GetBalance()); // ... and back to our own parallel universe. var b5 = b2.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); _chain.Add(b5); var b6 = b5.CreateNextBlock(new EcKey().ToAddress(_unitTestParams)); _chain.Add(b6); // genesis -> b1 -> b2 -> b5 -> b6 [t1 pending] // \-> b3 [t2 inactive] -> b4 Assert.AreEqual(Utils.ToNanoCoins(0, 0), _wallet.GetBalance()); Assert.AreEqual(Utils.ToNanoCoins(40, 0), _wallet.GetBalance(Wallet.BalanceType.Estimated)); } } }
/* * Copyright 2008-2014, 2016, 2017 the GAP developers. See the NOTICE file at the * top-level directory of this distribution, and at * https://gapwiki.chiro.be/copyright * * 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.ServiceModel; using System.Web.Mvc; using Chiro.Cdf.Authentication; using Chiro.Cdf.ServiceHelper; using Chiro.Gap.Domain; using Chiro.Gap.ServiceContracts; using Chiro.Gap.ServiceContracts.DataContracts; using Chiro.Gap.ServiceContracts.FaultContracts; using Chiro.Gap.Validatie; using Chiro.Gap.WebApp.Models; namespace Chiro.Gap.WebApp.Controllers { /// <summary> /// Controller voor toegang tot groepsinstellingen /// </summary> [HandleError] public class GroepController : BaseController { /// <summary> /// Standaardconstructor. <paramref name="veelGebruikt"/> wordt /// best toegewezen via inversion of control. /// </summary> /// <param name="veelGebruikt">Haalt veel gebruikte zaken op uit cache, of indien niet beschikbaar, via /// service</param> /// <param name="serviceHelper"></param> /// <param name="authenticator"></param> public GroepController(IVeelGebruikt veelGebruikt, ServiceHelper serviceHelper, IAuthenticator authenticator) : base(veelGebruikt, serviceHelper, authenticator) { } /// <summary> /// Genereert een view met algemene gegevens over de groep /// </summary> /// <param name="groepID">ID van de gewenste groep</param> /// <returns>View met algemene gegevens over de groep</returns> [HandleError] public override ActionResult Index(int groepID) { var gwj = VeelGebruikt.GroepsWerkJaarOphalen(groepID); var werkjaarID = gwj.WerkJaarID; var model = new GroepsInstellingenModel { Titel = Properties.Resources.GroepsInstellingenTitel, Detail = ServiceHelper.CallService<IGroepenService, GroepDetail>(svc => svc.DetailOphalen(groepID)), NonActieveAfdelingen = ServiceHelper.CallService<IGroepenService, List<AfdelingInfo>>( svc => svc.OngebruikteAfdelingenOphalen(werkjaarID)), IsLive = VeelGebruikt.IsLive() }; BaseModelInit(model, groepID); return View(model); } // NOTE: onderstaande methodes komen voort uit opsplitsing groepenscherm, maar halen dus eigenlijk wat teveel info op. /// <summary> /// Genereert een view met actieve afdelings gegevens over de groep /// </summary> /// <param name="groepID">ID van de gewenste groep</param> /// <returns>View met actieve afdelings gegevens over de groep</returns> [HandleError] public ActionResult Afdelingen(int groepID) { return Index(groepID); } /// <summary> /// Genereert een view met categorie gegevens over de groep /// </summary> /// <param name="groepID">ID van de gewenste groep</param> /// <returns>View met categorie gegevens over de groep</returns> [HandleError] public ActionResult Categorieen(int groepID) { return Index(groepID); } /// <summary> /// Genereert een view met functie gegevens over de groep /// </summary> /// <param name="groepID">ID van de gewenste groep</param> /// <returns>View met functie gegevens over de groep</returns> [HandleError] public ActionResult Functies(int groepID) { return Index(groepID); } /// <summary> /// Laat de gebruiker de naam van de groep <paramref name="groepID"/> bewerken. /// </summary> /// <param name="groepID">ID van de geselecteerde groep</param> /// <returns>De view 'afdelingsinstellingen'</returns> [HandleError] public JsonResult NaamWijzigen(int groepID) { var model = new GroepsInstellingenModel { Titel = "Groepsnaam wijzigen", Detail = ServiceHelper.CallService<IGroepenService, GroepDetail>(svc => svc.DetailOphalen(groepID)) }; BaseModelInit(model, groepID); return Json(model, JsonRequestBehavior.AllowGet); } /// <summary> /// Postback voor bewerken van de groepsnaam /// </summary> /// <param name="model">De property <c>model.AfdelingsJaar</c> bevat de relevante details over de groep</param> /// <param name="groepID">Groep waarin de gebruiker momenteel aan het werken is</param> /// <returns>De view 'afdelingsinstellingen'</returns> [AcceptVerbs(HttpVerbs.Post)] [HandleError] public ActionResult NaamWijzigen(GroepInfoModel model, int groepID) { BaseModelInit(model, groepID); try { ServiceHelper.CallService<IGroepenService>(e => e.Bewaren(model.Info)); TempData["succes"] = Properties.Resources.WijzigingenOpgeslagenFeedback; // Aangemaakt om de gecachte naam te kunnen leegmaken. Zie bug #1270 VeelGebruikt.GroepsWerkJaarResetten(groepID); return RedirectToAction("Index"); } catch (FaultException<FoutNummerFault> ex) { ModelState.AddModelError("fout", ex.Detail.Bericht); model.Titel = "Groepsnaam wijzigen"; return View("NaamWijzigen", model); } } /// <summary> /// Laat de user het adres van de lokalen bewerken. /// </summary> /// <param name="groepID">ID van de groep waarvan we het adres willen bewerken.</param> /// <returns>Het formulier voor het aanpassen van het lokalenadres.</returns> [AcceptVerbs(HttpVerbs.Get)] public ActionResult AdresBewerken(int groepID) { var model = new GroepsAdresModel(); BaseModelInit(model, groepID); model.Adres = ServiceHelper.CallService<IGroepenService, GroepDetail>(svc => svc.DetailOphalen(groepID)).Adres ?? new AdresInfo { LandNaam = Properties.Resources.Belgie }; // Als het adres buitenlands is, dan moeten we de woonplaats nog eens overnemen in // WoonPlaatsBuitenland. Dat is nodig voor de AdresBewerkenControl, die een beetje // raar ineen zit. if (String.Compare(model.Adres.LandNaam, Properties.Resources.Belgie, StringComparison.OrdinalIgnoreCase) != 0) { model.WoonPlaatsBuitenLand = model.Adres.WoonPlaatsNaam; } model.Titel = Properties.Resources.AdresLokalen; model.AlleLanden = VeelGebruikt.LandenOphalen(); model.BeschikbareWoonPlaatsen = VeelGebruikt.WoonPlaatsenOphalen(model.Adres.PostNr); return View(model); } /// <summary> /// Als <paramref name="model"/> geen fouten bevat, stuurt deze controller action het /// bijgewerkte adres naar de backend om te persisteren. /// </summary> /// <param name="groepID">Huidige groep</param> /// <param name="model">Bevat de nieuw adres voor de lokalen van een groep</param> /// <returns>Als alles goed liep, wordt geredirect naar de groepsinstellingen. Anders /// opnieuw de view voor het aanpassen van de uitstap, met de nodige feedback</returns> [AcceptVerbs(HttpVerbs.Post)] public ActionResult AdresBewerken(int groepID, GroepsAdresModel model) { // Als het adres buitenlands is, neem dan de woonplaats over uit het // vrij in te vullen veld. if (String.Compare(model.Land, Properties.Resources.Belgie, StringComparison.OrdinalIgnoreCase) != 0) { model.WoonPlaatsNaam = model.WoonPlaatsBuitenLand; } try { // De service zal model.Adres.ID negeren; dit wordt // steeds opnieuw opgezocht. Adressen worden nooit // gewijzigd, enkel bijgemaakt (en eventueel verwijderd.) ServiceHelper.CallService<IGroepenService>(l => l.AdresInstellen(groepID, model.Adres)); return RedirectToAction("Index"); } catch (FaultException<OngeldigObjectFault> ex) { BaseModelInit(model, groepID); new ModelStateWrapper(ModelState).BerichtenToevoegen(ex.Detail, String.Empty); model.BeschikbareWoonPlaatsen = VeelGebruikt.WoonPlaatsenOphalen(model.PostNr); model.AlleLanden = VeelGebruikt.LandenOphalen(); model.Titel = Properties.Resources.AdresLokalen; return View(model); } } } }
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Text; /// @file /// @addtogroup flatbuffers_csharp_api /// @{ namespace FlatBuffers { /// <summary> /// Responsible for building up and accessing a FlatBuffer formatted byte /// array (via ByteBuffer). /// </summary> internal class FlatBufferBuilder { private int _space; private ByteBuffer _bb; private int _minAlign = 1; // The vtable for the current table (if _vtableSize >= 0) private int[] _vtable = new int[16]; // The size of the vtable. -1 indicates no vtable private int _vtableSize = -1; // Starting offset of the current struct/table. private int _objectStart; // List of offsets of all vtables. private int[] _vtables = new int[16]; // Number of entries in `vtables` in use. private int _numVtables = 0; // For the current vector being built. private int _vectorNumElems = 0; /// <summary> /// Create a FlatBufferBuilder with a given initial size. /// </summary> /// <param name="initialSize"> /// The initial size to use for the internal buffer. /// </param> public FlatBufferBuilder(int initialSize) { if (initialSize <= 0) throw new ArgumentOutOfRangeException("initialSize", initialSize, "Must be greater than zero"); _space = initialSize; _bb = new ByteBuffer(initialSize); } /// <summary> /// Create a FlatBufferBuilder backed by the pased in ByteBuffer /// </summary> /// <param name="buffer">The ByteBuffer to write to</param> public FlatBufferBuilder(ByteBuffer buffer) { _bb = buffer; _space = buffer.Length; buffer.Reset(); } /// <summary> /// Reset the FlatBufferBuilder by purging all data that it holds. /// </summary> public void Clear() { _space = _bb.Length; _bb.Reset(); _minAlign = 1; while (_vtableSize > 0) _vtable[--_vtableSize] = 0; _vtableSize = -1; _objectStart = 0; _numVtables = 0; _vectorNumElems = 0; } /// <summary> /// Gets and sets a Boolean to disable the optimization when serializing /// default values to a Table. /// /// In order to save space, fields that are set to their default value /// don't get serialized into the buffer. /// </summary> public bool ForceDefaults { get; set; } /// @cond FLATBUFFERS_INTERNAL public int Offset { get { return _bb.Length - _space; } } public void Pad(int size) { _bb.PutByte(_space -= size, 0, size); } // Doubles the size of the ByteBuffer, and copies the old data towards // the end of the new buffer (since we build the buffer backwards). void GrowBuffer() { _bb.GrowFront(_bb.Length << 1); } // Prepare to write an element of `size` after `additional_bytes` // have been written, e.g. if you write a string, you need to align // such the int length field is aligned to SIZEOF_INT, and the string // data follows it directly. // If all you need to do is align, `additional_bytes` will be 0. public void Prep(int size, int additionalBytes) { // Track the biggest thing we've ever aligned to. if (size > _minAlign) _minAlign = size; // Find the amount of alignment needed such that `size` is properly // aligned after `additional_bytes` var alignSize = ((~((int)_bb.Length - _space + additionalBytes)) + 1) & (size - 1); // Reallocate the buffer if needed. while (_space < alignSize + size + additionalBytes) { var oldBufSize = (int)_bb.Length; GrowBuffer(); _space += (int)_bb.Length - oldBufSize; } if (alignSize > 0) Pad(alignSize); } public void PutBool(bool x) { _bb.PutByte(_space -= sizeof(byte), (byte)(x ? 1 : 0)); } public void PutSbyte(sbyte x) { _bb.PutSbyte(_space -= sizeof(sbyte), x); } public void PutByte(byte x) { _bb.PutByte(_space -= sizeof(byte), x); } public void PutShort(short x) { _bb.PutShort(_space -= sizeof(short), x); } public void PutUshort(ushort x) { _bb.PutUshort(_space -= sizeof(ushort), x); } public void PutInt(int x) { _bb.PutInt(_space -= sizeof(int), x); } public void PutUint(uint x) { _bb.PutUint(_space -= sizeof(uint), x); } public void PutLong(long x) { _bb.PutLong(_space -= sizeof(long), x); } public void PutUlong(ulong x) { _bb.PutUlong(_space -= sizeof(ulong), x); } public void PutFloat(float x) { _bb.PutFloat(_space -= sizeof(float), x); } /// <summary> /// Puts an array of type T into this builder at the /// current offset /// </summary> /// <typeparam name="T">The type of the input data </typeparam> /// <param name="x">The array to copy data from</param> public void Put<T>(T[] x) where T : struct { _space = _bb.Put(_space, x); } #if ENABLE_SPAN_T /// <summary> /// Puts a span of type T into this builder at the /// current offset /// </summary> /// <typeparam name="T">The type of the input data </typeparam> /// <param name="x">The span to copy data from</param> public void Put<T>(Span<T> x) where T : struct { _space = _bb.Put(_space, x); } #endif public void PutDouble(double x) { _bb.PutDouble(_space -= sizeof(double), x); } /// @endcond /// <summary> /// Add a `bool` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `bool` to add to the buffer.</param> public void AddBool(bool x) { Prep(sizeof(byte), 0); PutBool(x); } /// <summary> /// Add a `sbyte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `sbyte` to add to the buffer.</param> public void AddSbyte(sbyte x) { Prep(sizeof(sbyte), 0); PutSbyte(x); } /// <summary> /// Add a `byte` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `byte` to add to the buffer.</param> public void AddByte(byte x) { Prep(sizeof(byte), 0); PutByte(x); } /// <summary> /// Add a `short` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `short` to add to the buffer.</param> public void AddShort(short x) { Prep(sizeof(short), 0); PutShort(x); } /// <summary> /// Add an `ushort` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ushort` to add to the buffer.</param> public void AddUshort(ushort x) { Prep(sizeof(ushort), 0); PutUshort(x); } /// <summary> /// Add an `int` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `int` to add to the buffer.</param> public void AddInt(int x) { Prep(sizeof(int), 0); PutInt(x); } /// <summary> /// Add an `uint` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `uint` to add to the buffer.</param> public void AddUint(uint x) { Prep(sizeof(uint), 0); PutUint(x); } /// <summary> /// Add a `long` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `long` to add to the buffer.</param> public void AddLong(long x) { Prep(sizeof(long), 0); PutLong(x); } /// <summary> /// Add an `ulong` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `ulong` to add to the buffer.</param> public void AddUlong(ulong x) { Prep(sizeof(ulong), 0); PutUlong(x); } /// <summary> /// Add a `float` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `float` to add to the buffer.</param> public void AddFloat(float x) { Prep(sizeof(float), 0); PutFloat(x); } /// <summary> /// Add an array of type T to the buffer (aligns the data and grows if necessary). /// </summary> /// <typeparam name="T">The type of the input data</typeparam> /// <param name="x">The array to copy data from</param> public void Add<T>(T[] x) where T : struct { if (x == null) { throw new ArgumentNullException("Cannot add a null array"); } if( x.Length == 0) { // don't do anything if the array is empty return; } if(!ByteBuffer.IsSupportedType<T>()) { throw new ArgumentException("Cannot add this Type array to the builder"); } int size = ByteBuffer.SizeOf<T>(); // Need to prep on size (for data alignment) and then we pass the // rest of the length (minus 1) as additional bytes Prep(size, size * (x.Length - 1)); Put(x); } #if ENABLE_SPAN_T /// <summary> /// Add a span of type T to the buffer (aligns the data and grows if necessary). /// </summary> /// <typeparam name="T">The type of the input data</typeparam> /// <param name="x">The span to copy data from</param> public void Add<T>(Span<T> x) where T : struct { if (!ByteBuffer.IsSupportedType<T>()) { throw new ArgumentException("Cannot add this Type array to the builder"); } int size = ByteBuffer.SizeOf<T>(); // Need to prep on size (for data alignment) and then we pass the // rest of the length (minus 1) as additional bytes Prep(size, size * (x.Length - 1)); Put(x); } #endif /// <summary> /// Add a `double` to the buffer (aligns the data and grows if necessary). /// </summary> /// <param name="x">The `double` to add to the buffer.</param> public void AddDouble(double x) { Prep(sizeof(double), 0); PutDouble(x); } /// <summary> /// Adds an offset, relative to where it will be written. /// </summary> /// <param name="off">The offset to add to the buffer.</param> public void AddOffset(int off) { Prep(sizeof(int), 0); // Ensure alignment is already done. if (off > Offset) throw new ArgumentException(); off = Offset - off + sizeof(int); PutInt(off); } /// @cond FLATBUFFERS_INTERNAL public void StartVector(int elemSize, int count, int alignment) { NotNested(); _vectorNumElems = count; Prep(sizeof(int), elemSize * count); Prep(alignment, elemSize * count); // Just in case alignment > int. } /// @endcond /// <summary> /// Writes data necessary to finish a vector construction. /// </summary> public VectorOffset EndVector() { PutInt(_vectorNumElems); return new VectorOffset(Offset); } /// <summary> /// Creates a vector of tables. /// </summary> /// <param name="offsets">Offsets of the tables.</param> public VectorOffset CreateVectorOfTables<T>(Offset<T>[] offsets) where T : struct { NotNested(); StartVector(sizeof(int), offsets.Length, sizeof(int)); for (int i = offsets.Length - 1; i >= 0; i--) AddOffset(offsets[i].Value); return EndVector(); } /// @cond FLATBUFFERS_INTENRAL public void Nested(int obj) { // Structs are always stored inline, so need to be created right // where they are used. You'll get this assert if you created it // elsewhere. if (obj != Offset) throw new Exception( "FlatBuffers: struct must be serialized inline."); } public void NotNested() { // You should not be creating any other objects or strings/vectors // while an object is being constructed if (_vtableSize >= 0) throw new Exception( "FlatBuffers: object serialization must not be nested."); } public void StartObject(int numfields) { if (numfields < 0) throw new ArgumentOutOfRangeException("Flatbuffers: invalid numfields"); NotNested(); if (_vtable.Length < numfields) _vtable = new int[numfields]; _vtableSize = numfields; _objectStart = Offset; } // Set the current vtable at `voffset` to the current location in the // buffer. public void Slot(int voffset) { if (voffset >= _vtableSize) throw new IndexOutOfRangeException("Flatbuffers: invalid voffset"); _vtable[voffset] = Offset; } /// <summary> /// Adds a Boolean to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddBool(int o, bool x, bool d) { if (ForceDefaults || x != d) { AddBool(x); Slot(o); } } /// <summary> /// Adds a SByte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddSbyte(int o, sbyte x, sbyte d) { if (ForceDefaults || x != d) { AddSbyte(x); Slot(o); } } /// <summary> /// Adds a Byte to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddByte(int o, byte x, byte d) { if (ForceDefaults || x != d) { AddByte(x); Slot(o); } } /// <summary> /// Adds a Int16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddShort(int o, short x, int d) { if (ForceDefaults || x != d) { AddShort(x); Slot(o); } } /// <summary> /// Adds a UInt16 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUshort(int o, ushort x, ushort d) { if (ForceDefaults || x != d) { AddUshort(x); Slot(o); } } /// <summary> /// Adds an Int32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddInt(int o, int x, int d) { if (ForceDefaults || x != d) { AddInt(x); Slot(o); } } /// <summary> /// Adds a UInt32 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUint(int o, uint x, uint d) { if (ForceDefaults || x != d) { AddUint(x); Slot(o); } } /// <summary> /// Adds an Int64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddLong(int o, long x, long d) { if (ForceDefaults || x != d) { AddLong(x); Slot(o); } } /// <summary> /// Adds a UInt64 to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddUlong(int o, ulong x, ulong d) { if (ForceDefaults || x != d) { AddUlong(x); Slot(o); } } /// <summary> /// Adds a Single to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddFloat(int o, float x, double d) { if (ForceDefaults || x != d) { AddFloat(x); Slot(o); } } /// <summary> /// Adds a Double to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddDouble(int o, double x, double d) { if (ForceDefaults || x != d) { AddDouble(x); Slot(o); } } /// <summary> /// Adds a buffer offset to the Table at index `o` in its vtable using the value `x` and default `d` /// </summary> /// <param name="o">The index into the vtable</param> /// <param name="x">The value to put into the buffer. If the value is equal to the default /// and <see cref="ForceDefaults"/> is false, the value will be skipped.</param> /// <param name="d">The default value to compare the value against</param> public void AddOffset(int o, int x, int d) { if (ForceDefaults || x != d) { AddOffset(x); Slot(o); } } /// @endcond /// <summary> /// Encode the string `s` in the buffer using UTF-8. /// </summary> /// <param name="s">The string to encode.</param> /// <returns> /// The offset in the buffer where the encoded string starts. /// </returns> public StringOffset CreateString(string s) { NotNested(); AddByte(0); var utf8StringLen = Encoding.UTF8.GetByteCount(s); StartVector(1, utf8StringLen, 1); _bb.PutStringUTF8(_space -= utf8StringLen, s); return new StringOffset(EndVector().Value); } #if ENABLE_SPAN_T /// <summary> /// Creates a string in the buffer from a Span containing /// a UTF8 string. /// </summary> /// <param name="chars">the UTF8 string to add to the buffer</param> /// <returns> /// The offset in the buffer where the encoded string starts. /// </returns> public StringOffset CreateUTF8String(Span<byte> chars) { NotNested(); AddByte(0); var utf8StringLen = chars.Length; StartVector(1, utf8StringLen, 1); _space = _bb.Put(_space, chars); return new StringOffset(EndVector().Value); } #endif /// @cond FLATBUFFERS_INTERNAL // Structs are stored inline, so nothing additional is being added. // `d` is always 0. public void AddStruct(int voffset, int x, int d) { if (x != d) { Nested(x); Slot(voffset); } } public int EndObject() { if (_vtableSize < 0) throw new InvalidOperationException( "Flatbuffers: calling endObject without a startObject"); AddInt((int)0); var vtableloc = Offset; // Write out the current vtable. int i = _vtableSize - 1; // Trim trailing zeroes. for (; i >= 0 && _vtable[i] == 0; i--) {} int trimmedSize = i + 1; for (; i >= 0 ; i--) { // Offset relative to the start of the table. short off = (short)(_vtable[i] != 0 ? vtableloc - _vtable[i] : 0); AddShort(off); // clear out written entry _vtable[i] = 0; } const int standardFields = 2; // The fields below: AddShort((short)(vtableloc - _objectStart)); AddShort((short)((trimmedSize + standardFields) * sizeof(short))); // Search for an existing vtable that matches the current one. int existingVtable = 0; for (i = 0; i < _numVtables; i++) { int vt1 = _bb.Length - _vtables[i]; int vt2 = _space; short len = _bb.GetShort(vt1); if (len == _bb.GetShort(vt2)) { for (int j = sizeof(short); j < len; j += sizeof(short)) { if (_bb.GetShort(vt1 + j) != _bb.GetShort(vt2 + j)) { goto endLoop; } } existingVtable = _vtables[i]; break; } endLoop: { } } if (existingVtable != 0) { // Found a match: // Remove the current vtable. _space = _bb.Length - vtableloc; // Point table to existing vtable. _bb.PutInt(_space, existingVtable - vtableloc); } else { // No match: // Add the location of the current vtable to the list of // vtables. if (_numVtables == _vtables.Length) { // Arrays.CopyOf(vtables num_vtables * 2); var newvtables = new int[ _numVtables * 2]; Array.Copy(_vtables, newvtables, _vtables.Length); _vtables = newvtables; }; _vtables[_numVtables++] = Offset; // Point table to current vtable. _bb.PutInt(_bb.Length - vtableloc, Offset - vtableloc); } _vtableSize = -1; return vtableloc; } // This checks a required field has been set in a given table that has // just been constructed. public void Required(int table, int field) { int table_start = _bb.Length - table; int vtable_start = table_start - _bb.GetInt(table_start); bool ok = _bb.GetShort(vtable_start + field) != 0; // If this fails, the caller will show what field needs to be set. if (!ok) throw new InvalidOperationException("FlatBuffers: field " + field + " must be set"); } /// @endcond /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="sizePrefix"> /// Whether to prefix the size to the buffer. /// </param> protected void Finish(int rootTable, bool sizePrefix) { Prep(_minAlign, sizeof(int) + (sizePrefix ? sizeof(int) : 0)); AddOffset(rootTable); if (sizePrefix) { AddInt(_bb.Length - _space); } _bb.Position = _space; } /// <summary> /// Finalize a buffer, pointing to the given `root_table`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void Finish(int rootTable) { Finish(rootTable, false); } /// <summary> /// Finalize a buffer, pointing to the given `root_table`, with the size prefixed. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> public void FinishSizePrefixed(int rootTable) { Finish(rootTable, true); } /// <summary> /// Get the ByteBuffer representing the FlatBuffer. /// </summary> /// <remarks> /// This is typically only called after you call `Finish()`. /// The actual data starts at the ByteBuffer's current position, /// not necessarily at `0`. /// </remarks> /// <returns> /// Returns the ByteBuffer for this FlatBuffer. /// </returns> public ByteBuffer DataBuffer { get { return _bb; } } /// <summary> /// A utility function to copy and return the ByteBuffer data as a /// `byte[]`. /// </summary> /// <returns> /// A full copy of the FlatBuffer data. /// </returns> public byte[] SizedByteArray() { return _bb.ToSizedArray(); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> /// <param name="sizePrefix"> /// Whether to prefix the size to the buffer. /// </param> protected void Finish(int rootTable, string fileIdentifier, bool sizePrefix) { Prep(_minAlign, sizeof(int) + (sizePrefix ? sizeof(int) : 0) + FlatBufferConstants.FileIdentifierLength); if (fileIdentifier.Length != FlatBufferConstants.FileIdentifierLength) throw new ArgumentException( "FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "fileIdentifier"); for (int i = FlatBufferConstants.FileIdentifierLength - 1; i >= 0; i--) { AddByte((byte)fileIdentifier[i]); } Finish(rootTable, sizePrefix); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void Finish(int rootTable, string fileIdentifier) { Finish(rootTable, fileIdentifier, false); } /// <summary> /// Finalize a buffer, pointing to the given `rootTable`, with the size prefixed. /// </summary> /// <param name="rootTable"> /// An offset to be added to the buffer. /// </param> /// <param name="fileIdentifier"> /// A FlatBuffer file identifier to be added to the buffer before /// `root_table`. /// </param> public void FinishSizePrefixed(int rootTable, string fileIdentifier) { Finish(rootTable, fileIdentifier, true); } } } /// @}
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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.Collections.Generic; using System.Linq; using System.Abstract.Parts; namespace System.Abstract { /// <summary> /// ServiceCacheExtensions /// </summary> public static class ServiceCacheExtensions { /// <summary> /// Adds the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Add(this IServiceCache service, string name, object value) { return service.Add(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Adds the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <param name="itemPolicy">The item policy.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Add(this IServiceCache service, string name, CacheItemPolicy itemPolicy, object value) { return service.Add(null, name, itemPolicy, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Adds the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Add(this IServiceCache service, object tag, string name, object value) { return service.Add(tag, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Adds the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="itemPolicy">The item policy.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Add(this IServiceCache service, object tag, string name, CacheItemPolicy itemPolicy, object value) { return service.Add(tag, name, itemPolicy, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Gets the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <returns></returns> public static object Get(this IServiceCache service, string name) { return service.Get(null, name); } /// <summary> /// Gets the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="names">The names.</param> /// <returns></returns> public static object Get(this IServiceCache service, IEnumerable<string> names) { return service.Get(null, names); } /// <summary> /// Tries the get. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public static bool TryGet(this IServiceCache service, string name, out object value) { return service.TryGet(null, name, out value); } /// <summary> /// Removes the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <returns></returns> public static object Remove(this IServiceCache service, string name) { return service.Remove(null, name, null); } /// <summary> /// Removes the specified service. /// </summary> /// <param name="service">The service.</param> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <returns></returns> public static object Remove(this IServiceCache service, object tag, string name) { return service.Remove(tag, name, null); } /// <summary> /// Sets the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Set(this IServiceCache service, string name, object value) { return service.Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Sets the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="name">The name.</param> /// <param name="itemPolicy">The item policy.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Set(this IServiceCache service, string name, CacheItemPolicy itemPolicy, object value) { return service.Set(null, name, itemPolicy, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Sets the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Set(this IServiceCache service, object tag, string name, object value) { return service.Set(tag, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Sets the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="name">The name.</param> /// <param name="itemPolicy">The item policy.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object Set(this IServiceCache service, object tag, string name, CacheItemPolicy itemPolicy, object value) { return service.Set(tag, name, itemPolicy, value, ServiceCacheByDispatcher.Empty); } /// <summary> /// Ensures the cache dependency. /// </summary> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="dependency">The dependency.</param> public static void EnsureCacheDependency(IServiceCache service, object tag, CacheItemDependency dependency) { if (service == null) throw new ArgumentNullException("service"); string[] names; if (dependency == null || (names = (dependency(service, null, tag, null) as string[])) == null) return; EnsureCacheDependency(service, names); } /// <summary> /// Ensures the cache dependency. /// </summary> /// <param name="service">The cache.</param> /// <param name="names">The names.</param> public static void EnsureCacheDependency(IServiceCache service, IEnumerable<string> names) { if (service == null) throw new ArgumentNullException("service"); if (names != null) foreach (var name in names) service.Add(null, name, new CacheItemPolicy { AbsoluteExpiration = ServiceCache.InfiniteAbsoluteExpiration }, string.Empty); } /// <summary> /// Touches the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="names">The names.</param> public static void Touch(this IServiceCache service, params string[] names) { Touch(service, null, names); } /// <summary> /// Touches the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="names">The names.</param> public static void Touch(this IServiceCache service, object tag, params string[] names) { if (service == null) throw new ArgumentNullException("service"); var touchable = service.Settings.Touchable; if (touchable == null) throw new NotSupportedException("Touchables are not supported"); touchable.Touch(tag, names); } /// <summary> /// Makes the dependency. /// </summary> /// <param name="service">The cache.</param> /// <param name="names">The names.</param> /// <returns></returns> public static CacheItemDependency MakeDependency(this IServiceCache service, params string[] names) { if (service == null) throw new ArgumentNullException("service"); var touchable = service.Settings.Touchable; if (touchable == null) throw new NotSupportedException("Touchables are not supported"); return (c, r, tag, values) => touchable.MakeDependency(tag, names); } #region BehaveAs /// <summary> /// Behaves as. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <returns></returns> public static T BehaveAs<T>(this IServiceCache service) where T : class, IServiceCache { IServiceWrapper<IServiceCache> serviceWrapper; do { serviceWrapper = (service as IServiceWrapper<IServiceCache>); if (serviceWrapper != null) service = serviceWrapper.Parent; } while (serviceWrapper != null); return (service as T); } /// <summary> /// Behaves as. /// </summary> /// <param name="service">The cache.</param> /// <param name="namespace">The @namespace.</param> /// <returns></returns> public static IServiceCache BehaveAs(this IServiceCache service, string @namespace) { if (service == null) throw new ArgumentNullException("service"); if (@namespace == null) throw new ArgumentNullException("@namespace"); return new ServiceCacheNamespaceBehaviorWrapper(service, @namespace); } /// <summary> /// Behaves as. /// </summary> /// <param name="service">The cache.</param> /// <param name="values">The values.</param> /// <param name="namespace">The @namespace.</param> /// <returns></returns> public static IServiceCache BehaveAs(this IServiceCache service, IEnumerable<object> values, out string @namespace) { if (service == null) throw new ArgumentNullException("service"); @namespace = ServiceCache.GetNamespace(values); if (@namespace == null) throw new ArgumentNullException("@values"); return new ServiceCacheNamespaceBehaviorWrapper(service, @namespace); } #endregion #region Registrations /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <returns></returns> public static object Get(this IServiceCache service, IServiceCacheRegistration registration) { return Get<object>(service, registration, null, null); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <returns></returns> public static T Get<T>(this IServiceCache service, IServiceCacheRegistration registration) { return Get<T>(service, registration, null, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache service, IServiceCacheRegistration registration) { return Get<IEnumerable<T>>(service, registration, null, null); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache service, IServiceCacheRegistration registration) { return Get<IDictionary<TKey, TValue>>(service, registration, null, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache service, IServiceCacheRegistration registration) { return Get<IQueryable<T>>(service, registration, null, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(this IServiceCache service, IServiceCacheRegistration registration, object[] values) { return Get<object>(service, registration, null, values); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(this IServiceCache service, IServiceCacheRegistration registration, object[] values) { return Get<T>(service, registration, null, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache service, IServiceCacheRegistration registration, object[] values) { return Get<IEnumerable<T>>(service, registration, null, values); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache service, IServiceCacheRegistration registration, object[] values) { return Get<IDictionary<TKey, TValue>>(service, registration, null, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache service, IServiceCacheRegistration registration, object[] values) { return Get<IQueryable<T>>(service, registration, null, values); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static object Get(this IServiceCache service, IServiceCacheRegistration registration, object tag) { return Get<object>(service, registration, tag, null); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static T Get<T>(this IServiceCache service, IServiceCacheRegistration registration, object tag) { return Get<T>(service, registration, tag, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache service, IServiceCacheRegistration registration, object tag) { return Get<IEnumerable<T>>(service, registration, tag, null); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache service, IServiceCacheRegistration registration, object tag) { return Get<IDictionary<TKey, TValue>>(service, registration, tag, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache service, IServiceCacheRegistration registration, object tag) { return Get<IQueryable<T>>(service, registration, tag, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(this IServiceCache service, IServiceCacheRegistration registration, object tag, object[] values) { return Get<object>(service, registration, tag, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache service, IServiceCacheRegistration registration, object tag, object[] values) { return Get<IEnumerable<T>>(service, registration, tag, values); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache service, IServiceCacheRegistration registration, object tag, object[] values) { return Get<IDictionary<TKey, TValue>>(service, registration, tag, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache service, ServiceCacheRegistration registration, object tag, object[] values) { return Get<IQueryable<T>>(service, registration, tag, values); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(this IServiceCache service, IServiceCacheRegistration registration, object tag, object[] values) { if (service == null) throw new ArgumentNullException("service"); if (registration == null) throw new ArgumentNullException("registration"); var registrationDispatcher = GetRegistrationDispatcher(service); // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(registration, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationAB, (registration.Registrar != null ? registration.Registrar.AnchorType.ToString() : "{unregistered}"), registration.Name)); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); return registrationDispatcher.Get<T>(service, foundRegistration, tag, values); } /// <summary> /// Sends the specified service. /// </summary> /// <param name="service">The service.</param> /// <param name="registration">The registration.</param> /// <param name="messages">The messages.</param> public static void Send(this IServiceCache service, IServiceCacheRegistration registration, object[] messages) { Send(service, registration, null, messages); } /// <summary> /// Sends the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="registration">The registration.</param> /// <param name="tag">The tag.</param> /// <param name="messages">The messages.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.InvalidOperationException"></exception> public static void Send(this IServiceCache service, IServiceCacheRegistration registration, object tag, object[] messages) { if (service == null) throw new ArgumentNullException("service"); if (registration == null) throw new ArgumentNullException("registration"); if (messages == null) throw new ArgumentNullException("messages"); var registrationDispatcher = GetRegistrationDispatcher(service); // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(registration, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationAB, (registration.Registrar != null ? registration.Registrar.AnchorType.ToString() : "{unregistered}"), registration.Name)); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); registrationDispatcher.Send(service, foundRegistration, tag, messages); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="cache">The cache.</param> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <returns></returns> public static object Get(this IServiceCache cache, Type anchorType, string registrationName) { return Get<object>(cache, anchorType, registrationName, null, null); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static T Get<T>(this IServiceCache cache, Type anchorType, string registrationName) { return Get<T>(cache, anchorType, registrationName, null, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache cache, Type anchorType, string registrationName) { return Get<IEnumerable<T>>(cache, anchorType, registrationName, null, null); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache cache, Type anchorType, string registrationName) { return Get<IDictionary<TKey, TValue>>(cache, anchorType, registrationName, null, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache cache, Type anchorType, string registrationName) { return Get<IQueryable<T>>(cache, anchorType, registrationName, null, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="cache">The cache.</param> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(this IServiceCache cache, Type anchorType, string registrationName, object[] values) { return Get<object>(cache, anchorType, registrationName, null, values); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(this IServiceCache cache, Type anchorType, string registrationName, object[] values) { return Get<T>(cache, anchorType, registrationName, null, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache cache, Type anchorType, string registrationName, object[] values) { return Get<IEnumerable<T>>(cache, anchorType, registrationName, string.Empty, values); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache cache, Type anchorType, string registrationName, object[] values) { return Get<IDictionary<TKey, TValue>>(cache, anchorType, registrationName, string.Empty, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache cache, Type anchorType, string registrationName, object[] values) { return Get<IQueryable<T>>(cache, anchorType, registrationName, string.Empty, values); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="cache">The cache.</param> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static object Get(this IServiceCache cache, Type anchorType, string registrationName, object tag) { return Get<object>(cache, anchorType, registrationName, tag, null); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static T Get<T>(this IServiceCache cache, Type anchorType, string registrationName, object tag) { return Get<T>(cache, anchorType, registrationName, tag, null); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache cache, Type anchorType, string registrationName, object tag) { return Get<IEnumerable<T>>(cache, anchorType, registrationName, tag, null); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache cache, Type anchorType, string registrationName, object tag) { return Get<IDictionary<TKey, TValue>>(cache, anchorType, registrationName, tag, null); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache cache, Type anchorType, string registrationName, object tag) { return Get<IQueryable<T>>(cache, anchorType, registrationName, tag, null); } /// <summary> /// Gets the specified cached item. /// </summary> /// <param name="cache">The cache.</param> /// <param name="anchorType">The type.</param> /// <param name="registrationName">The registration id.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static object Get(this IServiceCache cache, Type anchorType, string registrationName, object tag, object[] values) { return Get<object>(cache, anchorType, registrationName, tag, values); } /// <summary> /// Gets the many. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IEnumerable<T> GetMany<T>(this IServiceCache cache, Type anchorType, string registrationName, object tag, object[] values) { return Get<IEnumerable<T>>(cache, anchorType, registrationName, tag, values); } /// <summary> /// Gets the dictionary. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IDictionary<TKey, TValue> GetMany<TKey, TValue>(this IServiceCache cache, Type anchorType, string registrationName, object tag, object[] values) { return Get<IDictionary<TKey, TValue>>(cache, anchorType, registrationName, tag, values); } /// <summary> /// Gets the query. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static IQueryable<T> GetQuery<T>(this IServiceCache cache, Type anchorType, string registrationName, object tag, object[] values) { return Get<IQueryable<T>>(cache, anchorType, registrationName, tag, values); } /// <summary> /// Gets the specified cache. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="values">The values.</param> /// <returns></returns> public static T Get<T>(this IServiceCache cache, Type anchorType, string registrationName, object tag, object[] values) { if (anchorType == null) throw new ArgumentNullException("anchorType"); if (string.IsNullOrEmpty(registrationName)) throw new ArgumentNullException("registrationName"); var registrationDispatcher = GetRegistrationDispatcher(cache); // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(anchorType, registrationName, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationAB, anchorType.ToString(), registrationName)); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); return registrationDispatcher.Get<T>(cache, foundRegistration, tag, values); } /// <summary> /// Sends the specified service. /// </summary> /// <param name="service">The service.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="messages">The messages.</param> public static void Send(this IServiceCache service, Type anchorType, string registrationName, object[] messages) { Send(service, anchorType, registrationName, null, messages); } /// <summary> /// Sends the specified cache. /// </summary> /// <param name="service">The service.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> /// <param name="tag">The tag.</param> /// <param name="messages">The messages.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.InvalidOperationException"></exception> public static void Send(this IServiceCache service, Type anchorType, string registrationName, object tag, object[] messages) { if (service == null) throw new ArgumentNullException("service"); if (anchorType == null) throw new ArgumentNullException("anchorType"); if (string.IsNullOrEmpty(registrationName)) throw new ArgumentNullException("registrationName"); if (messages == null) throw new ArgumentNullException("messages"); var registrationDispatcher = GetRegistrationDispatcher(service); // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(anchorType, registrationName, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationAB, anchorType.ToString(), registrationName)); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); registrationDispatcher.Send(service, foundRegistration, tag, messages); } /// <summary> /// Sends the specified service. /// </summary> /// <typeparam name="TAnchor">The type of the anchor.</typeparam> /// <param name="service">The service.</param> /// <param name="messages">The messages.</param> public static void SendAll<TAnchor>(this IServiceCache service, object[] messages) { SendAll(service, typeof(TAnchor), null, messages); } /// <summary> /// Sends the specified cache. /// </summary> /// <typeparam name="TAnchor">The type of the anchor.</typeparam> /// <param name="service">The cache.</param> /// <param name="tag">The tag.</param> /// <param name="messages">The messages.</param> public static void SendAll<TAnchor>(this IServiceCache service, object tag, object[] messages) { SendAll(service, typeof(TAnchor), tag, messages); } /// <summary> /// Sends the specified service. /// </summary> /// <param name="service">The service.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="messages">The messages.</param> public static void SendAll(this IServiceCache service, Type anchorType, object[] messages) { SendAll(service, anchorType, null, messages); } /// <summary> /// Sends the specified cache. /// </summary> /// <param name="service">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="tag">The tag.</param> /// <param name="messages">The messages.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.InvalidOperationException"></exception> public static void SendAll(this IServiceCache service, Type anchorType, object tag, object[] messages) { if (service == null) throw new ArgumentNullException("service"); if (anchorType == null) throw new ArgumentNullException("anchorType"); if (messages == null) throw new ArgumentNullException("messages"); var registrationDispatcher = GetRegistrationDispatcher(service); // fetch all registrations ServiceCacheRegistrar registrar; ServiceCacheRegistrar.TryGet(anchorType, out registrar, false); if (registrar != null) foreach (var registration in registrar.All) { // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(registration, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationAB, (registration.Registrar != null ? registration.Registrar.AnchorType.ToString() : "{unregistered}"), registration.Name)); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); registrationDispatcher.Send(service, foundRegistration, tag, messages); } } /// <summary> /// Removes all. /// </summary> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> public static void RemoveAll(this IServiceCache cache, Type anchorType) { if (anchorType == null) throw new ArgumentNullException("anchorType"); var registrationDispatcher = GetRegistrationDispatcher(cache); // fetch registrar ServiceCacheRegistrar registrar; if (!ServiceCacheRegistrar.TryGet(anchorType, out registrar, false)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationA, anchorType.ToString())); foreach (var registration in registrar.All) registrationDispatcher.Remove(cache, registration); } /// <summary> /// Removes the specified cache. /// </summary> /// <param name="cache">The cache.</param> /// <param name="registration">The registration.</param> public static void Remove(this IServiceCache cache, ServiceCacheRegistration registration) { if (registration == null) throw new ArgumentNullException("registration"); var registrationDispatcher = GetRegistrationDispatcher(cache); // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(registration, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationA, registration.ToString())); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); registrationDispatcher.Remove(cache, foundRegistration); } /// <summary> /// Removes the specified cache. /// </summary> /// <param name="cache">The cache.</param> /// <param name="anchorType">Type of the anchor.</param> /// <param name="registrationName">Name of the registration.</param> public static void Remove(this IServiceCache cache, Type anchorType, string registrationName) { if (anchorType == null) throw new ArgumentNullException("anchorType"); if (string.IsNullOrEmpty(registrationName)) throw new ArgumentNullException("registrationName"); var registrationDispatcher = GetRegistrationDispatcher(cache); // fetch registration var recurses = 0; IServiceCacheRegistration foundRegistration; if (!ServiceCacheRegistrar.TryGetValue(anchorType, registrationName, ref recurses, out foundRegistration)) throw new InvalidOperationException(string.Format(Local.UndefinedServiceCacheRegistrationAB, anchorType.ToString(), registrationName)); if (foundRegistration is ServiceCacheForeignRegistration) throw new InvalidOperationException(Local.InvalidDataSource); registrationDispatcher.Remove(cache, foundRegistration); } private static ServiceCacheRegistration.IDispatcher GetRegistrationDispatcher(IServiceCache cache) { var settings = cache.Settings; if (settings == null) throw new NullReferenceException("settings"); var registrationDispatcher = settings.RegistrationDispatcher; if (registrationDispatcher == null) throw new NullReferenceException("cache.Settings.RegistrationDispatch"); return registrationDispatcher; } #endregion #region Lazy Setup /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator<T>(this Lazy<IServiceCache> service) where T : class, IServiceCache { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, ServiceLocatorManager.Lazy, null); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="name">The name.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator<T>(this Lazy<IServiceCache> service, string name) where T : class, IServiceCache { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, ServiceLocatorManager.Lazy, name); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator<T>(this Lazy<IServiceCache> service, Lazy<IServiceLocator> locator) where T : class, IServiceCache { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, null); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <param name="name">The name.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator<T>(this Lazy<IServiceCache> service, Lazy<IServiceLocator> locator, string name) where T : class, IServiceCache { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, name); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator(this Lazy<IServiceCache> service) { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, ServiceLocatorManager.Lazy, null); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="name">The name.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator(this Lazy<IServiceCache> service, string name) { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, ServiceLocatorManager.Lazy, name); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator(this Lazy<IServiceCache> service, Lazy<IServiceLocator> locator) { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, null); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <param name="name">The name.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator(this Lazy<IServiceCache> service, Lazy<IServiceLocator> locator, string name) { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, name); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator<T>(this Lazy<IServiceCache> service, IServiceLocator locator) where T : class, IServiceCache { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, null); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <param name="name">The name.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator<T>(this Lazy<IServiceCache> service, IServiceLocator locator, string name) where T : class, IServiceCache { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator<T>(service, locator, name); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator(this Lazy<IServiceCache> service, IServiceLocator locator) { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, null); return service; } /// <summary> /// Registers the with service locator. /// </summary> /// <param name="service">The service.</param> /// <param name="locator">The locator.</param> /// <param name="name">The name.</param> /// <returns></returns> public static Lazy<IServiceCache> RegisterWithServiceLocator(this Lazy<IServiceCache> service, IServiceLocator locator, string name) { ServiceCacheManager.GetSetupDescriptor(service).RegisterWithServiceLocator(service, locator, name); return service; } #endregion } }
using IuriiO.Apps.Avidoc.Models; using IuriiO.Apps.Avidoc.Services.CategoryServices; using IuriiO.Apps.Avidoc.Services.ItemServices; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; using Template10.Mvvm; using Template10.Services.LoggingService; using Template10.Services.NavigationService; using Windows.UI.Popups; using Windows.UI.Xaml.Media.Animation; using Windows.UI.Xaml.Navigation; using System; using Windows.Storage; using System.IO; using Windows.Storage.Pickers; using IuriiO.Apps.Avidoc.Services.ImportServices; namespace IuriiO.Apps.Avidoc.ViewModels { public class MainPageViewModel : ViewModelBase { private ICategoryService categoryService; private IItemService itemService; private IImportService importService; private Category currentCategory; public ObservableCollection<BrowsableItemViewModel> Items { get; set; } public String Title { get; set; } public MainPageViewModel(ICategoryService categoryService, IItemService itemService, IImportService importService) { this.categoryService = categoryService; this.itemService = itemService; this.importService = importService; this.Items = new ObservableCollection<BrowsableItemViewModel>(); } public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState) { string id = parameter as string; if (mode == NavigationMode.Back) { id = suspensionState["ID"] as string; } // If ID was null for whatever reason reset to root. if (String.IsNullOrWhiteSpace(id)) { id = Category.ROOT_ID; } LoggingService.WriteLine("Navigated with parameter: " + parameter); this.currentCategory = this.categoryService.GetCategory(id); RefreshCategory(this.currentCategory); await Task.CompletedTask; } private void RefreshCategory(Category c) { this.Items.Clear(); if (c != null) { this.Title = c.Title; if (c.ChildItems != null) { foreach (var item in c.ChildItems) { this.Items.Add(new BrowsableItemViewModel(item)); } } if (c.ChildCategories != null) { foreach (var category in c.ChildCategories) { this.Items.Add(new BrowsableItemViewModel(category)); } } } this.RaisePropertyChanged(nameof(this.Items)); this.RaisePropertyChanged(nameof(this.Title)); } private DelegateCommand<BrowsableItemViewModel> selectItemCommand; public DelegateCommand<BrowsableItemViewModel> SelectItemCommand => this.selectItemCommand ?? (this.selectItemCommand = new DelegateCommand<BrowsableItemViewModel>( (p) => this.onItemSelectedAsync(p), (c) => true)); private DelegateCommand<BrowsableItemViewModel> deleteSelectedCommand; public DelegateCommand<BrowsableItemViewModel> DeleteSelectedCommand => this.deleteSelectedCommand ?? (this.deleteSelectedCommand = new DelegateCommand<BrowsableItemViewModel>( (c) => this.onDeleteSelectedAsync(c), (c) => this.onCanDeleteSelected())); private async void onDeleteSelectedAsync(BrowsableItemViewModel model) { var message = new MessageDialog(model.Description); await message.ShowAsync(); } private bool onCanDeleteSelected() { return true; } private async void onItemSelectedAsync(BrowsableItemViewModel p) { LoggingService.WriteLine("Received: " + p); if (p.IsCategory) { NavigationService.Navigate(PageRegistry.Pages.Main, p.Id, new SuppressNavigationTransitionInfo()); } else { NavigationService.Navigate(PageRegistry.Pages.ItemView, p.Id, new SuppressNavigationTransitionInfo()); } } public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending) { suspensionState["ID"] = this.currentCategory.Id; await Task.CompletedTask; } public override async Task OnNavigatingFromAsync(NavigatingEventArgs args) { args.Cancel = false; await Task.CompletedTask; } public async void DeleteAsync() { if (this.currentCategory == null || this.currentCategory.Id == null || this.currentCategory.Parent == null) { return; } this.categoryService.Delete(this.currentCategory); NavigationService.GoBack(); } public async void AddNewAsync() { var category = this.categoryService.New(); category.Title = "Category " + Guid.NewGuid().ToString().Substring(0, 4); category.Parent = this.currentCategory; this.categoryService.SaveCategory(category); this.currentCategory = this.categoryService.GetCategory(this.currentCategory.Id); this.RefreshCategory(this.currentCategory); } public async void EditAsync() { await new MessageDialog(this.currentCategory.Title).ShowAsync(); } public async void ImportAsync() { var openPicker = new FileOpenPicker(); openPicker.SuggestedStartLocation = PickerLocationId.Desktop; openPicker.FileTypeFilter.Add(".pdf"); var source = await openPicker.PickSingleFileAsync(); var sourceExt = Path.GetExtension(source.Path); var savePicker = new FileSavePicker(); savePicker.DefaultFileExtension = sourceExt; savePicker.SuggestedFileName = source.Name; savePicker.FileTypeChoices.Add("Import", new List<string>() { sourceExt }); savePicker.SuggestedStartLocation = PickerLocationId.Desktop; StorageFile destination = await savePicker.PickSaveFileAsync(); this.importService.ImportFile(this.currentCategory, source, destination); this.currentCategory = this.categoryService.GetCategory(this.currentCategory.Id); this.RefreshCategory(this.currentCategory); } public async void ImportAllAsync() { // TODO: Same as ImportAsync, but should import all files in the directory. } public void GotoDetailsPage() => NavigationService.Navigate(PageRegistry.Pages.ItemView, "", new SuppressNavigationTransitionInfo()); public void GotoSettings() => NavigationService.Navigate(PageRegistry.Pages.Settings, 0); public void GotoPrivacy() => NavigationService.Navigate(PageRegistry.Pages.Settings, 1); public void GotoAbout() => NavigationService.Navigate(PageRegistry.Pages.Settings, 2); } }
// // Pop3Engine.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.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.IO; using System.Text; using System.Threading; using System.Collections.Generic; #if NETFX_CORE using Encoding = Portable.Text.Encoding; using EncoderExceptionFallback = Portable.Text.EncoderExceptionFallback; using DecoderExceptionFallback = Portable.Text.DecoderExceptionFallback; using DecoderFallbackException = Portable.Text.DecoderFallbackException; #endif namespace MailKit.Net.Pop3 { /// <summary> /// The state of the <see cref="Pop3Engine"/>. /// </summary> enum Pop3EngineState { /// <summary> /// The Pop3Engine is in the disconnected state. /// </summary> Disconnected, /// <summary> /// The Pop3Engine is in the connected state. /// </summary> Connected, /// <summary> /// The Pop3Engine is in the transaction state, indicating that it is /// authenticated and may retrieve messages from the server. /// </summary> Transaction } /// <summary> /// A POP3 command engine. /// </summary> class Pop3Engine { static readonly Encoding UTF8 = Encoding.GetEncoding (65001, new EncoderExceptionFallback (), new DecoderExceptionFallback ()); static readonly Encoding Latin1 = Encoding.GetEncoding (28591); readonly List<Pop3Command> queue; Pop3Stream stream; int nextId; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Net.Pop3.Pop3Engine"/> class. /// </summary> public Pop3Engine () { AuthenticationMechanisms = new HashSet<string> (); Capabilities = Pop3Capabilities.User; queue = new List<Pop3Command> (); nextId = 1; } /// <summary> /// Gets the URI of the POP3 server. /// </summary> /// <remarks> /// Gets the URI of the POP3 server. /// </remarks> /// <value>The URI of the POP3 server.</value> public Uri Uri { get; internal set; } /// <summary> /// Gets the authentication mechanisms supported by the POP3 server. /// </summary> /// <remarks> /// The authentication mechanisms are queried durring the /// <see cref="Connect"/> method. /// </remarks> /// <value>The authentication mechanisms.</value> public HashSet<string> AuthenticationMechanisms { get; private set; } /// <summary> /// Gets the capabilities supported by the POP3 server. /// </summary> /// <remarks> /// The capabilities will not be known until a successful connection /// has been made via the <see cref="Connect"/> method. /// </remarks> /// <value>The capabilities.</value> public Pop3Capabilities Capabilities { get; set; } /// <summary> /// Gets the underlying POP3 stream. /// </summary> /// <remarks> /// Gets the underlying POP3 stream. /// </remarks> /// <value>The pop3 stream.</value> public Pop3Stream Stream { get { return stream; } } /// <summary> /// Gets or sets the state of the engine. /// </summary> /// <remarks> /// Gets or sets the state of the engine. /// </remarks> /// <value>The engine state.</value> public Pop3EngineState State { get; internal set; } /// <summary> /// Gets whether or not the engine is currently connected to a POP3 server. /// </summary> /// <remarks> /// Gets whether or not the engine is currently connected to a POP3 server. /// </remarks> /// <value><c>true</c> if the engine is connected; otherwise, <c>false</c>.</value> public bool IsConnected { get { return stream != null && stream.IsConnected; } } /// <summary> /// Gets the APOP authentication token. /// </summary> /// <remarks> /// Gets the APOP authentication token. /// </remarks> /// <value>The APOP authentication token.</value> public string ApopToken { get; private set; } /// <summary> /// Gets the EXPIRE extension policy value. /// </summary> /// <remarks> /// Gets the EXPIRE extension policy value. /// </remarks> /// <value>The EXPIRE policy.</value> public int ExpirePolicy { get; private set; } /// <summary> /// Gets the implementation details of the server. /// </summary> /// <remarks> /// Gets the implementation details of the server. /// </remarks> /// <value>The implementation details.</value> public string Implementation { get; private set; } /// <summary> /// Gets the login delay. /// </summary> /// <remarks> /// Gets the login delay. /// </remarks> /// <value>The login delay.</value> public int LoginDelay { get; private set; } /// <summary> /// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting. /// </summary> /// <remarks> /// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting. /// </remarks> /// <param name="pop3">The pop3 stream.</param> /// <param name="cancellationToken">The cancellation token</param> public void Connect (Pop3Stream pop3, CancellationToken cancellationToken) { if (stream != null) stream.Dispose (); Capabilities = Pop3Capabilities.User; AuthenticationMechanisms.Clear (); State = Pop3EngineState.Disconnected; ApopToken = null; stream = pop3; // read the pop3 server greeting var greeting = ReadLine (cancellationToken).TrimEnd (); int index = greeting.IndexOf (' '); string token, text; if (index != -1) { token = greeting.Substring (0, index); while (index < greeting.Length && char.IsWhiteSpace (greeting[index])) index++; if (index < greeting.Length) text = greeting.Substring (index); else text = string.Empty; } else { text = string.Empty; token = greeting; } if (token != "+OK") { stream.Dispose (); stream = null; throw new Pop3ProtocolException (string.Format ("Unexpected greeting from server: {0}", greeting)); } index = text.IndexOf ('>'); if (text.Length > 0 && text[0] == '<' && index != -1) { ApopToken = text.Substring (0, index + 1); Capabilities |= Pop3Capabilities.Apop; } State = Pop3EngineState.Connected; } public event EventHandler<EventArgs> Disconnected; void OnDisconnected () { var handler = Disconnected; if (handler != null) handler (this, EventArgs.Empty); } /// <summary> /// Disconnects the <see cref="Pop3Engine"/>. /// </summary> /// <remarks> /// Disconnects the <see cref="Pop3Engine"/>. /// </remarks> public void Disconnect () { Uri = null; if (stream != null) { stream.Dispose (); stream = null; } if (State != Pop3EngineState.Disconnected) { State = Pop3EngineState.Disconnected; OnDisconnected (); } } /// <summary> /// Reads a single line from the <see cref="Pop3Stream"/>. /// </summary> /// <returns>The line.</returns> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.InvalidOperationException"> /// The engine is not connected. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public string ReadLine (CancellationToken cancellationToken) { if (stream == null) throw new InvalidOperationException (); using (var memory = new MemoryStream ()) { int offset, count; byte[] buf; while (!stream.ReadLine (out buf, out offset, out count, cancellationToken)) memory.Write (buf, offset, count); memory.Write (buf, offset, count); count = (int) memory.Length; #if !NETFX_CORE buf = memory.GetBuffer (); #else buf = memory.ToArray (); #endif // Trim the <CR><LF> sequence from the end of the line. if (buf[count - 1] == (byte) '\n') { count--; if (buf[count - 1] == (byte) '\r') count--; } try { return UTF8.GetString (buf, 0, count); } catch (DecoderFallbackException) { return Latin1.GetString (buf, 0, count); } } } public static Pop3CommandStatus GetCommandStatus (string response, out string text) { int index = response.IndexOf (' '); string token; if (index != -1) { token = response.Substring (0, index); while (index < response.Length && char.IsWhiteSpace (response[index])) index++; if (index < response.Length) text = response.Substring (index); else text = string.Empty; } else { text = string.Empty; token = response; } if (token == "+OK") return Pop3CommandStatus.Ok; if (token == "-ERR") return Pop3CommandStatus.Error; if (token == "+") return Pop3CommandStatus.Continue; return Pop3CommandStatus.ProtocolError; } void SendCommand (Pop3Command pc) { var buf = Encoding.UTF8.GetBytes (pc.Command + "\r\n"); stream.Write (buf, 0, buf.Length); } void ReadResponse (Pop3Command pc) { string response, text; try { response = ReadLine (pc.CancellationToken).TrimEnd (); } catch { pc.Status = Pop3CommandStatus.ProtocolError; Disconnect (); throw; } pc.Status = GetCommandStatus (response, out text); pc.StatusText = text; switch (pc.Status) { case Pop3CommandStatus.ProtocolError: Disconnect (); throw new Pop3ProtocolException (string.Format ("Unexpected response from server: {0}", response)); case Pop3CommandStatus.Continue: case Pop3CommandStatus.Ok: if (pc.Handler != null) { try { pc.Handler (this, pc, text); } catch { pc.Status = Pop3CommandStatus.ProtocolError; Disconnect (); throw; } } break; } } public int Iterate () { if (stream == null) throw new InvalidOperationException (); if (queue.Count == 0) return 0; int count = (Capabilities & Pop3Capabilities.Pipelining) != 0 ? queue.Count : 1; var cancellationToken = queue[0].CancellationToken; var active = new List<Pop3Command> (); if (cancellationToken.IsCancellationRequested) { queue.RemoveAll (x => x.CancellationToken.IsCancellationRequested); cancellationToken.ThrowIfCancellationRequested (); } for (int i = 0; i < count; i++) { var pc = queue[0]; if (i > 0 && !pc.CancellationToken.Equals (cancellationToken)) break; queue.RemoveAt (0); pc.Status = Pop3CommandStatus.Active; active.Add (pc); SendCommand (pc); } stream.Flush (cancellationToken); for (int i = 0; i < active.Count; i++) ReadResponse (active[i]); return active[active.Count - 1].Id; } public Pop3Command QueueCommand (CancellationToken cancellationToken, Pop3CommandHandler handler, string format, params object[] args) { var pc = new Pop3Command (cancellationToken, handler, format, args); pc.Id = nextId++; queue.Add (pc); return pc; } static void CapaHandler (Pop3Engine engine, Pop3Command pc, string text) { if (pc.Status != Pop3CommandStatus.Ok) return; string response; do { if ((response = engine.ReadLine (pc.CancellationToken)) == ".") break; int index = response.IndexOf (' '); string token, data; int value; if (index != -1) { token = response.Substring (0, index); while (index < response.Length && char.IsWhiteSpace (response[index])) index++; if (index < response.Length) data = response.Substring (index); else data = string.Empty; } else { data = string.Empty; token = response; } switch (token) { case "EXPIRE": engine.Capabilities |= Pop3Capabilities.Expire; var tokens = data.Split (' '); if (int.TryParse (tokens[0], out value)) engine.ExpirePolicy = value; else if (tokens[0] == "NEVER") engine.ExpirePolicy = -1; break; case "IMPLEMENTATION": engine.Implementation = data; break; case "LOGIN-DELAY": if (int.TryParse (data, out value)) { engine.Capabilities |= Pop3Capabilities.LoginDelay; engine.LoginDelay = value; } break; case "PIPELINING": engine.Capabilities |= Pop3Capabilities.Pipelining; break; case "RESP-CODES": engine.Capabilities |= Pop3Capabilities.ResponseCodes; break; case "SASL": engine.Capabilities |= Pop3Capabilities.Sasl; foreach (var authmech in data.Split (new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) engine.AuthenticationMechanisms.Add (authmech); break; case "STLS": engine.Capabilities |= Pop3Capabilities.StartTLS; break; case "TOP": engine.Capabilities |= Pop3Capabilities.Top; break; case "UIDL": engine.Capabilities |= Pop3Capabilities.UIDL; break; case "USER": engine.Capabilities |= Pop3Capabilities.User; break; case "UTF8": engine.Capabilities |= Pop3Capabilities.UTF8; foreach (var item in data.Split (' ')) { if (item == "USER") engine.Capabilities |= Pop3Capabilities.UTF8User; } break; case "LANG": engine.Capabilities |= Pop3Capabilities.Lang; break; } } while (true); } public Pop3CommandStatus QueryCapabilities (CancellationToken cancellationToken) { if (stream == null) throw new InvalidOperationException (); // clear all CAPA response capabilities (except the APOP capability) Capabilities &= Pop3Capabilities.Apop; AuthenticationMechanisms.Clear (); Implementation = null; ExpirePolicy = 0; LoginDelay = 0; var pc = QueueCommand (cancellationToken, CapaHandler, "CAPA"); while (Iterate () < pc.Id) { // continue processing commands... } return pc.Status; } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; namespace OpenTK.Graphics.ES20 { #pragma warning disable 1591 public enum ActiveAttribType : int { Float = ((int)0X1406), FloatVec2 = ((int)0X8b50), FloatVec3 = ((int)0X8b51), FloatVec4 = ((int)0X8b52), FloatMat2 = ((int)0X8b5a), FloatMat3 = ((int)0X8b5b), FloatMat4 = ((int)0X8b5c), } public enum ActiveUniformType : int { Int = ((int)0X1404), Float = ((int)0X1406), FloatVec2 = ((int)0X8b50), FloatVec3 = ((int)0X8b51), FloatVec4 = ((int)0X8b52), IntVec2 = ((int)0X8b53), IntVec3 = ((int)0X8b54), IntVec4 = ((int)0X8b55), Bool = ((int)0X8b56), BoolVec2 = ((int)0X8b57), BoolVec3 = ((int)0X8b58), BoolVec4 = ((int)0X8b59), FloatMat2 = ((int)0X8b5a), FloatMat3 = ((int)0X8b5b), FloatMat4 = ((int)0X8b5c), Sampler2D = ((int)0X8b5e), SamplerCube = ((int)0X8b60), } public enum All : int { False = ((int)0), NoError = ((int)0), None = ((int)0), Zero = ((int)0), Points = ((int)0x0000), ColorBufferBit0Qcom = ((int)0x00000001), ColorBufferBit1Qcom = ((int)0x00000002), ColorBufferBit2Qcom = ((int)0x00000004), ColorBufferBit3Qcom = ((int)0x00000008), ColorBufferBit4Qcom = ((int)0x00000010), ColorBufferBit5Qcom = ((int)0x00000020), ColorBufferBit6Qcom = ((int)0x00000040), ColorBufferBit7Qcom = ((int)0x00000080), DepthBufferBit = ((int)0x00000100), DepthBufferBit0Qcom = ((int)0x00000100), DepthBufferBit1Qcom = ((int)0x00000200), DepthBufferBit2Qcom = ((int)0x00000400), StencilBufferBit = ((int)0x00000400), DepthBufferBit3Qcom = ((int)0x00000800), DepthBufferBit4Qcom = ((int)0x00001000), DepthBufferBit5Qcom = ((int)0x00002000), ColorBufferBit = ((int)0x00004000), DepthBufferBit6Qcom = ((int)0x00004000), DepthBufferBit7Qcom = ((int)0x00008000), Lines = ((int)0x0001), StencilBufferBit0Qcom = ((int)0x00010000), LineLoop = ((int)0x0002), StencilBufferBit1Qcom = ((int)0x00020000), LineStrip = ((int)0x0003), Triangles = ((int)0x0004), StencilBufferBit2Qcom = ((int)0x00040000), TriangleStrip = ((int)0x0005), TriangleFan = ((int)0x0006), StencilBufferBit3Qcom = ((int)0x00080000), StencilBufferBit4Qcom = ((int)0x00100000), StencilBufferBit5Qcom = ((int)0x00200000), StencilBufferBit6Qcom = ((int)0x00400000), StencilBufferBit7Qcom = ((int)0x00800000), MultisampleBufferBit0Qcom = ((int)0x01000000), Never = ((int)0x0200), MultisampleBufferBit1Qcom = ((int)0x02000000), Less = ((int)0x0201), Equal = ((int)0x0202), Lequal = ((int)0x0203), Greater = ((int)0x0204), Notequal = ((int)0x0205), Gequal = ((int)0x0206), Always = ((int)0x0207), SrcColor = ((int)0x0300), OneMinusSrcColor = ((int)0x0301), SrcAlpha = ((int)0x0302), OneMinusSrcAlpha = ((int)0x0303), DstAlpha = ((int)0x0304), OneMinusDstAlpha = ((int)0x0305), DstColor = ((int)0x0306), OneMinusDstColor = ((int)0x0307), SrcAlphaSaturate = ((int)0x0308), MultisampleBufferBit2Qcom = ((int)0x04000000), Front = ((int)0x0404), Back = ((int)0x0405), FrontAndBack = ((int)0x0408), InvalidEnum = ((int)0x0500), InvalidValue = ((int)0x0501), InvalidOperation = ((int)0x0502), OutOfMemory = ((int)0x0505), InvalidFramebufferOperation = ((int)0x0506), MultisampleBufferBit3Qcom = ((int)0x08000000), Cw = ((int)0x0900), Ccw = ((int)0x0901), LineWidth = ((int)0x0B21), CullFace = ((int)0x0B44), CullFaceMode = ((int)0x0B45), FrontFace = ((int)0x0B46), DepthRange = ((int)0x0B70), DepthTest = ((int)0x0B71), DepthWritemask = ((int)0x0B72), DepthClearValue = ((int)0x0B73), DepthFunc = ((int)0x0B74), StencilTest = ((int)0x0B90), StencilClearValue = ((int)0x0B91), StencilFunc = ((int)0x0B92), StencilValueMask = ((int)0x0B93), StencilFail = ((int)0x0B94), StencilPassDepthFail = ((int)0x0B95), StencilPassDepthPass = ((int)0x0B96), StencilRef = ((int)0x0B97), StencilWritemask = ((int)0x0B98), Viewport = ((int)0x0BA2), Dither = ((int)0x0BD0), Blend = ((int)0x0BE2), ScissorBox = ((int)0x0C10), ScissorTest = ((int)0x0C11), ColorClearValue = ((int)0x0C22), ColorWritemask = ((int)0x0C23), UnpackAlignment = ((int)0x0CF5), PackAlignment = ((int)0x0D05), MaxTextureSize = ((int)0x0D33), MaxViewportDims = ((int)0x0D3A), SubpixelBits = ((int)0x0D50), RedBits = ((int)0x0D52), GreenBits = ((int)0x0D53), BlueBits = ((int)0x0D54), AlphaBits = ((int)0x0D55), DepthBits = ((int)0x0D56), StencilBits = ((int)0x0D57), Texture2D = ((int)0x0DE1), MultisampleBufferBit4Qcom = ((int)0x10000000), DontCare = ((int)0x1100), Fastest = ((int)0x1101), Nicest = ((int)0x1102), Byte = ((int)0x1400), UnsignedByte = ((int)0x1401), Short = ((int)0x1402), UnsignedShort = ((int)0x1403), Int = ((int)0x1404), UnsignedInt = ((int)0x1405), Float = ((int)0x1406), Fixed = ((int)0x140C), Invert = ((int)0x150A), Texture = ((int)0x1702), ColorExt = ((int)0x1800), DepthExt = ((int)0x1801), StencilExt = ((int)0x1802), StencilIndex = ((int)0x1901), DepthComponent = ((int)0x1902), Alpha = ((int)0x1906), Rgb = ((int)0x1907), Rgba = ((int)0x1908), Luminance = ((int)0x1909), LuminanceAlpha = ((int)0x190A), Keep = ((int)0x1E00), Replace = ((int)0x1E01), Incr = ((int)0x1E02), Decr = ((int)0x1E03), Vendor = ((int)0x1F00), Renderer = ((int)0x1F01), Version = ((int)0x1F02), Extensions = ((int)0x1F03), MultisampleBufferBit5Qcom = ((int)0x20000000), Nearest = ((int)0x2600), Linear = ((int)0x2601), NearestMipmapNearest = ((int)0x2700), LinearMipmapNearest = ((int)0x2701), NearestMipmapLinear = ((int)0x2702), LinearMipmapLinear = ((int)0x2703), TextureMagFilter = ((int)0x2800), TextureMinFilter = ((int)0x2801), TextureWrapS = ((int)0x2802), TextureWrapT = ((int)0x2803), Repeat = ((int)0x2901), PolygonOffsetUnits = ((int)0x2A00), MultisampleBufferBit6Qcom = ((int)0x40000000), CoverageBufferBitNv = ((int)0x8000), MultisampleBufferBit7Qcom = unchecked((int)0x80000000), ConstantColor = ((int)0x8001), OneMinusConstantColor = ((int)0x8002), ConstantAlpha = ((int)0x8003), OneMinusConstantAlpha = ((int)0x8004), BlendColor = ((int)0x8005), FuncAdd = ((int)0x8006), MinExt = ((int)0x8007), MaxExt = ((int)0x8008), BlendEquation = ((int)0x8009), BlendEquationRgb = ((int)0X8009), FuncSubtract = ((int)0x800A), FuncReverseSubtract = ((int)0x800B), UnsignedShort4444 = ((int)0x8033), UnsignedShort5551 = ((int)0x8034), PolygonOffsetFill = ((int)0x8037), PolygonOffsetFactor = ((int)0x8038), Rgb8Oes = ((int)0x8051), Rgba4 = ((int)0x8056), Rgb5A1 = ((int)0x8057), Rgba8Oes = ((int)0x8058), TextureBinding2D = ((int)0x8069), TextureBinding3DOes = ((int)0x806A), Texture3DOes = ((int)0x806F), TextureWrapROes = ((int)0x8072), Max3DTextureSizeOes = ((int)0x8073), SampleAlphaToCoverage = ((int)0x809E), SampleCoverage = ((int)0x80A0), SampleBuffers = ((int)0x80A8), Samples = ((int)0x80A9), SampleCoverageValue = ((int)0x80AA), SampleCoverageInvert = ((int)0x80AB), BlendDstRgb = ((int)0x80C8), BlendSrcRgb = ((int)0x80C9), BlendDstAlpha = ((int)0x80CA), BlendSrcAlpha = ((int)0x80CB), BgraExt = ((int)0x80E1), BgraImg = ((int)0x80E1), ClampToEdge = ((int)0x812F), TextureMaxLevelApple = ((int)0x813D), GenerateMipmapHint = ((int)0x8192), DepthComponent16 = ((int)0x81A5), DepthComponent24Oes = ((int)0x81A6), DepthComponent32Oes = ((int)0x81A7), UnsignedShort565 = ((int)0x8363), UnsignedShort4444RevExt = ((int)0x8365), UnsignedShort4444RevImg = ((int)0x8365), UnsignedShort1555RevExt = ((int)0x8366), UnsignedInt2101010RevExt = ((int)0x8368), MirroredRepeat = ((int)0x8370), CompressedRgbS3tcDxt1Ext = ((int)0x83F0), CompressedRgbaS3tcDxt1Ext = ((int)0x83F1), AliasedPointSizeRange = ((int)0x846D), AliasedLineWidthRange = ((int)0x846E), Texture0 = ((int)0x84C0), Texture1 = ((int)0x84C1), Texture2 = ((int)0x84C2), Texture3 = ((int)0x84C3), Texture4 = ((int)0x84C4), Texture5 = ((int)0x84C5), Texture6 = ((int)0x84C6), Texture7 = ((int)0x84C7), Texture8 = ((int)0x84C8), Texture9 = ((int)0x84C9), Texture10 = ((int)0x84CA), Texture11 = ((int)0x84CB), Texture12 = ((int)0x84CC), Texture13 = ((int)0x84CD), Texture14 = ((int)0x84CE), Texture15 = ((int)0x84CF), Texture16 = ((int)0x84D0), Texture17 = ((int)0x84D1), Texture18 = ((int)0x84D2), Texture19 = ((int)0x84D3), Texture20 = ((int)0x84D4), Texture21 = ((int)0x84D5), Texture22 = ((int)0x84D6), Texture23 = ((int)0x84D7), Texture24 = ((int)0x84D8), Texture25 = ((int)0x84D9), Texture26 = ((int)0x84DA), Texture27 = ((int)0x84DB), Texture28 = ((int)0x84DC), Texture29 = ((int)0x84DD), Texture30 = ((int)0x84DE), Texture31 = ((int)0x84DF), ActiveTexture = ((int)0x84E0), MaxRenderbufferSize = ((int)0x84E8), AllCompletedNv = ((int)0x84F2), FenceStatusNv = ((int)0x84F3), FenceConditionNv = ((int)0x84F4), DepthStencilOes = ((int)0x84F9), UnsignedInt248Oes = ((int)0x84FA), TextureMaxAnisotropyExt = ((int)0x84FE), MaxTextureMaxAnisotropyExt = ((int)0x84FF), IncrWrap = ((int)0x8507), DecrWrap = ((int)0x8508), TextureCubeMap = ((int)0x8513), TextureBindingCubeMap = ((int)0x8514), TextureCubeMapPositiveX = ((int)0x8515), TextureCubeMapNegativeX = ((int)0x8516), TextureCubeMapPositiveY = ((int)0x8517), TextureCubeMapNegativeY = ((int)0x8518), TextureCubeMapPositiveZ = ((int)0x8519), TextureCubeMapNegativeZ = ((int)0x851A), MaxCubeMapTextureSize = ((int)0x851C), VertexArrayBindingOes = ((int)0x85B5), UnsignedShort88Apple = ((int)0x85BA), UnsignedShort88RevApple = ((int)0x85BB), VertexAttribArrayEnabled = ((int)0x8622), VertexAttribArraySize = ((int)0x8623), VertexAttribArrayStride = ((int)0x8624), VertexAttribArrayType = ((int)0x8625), CurrentVertexAttrib = ((int)0x8626), VertexAttribArrayPointer = ((int)0x8645), NumCompressedTextureFormats = ((int)0x86A2), CompressedTextureFormats = ((int)0x86A3), Z400BinaryAmd = ((int)0x8740), ProgramBinaryLengthOes = ((int)0x8741), BufferSize = ((int)0x8764), BufferUsage = ((int)0x8765), AtcRgbaInterpolatedAlphaAmd = ((int)0x87EE), Gl3DcXAmd = ((int)0x87F9), Gl3DcXyAmd = ((int)0x87FA), NumProgramBinaryFormatsOes = ((int)0x87FE), ProgramBinaryFormatsOes = ((int)0x87FF), StencilBackFunc = ((int)0x8800), StencilBackFail = ((int)0x8801), StencilBackPassDepthFail = ((int)0x8802), StencilBackPassDepthPass = ((int)0x8803), WriteonlyRenderingQcom = ((int)0x8823), BlendEquationAlpha = ((int)0x883D), MaxVertexAttribs = ((int)0x8869), VertexAttribArrayNormalized = ((int)0x886A), MaxTextureImageUnits = ((int)0x8872), ArrayBuffer = ((int)0x8892), ElementArrayBuffer = ((int)0x8893), ArrayBufferBinding = ((int)0x8894), ElementArrayBufferBinding = ((int)0x8895), VertexAttribArrayBufferBinding = ((int)0x889F), WriteOnlyOes = ((int)0x88B9), BufferAccessOes = ((int)0x88BB), BufferMappedOes = ((int)0x88BC), BufferMapPointerOes = ((int)0x88BD), StreamDraw = ((int)0x88E0), StaticDraw = ((int)0x88E4), DynamicDraw = ((int)0x88E8), Depth24Stencil8Oes = ((int)0x88F0), Rgb422Apple = ((int)0x8A1F), FragmentShader = ((int)0x8B30), VertexShader = ((int)0x8B31), MaxVertexTextureImageUnits = ((int)0x8B4C), MaxCombinedTextureImageUnits = ((int)0x8B4D), ShaderType = ((int)0x8B4F), FloatVec2 = ((int)0x8B50), FloatVec3 = ((int)0x8B51), FloatVec4 = ((int)0x8B52), IntVec2 = ((int)0x8B53), IntVec3 = ((int)0x8B54), IntVec4 = ((int)0x8B55), Bool = ((int)0x8B56), BoolVec2 = ((int)0x8B57), BoolVec3 = ((int)0x8B58), BoolVec4 = ((int)0x8B59), FloatMat2 = ((int)0x8B5A), FloatMat3 = ((int)0x8B5B), FloatMat4 = ((int)0x8B5C), Sampler2D = ((int)0x8B5E), Sampler3DOes = ((int)0x8B5F), SamplerCube = ((int)0x8B60), DeleteStatus = ((int)0x8B80), CompileStatus = ((int)0x8B81), LinkStatus = ((int)0x8B82), ValidateStatus = ((int)0x8B83), InfoLogLength = ((int)0x8B84), AttachedShaders = ((int)0x8B85), ActiveUniforms = ((int)0x8B86), ActiveUniformMaxLength = ((int)0x8B87), ShaderSourceLength = ((int)0x8B88), ActiveAttributes = ((int)0x8B89), ActiveAttributeMaxLength = ((int)0x8B8A), FragmentShaderDerivativeHintOes = ((int)0x8B8B), ShadingLanguageVersion = ((int)0x8B8C), CurrentProgram = ((int)0x8B8D), Palette4Rgb8Oes = ((int)0x8B90), Palette4Rgba8Oes = ((int)0x8B91), Palette4R5G6B5Oes = ((int)0x8B92), Palette4Rgba4Oes = ((int)0x8B93), Palette4Rgb5A1Oes = ((int)0x8B94), Palette8Rgb8Oes = ((int)0x8B95), Palette8Rgba8Oes = ((int)0x8B96), Palette8R5G6B5Oes = ((int)0x8B97), Palette8Rgba4Oes = ((int)0x8B98), Palette8Rgb5A1Oes = ((int)0x8B99), ImplementationColorReadType = ((int)0x8B9A), ImplementationColorReadFormat = ((int)0x8B9B), CounterTypeAmd = ((int)0x8BC0), CounterRangeAmd = ((int)0x8BC1), UnsignedInt64Amd = ((int)0x8BC2), PercentageAmd = ((int)0x8BC3), PerfmonResultAvailableAmd = ((int)0x8BC4), PerfmonResultSizeAmd = ((int)0x8BC5), PerfmonResultAmd = ((int)0x8BC6), TextureWidthQcom = ((int)0x8BD2), TextureHeightQcom = ((int)0x8BD3), TextureDepthQcom = ((int)0x8BD4), TextureInternalFormatQcom = ((int)0x8BD5), TextureFormatQcom = ((int)0x8BD6), TextureTypeQcom = ((int)0x8BD7), TextureImageValidQcom = ((int)0x8BD8), TextureNumLevelsQcom = ((int)0x8BD9), TextureTargetQcom = ((int)0x8BDA), TextureObjectValidQcom = ((int)0x8BDB), StateRestore = ((int)0x8BDC), CompressedRgbPvrtc4Bppv1Img = ((int)0x8C00), CompressedRgbPvrtc2Bppv1Img = ((int)0x8C01), CompressedRgbaPvrtc4Bppv1Img = ((int)0x8C02), CompressedRgbaPvrtc2Bppv1Img = ((int)0x8C03), SgxBinaryImg = ((int)0x8C0A), AtcRgbAmd = ((int)0x8C92), AtcRgbaExplicitAlphaAmd = ((int)0x8C93), StencilBackRef = ((int)0x8CA3), StencilBackValueMask = ((int)0x8CA4), StencilBackWritemask = ((int)0x8CA5), DrawFramebufferBindingAngle = ((int)0x8CA6), DrawFramebufferBindingApple = ((int)0x8CA6), FramebufferBinding = ((int)0x8CA6), RenderbufferBinding = ((int)0x8CA7), ReadFramebufferAngle = ((int)0x8CA8), ReadFramebufferApple = ((int)0x8CA8), DrawFramebufferAngle = ((int)0x8CA9), DrawFramebufferApple = ((int)0x8CA9), ReadFramebufferBindingAngle = ((int)0x8CAA), ReadFramebufferBindingApple = ((int)0x8CAA), RenderbufferSamplesAngle = ((int)0x8CAB), RenderbufferSamplesApple = ((int)0x8CAB), FramebufferAttachmentObjectType = ((int)0x8CD0), FramebufferAttachmentObjectName = ((int)0x8CD1), FramebufferAttachmentTextureLevel = ((int)0x8CD2), FramebufferAttachmentTextureCubeMapFace = ((int)0x8CD3), FramebufferAttachmentTexture3DZoffsetOes = ((int)0x8CD4), FramebufferComplete = ((int)0x8CD5), FramebufferIncompleteAttachment = ((int)0x8CD6), FramebufferIncompleteMissingAttachment = ((int)0x8CD7), FramebufferIncompleteDimensions = ((int)0x8CD9), FramebufferUnsupported = ((int)0x8CDD), ColorAttachment0 = ((int)0x8CE0), DepthAttachment = ((int)0x8D00), StencilAttachment = ((int)0x8D20), Framebuffer = ((int)0x8D40), Renderbuffer = ((int)0x8D41), RenderbufferWidth = ((int)0x8D42), RenderbufferHeight = ((int)0x8D43), RenderbufferInternalFormat = ((int)0x8D44), StencilIndex1Oes = ((int)0x8D46), StencilIndex4Oes = ((int)0x8D47), StencilIndex8 = ((int)0x8D48), RenderbufferRedSize = ((int)0x8D50), RenderbufferGreenSize = ((int)0x8D51), RenderbufferBlueSize = ((int)0x8D52), RenderbufferAlphaSize = ((int)0x8D53), RenderbufferDepthSize = ((int)0x8D54), RenderbufferStencilSize = ((int)0x8D55), FramebufferIncompleteMultisampleAngle = ((int)0x8D56), FramebufferIncompleteMultisampleApple = ((int)0x8D56), MaxSamplesAngle = ((int)0x8D57), MaxSamplesApple = ((int)0x8D57), HalfFloatOes = ((int)0x8D61), Rgb565 = ((int)0x8D62), Etc1Rgb8Oes = ((int)0x8D64), LowFloat = ((int)0x8DF0), MediumFloat = ((int)0x8DF1), HighFloat = ((int)0x8DF2), LowInt = ((int)0x8DF3), MediumInt = ((int)0x8DF4), HighInt = ((int)0x8DF5), UnsignedInt1010102Oes = ((int)0x8DF6), Int1010102Oes = ((int)0x8DF7), ShaderBinaryFormats = ((int)0x8DF8), NumShaderBinaryFormats = ((int)0x8DF9), ShaderCompiler = ((int)0x8DFA), MaxVertexUniformVectors = ((int)0x8DFB), MaxVaryingVectors = ((int)0x8DFC), MaxFragmentUniformVectors = ((int)0x8DFD), DepthComponent16NonlinearNv = ((int)0x8E2C), CoverageComponentNv = ((int)0x8ED0), CoverageComponent4Nv = ((int)0x8ED1), CoverageAttachmentNv = ((int)0x8ED2), CoverageBuffersNv = ((int)0x8ED3), CoverageSamplesNv = ((int)0x8ED4), CoverageAllFragmentsNv = ((int)0x8ED5), CoverageEdgeFragmentsNv = ((int)0x8ED6), CoverageAutomaticNv = ((int)0x8ED7), MaliShaderBinaryArm = ((int)0x8F60), PerfmonGlobalModeQcom = ((int)0x8FA0), ShaderBinaryViv = ((int)0x8FC4), SgxProgramBinaryImg = ((int)0x9130), RenderbufferSamplesImg = ((int)0x9133), FramebufferIncompleteMultisampleImg = ((int)0x9134), MaxSamplesImg = ((int)0x9135), TextureSamplesImg = ((int)0x9136), AmdCompressed3DcTexture = ((int)1), AmdCompressedAtcTexture = ((int)1), AmdPerformanceMonitor = ((int)1), AmdProgramBinaryZ400 = ((int)1), AngleFramebufferBlit = ((int)1), AngleFramebufferMultisample = ((int)1), AppleFramebufferMultisample = ((int)1), AppleRgb422 = ((int)1), AppleTextureFormatBgra8888 = ((int)1), AppleTextureMaxLevel = ((int)1), ArmMaliShaderBinary = ((int)1), ArmRgba8 = ((int)1), EsVersion20 = ((int)1), ExtBlendMinmax = ((int)1), ExtDiscardFramebuffer = ((int)1), ExtMultiDrawArrays = ((int)1), ExtReadFormatBgra = ((int)1), ExtShaderTextureLod = ((int)1), ExtTextureCompressionDxt1 = ((int)1), ExtTextureFilterAnisotropic = ((int)1), ExtTextureFormatBgra8888 = ((int)1), ExtTextureType2101010Rev = ((int)1), ImgMultisampledRenderToTexture = ((int)1), ImgProgramBinary = ((int)1), ImgReadFormat = ((int)1), ImgShaderBinary = ((int)1), ImgTextureCompressionPvrtc = ((int)1), NvCoverageSample = ((int)1), NvDepthNonlinear = ((int)1), NvFence = ((int)1), OesCompressedEtc1Rgb8Texture = ((int)1), OesCompressedPalettedTexture = ((int)1), OesDepth24 = ((int)1), OesDepth32 = ((int)1), OesDepthTexture = ((int)1), OesEglImage = ((int)1), OesElementIndexUint = ((int)1), OesFboRenderMipmap = ((int)1), OesFragmentPrecisionHigh = ((int)1), OesGetProgramBinary = ((int)1), OesMapbuffer = ((int)1), OesPackedDepthStencil = ((int)1), OesRgb8Rgba8 = ((int)1), OesStandardDerivatives = ((int)1), OesStencil1 = ((int)1), OesStencil4 = ((int)1), OesTexture3D = ((int)1), OesTextureFloat = ((int)1), OesTextureFloatLinear = ((int)1), OesTextureHalfFloat = ((int)1), OesTextureHalfFloatLinear = ((int)1), OesTextureNpot = ((int)1), OesVertexArrayObject = ((int)1), OesVertexHalfFloat = ((int)1), OesVertexType1010102 = ((int)1), One = ((int)1), QcomDriverControl = ((int)1), QcomExtendedGet = ((int)1), QcomExtendedGet2 = ((int)1), QcomPerfmonGlobalMode = ((int)1), QcomTiledRendering = ((int)1), QcomWriteonlyRendering = ((int)1), True = ((int)1), VivShaderBinary = ((int)1), } public enum AmdCompressed3Dctexture : int { Gl3DcXAmd = ((int)0x87F9), Gl3DcXyAmd = ((int)0x87FA), AmdCompressed3DcTexture = ((int)1), } public enum AmdCompressedAtctexture : int { AtcRgbaInterpolatedAlphaAmd = ((int)0x87EE), AtcRgbAmd = ((int)0x8C92), AtcRgbaExplicitAlphaAmd = ((int)0x8C93), AmdCompressedAtcTexture = ((int)1), } public enum AmdPerformanceMonitor : int { CounterTypeAmd = ((int)0x8BC0), CounterRangeAmd = ((int)0x8BC1), UnsignedInt64Amd = ((int)0x8BC2), PercentageAmd = ((int)0x8BC3), PerfmonResultAvailableAmd = ((int)0x8BC4), PerfmonResultSizeAmd = ((int)0x8BC5), PerfmonResultAmd = ((int)0x8BC6), AmdPerformanceMonitor = ((int)1), } public enum AmdProgramBinaryZ400 : int { Z400BinaryAmd = ((int)0x8740), AmdProgramBinaryZ400 = ((int)1), } public enum AngleFramebufferBlit : int { DrawFramebufferBindingAngle = ((int)0x8CA6), ReadFramebufferAngle = ((int)0x8CA8), DrawFramebufferAngle = ((int)0x8CA9), ReadFramebufferBindingAngle = ((int)0x8CAA), AngleFramebufferBlit = ((int)1), } public enum AngleFramebufferMultisample : int { RenderbufferSamplesAngle = ((int)0x8CAB), FramebufferIncompleteMultisampleAngle = ((int)0x8D56), MaxSamplesAngle = ((int)0x8D57), AngleFramebufferMultisample = ((int)1), } public enum AppleFramebufferMultisample : int { DrawFramebufferBindingApple = ((int)0x8CA6), ReadFramebufferApple = ((int)0x8CA8), DrawFramebufferApple = ((int)0x8CA9), ReadFramebufferBindingApple = ((int)0x8CAA), RenderbufferSamplesApple = ((int)0x8CAB), FramebufferIncompleteMultisampleApple = ((int)0x8D56), MaxSamplesApple = ((int)0x8D57), AppleFramebufferMultisample = ((int)1), } public enum AppleRgb422 : int { UnsignedShort88Apple = ((int)0x85BA), UnsignedShort88RevApple = ((int)0x85BB), Rgb422Apple = ((int)0x8A1F), AppleRgb422 = ((int)1), } public enum AppleTextureFormatBgra8888 : int { BgraExt = ((int)0x80E1), AppleTextureFormatBgra8888 = ((int)1), } public enum AppleTextureMaxLevel : int { TextureMaxLevelApple = ((int)0x813D), AppleTextureMaxLevel = ((int)1), } public enum ArmMaliShaderBinary : int { MaliShaderBinaryArm = ((int)0x8F60), ArmMaliShaderBinary = ((int)1), } public enum ArmRgba8 : int { ArmRgba8 = ((int)1), } public enum BeginMode : int { Points = ((int)0x0000), Lines = ((int)0x0001), LineLoop = ((int)0x0002), LineStrip = ((int)0x0003), Triangles = ((int)0x0004), TriangleStrip = ((int)0x0005), TriangleFan = ((int)0x0006), } public enum BlendEquationMode : int { FuncAdd = ((int)0X8006), FuncSubtract = ((int)0X800a), FuncReverseSubtract = ((int)0X800b), } public enum BlendEquationSeparate : int { FuncAdd = ((int)0x8006), BlendEquation = ((int)0x8009), BlendEquationAlpha = ((int)0x883D), } public enum BlendingFactorDest : int { Zero = ((int)0), SrcColor = ((int)0x0300), OneMinusSrcColor = ((int)0x0301), SrcAlpha = ((int)0x0302), OneMinusSrcAlpha = ((int)0x0303), DstAlpha = ((int)0x0304), OneMinusDstAlpha = ((int)0x0305), DstColor = ((int)0X0306), OneMinusDstColor = ((int)0X0307), SrcAlphaSaturate = ((int)0X0308), ConstantColor = ((int)0X8001), OneMinusConstantColor = ((int)0X8002), ConstantAlpha = ((int)0X8003), OneMinusConstantAlpha = ((int)0X8004), One = ((int)1), } public enum BlendingFactorSrc : int { Zero = ((int)0), SrcColor = ((int)0X0300), OneMinusSrcColor = ((int)0X0301), SrcAlpha = ((int)0X0302), OneMinusSrcAlpha = ((int)0X0303), DstAlpha = ((int)0X0304), OneMinusDstAlpha = ((int)0X0305), DstColor = ((int)0x0306), OneMinusDstColor = ((int)0x0307), SrcAlphaSaturate = ((int)0x0308), ConstantColor = ((int)0X8001), OneMinusConstantColor = ((int)0X8002), ConstantAlpha = ((int)0X8003), OneMinusConstantAlpha = ((int)0X8004), One = ((int)1), } public enum BlendSubtract : int { FuncSubtract = ((int)0x800A), FuncReverseSubtract = ((int)0x800B), } public enum Boolean : int { False = ((int)0), True = ((int)1), } public enum BufferObjects : int { CurrentVertexAttrib = ((int)0x8626), BufferSize = ((int)0x8764), BufferUsage = ((int)0x8765), ArrayBuffer = ((int)0x8892), ElementArrayBuffer = ((int)0x8893), ArrayBufferBinding = ((int)0x8894), ElementArrayBufferBinding = ((int)0x8895), StreamDraw = ((int)0x88E0), StaticDraw = ((int)0x88E4), DynamicDraw = ((int)0x88E8), } public enum BufferParameterName : int { BufferSize = ((int)0X8764), BufferUsage = ((int)0X8765), } public enum BufferTarget : int { ArrayBuffer = ((int)0X8892), ElementArrayBuffer = ((int)0X8893), } public enum BufferUsage : int { StreamDraw = ((int)0X88e0), StaticDraw = ((int)0X88e4), DynamicDraw = ((int)0X88e8), } [Flags] public enum ClearBufferMask : int { DepthBufferBit = ((int)0x00000100), StencilBufferBit = ((int)0x00000400), ColorBufferBit = ((int)0x00004000), } public enum CullFaceMode : int { Front = ((int)0x0404), Back = ((int)0x0405), FrontAndBack = ((int)0x0408), } public enum DataType : int { Byte = ((int)0x1400), UnsignedByte = ((int)0x1401), Short = ((int)0x1402), UnsignedShort = ((int)0x1403), Int = ((int)0x1404), UnsignedInt = ((int)0x1405), Float = ((int)0x1406), Fixed = ((int)0x140C), } public enum DepthFunction : int { Never = ((int)0X0200), Less = ((int)0X0201), Equal = ((int)0X0202), Lequal = ((int)0X0203), Greater = ((int)0X0204), Notequal = ((int)0X0205), Gequal = ((int)0X0206), Always = ((int)0X0207), } public enum DrawElementsType : int { UnsignedByte = ((int)0X1401), UnsignedShort = ((int)0X1403), } public enum EnableCap : int { CullFace = ((int)0x0B44), DepthTest = ((int)0x0B71), StencilTest = ((int)0x0B90), Dither = ((int)0x0BD0), Blend = ((int)0x0BE2), ScissorTest = ((int)0x0C11), Texture2D = ((int)0x0DE1), PolygonOffsetFill = ((int)0x8037), SampleAlphaToCoverage = ((int)0x809E), SampleCoverage = ((int)0x80A0), } public enum ErrorCode : int { NoError = ((int)0), InvalidEnum = ((int)0x0500), InvalidValue = ((int)0x0501), InvalidOperation = ((int)0x0502), OutOfMemory = ((int)0x0505), InvalidFramebufferOperation = ((int)0X0506), } public enum ExtBlendMinmax : int { MinExt = ((int)0x8007), MaxExt = ((int)0x8008), ExtBlendMinmax = ((int)1), } public enum ExtDiscardFramebuffer : int { ColorExt = ((int)0x1800), DepthExt = ((int)0x1801), StencilExt = ((int)0x1802), ExtDiscardFramebuffer = ((int)1), } public enum ExtReadFormatBgra : int { BgraExt = ((int)0x80E1), UnsignedShort4444RevExt = ((int)0x8365), UnsignedShort1555RevExt = ((int)0x8366), ExtReadFormatBgra = ((int)1), } public enum ExtShaderTextureLod : int { ExtShaderTextureLod = ((int)1), } public enum ExtTextureCompressionDxt1 : int { CompressedRgbS3tcDxt1Ext = ((int)0x83F0), CompressedRgbaS3tcDxt1Ext = ((int)0x83F1), ExtTextureCompressionDxt1 = ((int)1), } public enum ExtTextureFilterAnisotropic : int { TextureMaxAnisotropyExt = ((int)0x84FE), MaxTextureMaxAnisotropyExt = ((int)0x84FF), ExtTextureFilterAnisotropic = ((int)1), } public enum ExtTextureFormatBgra8888 : int { BgraExt = ((int)0x80E1), ExtTextureFormatBgra8888 = ((int)1), } public enum ExtTextureType2101010Rev : int { UnsignedInt2101010RevExt = ((int)0x8368), ExtTextureType2101010Rev = ((int)1), } public enum FramebufferErrorCode : int { FramebufferComplete = ((int)0X8cd5), FramebufferIncompleteAttachment = ((int)0X8cd6), FramebufferIncompleteMissingAttachment = ((int)0X8cd7), FramebufferIncompleteDimensions = ((int)0X8cd9), FramebufferUnsupported = ((int)0X8cdd), } public enum FramebufferObject : int { None = ((int)0), InvalidFramebufferOperation = ((int)0x0506), StencilIndex = ((int)0x1901), Rgba4 = ((int)0x8056), Rgb5A1 = ((int)0x8057), DepthComponent16 = ((int)0x81A5), MaxRenderbufferSize = ((int)0x84E8), FramebufferBinding = ((int)0x8CA6), RenderbufferBinding = ((int)0x8CA7), FramebufferAttachmentObjectType = ((int)0x8CD0), FramebufferAttachmentObjectName = ((int)0x8CD1), FramebufferAttachmentTextureLevel = ((int)0x8CD2), FramebufferAttachmentTextureCubeMapFace = ((int)0x8CD3), FramebufferComplete = ((int)0x8CD5), FramebufferIncompleteAttachment = ((int)0x8CD6), FramebufferIncompleteMissingAttachment = ((int)0x8CD7), FramebufferIncompleteDimensions = ((int)0x8CD9), FramebufferUnsupported = ((int)0x8CDD), ColorAttachment0 = ((int)0x8CE0), DepthAttachment = ((int)0x8D00), StencilAttachment = ((int)0x8D20), Framebuffer = ((int)0x8D40), Renderbuffer = ((int)0x8D41), RenderbufferWidth = ((int)0x8D42), RenderbufferHeight = ((int)0x8D43), RenderbufferInternalFormat = ((int)0x8D44), StencilIndex8 = ((int)0x8D48), RenderbufferRedSize = ((int)0x8D50), RenderbufferGreenSize = ((int)0x8D51), RenderbufferBlueSize = ((int)0x8D52), RenderbufferAlphaSize = ((int)0x8D53), RenderbufferDepthSize = ((int)0x8D54), RenderbufferStencilSize = ((int)0x8D55), Rgb565 = ((int)0x8D62), } public enum FramebufferParameterName : int { FramebufferAttachmentObjectType = ((int)0X8cd0), FramebufferAttachmentObjectName = ((int)0X8cd1), FramebufferAttachmentTextureLevel = ((int)0X8cd2), FramebufferAttachmentTextureCubeMapFace = ((int)0X8cd3), } public enum FramebufferSlot : int { ColorAttachment0 = ((int)0X8ce0), DepthAttachment = ((int)0X8d00), StencilAttachment = ((int)0X8d20), } public enum FramebufferTarget : int { Framebuffer = ((int)0X8d40), } public enum FrontFaceDirection : int { Cw = ((int)0x0900), Ccw = ((int)0x0901), } public enum GetPName : int { LineWidth = ((int)0x0B21), CullFace = ((int)0X0b44), CullFaceMode = ((int)0x0B45), FrontFace = ((int)0x0B46), DepthRange = ((int)0x0B70), DepthTest = ((int)0X0b71), DepthWritemask = ((int)0x0B72), DepthClearValue = ((int)0x0B73), DepthFunc = ((int)0x0B74), StencilTest = ((int)0X0b90), StencilClearValue = ((int)0x0B91), StencilFunc = ((int)0x0B92), StencilValueMask = ((int)0x0B93), StencilFail = ((int)0x0B94), StencilPassDepthFail = ((int)0x0B95), StencilPassDepthPass = ((int)0x0B96), StencilRef = ((int)0x0B97), StencilWritemask = ((int)0x0B98), Viewport = ((int)0x0BA2), Dither = ((int)0X0bd0), Blend = ((int)0X0be2), ScissorBox = ((int)0x0C10), ScissorTest = ((int)0X0c11), ColorClearValue = ((int)0x0C22), ColorWritemask = ((int)0x0C23), UnpackAlignment = ((int)0x0CF5), PackAlignment = ((int)0x0D05), MaxTextureSize = ((int)0x0D33), MaxViewportDims = ((int)0x0D3A), SubpixelBits = ((int)0x0D50), RedBits = ((int)0x0D52), GreenBits = ((int)0x0D53), BlueBits = ((int)0x0D54), AlphaBits = ((int)0x0D55), DepthBits = ((int)0x0D56), StencilBits = ((int)0x0D57), Texture2D = ((int)0X0de1), PolygonOffsetUnits = ((int)0x2A00), BlendColor = ((int)0X8005), BlendEquation = ((int)0X8009), BlendEquationRgb = ((int)0X8009), PolygonOffsetFill = ((int)0X8037), PolygonOffsetFactor = ((int)0x8038), TextureBinding2D = ((int)0x8069), SampleAlphaToCoverage = ((int)0X809e), SampleCoverage = ((int)0X80a0), SampleBuffers = ((int)0x80A8), Samples = ((int)0x80A9), SampleCoverageValue = ((int)0x80AA), SampleCoverageInvert = ((int)0x80AB), BlendDstRgb = ((int)0X80c8), BlendSrcRgb = ((int)0X80c9), BlendDstAlpha = ((int)0X80ca), BlendSrcAlpha = ((int)0X80cb), GenerateMipmapHint = ((int)0X8192), AliasedPointSizeRange = ((int)0x846D), AliasedLineWidthRange = ((int)0x846E), ActiveTexture = ((int)0X84e0), MaxRenderbufferSize = ((int)0X84e8), TextureBindingCubeMap = ((int)0X8514), MaxCubeMapTextureSize = ((int)0X851c), NumCompressedTextureFormats = ((int)0X86a2), CompressedTextureFormats = ((int)0X86a3), StencilBackFunc = ((int)0x8800), StencilBackFail = ((int)0x8801), StencilBackPassDepthFail = ((int)0x8802), StencilBackPassDepthPass = ((int)0x8803), BlendEquationAlpha = ((int)0X883d), MaxVertexAttribs = ((int)0X8869), MaxTextureImageUnits = ((int)0X8872), ArrayBufferBinding = ((int)0X8894), ElementArrayBufferBinding = ((int)0X8895), MaxVertexTextureImageUnits = ((int)0X8b4c), MaxCombinedTextureImageUnits = ((int)0X8b4d), CurrentProgram = ((int)0X8b8d), ImplementationColorReadType = ((int)0X8b9a), ImplementationColorReadFormat = ((int)0X8b9b), StencilBackRef = ((int)0x8CA3), StencilBackValueMask = ((int)0x8CA4), StencilBackWritemask = ((int)0x8CA5), FramebufferBinding = ((int)0X8ca6), RenderbufferBinding = ((int)0X8ca7), ShaderBinaryFormats = ((int)0X8df8), NumShaderBinaryFormats = ((int)0X8df9), ShaderCompiler = ((int)0X8dfa), MaxVertexUniformVectors = ((int)0X8dfb), MaxVaryingVectors = ((int)0X8dfc), MaxFragmentUniformVectors = ((int)0X8dfd), } public enum GetTextureParameter : int { TextureMagFilter = ((int)0X2800), TextureMinFilter = ((int)0X2801), TextureWrapS = ((int)0X2802), TextureWrapT = ((int)0X2803), NumCompressedTextureFormats = ((int)0x86A2), CompressedTextureFormats = ((int)0x86A3), } public enum HintMode : int { DontCare = ((int)0x1100), Fastest = ((int)0x1101), Nicest = ((int)0x1102), } public enum HintTarget : int { GenerateMipmapHint = ((int)0x8192), } public enum ImgmultisampledRenderToTexture : int { RenderbufferSamplesImg = ((int)0x9133), FramebufferIncompleteMultisampleImg = ((int)0x9134), MaxSamplesImg = ((int)0x9135), TextureSamplesImg = ((int)0x9136), ImgMultisampledRenderToTexture = ((int)1), } public enum ImgprogramBinary : int { SgxProgramBinaryImg = ((int)0x9130), ImgProgramBinary = ((int)1), } public enum ImgreadFormat : int { BgraImg = ((int)0x80E1), UnsignedShort4444RevImg = ((int)0x8365), ImgReadFormat = ((int)1), } public enum ImgshaderBinary : int { SgxBinaryImg = ((int)0x8C0A), ImgShaderBinary = ((int)1), } public enum ImgtextureCompressionPvrtc : int { CompressedRgbPvrtc4Bppv1Img = ((int)0x8C00), CompressedRgbPvrtc2Bppv1Img = ((int)0x8C01), CompressedRgbaPvrtc4Bppv1Img = ((int)0x8C02), CompressedRgbaPvrtc2Bppv1Img = ((int)0x8C03), ImgTextureCompressionPvrtc = ((int)1), } public enum NvcoverageSample : int { CoverageBufferBitNv = ((int)0x8000), CoverageComponentNv = ((int)0x8ED0), CoverageComponent4Nv = ((int)0x8ED1), CoverageAttachmentNv = ((int)0x8ED2), CoverageBuffersNv = ((int)0x8ED3), CoverageSamplesNv = ((int)0x8ED4), CoverageAllFragmentsNv = ((int)0x8ED5), CoverageEdgeFragmentsNv = ((int)0x8ED6), CoverageAutomaticNv = ((int)0x8ED7), NvCoverageSample = ((int)1), } public enum NvdepthNonlinear : int { DepthComponent16NonlinearNv = ((int)0x8E2C), NvDepthNonlinear = ((int)1), } public enum Nvfence : int { AllCompletedNv = ((int)0x84F2), FenceStatusNv = ((int)0x84F3), FenceConditionNv = ((int)0x84F4), NvFence = ((int)1), } public enum OesCompressedEtc1Rgb8Texture : int { Etc1Rgb8Oes = ((int)0x8D64), OesCompressedEtc1Rgb8Texture = ((int)1), } public enum OesCompressedPalettedTexture : int { Palette4Rgb8Oes = ((int)0x8B90), Palette4Rgba8Oes = ((int)0x8B91), Palette4R5G6B5Oes = ((int)0x8B92), Palette4Rgba4Oes = ((int)0x8B93), Palette4Rgb5A1Oes = ((int)0x8B94), Palette8Rgb8Oes = ((int)0x8B95), Palette8Rgba8Oes = ((int)0x8B96), Palette8R5G6B5Oes = ((int)0x8B97), Palette8Rgba4Oes = ((int)0x8B98), Palette8Rgb5A1Oes = ((int)0x8B99), OesCompressedPalettedTexture = ((int)1), } public enum OesDepth24 : int { DepthComponent24Oes = ((int)0x81A6), OesDepth24 = ((int)1), } public enum OesDepth32 : int { DepthComponent32Oes = ((int)0x81A7), OesDepth32 = ((int)1), } public enum OesDepthTexture : int { OesDepthTexture = ((int)1), } public enum OesEglimage : int { OesEglImage = ((int)1), } public enum OesElementIndexUint : int { UnsignedInt = ((int)0x1405), OesElementIndexUint = ((int)1), } public enum OesFboRenderMipmap : int { OesFboRenderMipmap = ((int)1), } public enum OesFragmentPrecisionHigh : int { OesFragmentPrecisionHigh = ((int)1), } public enum OesGetProgramBinary : int { ProgramBinaryLengthOes = ((int)0x8741), NumProgramBinaryFormatsOes = ((int)0x87FE), ProgramBinaryFormatsOes = ((int)0x87FF), OesGetProgramBinary = ((int)1), } public enum OesMapbuffer : int { WriteOnlyOes = ((int)0x88B9), BufferAccessOes = ((int)0x88BB), BufferMappedOes = ((int)0x88BC), BufferMapPointerOes = ((int)0x88BD), OesMapbuffer = ((int)1), } public enum OesPackedDepthStencil : int { DepthStencilOes = ((int)0x84F9), UnsignedInt248Oes = ((int)0x84FA), Depth24Stencil8Oes = ((int)0x88F0), OesPackedDepthStencil = ((int)1), } public enum OesRgb8Rgba8 : int { Rgb8Oes = ((int)0x8051), Rgba8Oes = ((int)0x8058), OesRgb8Rgba8 = ((int)1), } public enum OesStandardDerivatives : int { FragmentShaderDerivativeHintOes = ((int)0x8B8B), OesStandardDerivatives = ((int)1), } public enum OesStencil1 : int { StencilIndex1Oes = ((int)0x8D46), OesStencil1 = ((int)1), } public enum OesStencil4 : int { StencilIndex4Oes = ((int)0x8D47), OesStencil4 = ((int)1), } public enum OesTexture3D : int { TextureBinding3DOes = ((int)0x806A), Texture3DOes = ((int)0x806F), TextureWrapROes = ((int)0x8072), Max3DTextureSizeOes = ((int)0x8073), Sampler3DOes = ((int)0x8B5F), FramebufferAttachmentTexture3DZoffsetOes = ((int)0x8CD4), OesTexture3D = ((int)1), } public enum OesTextureFloat : int { OesTextureFloat = ((int)1), } public enum OesTextureFloatLinear : int { OesTextureFloatLinear = ((int)1), } public enum OesTextureHalfFloat : int { HalfFloatOes = ((int)0x8D61), OesTextureHalfFloat = ((int)1), } public enum OesTextureHalfFloatLinear : int { OesTextureHalfFloatLinear = ((int)1), } public enum OesTextureNpot : int { OesTextureNpot = ((int)1), } public enum OesVertexArrayObject : int { VertexArrayBindingOes = ((int)0x85B5), OesVertexArrayObject = ((int)1), } public enum OesVertexHalfFloat : int { OesVertexHalfFloat = ((int)1), } public enum OesVertexType1010102 : int { UnsignedInt1010102Oes = ((int)0x8DF6), Int1010102Oes = ((int)0x8DF7), OesVertexType1010102 = ((int)1), } public enum OpenGlescoreVersions : int { EsVersion20 = ((int)1), } public enum PixelFormat : int { DepthComponent = ((int)0x1902), Alpha = ((int)0x1906), Rgb = ((int)0x1907), Rgba = ((int)0x1908), Luminance = ((int)0x1909), LuminanceAlpha = ((int)0x190A), } public enum PixelInternalFormat : int { Alpha = ((int)0X1906), Rgb = ((int)0X1907), Rgba = ((int)0X1908), Luminance = ((int)0X1909), LuminanceAlpha = ((int)0X190a), } public enum PixelStoreParameter : int { UnpackAlignment = ((int)0X0cf5), PackAlignment = ((int)0X0d05), } public enum PixelType : int { UnsignedByte = ((int)0X1401), UnsignedShort4444 = ((int)0x8033), UnsignedShort5551 = ((int)0x8034), UnsignedShort565 = ((int)0x8363), } public enum ProgramParameter : int { DeleteStatus = ((int)0X8b80), LinkStatus = ((int)0X8b82), ValidateStatus = ((int)0X8b83), InfoLogLength = ((int)0X8b84), AttachedShaders = ((int)0X8b85), ActiveUniforms = ((int)0X8b86), ActiveUniformMaxLength = ((int)0X8b87), ActiveAttributes = ((int)0X8b89), ActiveAttributeMaxLength = ((int)0X8b8a), } public enum QcomDriverControl : int { QcomDriverControl = ((int)1), } public enum QcomExtendedGet : int { TextureWidthQcom = ((int)0x8BD2), TextureHeightQcom = ((int)0x8BD3), TextureDepthQcom = ((int)0x8BD4), TextureInternalFormatQcom = ((int)0x8BD5), TextureFormatQcom = ((int)0x8BD6), TextureTypeQcom = ((int)0x8BD7), TextureImageValidQcom = ((int)0x8BD8), TextureNumLevelsQcom = ((int)0x8BD9), TextureTargetQcom = ((int)0x8BDA), TextureObjectValidQcom = ((int)0x8BDB), StateRestore = ((int)0x8BDC), QcomExtendedGet = ((int)1), } public enum QcomExtendedGet2 : int { QcomExtendedGet2 = ((int)1), } public enum QcomPerfmonGlobalMode : int { PerfmonGlobalModeQcom = ((int)0x8FA0), QcomPerfmonGlobalMode = ((int)1), } public enum QcomTiledRendering : int { ColorBufferBit0Qcom = ((int)0x00000001), ColorBufferBit1Qcom = ((int)0x00000002), ColorBufferBit2Qcom = ((int)0x00000004), ColorBufferBit3Qcom = ((int)0x00000008), ColorBufferBit4Qcom = ((int)0x00000010), ColorBufferBit5Qcom = ((int)0x00000020), ColorBufferBit6Qcom = ((int)0x00000040), ColorBufferBit7Qcom = ((int)0x00000080), DepthBufferBit0Qcom = ((int)0x00000100), DepthBufferBit1Qcom = ((int)0x00000200), DepthBufferBit2Qcom = ((int)0x00000400), DepthBufferBit3Qcom = ((int)0x00000800), DepthBufferBit4Qcom = ((int)0x00001000), DepthBufferBit5Qcom = ((int)0x00002000), DepthBufferBit6Qcom = ((int)0x00004000), DepthBufferBit7Qcom = ((int)0x00008000), StencilBufferBit0Qcom = ((int)0x00010000), StencilBufferBit1Qcom = ((int)0x00020000), StencilBufferBit2Qcom = ((int)0x00040000), StencilBufferBit3Qcom = ((int)0x00080000), StencilBufferBit4Qcom = ((int)0x00100000), StencilBufferBit5Qcom = ((int)0x00200000), StencilBufferBit6Qcom = ((int)0x00400000), StencilBufferBit7Qcom = ((int)0x00800000), MultisampleBufferBit0Qcom = ((int)0x01000000), MultisampleBufferBit1Qcom = ((int)0x02000000), MultisampleBufferBit2Qcom = ((int)0x04000000), MultisampleBufferBit3Qcom = ((int)0x08000000), MultisampleBufferBit4Qcom = ((int)0x10000000), MultisampleBufferBit5Qcom = ((int)0x20000000), MultisampleBufferBit6Qcom = ((int)0x40000000), MultisampleBufferBit7Qcom = unchecked((int)0x80000000), QcomTiledRendering = ((int)1), } public enum QcomWriteonlyRendering : int { WriteonlyRenderingQcom = ((int)0x8823), QcomWriteonlyRendering = ((int)1), } public enum ReadFormat : int { ImplementationColorReadType = ((int)0x8B9A), ImplementationColorReadFormat = ((int)0x8B9B), } public enum RenderbufferInternalFormat : int { Rgba4 = ((int)0X8056), Rgb5A1 = ((int)0X8057), DepthComponent16 = ((int)0X81a5), StencilIndex8 = ((int)0X8d48), Rgb565 = ((int)0X8d62), } public enum RenderbufferParameterName : int { RenderbufferWidth = ((int)0X8d42), RenderbufferHeight = ((int)0X8d43), RenderbufferInternalFormat = ((int)0X8d44), RenderbufferRedSize = ((int)0X8d50), RenderbufferGreenSize = ((int)0X8d51), RenderbufferBlueSize = ((int)0X8d52), RenderbufferAlphaSize = ((int)0X8d53), RenderbufferDepthSize = ((int)0X8d54), RenderbufferStencilSize = ((int)0X8d55), } public enum RenderbufferTarget : int { Renderbuffer = ((int)0X8d41), } public enum SeparateBlendFunctions : int { ConstantColor = ((int)0x8001), OneMinusConstantColor = ((int)0x8002), ConstantAlpha = ((int)0x8003), OneMinusConstantAlpha = ((int)0x8004), BlendColor = ((int)0x8005), BlendDstRgb = ((int)0x80C8), BlendSrcRgb = ((int)0x80C9), BlendDstAlpha = ((int)0x80CA), BlendSrcAlpha = ((int)0x80CB), } public enum ShaderBinary : int { ShaderBinaryFormats = ((int)0x8DF8), NumShaderBinaryFormats = ((int)0x8DF9), } public enum ShaderBinaryFormat : int { } public enum ShaderParameter : int { ShaderType = ((int)0X8b4f), DeleteStatus = ((int)0X8b80), CompileStatus = ((int)0X8b81), InfoLogLength = ((int)0X8b84), ShaderSourceLength = ((int)0X8b88), } public enum ShaderPrecision : int { LowFloat = ((int)0X8df0), MediumFloat = ((int)0X8df1), HighFloat = ((int)0X8df2), LowInt = ((int)0X8df3), MediumInt = ((int)0X8df4), HighInt = ((int)0X8df5), } public enum ShaderPrecisionSpecifiedTypes : int { LowFloat = ((int)0x8DF0), MediumFloat = ((int)0x8DF1), HighFloat = ((int)0x8DF2), LowInt = ((int)0x8DF3), MediumInt = ((int)0x8DF4), HighInt = ((int)0x8DF5), } public enum Shaders : int { MaxVertexAttribs = ((int)0x8869), MaxTextureImageUnits = ((int)0x8872), FragmentShader = ((int)0x8B30), VertexShader = ((int)0x8B31), MaxVertexTextureImageUnits = ((int)0x8B4C), MaxCombinedTextureImageUnits = ((int)0x8B4D), ShaderType = ((int)0x8B4F), DeleteStatus = ((int)0x8B80), LinkStatus = ((int)0x8B82), ValidateStatus = ((int)0x8B83), AttachedShaders = ((int)0x8B85), ActiveUniforms = ((int)0x8B86), ActiveUniformMaxLength = ((int)0x8B87), ActiveAttributes = ((int)0x8B89), ActiveAttributeMaxLength = ((int)0x8B8A), ShadingLanguageVersion = ((int)0x8B8C), CurrentProgram = ((int)0x8B8D), MaxVertexUniformVectors = ((int)0x8DFB), MaxVaryingVectors = ((int)0x8DFC), MaxFragmentUniformVectors = ((int)0x8DFD), } public enum ShaderSource : int { CompileStatus = ((int)0x8B81), InfoLogLength = ((int)0x8B84), ShaderSourceLength = ((int)0x8B88), ShaderCompiler = ((int)0x8DFA), } public enum ShaderType : int { FragmentShader = ((int)0X8b30), VertexShader = ((int)0X8b31), } public enum StencilFunction : int { Never = ((int)0x0200), Less = ((int)0x0201), Equal = ((int)0x0202), Lequal = ((int)0x0203), Greater = ((int)0x0204), Notequal = ((int)0x0205), Gequal = ((int)0x0206), Always = ((int)0x0207), } public enum StencilOp : int { Zero = ((int)0X0000), Invert = ((int)0x150A), Keep = ((int)0x1E00), Replace = ((int)0x1E01), Incr = ((int)0x1E02), Decr = ((int)0x1E03), IncrWrap = ((int)0x8507), DecrWrap = ((int)0x8508), } public enum StringName : int { Vendor = ((int)0x1F00), Renderer = ((int)0x1F01), Version = ((int)0x1F02), Extensions = ((int)0x1F03), ShadingLanguageVersion = ((int)0X8b8c), } public enum TextureMagFilter : int { Nearest = ((int)0x2600), Linear = ((int)0x2601), } public enum TextureMinFilter : int { Nearest = ((int)0X2600), Linear = ((int)0X2601), NearestMipmapNearest = ((int)0x2700), LinearMipmapNearest = ((int)0x2701), NearestMipmapLinear = ((int)0x2702), LinearMipmapLinear = ((int)0x2703), } public enum TextureParameterName : int { TextureMagFilter = ((int)0x2800), TextureMinFilter = ((int)0x2801), TextureWrapS = ((int)0x2802), TextureWrapT = ((int)0x2803), } public enum TextureTarget : int { Texture2D = ((int)0X0de1), Texture = ((int)0x1702), TextureCubeMap = ((int)0x8513), TextureBindingCubeMap = ((int)0x8514), TextureCubeMapPositiveX = ((int)0x8515), TextureCubeMapNegativeX = ((int)0x8516), TextureCubeMapPositiveY = ((int)0x8517), TextureCubeMapNegativeY = ((int)0x8518), TextureCubeMapPositiveZ = ((int)0x8519), TextureCubeMapNegativeZ = ((int)0x851A), MaxCubeMapTextureSize = ((int)0x851C), } public enum TextureUnit : int { Texture0 = ((int)0x84C0), Texture1 = ((int)0x84C1), Texture2 = ((int)0x84C2), Texture3 = ((int)0x84C3), Texture4 = ((int)0x84C4), Texture5 = ((int)0x84C5), Texture6 = ((int)0x84C6), Texture7 = ((int)0x84C7), Texture8 = ((int)0x84C8), Texture9 = ((int)0x84C9), Texture10 = ((int)0x84CA), Texture11 = ((int)0x84CB), Texture12 = ((int)0x84CC), Texture13 = ((int)0x84CD), Texture14 = ((int)0x84CE), Texture15 = ((int)0x84CF), Texture16 = ((int)0x84D0), Texture17 = ((int)0x84D1), Texture18 = ((int)0x84D2), Texture19 = ((int)0x84D3), Texture20 = ((int)0x84D4), Texture21 = ((int)0x84D5), Texture22 = ((int)0x84D6), Texture23 = ((int)0x84D7), Texture24 = ((int)0x84D8), Texture25 = ((int)0x84D9), Texture26 = ((int)0x84DA), Texture27 = ((int)0x84DB), Texture28 = ((int)0x84DC), Texture29 = ((int)0x84DD), Texture30 = ((int)0x84DE), Texture31 = ((int)0x84DF), ActiveTexture = ((int)0x84E0), } public enum TextureWrapMode : int { Repeat = ((int)0x2901), ClampToEdge = ((int)0x812F), MirroredRepeat = ((int)0x8370), } public enum UniformTypes : int { FloatVec2 = ((int)0x8B50), FloatVec3 = ((int)0x8B51), FloatVec4 = ((int)0x8B52), IntVec2 = ((int)0x8B53), IntVec3 = ((int)0x8B54), IntVec4 = ((int)0x8B55), Bool = ((int)0x8B56), BoolVec2 = ((int)0x8B57), BoolVec3 = ((int)0x8B58), BoolVec4 = ((int)0x8B59), FloatMat2 = ((int)0x8B5A), FloatMat3 = ((int)0x8B5B), FloatMat4 = ((int)0x8B5C), Sampler2D = ((int)0x8B5E), SamplerCube = ((int)0x8B60), } public enum Unknown : int { ExtMultiDrawArrays = ((int)1), } public enum VertexArrays : int { VertexAttribArrayEnabled = ((int)0x8622), VertexAttribArraySize = ((int)0x8623), VertexAttribArrayStride = ((int)0x8624), VertexAttribArrayType = ((int)0x8625), VertexAttribArrayPointer = ((int)0x8645), VertexAttribArrayNormalized = ((int)0x886A), VertexAttribArrayBufferBinding = ((int)0x889F), } public enum VertexAttribParameter : int { VertexAttribArrayEnabled = ((int)0X8622), VertexAttribArraySize = ((int)0X8623), VertexAttribArrayStride = ((int)0X8624), VertexAttribArrayType = ((int)0X8625), CurrentVertexAttrib = ((int)0X8626), VertexAttribArrayNormalized = ((int)0X886a), VertexAttribArrayBufferBinding = ((int)0X889f), } public enum VertexAttribPointerParameter : int { VertexAttribArrayPointer = ((int)0X8645), } public enum VertexAttribPointerType : int { Byte = ((int)0X1400), UnsignedByte = ((int)0X1401), Short = ((int)0X1402), UnsignedShort = ((int)0X1403), Float = ((int)0X1406), Fixed = ((int)0X140c), } public enum VivshaderBinary : int { ShaderBinaryViv = ((int)0x8FC4), VivShaderBinary = ((int)1), } }
using NUnit.Framework; using Revolver.Core; using Sitecore; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Layouts; using System.Xml; using Cmd = Revolver.Core.Commands; namespace Revolver.Test { [TestFixture] [Category("CopyPresentation")] public class CopyPresentation : BaseCommandTest { private Item _sourceItem = null; private Item _targetItem = null; private string _defaultDeviceId = string.Empty; private string _printDeviceId = string.Empty; [TestFixtureSetUp] public void Init() { Sitecore.Context.IsUnitTesting = true; Sitecore.Context.SkipSecurityInUnitTests = true; _defaultDeviceId = _context.CurrentDatabase.Resources.Devices["default"].ID.ToString(); _printDeviceId = _context.CurrentDatabase.Resources.Devices["print"].ID.ToString(); InitContent(); } [SetUp] public void SetUp() { _context.CurrentDatabase = Sitecore.Configuration.Factory.GetDatabase("web"); var template = _context.CurrentDatabase.Templates[Constants.Paths.DocTemplate]; _sourceItem = _testRoot.Add("source item", template); _targetItem = _testRoot.Add("target item", template); using (new EditContext(_targetItem)) { _targetItem[FieldIDs.LayoutField] = string.Empty; } } [TearDown] public void TearDown() { _testRoot.DeleteChildren(); } [Test] public void NoPaths() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; var previousLayout = _sourceItem[FieldIDs.LayoutField]; var result = cmd.Run(); _sourceItem.Reload(); Assert.AreEqual(CommandStatus.Success, result.Status); Assert.AreEqual(previousLayout, _sourceItem[FieldIDs.LayoutField]); } [Test] public void InvalidSourceDevice() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = "this is an invalid device"; cmd.TargetDeviceName = _context.CurrentDatabase.Resources.Devices.GetAll()[0].Name; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Failure, result.Status); } [Test] public void InvalidTargetDevice() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = _context.CurrentDatabase.Resources.Devices.GetAll()[0].Name; cmd.TargetDeviceName = "this is an invalid device"; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Failure, result.Status); } [Test] public void MissingTargetDevice() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = _context.CurrentDatabase.Resources.Devices.GetAll()[0].Name; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Failure, result.Status); } [Test] public void BetweenDevicesOnSameItem() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = "default"; cmd.TargetDeviceName = "print"; cmd.SourcePath = _context.CurrentItem.ID.ToString(); cmd.TargetPath = _context.CurrentItem.Paths.FullPath; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _sourceItem.Reload(); var layout = LayoutDefinition.Parse(LayoutField.GetFieldValue(_sourceItem.Fields[FieldIDs.LayoutField])); var defaultDevice = layout.GetDevice(_defaultDeviceId); var printDevice = layout.GetDevice(_printDeviceId); AssertLayout(defaultDevice, printDevice); } [Test] public void BetweenDevicesNoPaths() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = "default"; cmd.TargetDeviceName = "print"; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _sourceItem.Reload(); var layout = LayoutDefinition.Parse(LayoutField.GetFieldValue(_sourceItem.Fields[FieldIDs.LayoutField])); var defaultDevice = layout.GetDevice(_defaultDeviceId); var printDevice = layout.GetDevice(_printDeviceId); AssertLayout(defaultDevice, printDevice); } [Test] public void BetweenDevicesByIDOnSameItem() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = _defaultDeviceId; cmd.TargetDeviceName = _printDeviceId; cmd.SourcePath = _context.CurrentItem.ID.ToString(); cmd.TargetPath = _context.CurrentItem.ID.ToString(); var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _sourceItem.Reload(); var layout = LayoutDefinition.Parse(LayoutField.GetFieldValue(_sourceItem.Fields[FieldIDs.LayoutField])); var defaultDevice = layout.GetDevice(_defaultDeviceId); var printDevice = layout.GetDevice(_printDeviceId); AssertLayout(defaultDevice, printDevice); } [Test] public void AllDevicesToTarget() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.TargetPath = "../" + _targetItem.Name; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _sourceItem.Reload(); _targetItem.Reload(); Assert.AreEqual(_sourceItem[FieldIDs.LayoutField], _targetItem[FieldIDs.LayoutField]); } [Test] public void AllDevicesFromSource() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _targetItem; cmd.SourcePath = _sourceItem.ID.ToString(); var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _sourceItem.Reload(); _targetItem.Reload(); Assert.AreEqual(_sourceItem[FieldIDs.LayoutField], _targetItem[FieldIDs.LayoutField]); } [Test] public void SameDevicesOnDifferentItems() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _testRoot; cmd.SourceDeviceName = "default"; cmd.TargetDeviceName = "default"; cmd.SourcePath = _sourceItem.Name; cmd.TargetPath = _targetItem.Name; var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _targetItem.Reload(); var sourceDevice = LayoutDefinition.Parse(LayoutField.GetFieldValue(_sourceItem.Fields[FieldIDs.LayoutField])).GetDevice(_defaultDeviceId); var targetDevice = LayoutDefinition.Parse(LayoutField.GetFieldValue(_targetItem.Fields[FieldIDs.LayoutField])).GetDevice(_defaultDeviceId); AssertLayout(sourceDevice, targetDevice); } [Test] public void SameDeviceSameItem() { var cmd = new Cmd.CopyPresentation(); InitCommand(cmd); _context.CurrentItem = _sourceItem; cmd.SourceDeviceName = "default"; cmd.TargetDeviceName = "default"; cmd.SourcePath = _context.CurrentItem.ID.ToString(); cmd.TargetPath = _context.CurrentItem.Paths.FullPath; // Sometimes playing with the layout field can introduce non-significant whitespace var layoutBefore = new XmlDocument(); layoutBefore.LoadXml(_sourceItem[FieldIDs.LayoutField]); var result = cmd.Run(); Assert.AreEqual(CommandStatus.Success, result.Status); _sourceItem.Reload(); var layoutAfter = new XmlDocument(); layoutAfter.LoadXml(_sourceItem[FieldIDs.LayoutField]); Assert.AreEqual(layoutBefore.DocumentElement.OuterXml, layoutAfter.DocumentElement.OuterXml); } private void AssertLayout(DeviceDefinition expected, DeviceDefinition actual) { Assert.That(actual.Layout, Is.EqualTo(expected.Layout)); Assert.That(actual.Renderings.Count, Is.EqualTo(expected.Renderings.Count)); for (var i = 0; i < expected.Renderings.Count; i++) { Assert.That(((RenderingDefinition)actual.Renderings[i]).ToXml(), Is.EqualTo(((RenderingDefinition)expected.Renderings[i]).ToXml())); } } } }
using J2N; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using JCG = J2N.Collections.Generic; /* * dk.brics.automaton * * Copyright (c) 2001-2009 Anders Moeller * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Lucene.Net.Util.Automaton { /// <summary> /// Finite-state automaton with regular expression operations. /// <para/> /// Class invariants: /// <list type="bullet"> /// <item><description>An automaton is either represented explicitly (with <see cref="State"/> and /// <see cref="Transition"/> objects) or with a singleton string (see /// <see cref="Singleton"/> and <see cref="ExpandSingleton()"/>) in case the automaton /// is known to accept exactly one string. (Implicitly, all states and /// transitions of an automaton are reachable from its initial state.)</description></item> /// <item><description>Automata are always reduced (see <see cref="Reduce()"/>) and have no /// transitions to dead states (see <see cref="RemoveDeadTransitions()"/>).</description></item> /// <item><description>If an automaton is nondeterministic, then <see cref="IsDeterministic"/> /// returns <c>false</c> (but the converse is not required).</description></item> /// <item><description>Automata provided as input to operations are generally assumed to be /// disjoint.</description></item> /// </list> /// <para/> /// If the states or transitions are manipulated manually, the /// <see cref="RestoreInvariant()"/> method and <see cref="IsDeterministic"/> setter /// should be used afterwards to restore representation invariants that are /// assumed by the built-in automata operations. /// /// <para/> /// <para> /// Note: this class has internal mutable state and is not thread safe. It is /// the caller's responsibility to ensure any necessary synchronization if you /// wish to use the same Automaton from multiple threads. In general it is instead /// recommended to use a <see cref="RunAutomaton"/> for multithreaded matching: it is immutable, /// thread safe, and much faster. /// </para> /// @lucene.experimental /// </summary> public class Automaton #if FEATURE_CLONEABLE : System.ICloneable #endif { /// <summary> /// Minimize using Hopcroft's O(n log n) algorithm. this is regarded as one of /// the most generally efficient algorithms that exist. /// </summary> /// <seealso cref="SetMinimization(int)"/> public const int MINIMIZE_HOPCROFT = 2; /// <summary> /// Selects minimization algorithm (default: <c>MINIMIZE_HOPCROFT</c>). </summary> internal static int minimization = MINIMIZE_HOPCROFT; /// <summary> /// Initial state of this automaton. </summary> internal State initial; /// <summary> /// If <c>true</c>, then this automaton is definitely deterministic (i.e., there are /// no choices for any run, but a run may crash). /// </summary> internal bool deterministic; /// <summary> /// Extra data associated with this automaton. </summary> internal object info; ///// <summary> ///// Hash code. Recomputed by <see cref="MinimizationOperations#minimize(Automaton)"/> ///// </summary> //int hash_code; /// <summary> /// Singleton string. Null if not applicable. </summary> internal string singleton; /// <summary> /// Minimize always flag. </summary> internal static bool minimize_always = false; /// <summary> /// Selects whether operations may modify the input automata (default: /// <c>false</c>). /// </summary> internal static bool allow_mutation = false; /// <summary> /// Constructs a new automaton that accepts the empty language. Using this /// constructor, automata can be constructed manually from <see cref="State"/> and /// <see cref="Transition"/> objects. /// </summary> /// <seealso cref="State"/> /// <seealso cref="Transition"/> public Automaton(State initial) { this.initial = initial; deterministic = true; singleton = null; } public Automaton() : this(new State()) { } /// <summary> /// Selects minimization algorithm (default: <c>MINIMIZE_HOPCROFT</c>). /// </summary> /// <param name="algorithm"> minimization algorithm </param> public static void SetMinimization(int algorithm) { minimization = algorithm; } /// <summary> /// Sets or resets minimize always flag. If this flag is set, then /// <see cref="MinimizationOperations.Minimize(Automaton)"/> will automatically be /// invoked after all operations that otherwise may produce non-minimal /// automata. By default, the flag is not set. /// </summary> /// <param name="flag"> if <c>true</c>, the flag is set </param> public static void SetMinimizeAlways(bool flag) { minimize_always = flag; } /// <summary> /// Sets or resets allow mutate flag. If this flag is set, then all automata /// operations may modify automata given as input; otherwise, operations will /// always leave input automata languages unmodified. By default, the flag is /// not set. /// </summary> /// <param name="flag"> if <c>true</c>, the flag is set </param> /// <returns> previous value of the flag </returns> public static bool SetAllowMutate(bool flag) { bool b = allow_mutation; allow_mutation = flag; return b; } /// <summary> /// Returns the state of the allow mutate flag. If this flag is set, then all /// automata operations may modify automata given as input; otherwise, /// operations will always leave input automata languages unmodified. By /// default, the flag is not set. /// </summary> /// <returns> current value of the flag </returns> internal static bool AllowMutate => allow_mutation; internal virtual void CheckMinimizeAlways() { if (minimize_always) { MinimizationOperations.Minimize(this); } } internal bool IsSingleton => singleton != null; /// <summary> /// Returns the singleton string for this automaton. An automaton that accepts /// exactly one string <i>may</i> be represented in singleton mode. In that /// case, this method may be used to obtain the string. /// </summary> /// <returns> String, <c>null</c> if this automaton is not in singleton mode. </returns> public virtual string Singleton => singleton; ///// <summary> ///// Sets initial state. ///// </summary> ///// <param name="s"> state </param> /* public void setInitialState(State s) { initial = s; singleton = null; } */ /// <summary> /// Gets initial state. /// </summary> /// <returns> state </returns> public virtual State GetInitialState() { ExpandSingleton(); return initial; } /// <summary> /// Returns deterministic flag for this automaton. /// </summary> /// <returns> <c>true</c> if the automaton is definitely deterministic, <c>false</c> if the /// automaton may be nondeterministic </returns> public virtual bool IsDeterministic { get => deterministic; set => deterministic = value; } /// <summary> /// Associates extra information with this automaton. /// </summary> /// <param name="value"> extra information </param> public virtual object Info { get => info; set => info = value; } // cached private State[] numberedStates; public virtual State[] GetNumberedStates() { if (numberedStates == null) { ExpandSingleton(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); LinkedList<State> worklist = new LinkedList<State>(); State[] states = new State[4]; int upto = 0; worklist.AddLast(initial); visited.Add(initial); initial.number = upto; states[upto] = initial; upto++; while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); for (int i = 0; i < s.numTransitions; i++) { Transition t = s.TransitionsArray[i]; if (!visited.Contains(t.to)) { visited.Add(t.to); worklist.AddLast(t.to); t.to.number = upto; if (upto == states.Length) { // LUCENENET: Resize rather than copy Array.Resize(ref states, ArrayUtil.Oversize(1 + upto, RamUsageEstimator.NUM_BYTES_OBJECT_REF)); } states[upto] = t.to; upto++; } } } if (states.Length != upto) { // LUCENENET: Resize rather than copy Array.Resize(ref states, upto); } numberedStates = states; } return numberedStates; } public virtual void SetNumberedStates(State[] states) { SetNumberedStates(states, states.Length); } public virtual void SetNumberedStates(State[] states, int count) { Debug.Assert(count <= states.Length); // TODO: maybe we can eventually allow for oversizing here... if (count < states.Length) { State[] newArray = new State[count]; Array.Copy(states, 0, newArray, 0, count); numberedStates = newArray; } else { numberedStates = states; } } public virtual void ClearNumberedStates() { numberedStates = null; } /// <summary> /// Returns the set of reachable accept states. /// </summary> /// <returns> Set of <see cref="State"/> objects. </returns> public virtual ISet<State> GetAcceptStates() { ExpandSingleton(); JCG.HashSet<State> accepts = new JCG.HashSet<State>(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); LinkedList<State> worklist = new LinkedList<State>(); worklist.AddLast(initial); visited.Add(initial); while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); if (s.accept) { accepts.Add(s); } foreach (Transition t in s.GetTransitions()) { if (!visited.Contains(t.to)) { visited.Add(t.to); worklist.AddLast(t.to); } } } return accepts; } /// <summary> /// Adds transitions to explicit crash state to ensure that transition function /// is total. /// </summary> internal virtual void Totalize() { State s = new State(); s.AddTransition(new Transition(Character.MinCodePoint, Character.MaxCodePoint, s)); foreach (State p in GetNumberedStates()) { int maxi = Character.MinCodePoint; p.SortTransitions(Transition.COMPARE_BY_MIN_MAX_THEN_DEST); foreach (Transition t in p.GetTransitions()) { if (t.min > maxi) { p.AddTransition(new Transition(maxi, (t.min - 1), s)); } if (t.max + 1 > maxi) { maxi = t.max + 1; } } if (maxi <= Character.MaxCodePoint) { p.AddTransition(new Transition(maxi, Character.MaxCodePoint, s)); } } ClearNumberedStates(); } /// <summary> /// Restores representation invariant. This method must be invoked before any /// built-in automata operation is performed if automaton states or transitions /// are manipulated manually. /// </summary> /// <seealso cref="IsDeterministic"/> public virtual void RestoreInvariant() { RemoveDeadTransitions(); } /// <summary> /// Reduces this automaton. An automaton is "reduced" by combining overlapping /// and adjacent edge intervals with same destination. /// </summary> public virtual void Reduce() { State[] states = GetNumberedStates(); if (IsSingleton) { return; } foreach (State s in states) { s.Reduce(); } } /// <summary> /// Returns sorted array of all interval start points. /// </summary> public virtual int[] GetStartPoints() { State[] states = GetNumberedStates(); JCG.HashSet<int> pointset = new JCG.HashSet<int>(); pointset.Add(Character.MinCodePoint); foreach (State s in states) { foreach (Transition t in s.GetTransitions()) { pointset.Add(t.min); if (t.max < Character.MaxCodePoint) { pointset.Add((t.max + 1)); } } } int[] points = new int[pointset.Count]; int n = 0; foreach (int m in pointset) { points[n++] = m; } Array.Sort(points); return points; } /// <summary> /// Returns the set of live states. A state is "live" if an accept state is /// reachable from it. /// </summary> /// <returns> Set of <see cref="State"/> objects. </returns> private State[] GetLiveStates() { State[] states = GetNumberedStates(); JCG.HashSet<State> live = new JCG.HashSet<State>(); foreach (State q in states) { if (q.Accept) { live.Add(q); } } // map<state, set<state>> ISet<State>[] map = new JCG.HashSet<State>[states.Length]; for (int i = 0; i < map.Length; i++) { map[i] = new JCG.HashSet<State>(); } foreach (State s in states) { for (int i = 0; i < s.numTransitions; i++) { map[s.TransitionsArray[i].to.Number].Add(s); } } LinkedList<State> worklist = new LinkedList<State>(live); while (worklist.Count > 0) { State s = worklist.First.Value; worklist.Remove(s); foreach (State p in map[s.number]) { if (!live.Contains(p)) { live.Add(p); worklist.AddLast(p); } } } return live.ToArray(/*new State[live.Count]*/); } /// <summary> /// Removes transitions to dead states and calls <see cref="Reduce()"/>. /// (A state is "dead" if no accept state is /// reachable from it.) /// </summary> public virtual void RemoveDeadTransitions() { State[] states = GetNumberedStates(); //clearHashCode(); if (IsSingleton) { return; } State[] live = GetLiveStates(); OpenBitSet liveSet = new OpenBitSet(states.Length); foreach (State s in live) { liveSet.Set(s.number); } foreach (State s in states) { // filter out transitions to dead states: int upto = 0; for (int i = 0; i < s.numTransitions; i++) { Transition t = s.TransitionsArray[i]; if (liveSet.Get(t.to.number)) { s.TransitionsArray[upto++] = s.TransitionsArray[i]; } } s.numTransitions = upto; } for (int i = 0; i < live.Length; i++) { live[i].number = i; } if (live.Length > 0) { SetNumberedStates(live); } else { // sneaky corner case -- if machine accepts no strings ClearNumberedStates(); } Reduce(); } /// <summary> /// Returns a sorted array of transitions for each state (and sets state /// numbers). /// </summary> public virtual Transition[][] GetSortedTransitions() { State[] states = GetNumberedStates(); Transition[][] transitions = new Transition[states.Length][]; foreach (State s in states) { s.SortTransitions(Transition.COMPARE_BY_MIN_MAX_THEN_DEST); s.TrimTransitionsArray(); transitions[s.number] = s.TransitionsArray; Debug.Assert(s.TransitionsArray != null); } return transitions; } /// <summary> /// Expands singleton representation to normal representation. Does nothing if /// not in singleton representation. /// </summary> public virtual void ExpandSingleton() { if (IsSingleton) { State p = new State(); initial = p; for (int i = 0, cp = 0; i < singleton.Length; i += Character.CharCount(cp)) { State q = new State(); p.AddTransition(new Transition(cp = Character.CodePointAt(singleton, i), q)); p = q; } p.accept = true; deterministic = true; singleton = null; } } /// <summary> /// Returns the number of states in this automaton. /// </summary> public virtual int GetNumberOfStates() { if (IsSingleton) { return singleton.CodePointCount(0, singleton.Length) + 1; } return GetNumberedStates().Length; } /// <summary> /// Returns the number of transitions in this automaton. This number is counted /// as the total number of edges, where one edge may be a character interval. /// </summary> public virtual int GetNumberOfTransitions() { if (IsSingleton) { return singleton.CodePointCount(0, singleton.Length); } int c = 0; foreach (State s in GetNumberedStates()) { c += s.NumTransitions; } return c; } public override bool Equals(object obj) { var other = obj as Automaton; return BasicOperations.SameLanguage(this, other); //throw new NotSupportedException("use BasicOperations.sameLanguage instead"); } // LUCENENET specific - in .NET, we can't simply throw an exception here because // collections use this to determine equality. Most of this code was pieced together from // BasicOperations.SubSetOf (which, when done both ways determines equality). public override int GetHashCode() { if (IsSingleton) { return singleton.GetHashCode(); } int hash = 31; // arbitrary prime this.Determinize(); // LUCENENET: should we do this ? Transition[][] transitions = this.GetSortedTransitions(); LinkedList<State> worklist = new LinkedList<State>(); JCG.HashSet<State> visited = new JCG.HashSet<State>(); State current = this.initial; worklist.AddLast(this.initial); visited.Add(this.initial); while (worklist.Count > 0) { current = worklist.First.Value; worklist.Remove(current); hash = 31 * hash + current.accept.GetHashCode(); Transition[] t1 = transitions[current.number]; for (int n1 = 0; n1 < t1.Length; n1++) { int min1 = t1[n1].min, max1 = t1[n1].max; hash = 31 * hash + min1.GetHashCode(); hash = 31 * hash + max1.GetHashCode(); State next = t1[n1].to; if (!visited.Contains(next)) { worklist.AddLast(next); visited.Add(next); } } } return hash; //throw new NotSupportedException(); } ///// <summary> ///// Must be invoked when the stored hash code may no longer be valid. ///// </summary> /* void clearHashCode() { hash_code = 0; } */ /// <summary> /// Returns a string representation of this automaton. /// </summary> public override string ToString() { StringBuilder b = new StringBuilder(); if (IsSingleton) { b.Append("singleton: "); int length = singleton.CodePointCount(0, singleton.Length); int[] codepoints = new int[length]; for (int i = 0, j = 0, cp = 0; i < singleton.Length; i += Character.CharCount(cp)) { codepoints[j++] = cp = singleton.CodePointAt(i); } foreach (int c in codepoints) { Transition.AppendCharString(c, b); } b.Append("\n"); } else { State[] states = GetNumberedStates(); b.Append("initial state: ").Append(initial.number).Append("\n"); foreach (State s in states) { b.Append(s.ToString()); } } return b.ToString(); } /// <summary> /// Returns <a href="http://www.research.att.com/sw/tools/graphviz/" /// target="_top">Graphviz Dot</a> representation of this automaton. /// </summary> public virtual string ToDot() { StringBuilder b = new StringBuilder("digraph Automaton {\n"); b.Append(" rankdir = LR;\n"); State[] states = GetNumberedStates(); foreach (State s in states) { b.Append(" ").Append(s.number); if (s.accept) { b.Append(" [shape=doublecircle,label=\"\"];\n"); } else { b.Append(" [shape=circle,label=\"\"];\n"); } if (s == initial) { b.Append(" initial [shape=plaintext,label=\"\"];\n"); b.Append(" initial -> ").Append(s.number).Append("\n"); } foreach (Transition t in s.GetTransitions()) { b.Append(" ").Append(s.number); t.AppendDot(b); } } return b.Append("}\n").ToString(); } /// <summary> /// Returns a clone of this automaton, expands if singleton. /// </summary> internal virtual Automaton CloneExpanded() { Automaton a = (Automaton)Clone(); a.ExpandSingleton(); return a; } /// <summary> /// Returns a clone of this automaton unless <see cref="allow_mutation"/> is /// set, expands if singleton. /// </summary> internal virtual Automaton CloneExpandedIfRequired() { if (allow_mutation) { ExpandSingleton(); return this; } else { return CloneExpanded(); } } /// <summary> /// Returns a clone of this automaton. /// </summary> public virtual object Clone() { Automaton a = (Automaton)base.MemberwiseClone(); if (!IsSingleton) { Dictionary<State, State> m = new Dictionary<State, State>(); State[] states = GetNumberedStates(); foreach (State s in states) { m[s] = new State(); } foreach (State s in states) { State p = m[s]; p.accept = s.accept; if (s == initial) { a.initial = p; } foreach (Transition t in s.GetTransitions()) { p.AddTransition(new Transition(t.min, t.max, m[t.to])); } } } a.ClearNumberedStates(); return a; } /// <summary> /// Returns a clone of this automaton, or this automaton itself if /// <see cref="allow_mutation"/> flag is set. /// </summary> internal virtual Automaton CloneIfRequired() { if (allow_mutation) { return this; } else { return (Automaton)Clone(); } } /// <summary> /// See <see cref="BasicOperations.Concatenate(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Concatenate(Automaton a) { return BasicOperations.Concatenate(this, a); } /// <summary> /// See <see cref="BasicOperations.Concatenate(IList{Automaton})"/>. /// </summary> public static Automaton Concatenate(IList<Automaton> l) { return BasicOperations.Concatenate(l); } /// <summary> /// See <see cref="BasicOperations.Optional(Automaton)"/>. /// </summary> public virtual Automaton Optional() { return BasicOperations.Optional(this); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton)"/>. /// </summary> public virtual Automaton Repeat() { return BasicOperations.Repeat(this); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton, int)"/>. /// </summary> public virtual Automaton Repeat(int min) { return BasicOperations.Repeat(this, min); } /// <summary> /// See <see cref="BasicOperations.Repeat(Automaton, int, int)"/>. /// </summary> public virtual Automaton Repeat(int min, int max) { return BasicOperations.Repeat(this, min, max); } /// <summary> /// See <see cref="BasicOperations.Complement(Automaton)"/>. /// </summary> public virtual Automaton Complement() { return BasicOperations.Complement(this); } /// <summary> /// See <see cref="BasicOperations.Minus(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Minus(Automaton a) { return BasicOperations.Minus(this, a); } /// <summary> /// See <see cref="BasicOperations.Intersection(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Intersection(Automaton a) { return BasicOperations.Intersection(this, a); } /// <summary> /// See <see cref="BasicOperations.SubsetOf(Automaton, Automaton)"/>. /// </summary> public virtual bool SubsetOf(Automaton a) { return BasicOperations.SubsetOf(this, a); } /// <summary> /// See <see cref="BasicOperations.Union(Automaton, Automaton)"/>. /// </summary> public virtual Automaton Union(Automaton a) { return BasicOperations.Union(this, a); } /// <summary> /// See <see cref="BasicOperations.Union(ICollection{Automaton})"/>. /// </summary> public static Automaton Union(ICollection<Automaton> l) { return BasicOperations.Union(l); } /// <summary> /// See <see cref="BasicOperations.Determinize(Automaton)"/>. /// </summary> public virtual void Determinize() { BasicOperations.Determinize(this); } /// <summary> /// See <see cref="BasicOperations.IsEmptyString(Automaton)"/>. /// </summary> public virtual bool IsEmptyString => BasicOperations.IsEmptyString(this); /// <summary> /// See <see cref="MinimizationOperations.Minimize(Automaton)"/>. Returns the /// automaton being given as argument. /// </summary> public static Automaton Minimize(Automaton a) { MinimizationOperations.Minimize(a); return a; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ServiceStack.CacheAccess.Providers; using TeamCityBuildChanges.ExternalApi; using TeamCityBuildChanges.ExternalApi.TeamCity; using TeamCityBuildChanges.IssueDetailResolvers; using TeamCityBuildChanges.NuGetPackage; using TeamCityBuildChanges.Output; namespace TeamCityBuildChanges { /// <summary> /// Calculates ChangeManifest objects based on TeamCity builds. /// </summary> public class AggregateBuildDeltaResolver { private readonly ITeamCityApi _api; private readonly IPackageChangeComparator _packageChangeComparator; private readonly PackageBuildMappingCache _packageBuildMappingCache; private readonly ConcurrentBag<NuGetPackageChange> _traversedPackageChanges; private readonly IIssueDetailResolver _issueDetailResolver; /// <summary> /// Provides the ability to generate delta change manifests between arbitrary build versions. /// </summary> /// <param name="api">A TeamCityApi.</param> /// <param name="issueDetailResolver"></param> /// <param name="packageChangeComparator">Provides package dependency comparison capability.</param> /// <param name="packageBuildMappingCache">Provides the ability to map from a Nuget package to the build that created the package.</param> /// <param name="traversedPackageChanges">Packages changes that we have already calculated and can reuse.</param> public AggregateBuildDeltaResolver(ITeamCityApi api, IIssueDetailResolver issueDetailResolver, IPackageChangeComparator packageChangeComparator, PackageBuildMappingCache packageBuildMappingCache, ConcurrentBag<NuGetPackageChange> traversedPackageChanges) { _api = api; _issueDetailResolver = issueDetailResolver; _packageChangeComparator = packageChangeComparator; _packageBuildMappingCache = packageBuildMappingCache; _traversedPackageChanges = traversedPackageChanges; } /// <summary> /// Creates a change manifest based on a build name and a project. /// </summary> /// <param name="projectName">The project name</param> /// <param name="buildName">The build type name to use.</param> /// <param name="referenceBuild">Any reference build that provides the actual build information.</param> /// <param name="from">The From build number</param> /// <param name="to">The To build number</param> /// <param name="useBuildSystemIssueResolution">Uses the issues resolved by the build system at time of build, rather than getting them directly from the version control system.</param> /// <param name="recurse">Recurses down through any detected package dependency changes.</param> /// <param name="branchName">Name of the branch.</param> /// <returns> /// The calculated ChangeManifest object. /// </returns> public ChangeManifest CreateChangeManifestFromBuildTypeName(string projectName, string buildName, string referenceBuild = null, string @from = null, string to = null, bool useBuildSystemIssueResolution = true, bool recurse = false) { return CreateChangeManifest(buildName, null, referenceBuild, from, to, projectName, useBuildSystemIssueResolution, recurse); } /// <summary> /// Creates a change manifest based on a build name and a project. /// </summary> /// <param name="buildType">The Build Type ID to work on.</param> /// <param name="referenceBuild">Any reference build that provides the actual build information.</param> /// <param name="from">The From build number</param> /// <param name="to">The To build number</param> /// <param name="useBuildSystemIssueResolution">Uses the issues resolved by the build system at time of build, rather than getting them directly from the version control system.</param> /// <param name="recurse">Recurses down through any detected package dependency changes.</param> /// <returns> /// The calculated ChangeManifest object. /// </returns> public ChangeManifest CreateChangeManifestFromBuildTypeId(string buildType, string referenceBuild = null, string from = null, string to = null, bool useBuildSystemIssueResolution = true, bool recurse = false, bool branchFiltering = true) { return CreateChangeManifest(null, buildType, referenceBuild, from, to, null, useBuildSystemIssueResolution, recurse, branchFiltering); } private ChangeManifest CreateChangeManifest(string buildName, string buildType, string referenceBuild = null, string from = null, string to = null, string projectName = null, bool useBuildSystemIssueResolution = true, bool recurse = false, bool branchFiltering = true) { var changeManifest = new ChangeManifest(); if (recurse && _packageBuildMappingCache == null) { changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now,Status.Warning,"Recurse option provided with no PackageBuildMappingCache, we will not be honoring the Recurse option.")); changeManifest.GenerationStatus = Status.Warning; } buildType = buildType ?? ResolveBuildTypeId(projectName, buildName); if (String.IsNullOrEmpty(from)) { changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Warning, "Resolving FROM version based on the provided BuildType (FROM was not provided).")); from = ResolveFromVersion(buildType); } if (String.IsNullOrEmpty(to)) { changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Warning, "Resolving TO version based on the provided BuildType (TO was not provided).")); to = ResolveToVersion(buildType); } var buildWithCommitData = referenceBuild ?? buildType; var buildTypeDetails = _api.GetBuildTypeDetailsById(buildType); var referenceBuildTypeDetails = !String.IsNullOrEmpty(referenceBuild) ? _api.GetBuildTypeDetailsById(referenceBuild) : null; if (!String.IsNullOrEmpty(from) && !String.IsNullOrEmpty(to) && !String.IsNullOrEmpty(buildWithCommitData)) { changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Ok, "Getting builds based on BuildType")); var builds = _api.GetBuildsByBuildType(buildWithCommitData); if (builds != null) { var buildList = builds as List<Build> ?? builds.ToList(); // Get to and from branch names if (branchFiltering) { var toBranchBuild = buildList.FirstOrDefault(b => b.Number == to); var fromBranchBuild = buildList.FirstOrDefault(b => b.Number == from); if (toBranchBuild != null && fromBranchBuild != null) buildList = buildList.Where(b => b.BranchName == toBranchBuild.BranchName || b.BranchName == fromBranchBuild.BranchName).ToList(); } changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now,Status.Ok, string.Format("Got {0} builds for BuildType {1}.",buildList.Count(), buildType))); var changeDetails =_api.GetChangeDetailsByBuildTypeAndBuildNumber(buildWithCommitData, @from, to, buildList).ToList(); //Rather than use TeamCity to resolve the issue to commit details (via TeamCity plugins) use the issue resolvers directly... var issues = useBuildSystemIssueResolution ? _api.GetIssuesByBuildTypeAndBuildRange(buildWithCommitData, @from, to, buildList).ToList() : _issueDetailResolver.GetAssociatedIssues(changeDetails).ToList(); changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now,Status.Ok, string.Format("Got {0} issues for BuildType {1}.", issues.Count(),buildType))); changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Ok, "Checking package dependencies.")); var buildFrom = buildList.FirstOrDefault(b => b.Number == @from); var buildTo = buildList.FirstOrDefault(b => b.Number == to); var initialPackages = new List<TeamCityApi.PackageDetails>(); var finalPackages = new List<TeamCityApi.PackageDetails>(); if (buildFrom != null) initialPackages = _api.GetNuGetDependenciesByBuildTypeAndBuildId(buildType,buildFrom.Id).ToList(); if (buildTo != null) finalPackages = _api.GetNuGetDependenciesByBuildTypeAndBuildId(buildType, buildTo.Id).ToList(); var packageChanges = _packageChangeComparator.GetPackageChanges(initialPackages, finalPackages).ToList(); var issueDetails = _issueDetailResolver.GetExternalIssueDetails(issues); changeManifest.NuGetPackageChanges = packageChanges; changeManifest.ChangeDetails.AddRange(changeDetails); changeManifest.IssueDetails.AddRange(issueDetails); changeManifest.Generated = DateTime.Now; changeManifest.FromVersion = @from; changeManifest.ToVersion = to; changeManifest.BuildConfiguration = buildTypeDetails; changeManifest.ReferenceBuildConfiguration = referenceBuildTypeDetails ?? new BuildTypeDetails(); } else { changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Warning, string.Format("No builds returned for BuildType {0}.", buildType))); } } //Now we need to see if we need to recurse, and whether we have been given a cache file.... var modifiedPackages = changeManifest.NuGetPackageChanges.Where(c => c.Type == NuGetPackageChangeType.Modified).ToList(); if (!modifiedPackages.Any() || !recurse || _packageBuildMappingCache == null) return changeManifest; Parallel.ForEach(modifiedPackages, dependency => { var traversedDependency = _traversedPackageChanges.FirstOrDefault( p => p.NewVersion == dependency.NewVersion && p.OldVersion == dependency.OldVersion && p.PackageId == dependency.PackageId); if (traversedDependency != null) { dependency.ChangeManifest = traversedDependency.ChangeManifest; return; } var mappings = _packageBuildMappingCache.PackageBuildMappings.Where( m => m.PackageId.Equals(dependency.PackageId, StringComparison.CurrentCultureIgnoreCase)).ToList(); PackageBuildMapping build = null; if (mappings.Count == 1) { //We only got one back, this is good... build = mappings.First(); changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Ok, string.Format("Found singular packages to build mapping {0}.", build.BuildConfigurationName))); } else if (mappings.Any()) { //Ok, so multiple builds are outputting this package, so we need to try and constrain on project... build = mappings.FirstOrDefault(m => m.Project.Equals(buildTypeDetails.Project.Name, StringComparison.OrdinalIgnoreCase)); if (build != null) changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Warning, string.Format("Found duplicate mappings, using package to build mapping {0}.", build.BuildConfigurationName))); } if (build != null) { if (build.BuildConfigurationId == buildType) return; //TODO if we are newing up a new RestClientFactory, we dont have a token for it...none passed in.... var instanceTeamCityApi = _api.Url.Equals(build.ServerUrl, StringComparison.OrdinalIgnoreCase) ? _api : new TeamCityApi(new CachingThreadSafeAuthenticatedRestClient(new MemoryCacheClient(), build.ServerUrl), new MemoryCacheClient()); var resolver = new AggregateBuildDeltaResolver(instanceTeamCityApi, _issueDetailResolver, _packageChangeComparator, _packageBuildMappingCache, _traversedPackageChanges); var dependencyManifest = resolver.CreateChangeManifest(null, build.BuildConfigurationId, null, dependency.OldVersion, dependency.NewVersion, null, true, true); dependency.ChangeManifest = dependencyManifest; } else { changeManifest.GenerationLog.Add(new LogEntry(DateTime.Now, Status.Warning, string.Format("Did not find a mapping for package: {0}.", dependency.PackageId))); } _traversedPackageChanges.Add(dependency); }); return changeManifest; } private string ResolveToVersion(string buildType) { var runningBuild = _api.GetRunningBuildByBuildType(buildType).FirstOrDefault(); if (runningBuild != null) { Console.WriteLine("TO: Found running build for {0}: {1}", buildType, runningBuild.Number); return runningBuild.Number; } throw new ApplicationException(String.Format("Could not resolve a build number for the running build.")); } private string ResolveFromVersion(string buildType) { var latestSuccessful = _api.GetLatestSuccessfulBuildByBuildType(buildType); if (latestSuccessful != null) { Console.WriteLine("FROM: Found latest successful for {0}: {1}", buildType, latestSuccessful.Number); return latestSuccessful.Number; } // fall back to the current running build var runningBuild = _api.GetRunningBuildByBuildType(buildType).FirstOrDefault(); if (runningBuild != null) { Console.WriteLine("FROM: Found fall back to the current running build for {0}: {1}", buildType, runningBuild.Number); return runningBuild.Number; } throw new ApplicationException(String.Format("Could not find <from> build for build type {0}", buildType)); } private string ResolveBuildTypeId(string projectName, string buildName) { if (String.IsNullOrEmpty(projectName) || String.IsNullOrEmpty(buildName)) { throw new ApplicationException(String.Format("Could not resolve Project: {0} and BuildName:{1} to a build type", projectName, buildName)); } var resolvedBuildType = _api.GetBuildTypeByProjectAndName(projectName, buildName).FirstOrDefault(); if (resolvedBuildType != null) return resolvedBuildType.Id; return String.Empty; } } }
// 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 OLEDB.Test.ModuleCore; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // TestCase TCXML ReadState // //////////////////////////////////////////////////////////////// [InheritRequired()] public abstract class TCReadState : TCXMLReaderBaseGeneral { public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.JUNK); return ret; } public override int Terminate(object objParam) { // just in case it failed without closing DataReader.Close(); DeleteTestFile(EREADER_TYPE.JUNK); return base.Terminate(objParam); } [Variation("XmlReader ReadState", Pri = 0)] public int ReadState1() { ReloadSource(EREADER_TYPE.JUNK); try { DataReader.Read(); } catch (XmlException) { CError.WriteLine(DataReader.ReadState); CError.Compare(DataReader.ReadState, ReadState.Error, "ReadState should be Error"); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, "wrong exception"); } } ///////////////////////////////////////////////////////////////////////// // TestCase ReadInnerXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract class TCReadInnerXml : TCXMLReaderBaseGeneral { public const String ST_ENT_TEXT = "xxx&gt;xxx&#66;xxx&#x44;xxx&e1;xxx"; private void VerifyNextNode(XmlNodeType nt, string name, string value) { while (DataReader.NodeType == XmlNodeType.Whitespace || DataReader.NodeType == XmlNodeType.SignificantWhitespace) { // skip all whitespace nodes // if EOF is reached NodeType=None DataReader.Read(); } CError.Compare(DataReader.VerifyNode(nt, name, value), "VerifyNextNode"); } //////////////////////////////////////////////////////////////// // Variations //////////////////////////////////////////////////////////////// [Variation("ReadInnerXml on Empty Tag", Pri = 0)] public int TestReadInnerXml1() { bool bPassed = false; String strExpected = String.Empty; ReloadSource(); DataReader.PositionOnElement("EMPTY1"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "EMPTY2", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on non Empty Tag", Pri = 0)] public int TestReadInnerXml2() { bool bPassed = false; String strExpected = String.Empty; ReloadSource(); DataReader.PositionOnElement("EMPTY2"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "EMPTY3", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on non Empty Tag with text content", Pri = 0)] public int TestReadInnerXml3() { bool bPassed = false; String strExpected = "ABCDE"; ReloadSource(); DataReader.PositionOnElement("NONEMPTY1"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "NONEMPTY2", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on non Empty Tag with Attribute", Pri = 0)] public int TestReadInnerXml4() { bool bPassed = false; String strExpected = "1234"; ReloadSource(); DataReader.PositionOnElement("NONEMPTY2"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "ACT2", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on non Empty Tag with text and markup content (mixed content)")] public int TestReadInnerXml5() { bool bPassed = false; String strExpected; strExpected = "xxx<MARKUP />yyy"; ReloadSource(); DataReader.PositionOnElement("CHARS2"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "CHARS_ELEM1", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml with multiple Level of elements")] public int TestReadInnerXml6() { bool bPassed = false; String strExpected; strExpected = "<ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 />"; ReloadSource(); DataReader.PositionOnElement("SKIP3"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "AFTERSKIP3", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml with multiple Level of elements, text and attributes", Pri = 0)] public int TestReadInnerXml7() { bool bPassed = false; String strExpected = "<e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1>"; strExpected = strExpected.Replace('\'', '"'); ReloadSource(); DataReader.PositionOnElement("CONTENT"); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "TITLE", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml with entity references, EntityHandling = ExpandEntities")] public int TestReadInnerXml8() { bool bPassed = false; String strExpected = ST_EXPAND_ENTITIES3; if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = ST_EXPAND_ENTITIES2; ReloadSource(); DataReader.PositionOnElement(ST_ENTTEST_NAME); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Element, "ENTITY2", String.Empty); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on attribute node", Pri = 0)] public int TestReadInnerXml9() { bool bPassed = false; String strExpected = "a1value"; ReloadSource(); DataReader.PositionOnElement("ATTRIBUTE2"); bPassed = DataReader.MoveToFirstAttribute(); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Attribute, "a1", strExpected); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on attribute node with entity reference in value", Pri = 0)] public int TestReadInnerXml10() { bool bPassed = false; string strExpected; if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader()) { strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES4; } else if (IsXmlNodeReader()) { strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES2; } else { strExpected = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES2; } string strExpectedAttValue = ST_ENT1_ATT_EXPAND_ENTITIES; if (IsXmlTextReader()) strExpectedAttValue = ST_ENT1_ATT_EXPAND_CHAR_ENTITIES; ReloadSource(); DataReader.PositionOnElement(ST_ENTTEST_NAME); bPassed = DataReader.MoveToFirstAttribute(); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); VerifyNextNode(XmlNodeType.Attribute, "att1", strExpectedAttValue); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on Text", Pri = 0)] public int TestReadInnerXml11() { XmlNodeType nt; string name; string value; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.Text); CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); // save status and compare with Read nt = DataReader.NodeType; name = DataReader.Name; value = DataReader.Value; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.Text); DataReader.Read(); CError.Compare(DataReader.VerifyNode(nt, name, value), "vn"); return TEST_PASS; } [Variation("ReadInnerXml on CDATA")] public int TestReadInnerXml12() { if (IsXsltReader() || IsXPathNavigatorReader()) { while (FindNodeType(XmlNodeType.CDATA) == TEST_PASS) return TEST_FAIL; return TEST_PASS; } ReloadSource(); if (FindNodeType(XmlNodeType.CDATA) == TEST_PASS) { CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } return TEST_FAIL; } [Variation("ReadInnerXml on ProcessingInstruction")] public int TestReadInnerXml13() { ReloadSource(); if (FindNodeType(XmlNodeType.ProcessingInstruction) == TEST_PASS) { CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } return TEST_FAIL; } [Variation("ReadInnerXml on Comment")] public int TestReadInnerXml14() { ReloadSource(); if (FindNodeType(XmlNodeType.Comment) == TEST_PASS) { CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } return TEST_FAIL; } [Variation("ReadInnerXml on EndElement")] public int TestReadInnerXml16() { ReloadSource(); if (FindNodeType(XmlNodeType.EndElement) == TEST_PASS) { CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } return TEST_FAIL; } [Variation("ReadInnerXml on XmlDeclaration")] public int TestReadInnerXml17() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); if (FindNodeType(XmlNodeType.XmlDeclaration) == TEST_PASS) { CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } return TEST_FAIL; } [Variation("Current node after ReadInnerXml on element", Pri = 0)] public int TestReadInnerXml18() { ReloadSource(); DataReader.PositionOnElement("SKIP2"); DataReader.ReadInnerXml(); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "AFTERSKIP2", String.Empty), true, "VN"); return TEST_PASS; } [Variation("Current node after ReadInnerXml on element")] public int TestReadInnerXml19() { ReloadSource(); DataReader.PositionOnElement("MARKUP"); CError.Compare(DataReader.ReadInnerXml(), String.Empty, "RIX"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Text, String.Empty, "yyy"), true, "VN"); return TEST_PASS; } [Variation("ReadInnerXml with entity references, EntityHandling = ExpandCharEntites")] public int TestTextReadInnerXml2() { bool bPassed = false; String strExpected; if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = ST_EXPAND_ENTITIES2; else { if (IsXmlNodeReader()) { strExpected = ST_EXPAND_ENTITIES3; } else { strExpected = ST_EXPAND_ENTITIES3; } } ReloadSource(); DataReader.PositionOnElement(ST_ENTTEST_NAME); bPassed = CError.Equals(DataReader.ReadInnerXml(), strExpected, CurVariation.Desc); return BoolToLTMResult(bPassed); } [Variation("ReadInnerXml on EntityReference")] public int TestTextReadInnerXml4() { if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.EntityReference); CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("ReadInnerXml on EndEntity")] public int TestTextReadInnerXml5() { if (IsXmlTextReader() || IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.EntityReference); CError.Compare(DataReader.ReadInnerXml(), String.Empty, CurVariation.Desc); return TEST_PASS; } [Variation("ReadInnerXml on XmlDeclaration attributes")] public int TestTextReadInnerXml16() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); if (IsBinaryReader()) { CError.Compare(DataReader.ReadInnerXml(), "utf-8", "inner"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "utf-8"), true, "vn"); } else { CError.Compare(DataReader.ReadInnerXml(), "UTF-8", "inner"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "UTF-8"), true, "vn"); } return TEST_PASS; } [Variation("One large element")] public int TestTextReadInnerXml18() { String strp = "a "; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; string strxml = "<Name a=\"b\">" + strp + "</Name>"; ReloadSourceStr(strxml); DataReader.Read(); CError.Compare(DataReader.ReadInnerXml(), strp, "rix"); return TEST_PASS; } } ///////////////////////////////////////////////////////////////////////// // TestCase MoveToContent // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCMoveToContent : TCXMLReaderBaseGeneral { public const String ST_TEST_NAME1 = "GOTOCONTENT"; public const String ST_TEST_NAME2 = "SKIPCONTENT"; public const String ST_TEST_NAME3 = "MIXCONTENT"; public const String ST_TEST_TEXT = "some text"; public const String ST_TEST_CDATA = "cdata info"; //////////////////////////////////////////////////////////////// // Variations //////////////////////////////////////////////////////////////// [Variation("MoveToContent on Skip XmlDeclaration", Pri = 0)] public int TestMoveToContent1() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.XmlDeclaration); CError.Compare(DataReader.MoveToContent(), XmlNodeType.Element, CurVariation.Desc); CError.Compare(DataReader.Name, "PLAY", CurVariation.Desc); return TEST_PASS; } [Variation("MoveToContent on Read through All invalid Content Node(PI, Comment and whitespace)", Pri = 0)] public int TestMoveToContent3() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_NAME2); CError.Compare(DataReader.MoveToContent(), XmlNodeType.Element, CurVariation.Desc); CError.Compare(DataReader.Name, ST_TEST_NAME2, "Element name"); DataReader.Read(); CError.Compare(DataReader.MoveToContent(), XmlNodeType.EndElement, "Move to EndElement"); CError.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value"); return TEST_PASS; } [Variation("MoveToContent on Attribute", Pri = 0)] public int TestMoveToContent5() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_NAME1); PositionOnNodeType(XmlNodeType.Attribute); CError.Compare(DataReader.MoveToContent(), XmlNodeType.Element, "Move to EndElement"); CError.Compare(DataReader.Name, ST_TEST_NAME2, "EndElement value"); return TEST_PASS; } public const String ST_ENT1_ELEM_ALL_ENTITIES_TYPE = "xxxBxxxDxxxe1fooxxx"; public const String ST_ATT1_NAME = "att1"; public const String ST_GEN_ENT_NAME = "e1"; public const String ST_GEN_ENT_VALUE = "e1foo"; } ///////////////////////////////////////////////////////////////////////// // TestCase IsStartElement // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCIsStartElement : TCXMLReaderBaseGeneral { private const String ST_TEST_ELEM = "DOCNAMESPACE"; private const String ST_TEST_EMPTY_ELEM = "NOSPACE"; private const String ST_TEST_ELEM_NS = "NAMESPACE1"; private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1"; [Variation("IsStartElement on Regular Element, no namespace", Pri = 0)] public int TestIsStartElement1() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); CError.Compare(DataReader.IsStartElement(ST_TEST_ELEM), true, "IsStartElement(n)"); CError.Compare(DataReader.IsStartElement(ST_TEST_ELEM, String.Empty), true, "IsStartElement(n,ns)"); return TEST_PASS; } [Variation("IsStartElement on Empty Element, no namespace", Pri = 0)] public int TestIsStartElement2() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM); CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM), true, "IsStartElement(n)"); CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM, String.Empty), true, "IsStartElement(n,ns)"); return TEST_PASS; } [Variation("IsStartElement on regular Element, with namespace", Pri = 0)] public int TestIsStartElement3() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); CError.Compare(DataReader.IsStartElement("check", "1"), true, "IsStartElement(n,ns)"); CError.Compare(DataReader.IsStartElement("check", String.Empty), false, "IsStartElement(n)"); CError.Compare(DataReader.IsStartElement("check"), false, "IsStartElement2(n)"); CError.Compare(DataReader.IsStartElement("bar:check"), true, "IsStartElement(qname)"); CError.Compare(DataReader.IsStartElement("bar1:check"), false, "IsStartElement(invalid_qname)"); return TEST_PASS; } [Variation("IsStartElement on Empty Tag, with default namespace", Pri = 0)] public int TestIsStartElement4() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); CError.Compare(DataReader.IsStartElement(), true, "IsStartElement()"); CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, "14"), true, "IsStartElement(n,ns)"); CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty), false, "IsStartElement(n)"); CError.Compare(DataReader.IsStartElement(ST_TEST_EMPTY_ELEM_NS), true, "IsStartElement2(n)"); return TEST_PASS; } [Variation("IsStartElement with Name=String.Empty")] public int TestIsStartElement5() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); CError.Compare(DataReader.IsStartElement(String.Empty), false, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on Empty Element with Name and Namespace=String.Empty")] public int TestIsStartElement6() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM); CError.Compare(DataReader.IsStartElement(String.Empty, String.Empty), false, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on CDATA")] public int TestIsStartElement7() { //XSLT doesn't deal with CDATA if (IsXsltReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.CDATA); CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on EndElement, no namespace")] public int TestIsStartElement8() { ReloadSource(); DataReader.PositionOnElement("NONAMESPACE"); PositionOnNodeType(XmlNodeType.EndElement); CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()"); CError.Compare(DataReader.IsStartElement("NONAMESPACE"), false, "IsStartElement(n)"); CError.Compare(DataReader.IsStartElement("NONAMESPACE", String.Empty), false, "IsStartElement(n,ns)"); return TEST_PASS; } [Variation("IsStartElement on EndElement, with namespace")] public int TestIsStartElement9() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); PositionOnNodeType(XmlNodeType.EndElement); CError.Compare(DataReader.IsStartElement(), false, "IsStartElement()"); CError.Compare(DataReader.IsStartElement("check", "1"), false, "IsStartElement(n,ns)"); CError.Compare(DataReader.IsStartElement("bar:check"), false, "IsStartElement(qname)"); return TEST_PASS; } [Variation("IsStartElement on Attribute")] public int TestIsStartElement10() { ReloadSource(); PositionOnNodeType(XmlNodeType.Attribute); CError.Compare(DataReader.IsStartElement(), true, CurVariation.Desc); CError.Compare(DataReader.NodeType, XmlNodeType.Element, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on Text")] public int TestIsStartElement11() { ReloadSource(); PositionOnNodeType(XmlNodeType.Text); CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on ProcessingInstruction")] public int TestIsStartElement12() { ReloadSource(); PositionOnNodeType(XmlNodeType.ProcessingInstruction); CError.Compare(DataReader.IsStartElement(), IsSubtreeReader() ? false : true, CurVariation.Desc); CError.Compare(DataReader.NodeType, IsSubtreeReader() ? XmlNodeType.Text : XmlNodeType.Element, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on Comment")] public int TestIsStartElement13() { ReloadSource(); PositionOnNodeType(XmlNodeType.Comment); CError.Compare(DataReader.IsStartElement(), IsSubtreeReader() ? false : true, CurVariation.Desc); CError.Compare(DataReader.NodeType, IsSubtreeReader() ? XmlNodeType.Text : XmlNodeType.Element, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on XmlDeclaration")] public int TestIsStartElement15() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.XmlDeclaration); CError.Compare(DataReader.IsStartElement(), true, CurVariation.Desc); CError.Compare(DataReader.NodeType, XmlNodeType.Element, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on EntityReference")] public int TestTextIsStartElement1() { if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.EntityReference); CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc); return TEST_PASS; } [Variation("IsStartElement on EndEntity")] public int TestTextIsStartElement2() { if (IsXsltReader() || IsXmlTextReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.EndEntity); CError.Compare(DataReader.IsStartElement(), false, CurVariation.Desc); return TEST_PASS; } } ///////////////////////////////////////////////////////////////////////// // TestCase ReadStartElement // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadStartElement : TCXMLReaderBaseGeneral { private const String ST_TEST_ELEM = "DOCNAMESPACE"; private const String ST_TEST_EMPTY_ELEM = "NOSPACE"; private const String ST_TEST_ELEM_NS = "NAMESPACE1"; private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1"; [Variation("ReadStartElement on Regular Element, no namespace", Pri = 0)] public int TestReadStartElement1() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); DataReader.ReadStartElement(); ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); DataReader.ReadStartElement(ST_TEST_ELEM); ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); DataReader.ReadStartElement(ST_TEST_ELEM, String.Empty); return TEST_PASS; } [Variation("ReadStartElement on Empty Element, no namespace", Pri = 0)] public int TestReadStartElement2() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM); DataReader.ReadStartElement(); ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM); ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM, String.Empty); return TEST_PASS; } [Variation("ReadStartElement on regular Element, with namespace", Pri = 0)] public int TestReadStartElement3() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); DataReader.ReadStartElement(); ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); DataReader.ReadStartElement("check", "1"); ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); DataReader.ReadStartElement("bar:check"); return TEST_PASS; } [Variation("Passing ns=String.EmptyErrorCase: ReadStartElement on regular Element, with namespace", Pri = 0)] public int TestReadStartElement4() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); try { DataReader.ReadStartElement("check", String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Passing no ns: ReadStartElement on regular Element, with namespace", Pri = 0)] public int TestReadStartElement5() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); try { DataReader.ReadStartElement("check"); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement on Empty Tag, with namespace")] public int TestReadStartElement6() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); DataReader.ReadStartElement(); ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, "14"); return TEST_PASS; } [Variation("ErrorCase: ReadStartElement on Empty Tag, with namespace, passing ns=String.Empty")] public int TestReadStartElement7() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); try { DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS, String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement on Empty Tag, with namespace, passing no ns")] public int TestReadStartElement8() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); DataReader.ReadStartElement(ST_TEST_EMPTY_ELEM_NS); return TEST_PASS; } [Variation("ReadStartElement with Name=String.Empty")] public int TestReadStartElement9() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); try { DataReader.ReadStartElement(String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement on Empty Element with Name and Namespace=String.Empty")] public int TestReadStartElement10() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); try { DataReader.ReadStartElement(String.Empty, String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement on CDATA")] public int TestReadStartElement11() { //XSLT doesn't deal with CDATA if (IsXsltReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.CDATA); try { DataReader.ReadStartElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement() on EndElement, no namespace")] public int TestReadStartElement12() { ReloadSource(); DataReader.PositionOnElement("NONAMESPACE"); PositionOnNodeType(XmlNodeType.EndElement); try { DataReader.ReadStartElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement(n) on EndElement, no namespace")] public int TestReadStartElement13() { ReloadSource(); DataReader.PositionOnElement("NONAMESPACE"); PositionOnNodeType(XmlNodeType.EndElement); try { DataReader.ReadStartElement("NONAMESPACE"); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement(n, String.Empty) on EndElement, no namespace")] public int TestReadStartElement14() { ReloadSource(); DataReader.PositionOnElement("NONAMESPACE"); PositionOnNodeType(XmlNodeType.EndElement); try { DataReader.ReadStartElement("NONAMESPACE", String.Empty); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement() on EndElement, with namespace")] public int TestReadStartElement15() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); PositionOnNodeType(XmlNodeType.EndElement); try { DataReader.ReadStartElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadStartElement(n,ns) on EndElement, with namespace")] public int TestReadStartElement16() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); PositionOnNodeType(XmlNodeType.EndElement); try { DataReader.ReadStartElement("check", "1"); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } ///////////////////////////////////////////////////////////////////////// // TestCase ReadEndElement // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadEndElement : TCXMLReaderBaseGeneral { private const String ST_TEST_ELEM = "DOCNAMESPACE"; private const String ST_TEST_EMPTY_ELEM = "NOSPACE"; private const String ST_TEST_ELEM_NS = "NAMESPACE1"; private const String ST_TEST_EMPTY_ELEM_NS = "EMPTY_NAMESPACE1"; [Variation("ReadEndElement() on EndElement, no namespace", Pri = 0)] public int TestReadEndElement1() { ReloadSource(); DataReader.PositionOnElement("NONAMESPACE"); PositionOnNodeType(XmlNodeType.EndElement); DataReader.ReadEndElement(); DataReader.VerifyNode(XmlNodeType.EndElement, "NONAMESPACE", String.Empty); return TEST_PASS; } [Variation("ReadEndElement() on EndElement, with namespace", Pri = 0)] public int TestReadEndElement2() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); PositionOnNodeType(XmlNodeType.EndElement); DataReader.ReadEndElement(); DataReader.VerifyNode(XmlNodeType.EndElement, "bar:check", String.Empty); return TEST_PASS; } [Variation("ReadEndElement on Start Element, no namespace")] public int TestReadEndElement3() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on Empty Element, no namespace", Pri = 0)] public int TestReadEndElement4() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on regular Element, with namespace", Pri = 0)] public int TestReadEndElement5() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_ELEM_NS); DataReader.PositionOnElement("bar:check"); CError.WriteLine(DataReader.NamespaceURI); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on Empty Tag, with namespace", Pri = 0)] public int TestReadEndElement6() { ReloadSource(); DataReader.PositionOnElement(ST_TEST_EMPTY_ELEM_NS); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on CDATA")] public int TestReadEndElement7() { //XSLT doesn't deal with CDATA if (IsXsltReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.CDATA); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on Text")] public int TestReadEndElement9() { ReloadSource(); PositionOnNodeType(XmlNodeType.Text); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on ProcessingInstruction")] public int TestReadEndElement10() { ReloadSource(); PositionOnNodeType(XmlNodeType.ProcessingInstruction); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on Comment")] public int TestReadEndElement11() { ReloadSource(); PositionOnNodeType(XmlNodeType.Comment); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on XmlDeclaration")] public int TestReadEndElement13() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.XmlDeclaration); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on EntityReference")] public int TestTextReadEndElement1() { if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.EntityReference); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("ReadEndElement on EndEntity")] public int TestTextReadEndElement2() { if (IsXsltReader() || IsXmlTextReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; ReloadSource(); PositionOnNodeType(XmlNodeType.EndEntity); try { DataReader.ReadEndElement(); } catch (XmlException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } //////////////////////////////////////////////////////////////// // TestCase TCXML MoveToElement // //////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCMoveToElement : TCXMLReaderBaseGeneral { [Variation("Attribute node")] public int v1() { ReloadSource(); DataReader.PositionOnElement("elem2"); DataReader.MoveToAttribute(1); CError.Compare(DataReader.MoveToElement(), "MTE on elem2 failed"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node"); return TEST_PASS; } [Variation("Element node")] public int v2() { ReloadSource(); DataReader.PositionOnElement("elem2"); CError.Compare(!DataReader.MoveToElement(), "MTE on elem2 failed"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "elem2", String.Empty), "MTE moved on wrong node"); return TEST_PASS; } [Variation("XmlDeclaration node")] public int v3() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration); CError.Compare(!DataReader.MoveToElement(), "MTE on xmldecl failed"); CError.Compare(DataReader.NodeType, XmlNodeType.XmlDeclaration, "xmldecl"); CError.Compare(DataReader.Name, "xml", "Name"); if (IsBinaryReader()) CError.Compare(DataReader.Value, "version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"", "Value"); else CError.Compare(DataReader.Value, "version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"", "Value"); return TEST_PASS; } [Variation("Comment node")] public int v5() { ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.Comment); CError.Compare(!DataReader.MoveToElement(), "MTE on comment failed"); CError.Compare(DataReader.NodeType, XmlNodeType.Comment, "comment"); return TEST_PASS; } } }
/* * MindTouch DekiScript - embeddable web-oriented scripting runtime * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Xml; using MindTouch.Deki.Script.Compiler; using MindTouch.Deki.Script.Expr; using MindTouch.Deki.Script.Runtime; using MindTouch.Deki.Script.Runtime.Library; using MindTouch.Xml; namespace MindTouch.Deki.Script { public static class DekiScriptInterpreterEx { //--- Extension Methods --- public static DekiScriptExpression Optimize(this DekiScriptRuntime runtime, DekiScriptExpression expr, DekiScriptEvalMode mode, DekiScriptEnv env) { return expr.VisitWith(DekiScriptExpressionOptimizer.Instance, new DekiScriptExpressionEvaluationState(mode, env, runtime)); } } public static class DekiScriptInterpreter { //--- Class Methods --- public static XmlNode Evaluate( XDoc script, XmlElement node, DekiScriptEvalContext context, DekiScriptEnv env, DekiScriptRuntime runtime, out bool scripted, ref bool error ) { if((context.Mode != DekiScriptEvalMode.Verify) && (context.Mode != DekiScriptEvalMode.EvaluateEditOnly) && (context.Mode != DekiScriptEvalMode.EvaluateSaveOnly)) { throw new InvalidOperationException("DekiScript interpreter can only used for save, edit, or verify evaluations."); } scripted = false; XmlNode next = node.NextSibling; try { // check if element needs to be evaluated if(StringUtil.EqualsInvariant(node.NamespaceURI, XDekiScript.ScriptNS)) { scripted = true; // NOTE (steveb): <eval:xyz> nodes are not processed by the interpreter anymore } else { XDoc current = script[node]; bool hasScriptClass = StringUtil.EqualsInvariant(node.GetAttribute("class"), "script"); #region <elem class="script" init="..." if="..." foreach="..." where="..." block="..."> // check if element has form <elem class="script" init="..." if="..." foreach="..." where="..." block="..."> scripted = node.HasAttribute("init") || node.HasAttribute("if") || node.HasAttribute("foreach") || node.HasAttribute("block"); if(context.Mode == DekiScriptEvalMode.Verify) { // check if "block" is present string blockAttr = node.GetAttribute("block"); if(!string.IsNullOrEmpty(blockAttr)) { // TODO (steveb): validate script expression } // check if "foreach" is present string foreachAttr = node.GetAttribute("foreach"); if(!string.IsNullOrEmpty(foreachAttr)) { // TODO (steveb): validate script expression } // check if "if" is present string ifAttr = node.GetAttribute("if"); if(!string.IsNullOrEmpty(ifAttr)) { // TODO (steveb): validate script expression } // check if "init" is present string initAttr = node.GetAttribute("init"); if(!string.IsNullOrEmpty(initAttr)) { // TODO (steveb): validate script expression } } #endregion // evaluate child nodes EvaluateChildren(script, node, context, env, runtime, out scripted, ref error); #region evaluate attributes for(int i = 0; i < node.Attributes.Count; ++i) { XmlAttribute attribute = node.Attributes[i]; // check if attribute needs to be evaluated if(attribute.NamespaceURI == XDekiScript.ScriptNS) { scripted = true; // NOTE (steveb): eval:xyz="abc" attributes are not processed by the interpreter anymore } else if(StringUtil.StartsWithInvariant(attribute.Value, "{{") && StringUtil.EndsWithInvariant(attribute.Value, "}}")) { scripted = true; // NOTE (steveb): key="{{value}}" string code = attribute.Value.Substring(2, attribute.Value.Length - 4).Trim(); // check if script content is substituted bool isPermanentReplacement = false; if(StringUtil.StartsWithInvariantIgnoreCase(code, DekiScriptRuntime.ON_SAVE_PATTERN)) { isPermanentReplacement = (context.Mode == DekiScriptEvalMode.EvaluateSaveOnly); code = code.Substring(DekiScriptRuntime.ON_SAVE_PATTERN.Length); } else if(StringUtil.StartsWithInvariantIgnoreCase(code, DekiScriptRuntime.ON_SUBST_PATTERN)) { isPermanentReplacement = (context.Mode == DekiScriptEvalMode.EvaluateSaveOnly); code = code.Substring(DekiScriptRuntime.ON_SUBST_PATTERN.Length); } else if(StringUtil.StartsWithInvariantIgnoreCase(code, DekiScriptRuntime.ON_EDIT_PATTERN)) { isPermanentReplacement = (context.Mode == DekiScriptEvalMode.EvaluateEditOnly); code = code.Substring(DekiScriptRuntime.ON_EDIT_PATTERN.Length); } // parse expression if((context.Mode == DekiScriptEvalMode.Verify) || isPermanentReplacement) { DekiScriptExpression expression = DekiScriptParser.Parse(ComputeNodeLocation(attribute), code); if(isPermanentReplacement) { DekiScriptLiteral eval = runtime.Evaluate(expression, DekiScriptEvalMode.EvaluateSafeMode, env); // determine what the outcome value is string value = eval.AsString(); // check if we have a value to replace the current attribute with if((value != null) && !DekiScriptLibrary.ContainsXSSVulnerability(attribute.LocalName, value)) { attribute.Value = value; } else { node.Attributes.RemoveAt(i); --i; } } } } } #endregion #region evaluate <span class="script"> or <pre class="script"> if(hasScriptClass && (StringUtil.EqualsInvariant(node.LocalName, "pre") || StringUtil.EqualsInvariant(node.LocalName, "span")) && !node.HasAttribute("function")) { // replace the non-breaking space character with space string code = node.InnerText.ReplaceAll("\u00A0", " ", "\u00AD", "").Trim(); // check if script content is substituted bool isPermanentReplacement = false; if(StringUtil.StartsWithInvariantIgnoreCase(code, DekiScriptRuntime.ON_SAVE_PATTERN)) { isPermanentReplacement = (context.Mode == DekiScriptEvalMode.EvaluateSaveOnly); code = code.Substring(DekiScriptRuntime.ON_SAVE_PATTERN.Length); } else if(StringUtil.StartsWithInvariantIgnoreCase(code, DekiScriptRuntime.ON_SUBST_PATTERN)) { isPermanentReplacement = (context.Mode == DekiScriptEvalMode.EvaluateSaveOnly); code = code.Substring(DekiScriptRuntime.ON_SUBST_PATTERN.Length); } else if(StringUtil.StartsWithInvariantIgnoreCase(code, DekiScriptRuntime.ON_EDIT_PATTERN)) { isPermanentReplacement = (context.Mode == DekiScriptEvalMode.EvaluateEditOnly); code = code.Substring(DekiScriptRuntime.ON_EDIT_PATTERN.Length); } // parse expression if((context.Mode == DekiScriptEvalMode.Verify) || isPermanentReplacement) { DekiScriptExpression expression = DekiScriptParser.Parse(ComputeNodeLocation(node), code); if(isPermanentReplacement) { DekiScriptLiteral value = runtime.Evaluate(expression, DekiScriptEvalMode.EvaluateSafeMode, env); context.ReplaceNodeWithValue(node, value); } if(!isPermanentReplacement) { scripted = true; } } } #endregion } } catch(Exception e) { // only embed error in verify mode, not in save/edit modes if(context.Mode == DekiScriptEvalMode.Verify) { context.InsertExceptionMessageBeforeNode(env, node.ParentNode, node, ComputeNodeLocation(node), e); node.ParentNode.RemoveChild(node); } error |= true; } return next; } private static void EvaluateChildren( XDoc script, XmlElement node, DekiScriptEvalContext context, DekiScriptEnv env, DekiScriptRuntime runtime, out bool scripted, ref bool error ) { scripted = false; // recurse first to evaluate nested script content XmlNode child = node.FirstChild; while(child != null) { XmlNode next = child.NextSibling; if(child.NodeType == XmlNodeType.Element) { bool childScripted; next = Evaluate(script, (XmlElement)child, context, env, runtime, out childScripted, ref error); scripted = scripted || childScripted; } child = next; } } private static Location ComputeNodeLocation(XmlNode node) { // compute node location List<string> pathSegments = new List<string>(); while((node != null) && !StringUtil.EqualsInvariant(node.Name, "body")) { if(node.NodeType == XmlNodeType.Attribute) { pathSegments.Add("@" + node.Name); node = ((XmlAttribute)node).OwnerElement; } else { // count how many nodes have the same name int index = 1; XmlNode sibling = node.PreviousSibling; while(sibling != null) { if(StringUtil.EqualsInvariant(sibling.Name, node.Name)) { ++index; } sibling = sibling.PreviousSibling; } // add path segment with or without index if(index > 1) { pathSegments.Add(node.Name + "[" + index + "]"); } else { pathSegments.Add(node.Name); } node = node.ParentNode; } } pathSegments.Reverse(); return new Location(string.Join("/", pathSegments.ToArray())); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The implementation of the environment of intervals using System; using System.Text; using System.Diagnostics; using Microsoft.Research.AbstractDomains.Expressions; using Microsoft.Research.DataStructures; using System.Collections.Generic; namespace Microsoft.Research.AbstractDomains.Numerical { /// <summary> /// An interval environment is a map from Variables to intervals /// </summary> public class IntervalEnvironment_IEEE754<Variable, Expression> : IntervalEnvironment_Base<IntervalEnvironment_IEEE754<Variable, Expression>, Variable, Expression, Interval_IEEE754, Double> { #region Constructor public IntervalEnvironment_IEEE754(ExpressionManager<Variable, Expression> expManager) : base(expManager) { } public IntervalEnvironment_IEEE754(IntervalEnvironment_IEEE754<Variable, Expression> original) : base(original) { } #endregion protected override IntervalEnvironment_IEEE754<Variable, Expression> DuplicateMe() { return new IntervalEnvironment_IEEE754<Variable, Expression>(this); } protected override IntervalEnvironment_IEEE754<Variable, Expression> NewInstance(ExpressionManager<Variable, Expression> expManager) { return new IntervalEnvironment_IEEE754<Variable, Expression>(expManager); } public override void AssumeDomainSpecificFact(DomainSpecificFact fact) { base.AssumeDomainSpecificFact(fact); Variable var; Interval_IEEE754 intv; if (fact.IsAssumeInFloatInterval(out var, out intv)) { Interval_IEEE754 prev; if (this.TryGetValue(var, out prev)) { intv = prev.Meet(intv); } this[var] = intv; } } public override IntervalEnvironment_IEEE754<Variable, Expression> TestTrueGeqZero(Expression exp) { return this; } public override IntervalEnvironment_IEEE754<Variable, Expression> TestTrueLessThan_Un(Expression exp1, Expression exp2) { return this.TestTrueLessThan(exp1, exp2); } public override IntervalEnvironment_IEEE754<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2) { var v1 = this.Eval(exp1); var v2 = this.Eval(exp2); if (v1.IsNotNaN) { this.AssumeKLessThanRight(v1, this.ExpressionManager.Decoder.UnderlyingVariable(exp2)); } if (v2.IsNotNaN) { this.AssumeLeftLessThanK(this.ExpressionManager.Decoder.UnderlyingVariable(exp1), v2); } return this; } public override IntervalEnvironment_IEEE754<Variable, Expression> TestNotEqual(Expression exp1, Expression exp2) { var v1 = this.Eval(exp1); var v2 = this.Eval(exp2); if (v1.IsNotNaN) { var exp2Var = this.ExpressionManager.Decoder.UnderlyingVariable(exp2); var intv1 = this.IntervalForKLessThanRight(v1, exp2Var); var intv2 = this.IntervalForLeftLessThanK(exp2Var, v1); var join = intv1.Join(intv2); if (join.IsNormal) { this[exp2Var] = join; } } if (v2.IsNotNaN) { var exp1Var = this.ExpressionManager.Decoder.UnderlyingVariable(exp1); var intv1 = this.IntervalForKLessThanRight(v2, exp1Var); var intv2 = this.IntervalForLeftLessThanK(exp1Var, v2); var join = intv1.Join(intv2); if (join.IsNormal) { this[exp1Var] = join; } } return this; } public override IntervalEnvironment_IEEE754<Variable, Expression> TestTrueLessEqualThan_Un(Expression exp1, Expression exp2) { return TestTrueLessEqualThan(exp1, exp2); } public override IntervalEnvironment_IEEE754<Variable, Expression> TestTrueLessEqualThan(Expression exp1, Expression exp2) { var intv1 = this.Eval(exp1); var intv2 = this.Eval(exp2); if (intv1.IsNormal) { var v2 = this.ExpressionManager.Decoder.UnderlyingVariable(exp2); this.AssumeKLessEqualThanRight(intv1, v2); this.AssumeKLessEqualThanRight(intv1, this.ExpressionManager.Decoder.UnderlyingVariable(this.ExpressionManager.Decoder.Stripped(exp2))); } if (intv2.IsNormal) { var v1 = this.ExpressionManager.Decoder.UnderlyingVariable(exp1); this.AssumeLeftLessEqualThanK(v1, intv2); this.AssumeLeftLessEqualThanK(this.ExpressionManager.Decoder.UnderlyingVariable(this.ExpressionManager.Decoder.Stripped(exp1)), intv2); } return this; } protected override IntervalEnvironment_IEEE754<Variable, Expression> TestNotEqualToZero(Expression guard) { return this; } protected override IntervalEnvironment_IEEE754<Variable, Expression> TestNotEqualToZero(Variable v) { // cannot capture v != 0 return this; } protected override IntervalEnvironment_IEEE754<Variable, Expression> TestEqualToZero(Variable v) { var intv = Interval_IEEE754.For(0); Interval_IEEE754 prevVal; if (this.TryGetValue(v, out prevVal)) { intv = prevVal.Meet(intv); } this[v] = intv; return this; } protected override void AssumeKLessThanRight(Interval_IEEE754 k, Variable leftExp) { if (k.IsSingleton) { if (k.LowerBound.IsZero()) { var kPlusEpsilon = Interval_IEEE754.For(Double.Epsilon, Double.PositiveInfinity); Interval_IEEE754 prevIntv; if (this.TryGetValue(leftExp, out prevIntv)) { this[leftExp] = prevIntv.Meet(kPlusEpsilon); } else { this[leftExp] = kPlusEpsilon; } } else // We overapproximate { var intv = Interval_IEEE754.For(k.LowerBound, Double.PositiveInfinity); Interval_IEEE754 prevIntv; if (this.TryGetValue(leftExp, out prevIntv)) { this[leftExp] = prevIntv.Meet(intv); } else { this[leftExp] = intv; } } } } private Interval_IEEE754 IntervalForKLessThanRight(Interval_IEEE754 k, Variable leftExp) { if (k.IsSingleton) { if (k.LowerBound.IsZero()) { var kPlusEpsilon = Interval_IEEE754.For(Double.Epsilon, Double.PositiveInfinity); Interval_IEEE754 prevIntv; if (this.TryGetValue(leftExp, out prevIntv)) { return prevIntv.Meet(kPlusEpsilon); } else { return kPlusEpsilon; } } else // We overapproximate { var intv = Interval_IEEE754.For(k.LowerBound, Double.PositiveInfinity); Interval_IEEE754 prevIntv; if (this.TryGetValue(leftExp, out prevIntv)) { return prevIntv.Meet(intv); } else { return intv; } } } return Interval_IEEE754.UnknownInterval; } protected override void AssumeLeftLessThanK(Variable leftExp, Interval_IEEE754 k) { if (k.IsSingleton) { Interval_IEEE754 intv; if (k.LowerBound.IsZero()) { // leftExp < 0 intv = Interval_IEEE754.For(Double.NegativeInfinity, -Double.Epsilon); } else // We overapproximate { intv = Interval_IEEE754.For(Double.NegativeInfinity, k.LowerBound - double.Epsilon); } Interval_IEEE754 prevIntv; if (this.TryGetValue(leftExp, out prevIntv)) { this[leftExp] = prevIntv.Meet(intv); } else { this[leftExp] = intv; } } } private Interval_IEEE754 IntervalForLeftLessThanK(Variable leftExp, Interval_IEEE754 k) { return Interval_IEEE754.UnknownInterval; } public override bool IsGreaterEqualThanZero(double val) { return val >= 0.0; } public override bool IsGreaterThanZero(double val) { return val > 0.0; } public override bool IsLessThanZero(double val) { return val < 0.0; } public override bool IsLessEqualThanZero(double val) { return val <= 0.0; } public override bool IsLessThan(double val1, double val2) { return val1 < val2; } public override bool IsLessEqualThan(double val1, double val2) { return val1 <= val2; } public override bool IsZero(double val) { return val == 0.0; } public override bool IsNotZero(double val) { return val != 0.0; } public override bool IsMaxInt32(Interval_IEEE754 intv) { return false; } public override bool IsMinInt32(Interval_IEEE754 intv) { return false; } public override bool IsPlusInfinity(double val) { return Double.IsPositiveInfinity(val); } public override bool IsMinusInfinity(double val) { return Double.IsNegativeInfinity(val); } public override double PlusInfinity { get { return Double.PositiveInfinity; } } public override double MinusInfinty { get { return Double.NegativeInfinity; } } public override bool TryAdd(double left, double right, out double result) { result = left + right; return true; } public override Interval_IEEE754 IntervalUnknown { get { return Interval_IEEE754.UnknownInterval; } } public override Interval_IEEE754 IntervalZero { get { return Interval_IEEE754.ZeroInterval_IEEE754; } } public override Interval_IEEE754 IntervalOne { get { return Interval_IEEE754.OneInterval_IEEE754; } } public override Interval_IEEE754 Interval_Positive { get { return Interval_IEEE754.PositiveInterval; } } public override Interval_IEEE754 Interval_StrictlyPositive { get { return this.IntervalRightOpen(1.0); } } public override Interval_IEEE754 IntervalGreaterEqualThanMinusOne { get { return Interval_IEEE754.For(-1, double.PositiveInfinity); } } public override Interval_IEEE754 IntervalSingleton(double val) { return Interval_IEEE754.For(val); } public override Interval_IEEE754 IntervalRightOpen(double inf) { return Interval_IEEE754.For(inf, double.PositiveInfinity); } public override Interval_IEEE754 IntervalLeftOpen(double sup) { return Interval_IEEE754.For(double.NegativeInfinity, sup); } public override bool AreEqual(Interval_IEEE754 left, Interval_IEEE754 right) { return left.IsNormal && right.IsNormal && left.LessEqual(right) && right.LessEqual(left); } public override Interval_IEEE754 Interval_Add(Interval_IEEE754 left, Interval_IEEE754 right) { return left + right; } public override Interval_IEEE754 Interval_Div(Interval_IEEE754 left, Interval_IEEE754 right) { return left / right; } public override Interval_IEEE754 Interval_Sub(Interval_IEEE754 left, Interval_IEEE754 right) { return left - right; } public override Interval_IEEE754 Interval_Mul(Interval_IEEE754 left, Interval_IEEE754 right) { return left * right; } public override Interval_IEEE754 Interval_UnaryMinus(Interval_IEEE754 left) { return -left; } public override Interval_IEEE754 Interval_Not(Interval_IEEE754 left) { double value; if (left.TryGetSingletonValue(out value) && value != 0.0) { return Interval_IEEE754.ZeroInterval_IEEE754; } return Interval_IEEE754.UnknownInterval; } public override Interval_IEEE754 Interval_Rem(Interval_IEEE754 left, Interval_IEEE754 right) { return left % right; } public override Interval_IEEE754 Interval_BitwiseAnd(Interval_IEEE754 left, Interval_IEEE754 right) { return left & right; } public override Interval_IEEE754 Interval_BitwiseOr(Interval_IEEE754 left, Interval_IEEE754 right) { return left | right; } public override Interval_IEEE754 Interval_BitwiseXor(Interval_IEEE754 left, Interval_IEEE754 right) { return left ^ right; } public override Interval_IEEE754 Interval_ShiftLeft(Interval_IEEE754 left, Interval_IEEE754 right) { return Interval_IEEE754.ShiftLeft(left, right); } public override Interval_IEEE754 Interval_ShiftRight(Interval_IEEE754 left, Interval_IEEE754 right) { return Interval_IEEE754.ShiftRight(left, right); } public override Interval_IEEE754 For(byte v) { return Interval_IEEE754.For(v); } public override Interval_IEEE754 For(short v) { return Interval_IEEE754.For(v); } public override Interval_IEEE754 For(int v) { return Interval_IEEE754.For(v); } public override Interval_IEEE754 For(long v) { return Interval_IEEE754.For(v); } public override Interval_IEEE754 For(sbyte s) { return Interval_IEEE754.For(s); } public override Interval_IEEE754 For(ushort u) { return Interval_IEEE754.For(u); } public override Interval_IEEE754 For(uint u) { return Interval_IEEE754.For(u); } public override Interval_IEEE754 For(Rational r) { return Interval_IEEE754.For(r); } public override Interval_IEEE754 For(double d) { return For(d, d); } public override Interval_IEEE754 For(double inf, double sup) { return Interval_IEEE754.For(inf, sup); } /// <summary> /// Abstraction ... For the moment is the identity /// </summary> protected override Interval_IEEE754 ApplyConversion(ExpressionOperator conversionType, Interval_IEEE754 val) { switch (conversionType) { case ExpressionOperator.ConvertToFloat32: case ExpressionOperator.ConvertToFloat64: return val; default: return val.Top; } } protected override T To<T>(double n, IFactory<T> factory) { return factory.Constant(n); } protected override IntervalEnvironment_IEEE754<Variable, Expression> Factory() { return new IntervalEnvironment_IEEE754<Variable, Expression>(this.ExpressionManager); } public override DisInterval BoundsFor(Expression exp) { return ConvertInterval_IEEE754(this.Eval(exp)); } public override DisInterval BoundsFor(Variable var) { Interval_IEEE754 res; if (this.TryGetValue(var, out res)) { return ConvertInterval_IEEE754(res); } else { return ConvertInterval_IEEE754(Interval_IEEE754.UnknownInterval); } } protected override void AssumeInDisInterval_Internal(Variable x, DisInterval disIntv) { Rational r; if (disIntv.TryGetSingletonValue(out r)) { Interval_IEEE754 value; long intValue; if (r.TryInt64(out intValue)) { value = Interval_IEEE754.For(intValue); } else { value = Interval_IEEE754.For((double)r); } Interval_IEEE754 prev; if (this.TryGetValue(x, out prev)) { value = value.Meet(prev); } this[x] = value; } } protected override Interval_IEEE754 ConvertInterval(Interval intv) { return Interval_IEEE754.ConvertInterval(intv); } protected DisInterval ConvertInterval_IEEE754(Interval_IEEE754 intv) { return Interval_IEEE754.ConvertInterval(intv); } } }
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 AnimalLookupWebservice.Areas.HelpPage.ModelDescriptions; using AnimalLookupWebservice.Areas.HelpPage.Models; namespace AnimalLookupWebservice.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); } } } }
//============================================================================== // LabEditor -> // Copyright (c) 2015 All Right Reserved, http://nordiklab.com/ //------------------------------------------------------------------------------ //============================================================================== $TPG_AutoStepGeneration = "1"; $TPG_StepGenerationMode = "1"; //============================================================================== // Terrain Paint Generator - Terrain Paint Generation Functions //============================================================================== //============================================================================== // Generate all the layers in the layer group function TPG::generateLayerGroup(%this) { //First make sure layers data is right TPG.checkLayersStackGroup(); foreach(%layer in TPG_LayerGroup) { %layer.inactive = false; %layer.failedSettings = ""; if ( !%layer.activeCtrl.isStateOn()) { %layer.inactive = true; continue; } %layer.fieldsValidated = false; %validated = %this.validateLayerObjSetting(%layer,true); if (strFind(%layer.matInternalName,"*")) %layer.failedSettings = "Invalid material assigned to layer, please select a valid from the menu"; if (%layer.failedSettings !$= "") { %validationgFailed = true; %badLayers = strAddRecord(%badLayers,%layer.internalName SPC "Bad fields:" SPC %layer.failedSettings); } } if (%validationgFailed) { if (%badLayers !$="" ) { LabMsgOk("Generation aborted!","Some layers have fail the validation. Here's the list:\c2" SPC %badLayers @ ". Please fix them before attempting generation again."); } return; } show(TPG_GenerateProgressWindow); TPG_GenerateLayerStack.clear(); foreach(%ctrl in TPG_StackLayers) { %layer = %ctrl.layerObj; if (%layer.inactive) continue; %heightMin = %layer.getFieldValue("heightMin"); %heightMax = %layer.getFieldValue("heightMax"); %slopeMin = %layer.getFieldValue("slopeMin"); %slopeMax = %layer.getFieldValue("slopeMax"); %coverage = %layer.getFieldValue("coverage"); %pill = cloneObject(TPG_GenerateInfoPill_v2,"",%layer.internalName,TPG_GenerateLayerStack); %pill.internalName = %layer.internalName; %pill-->id.text = "#"@%layerId++ @ "-"; %pill-->material.text = %layer.matInternalName; %pill-->slopeMinMax.setText(%slopeMin SPC "/" SPC %slopeMax); %pill-->heightMinMax.text = %heightMin SPC "/" SPC %heightMax; %pill-->coverage.text = %coverage; %pill-->duration.text = "pending"; } if (%layerId < 1) { LabMsgOk("No active layers","There's no active layers to generate terrain materials, operation aborted"); hide(TPG_GenerateProgressWindow); return; } TPG_GenerateProgressWindow-->cancelButton.visible = 1; TPG_GenerateProgressWindow-->reportButton.text = "Start process"; TPG_GenerateProgressWindow-->reportButton.active = 1; $TPG_GenerationStatus = "Pending"; TPG_GenerateProgressWindow-->reportText.text = %layerId SPC "layers are ready to be processed"; //LabMsgYesNo("Early development feature","The terrain pain generator is still in early development and can cause the engine to freeze. "@ // "We recommend you to save your work before proceeding with automated painting. Are you sure you want to start the painting process?","TPG.schedule(1000,\"startGeneration\");"); //%this.schedule(1000,"startGeneration"); } function TPG::toggleStepMode(%this,%checkbox) { return; if (%checkbox.isStateOn()) $TPG_AutoStepGeneration = "0"; else $TPG_AutoStepGeneration = "1"; } //------------------------------------------------------------------------------ function TPG_ReportButton::onClick(%this) { devLog("OnCLick"); switch$($TPG_GenerationStatus) { case "Pending": %this.text = "Processing"; %this.active = false; TPG_GenerateProgressWindow-->cancelButton.visible = 0; TPG.startGeneration(); case "Completed": hide(TPG_GenerateProgressWindow); } } //============================================================================== // Start the generation process now that everything is validated function TPG::startGeneration(%this) { if ($TPG_Generating) return; TPG.generationStartTime = $Sim::Time; $TPG_Generating = true; TPG.generatorSteps = ""; foreach(%ctrl in TPG_StackLayers) { %layer = %ctrl.layerObj; if (%layer.inactive) continue; TPG.generatorSteps = strAddWord(TPG.generatorSteps,%layer.getId()); } $TPG_Generating = false; //TPG_GenerateProgressWindow.setVisible(false); %this.doGenerateLayerStep(200); } //------------------------------------------------------------------------------ function TPG::doGenerateLayerStep(%this,%delay) { %layer = getWord(TPG.generatorSteps,0); if (%layer $= "") return; %pill = TPG_GenerateLayerStack.findObjectByInternalName(%layer.internalName,true); %pill-->duration.text = "Processing"; TPG_GenerateProgressWindow-->reportText.text ="Processing layer:" SPC %layer.matInternalName @"." SPC getWordCount(TPG.generatorSteps) SPC "left to process."; TPG.generatorSteps = removeWord(TPG.generatorSteps,0); $TPG_LayerStartTime = $Sim::Time; %this.schedule(%delay,"generateLayer",%layer,true); } //============================================================================== // Tell the engine to generate a layer with approved settings function TPG::generateLayer(%this,%layer,%stepMode) { ETerrainEditor.paintIndex = %layer.matIndex; %heightMin = %layer.getFieldValue("heightMin"); %heightMax = %layer.getFieldValue("heightMax"); %slopeMin = %layer.getFieldValue("slopeMin"); %slopeMax = %layer.getFieldValue("slopeMax"); %coverage = %layer.getFieldValue("coverage"); %terrain = ETerrainEditor.getActiveTerrain(); %heightMin_w = getWord(%terrain.position,2) + %heightMin; %heightMax_w = getWord(%terrain.position,2) + %heightMax; if (%stepMode) info("Step Painting terrain with Mat Index",%layer.matIndex,"Name",%layer.matInternalName,"Height and Slope",%heightMin_w@"("@%heightMin@")", %heightMax_w@"("@%heightMax@")", %slopeMin, %slopeMax,"Coverage",%coverage); else info("Painting terrain with Mat Index",%layer.matIndex,"Name",%layer.matInternalName,"Height and Slope",%heightMin, %heightMax, %slopeMin, %slopeMax,"Coverage",%coverage); ETerrainEditor.autoMaterialLayer(%heightMin_w, %heightMax_w, %slopeMin, %slopeMax,%coverage); %this.generateLayerCompleted(%layer); } //------------------------------------------------------------------------------ //============================================================================== // Tell the engine to generate a layer with approved settings function TPG::generateLayerCompleted(%this,%layer) { TPG.generationTotalTime = $Sim::Time - TPG.generationStartTime; %layerTime = $Sim::Time - $TPG_LayerStartTime; %pill = TPG_GenerateLayerStack.findObjectByInternalName(%layer.internalName,true); %pill-->duration.text = mFloatLength(%layerTime,2) SPC "sec"; //Get next layer step, if empty, process is completed %nextStep = getWord(TPG.generatorSteps,0); if (%nextStep !$= "") { //Call next step now if we are in Auto Step Generation mode, else wait for next step confirmation if (!TPG_StepModeCheckbox.isStateOn()) TPG.doGenerateLayerStep(200); else LabMsgYesNo(%layer.matInternalName SPC "step completed","Do you want to proceed with next step:" SPC getWord(TPG.generatorSteps,0).matInternalName SPC "?","TPG.doGenerateLayerStep(500);","TPG.generateProcessCompleted();"); } else { %this.generateProcessCompleted(); } } //------------------------------------------------------------------------------ //============================================================================== // Tell the engine to generate a layer with approved settings function TPG::generateProcessCompleted(%this) { if (TPG.generatorSteps !$= "") %result = "Process cancelled. ("@getWordCount(TPG.generatorSteps)@" unprocessed)."; else %result = "All layers have been processed."; TPG.generatorSteps = ""; $TPG_GenerationStatus = "Completed"; TPG_GenerateProgressWindow-->reportText.text = %result SPC "Process time:\c1 " @ TPG.generationTotalTime @ " sec"; TPG_GenerateProgressWindow-->reportButton.text = "Close report"; TPG_GenerateProgressWindow-->reportButton.active = 1; } //------------------------------------------------------------------------------
// 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. /*============================================================ ** ** ** ** Purpose: A wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using Internal.Runtime.CompilerServices; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Single : IComparable, IConvertible, IFormattable, IComparable<Single>, IEquatable<Single>, ISpanFormattable { private float m_value; // Do not rename (binary serialization) // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; // We use this explicit definition to avoid the confusion between 0.0 and -0.0. internal const float NegativeZero = (float)-0.0; /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsFinite(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) < 0x7F800000; } /// <summary>Determines whether the specified value is infinite.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsInfinity(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) == 0x7F800000; } /// <summary>Determines whether the specified value is NaN.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsNaN(float f) { var bits = BitConverter.SingleToInt32Bits(f); return (bits & 0x7FFFFFFF) > 0x7F800000; } /// <summary>Determines whether the specified value is negative.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsNegative(float f) { var bits = unchecked((uint)BitConverter.SingleToInt32Bits(f)); return (bits & 0x80000000) == 0x80000000; } /// <summary>Determines whether the specified value is negative infinity.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsNegativeInfinity(float f) { return (f == float.NegativeInfinity); } /// <summary>Determines whether the specified value is normal.</summary> [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public static unsafe bool IsNormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0); } /// <summary>Determines whether the specified value is positive infinity.</summary> [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static unsafe bool IsPositiveInfinity(float f) { return (f == float.PositiveInfinity); } /// <summary>Determines whether the specified value is subnormal.</summary> [NonVersionable] // This is probably not worth inlining, it has branches and should be rarely called public static unsafe bool IsSubnormal(float f) { var bits = BitConverter.SingleToInt32Bits(f); bits &= 0x7FFFFFFF; return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0); } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (m_value < f) return -1; if (m_value > f) return 1; if (m_value == f) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } [NonVersionable] public static bool operator ==(Single left, Single right) { return left == right; } [NonVersionable] public static bool operator !=(Single left, Single right) { return left != right; } [NonVersionable] public static bool operator <(Single left, Single right) { return left < right; } [NonVersionable] public static bool operator >(Single left, Single right) { return left > right; } [NonVersionable] public static bool operator <=(Single left, Single right) { return left <= right; } [NonVersionable] public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj).m_value; if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } public bool Equals(Single obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } public override int GetHashCode() { var bits = Unsafe.As<float, int>(ref m_value); // Optimized check for IsNan() || IsZero() if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000) { // Ensure that all NaNs and both zeros have the same hash code bits &= 0x7F800000; } return bits; } public override String ToString() { return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo); } public String ToString(IFormatProvider provider) { return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider)); } public String ToString(String format) { return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo); } public String ToString(String format, IFormatProvider provider) { return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider)); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo); } public static float Parse(String s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static Boolean TryParse(String s, out Single result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out float result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out float result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static Boolean TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Single result) { bool success = Number.TryParseSingle(s, style, info, out result); if (!success) { ReadOnlySpan<char> sTrim = s.Trim(); if (sTrim.EqualsOrdinal(info.PositiveInfinitySymbol)) { result = PositiveInfinity; } else if (sTrim.EqualsOrdinal(info.NegativeInfinitySymbol)) { result = NegativeInfinity; } else if (sTrim.EqualsOrdinal(info.NaNSymbol)) { result = NaN; } else { return false; // We really failed } } return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return m_value; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2016 Colin Green ([email protected]) * * SharpNEAT is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SharpNEAT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Threading; using log4net; using SharpNeat.Core; using System.Threading.Tasks; // Disable missing comment warnings for non-private variables. #pragma warning disable 1591 namespace SharpNeat.EvolutionAlgorithms { /// <summary> /// Abstract class providing some common/baseline data and methods for implementions of IEvolutionAlgorithm. /// </summary> /// <typeparam name="TGenome">The genome type that the algorithm will operate on.</typeparam> public abstract class AbstractGenerationalAlgorithm<TGenome> : IEvolutionAlgorithm<TGenome> where TGenome : class, IGenome<TGenome> { private static readonly ILog __log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #region Instance Fields protected IGenomeListEvaluator<TGenome> _genomeListEvaluator; protected IGenomeFactory<TGenome> _genomeFactory; protected List<TGenome> _genomeList; protected int _populationSize; protected TGenome _currentBestGenome; // Algorithm state data. RunState _runState = RunState.NotReady; protected uint _currentGeneration; // Update event scheme / data. UpdateScheme _updateScheme; uint _prevUpdateGeneration; long _prevUpdateTimeTick; // Misc working variables. Thread _algorithmThread; bool _pauseRequestFlag; readonly AutoResetEvent _awaitPauseEvent = new AutoResetEvent(false); readonly AutoResetEvent _awaitRestartEvent = new AutoResetEvent(false); #endregion #region Events /// <summary> /// Notifies listeners that some state change has occured. /// </summary> public event EventHandler UpdateEvent; /// <summary> /// Notifies listeners that the algorithm has paused. /// </summary> public event EventHandler PausedEvent; #endregion #region Properties /// <summary> /// Gets the current generation. /// </summary> public uint CurrentGeneration { get { return _currentGeneration; } } #endregion #region IEvolutionAlgorithm<TGenome> Members /// <summary> /// Gets or sets the algorithm's update scheme. /// </summary> public UpdateScheme UpdateScheme { get { return _updateScheme; } set { _updateScheme = value; } } /// <summary> /// Gets the current execution/run state of the IEvolutionAlgorithm. /// </summary> public RunState RunState { get { return _runState; } } /// <summary> /// Gets the population's current champion genome. /// </summary> public TGenome CurrentChampGenome { get { return _currentBestGenome; } } /// <summary> /// Gets a value indicating whether some goal fitness has been achieved and that the algorithm has therefore stopped. /// </summary> public bool StopConditionSatisfied { get { return _genomeListEvaluator.StopConditionSatisfied; } } /// <summary> /// Initializes the evolution algorithm with the provided IGenomeListEvaluator, IGenomeFactory /// and an initial population of genomes. /// </summary> /// <param name="genomeListEvaluator">The genome evaluation scheme for the evolution algorithm.</param> /// <param name="genomeFactory">The factory that was used to create the genomeList and which is therefore referenced by the genomes.</param> /// <param name="genomeList">An initial genome population.</param> public virtual void Initialize(IGenomeListEvaluator<TGenome> genomeListEvaluator, IGenomeFactory<TGenome> genomeFactory, List<TGenome> genomeList) { _currentGeneration = 0; _genomeListEvaluator = genomeListEvaluator; _genomeFactory = genomeFactory; _genomeList = genomeList; _populationSize = _genomeList.Count; _runState = RunState.Ready; _updateScheme = new UpdateScheme(new TimeSpan(0, 0, 1)); } /// <summary> /// Initializes the evolution algorithm with the provided IGenomeListEvaluator /// and an IGenomeFactory that can be used to create an initial population of genomes. /// </summary> /// <param name="genomeListEvaluator">The genome evaluation scheme for the evolution algorithm.</param> /// <param name="genomeFactory">The factory that was used to create the genomeList and which is therefore referenced by the genomes.</param> /// <param name="populationSize">The number of genomes to create for the initial population.</param> public virtual void Initialize(IGenomeListEvaluator<TGenome> genomeListEvaluator, IGenomeFactory<TGenome> genomeFactory, int populationSize) { _currentGeneration = 0; _genomeListEvaluator = genomeListEvaluator; _genomeFactory = genomeFactory; _genomeList = genomeFactory.CreateGenomeList(populationSize, _currentGeneration); _populationSize = populationSize; _runState = RunState.Ready; _updateScheme = new UpdateScheme(new TimeSpan(0, 0, 1)); } /// <summary> /// Starts the algorithm running. The algorithm will switch to the Running state from either /// the Ready or Paused states. /// </summary> public void StartContinue() { // RunState must be Ready or Paused. if(RunState.Ready == _runState) { // Create a new thread and start it running. _algorithmThread = new Thread(AlgorithmThreadMethod); _algorithmThread.IsBackground = true; _algorithmThread.Priority = ThreadPriority.BelowNormal; _runState = RunState.Running; OnUpdateEvent(); _algorithmThread.Start(); } else if(RunState.Paused == _runState) { // Thread is paused. Resume execution. _runState = RunState.Running; OnUpdateEvent(); _awaitRestartEvent.Set(); } else if(RunState.Running == _runState) { // Already running. Log a warning. __log.Warn("StartContinue() called but algorithm is already running."); } else { throw new SharpNeatException(string.Format("StartContinue() call failed. Unexpected RunState [{0}]", _runState)); } } /// <summary> /// Alias for RequestPause(). /// </summary> public void Stop() { RequestPause(); } /// <summary> /// Requests that the algorithm pauses but doesn't wait for the algorithm thread to stop. /// The algorithm thread will pause when it is next convenient to do so, and will notify /// listeners via an UpdateEvent. /// </summary> public void RequestPause() { if(RunState.Running == _runState) { _pauseRequestFlag = true; } else { __log.Warn("RequestPause() called but algorithm is not running."); } } /// <summary> /// Request that the algorithm pause and waits for the algorithm to do so. The algorithm /// thread will pause when it is next convenient to do so and notifies any UpdateEvent /// listeners prior to returning control to the caller. Therefore it's generally a bad idea /// to call this method from a GUI thread that also has code that may be called by the /// UpdateEvent - doing so will result in deadlocked threads. /// </summary> public void RequestPauseAndWait() { if(RunState.Running == _runState) { // Set a flag that tells the algorithm thread to enter the paused state and wait // for a signal that tells us the thread has paused. _pauseRequestFlag = true; _awaitPauseEvent.WaitOne(); } else { __log.Warn("RequestPauseAndWait() called but algorithm is not running."); } } #endregion #region Private/Protected Methods [Evolution Algorithm] private void AlgorithmThreadMethod() { try { _prevUpdateGeneration = 0; _prevUpdateTimeTick = DateTime.Now.Ticks; for(;;) { _currentGeneration++; PerformOneGeneration(); if(UpdateTest()) { _prevUpdateGeneration = _currentGeneration; _prevUpdateTimeTick = DateTime.Now.Ticks; OnUpdateEvent(); } // Check if a pause has been requested. // Access to the flag is not thread synchronized, but it doesn't really matter if // we miss it being set and perform one other generation before pausing. if(_pauseRequestFlag || _genomeListEvaluator.StopConditionSatisfied) { // Signal to any waiting thread that we are pausing _awaitPauseEvent.Set(); // Reset the flag. Update RunState and notify any listeners of the state change. _pauseRequestFlag = false; _runState = RunState.Paused; OnUpdateEvent(); OnPausedEvent(); // Wait indefinitely for a signal to wake up and continue. _awaitRestartEvent.WaitOne(); } } } catch(ThreadAbortException) { // Quietly exit thread. } } /// <summary> /// Returns true if it is time to raise an update event. /// </summary> private bool UpdateTest() { if(UpdateMode.Generational == _updateScheme.UpdateMode) { return (_currentGeneration - _prevUpdateGeneration) >= _updateScheme.Generations; } return (DateTime.Now.Ticks - _prevUpdateTimeTick) >= _updateScheme.TimeSpan.Ticks; } private void OnUpdateEvent() { if(null != UpdateEvent) { // Catch exceptions thrown by even listeners. This prevents listener exceptions from terminating the algorithm thread. try { UpdateEvent(this, EventArgs.Empty); } catch(Exception ex) { __log.Error("UpdateEvent listener threw exception", ex); } } } private void OnPausedEvent() { if(null != PausedEvent) { // Catch exceptions thrown by even listeners. This prevents listener exceptions from terminating the algorithm thread. try { PausedEvent(this, EventArgs.Empty); } catch(Exception ex) { __log.Error("PausedEvent listener threw exception", ex); } } } /// <summary> /// Progress forward by one generation. Perform one generation/cycle of the evolution algorithm. /// </summary> protected abstract void PerformOneGeneration(); #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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DiskConfig", SupportsShouldProcess = true)] [OutputType(typeof(PSDisk))] public partial class NewAzureRmDiskConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)] [Alias("AccountType")] [PSArgumentCompleter("Standard_LRS", "Premium_LRS", "StandardSSD_LRS", "UltraSSD_LRS")] public string SkuName { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public OperatingSystemTypes? OsType { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public int DiskSizeGB { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] [LocationCompleter("Microsoft.Compute/disks")] public string Location { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string[] Zone { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int DiskIOPSReadWrite { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public int DiskMBpsReadWrite { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string CreateOption { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string StorageAccountId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public ImageDiskReference ImageReference { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SourceUri { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SourceResourceId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public bool? EncryptionSettingsEnabled { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndSecretReference DiskEncryptionKey { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndKeyReference KeyEncryptionKey { get; set; } protected override void ProcessRecord() { if (ShouldProcess("Disk", "New")) { Run(); } } private void Run() { // Sku DiskSku vSku = null; // CreationData CreationData vCreationData = null; // EncryptionSettings EncryptionSettings vEncryptionSettings = null; if (this.MyInvocation.BoundParameters.ContainsKey("SkuName")) { if (vSku == null) { vSku = new DiskSku(); } vSku.Name = this.SkuName; } if (this.MyInvocation.BoundParameters.ContainsKey("CreateOption")) { if (vCreationData == null) { vCreationData = new CreationData(); } vCreationData.CreateOption = this.CreateOption; } if (this.MyInvocation.BoundParameters.ContainsKey("StorageAccountId")) { if (vCreationData == null) { vCreationData = new CreationData(); } vCreationData.StorageAccountId = this.StorageAccountId; } if (this.MyInvocation.BoundParameters.ContainsKey("ImageReference")) { if (vCreationData == null) { vCreationData = new CreationData(); } vCreationData.ImageReference = this.ImageReference; } if (this.MyInvocation.BoundParameters.ContainsKey("SourceUri")) { if (vCreationData == null) { vCreationData = new CreationData(); } vCreationData.SourceUri = this.SourceUri; } if (this.MyInvocation.BoundParameters.ContainsKey("SourceResourceId")) { if (vCreationData == null) { vCreationData = new CreationData(); } vCreationData.SourceResourceId = this.SourceResourceId; } if (this.MyInvocation.BoundParameters.ContainsKey("EncryptionSettingsEnabled")) { if (vEncryptionSettings == null) { vEncryptionSettings = new EncryptionSettings(); } vEncryptionSettings.Enabled = this.EncryptionSettingsEnabled; } if (this.MyInvocation.BoundParameters.ContainsKey("DiskEncryptionKey")) { if (vEncryptionSettings == null) { vEncryptionSettings = new EncryptionSettings(); } vEncryptionSettings.DiskEncryptionKey = this.DiskEncryptionKey; } if (this.MyInvocation.BoundParameters.ContainsKey("KeyEncryptionKey")) { if (vEncryptionSettings == null) { vEncryptionSettings = new EncryptionSettings(); } vEncryptionSettings.KeyEncryptionKey = this.KeyEncryptionKey; } var vDisk = new PSDisk { Zones = this.MyInvocation.BoundParameters.ContainsKey("Zone") ? this.Zone : null, OsType = this.MyInvocation.BoundParameters.ContainsKey("OsType") ? this.OsType : (OperatingSystemTypes?)null, DiskSizeGB = this.MyInvocation.BoundParameters.ContainsKey("DiskSizeGB") ? this.DiskSizeGB : (int?)null, DiskIOPSReadWrite = this.MyInvocation.BoundParameters.ContainsKey("DiskIOPSReadWrite") ? this.DiskIOPSReadWrite : (int?)null, DiskMBpsReadWrite = this.MyInvocation.BoundParameters.ContainsKey("DiskMBpsReadWrite") ? this.DiskMBpsReadWrite : (int?)null, Location = this.MyInvocation.BoundParameters.ContainsKey("Location") ? this.Location : null, Tags = this.MyInvocation.BoundParameters.ContainsKey("Tag") ? this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value) : null, Sku = vSku, CreationData = vCreationData, EncryptionSettings = vEncryptionSettings, }; WriteObject(vDisk); } } }
using System; using System.Collections.Generic; using System.Linq; using Core.Interfaces; using Core.Model; using Moq; using NUnit.Framework; using Ui.Console.Command; using Ui.Console.Provider; using Ui.Console.Startup; namespace Ui.Console.Test.Provider { [TestFixture] public class KeyCommandActivationProviderTest { private KeyCommandActivationProvider provider; private Mock<ICommandExecutor> commandExecutor; private ApplicationArguments arguments; [OneTimeSetUp] public void SetupCommandActivationProviderTest() { commandExecutor = new Mock<ICommandExecutor>(); provider = new KeyCommandActivationProvider(commandExecutor.Object, new KeyCommandProvider(), new FileCommandProvider()); } [TestFixture] public class CreateKeyPair : KeyCommandActivationProviderTest { private IAsymmetricKey privateKey; private IAsymmetricKey publicKey; private AsymmetricKeyPair createdKeyPair; [OneTimeSetUp] public void Setup() { privateKey = Mock.Of<IAsymmetricKey>(); publicKey = Mock.Of<IAsymmetricKey>(); createdKeyPair = new AsymmetricKeyPair(privateKey, publicKey); commandExecutor.Setup(c => c.Execute(It.IsAny<object>())) .Callback<object>(c => { if (c is WriteFileCommand<IAsymmetricKey> || c is WriteFileCommand<IAsymmetricKeyPair>) { return; } ((ICreateAsymmetricKeyCommand) c).Result = createdKeyPair; }); arguments = new ApplicationArguments { KeySize = 1024, EncryptionType = EncryptionType.Pkcs, PrivateKeyPath = "private.pem", PublicKeyPath = "public.pem", ContentType = ContentType.Pem, KeyType = CipherType.Rsa }; provider.CreateKeyPair(arguments); } [Test] public void ShouldCreateRsaKeyPair() { commandExecutor.Verify(ce => ce.Execute(It.Is<CreateKeyCommand<RsaKey>>(c => c.KeySize == 1024))); } [Test] public void ShouldCreateDsaKeyPair() { arguments.KeyType = CipherType.Dsa; provider.CreateKeyPair(arguments); commandExecutor.Verify(ce => ce.Execute(It.Is<CreateKeyCommand<DsaKey>>(c => c.KeySize == 1024))); } [Test] public void ShouldCreateEcKeyPair() { arguments.KeyType = CipherType.Ec; arguments.Curve = "foobar"; provider.CreateKeyPair(arguments); commandExecutor.Verify(ce => ce.Execute(It.Is<CreateKeyCommand<IEcKey>>(c => c.Curve == "foobar"))); } [Test] public void ShouldCreateElGamalKeyPair() { arguments.KeyType = CipherType.ElGamal; provider.CreateKeyPair(arguments); commandExecutor.Verify(ce => ce.Execute(It.Is<CreateKeyCommand<ElGamalKey>>(c => c.KeySize == 1024))); } [TestCase(CipherType.Pkcs5Encrypted)] [TestCase(CipherType.Pkcs12Encrypted)] [TestCase(CipherType.Unknown)] public void ShouldThrowExceptionWhenKeyTypeIsNotSupported(CipherType cipherType) { arguments.KeyType = cipherType; Assert.Throws<ArgumentException>(() => { provider.CreateKeyPair(arguments); }); } [Test] public void ShouldWriteCreatedPrivateKeyToFile() { commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(w => w.Out == privateKey && w.FilePath == "private.pem" && w.ContentType == ContentType.Pem && w.EncryptionType == EncryptionType.Pkcs))); } [Test] public void ShouldWriteCreatedPublicKeyToFile() { commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(w => w.Out == publicKey && w.FilePath == "public.pem" && w.ContentType == ContentType.Pem && w.EncryptionType == EncryptionType.None))); } [Test] public void ShouldWriteKeyPairAsPrivateKeyWhenKeyIsCurve25519OpenSsh() { Setup25519OpenSsh(); commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKeyPair>>(w => w.Out == createdKeyPair && w.FilePath == "private.pem" && w.ContentType == ContentType.OpenSsh && w.EncryptionType == EncryptionType.None))); } private void Setup25519OpenSsh() { arguments = new ApplicationArguments { Curve = "curve25519", PrivateKeyPath = "private.pem", PublicKeyPath = "public.pem", ContentType = ContentType.OpenSsh, KeyType = CipherType.Ec }; provider.CreateKeyPair(arguments); } [Test] public void ShouldWritePrivateKeyAsPublicKeyWhenKeyIsCurve25519OpenSsh() { Setup25519OpenSsh(); commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(w => w.Out == privateKey && w.FilePath == "public.pem" && w.ContentType == ContentType.OpenSsh && w.EncryptionType == EncryptionType.None))); } } [TestFixture] public class VerifyKeyPair : KeyCommandActivationProviderTest { private IAsymmetricKey publicKey; private IAsymmetricKey privateKey; [SetUp] public void Setup() { arguments = new ApplicationArguments { PrivateKeyPath = "private.key", PublicKeyPath = "public.key" }; publicKey = Mock.Of<IAsymmetricKey>(); privateKey = Mock.Of<IAsymmetricKey>(); commandExecutor.Setup(c => c.ExecuteSequence(It.IsAny<IEnumerable<object>>())) .Callback<IEnumerable<object>>(commands => { commands.ToList().ForEach(c => { var keyCommand = c as ReadKeyFromFileCommand; if (keyCommand != null && keyCommand.FilePath == "public.key") { keyCommand.Result = publicKey; } if (keyCommand != null && keyCommand.FilePath == "private.key") { keyCommand.Result = privateKey; } }); }); provider.VerifyKeyPair(arguments); } [Test] public void ShouldReadPrivateKey() { commandExecutor.Verify(ce => ce.ExecuteSequence(It.Is<IEnumerable<ReadKeyFromFileCommand>>(w => w.First().FilePath == "private.key"))); } [Test] public void ShouldReadPublicKey() { commandExecutor.Verify(ce => ce.ExecuteSequence(It.Is<IEnumerable<ReadKeyFromFileCommand>>(w => w.Last().FilePath == "public.key"))); } [Test] public void ShouldVerifyKeyPairWithGivenKeys() { commandExecutor.Verify(ce => ce.Execute(It.Is<IVerifyKeyPairCommand>(c => c.PrivateKey == privateKey && c.PublicKey == publicKey))); } } [TestFixture] public class ConvertKeyTest : KeyCommandActivationProviderTest { private IAsymmetricKey publicKey; private IAsymmetricKey privateKey; [SetUp] public void SetupConvertKeyTest() { arguments = new ApplicationArguments { ContentType = ContentType.Der }; privateKey = Mock.Of<IAsymmetricKey>(k => k.IsPrivateKey); publicKey = Mock.Of<IAsymmetricKey>(); commandExecutor.Setup(ce => ce.Execute(It.IsAny<object>())) .Callback<object>(rc => { var readCommand = rc as ReadKeyFromFileCommand; if (readCommand == null) { return; } readCommand.Result = readCommand.IsPrivateKey ? privateKey : publicKey; readCommand.OriginalContentType = ContentType.Pem; readCommand.OriginalEncryptionType = readCommand.IsPrivateKey ? EncryptionType.Pkcs : EncryptionType.None; }); } [Test] public void ShouldThrowExceptionWhenNoKeysAreSpecified() { arguments.PrivateKeyPath = string.Empty; arguments.PublicKeyPath = string.Empty; Assert.Throws<ArgumentException>(() => { provider.ConvertKeyPair(arguments); }); } [Test] public void ShouldThrowExceptionWhenNoContentTypeIsSpecified() { arguments.ContentType = ContentType.NotSpecified; arguments.PrivateKeyPath = "foo"; arguments.PublicKeyPath = "bar"; Assert.Throws<ArgumentException>(() => { provider.ConvertKeyPair(arguments); }); } [TestFixture] public class ConvertKeyPair : ConvertKeyTest { [SetUp] public void Setup() { arguments.PrivateKeyPath = "private.key"; arguments.PublicKeyPath = "public.key"; arguments.Password = "kensentme"; provider.ConvertKeyPair(arguments); } [Test] public void ShouldReadPublicKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<ReadKeyFromFileCommand>(c => !c.IsPrivateKey && c.FilePath == "public.key"))); } [Test] public void ShouldReadPrivateKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<ReadKeyFromFileCommand>(c => c.IsPrivateKey && c.FilePath == "private.key" && c.Password == "kensentme"))); } [Test] public void ShouldWritePublicKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(c => c.FilePath == "public.key.der" && c.Out == publicKey && c.ContentType == ContentType.Der))); } [Test] public void ShouldWritePrivateKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(c => c.FilePath == "private.key.der" && c.Out == privateKey && c.ContentType == ContentType.Der && c.EncryptionType == EncryptionType.Pkcs && c.Password == "kensentme"))); } [Test] public void ShouldThrowExceptionWhenKeyIsAlreadyInTheGivenType() { arguments.ContentType = ContentType.Pem; Assert.Throws<InvalidOperationException>(() => { provider.ConvertKeyPair(arguments); }); } } [TestFixture] public class ConvertPublicKey : ConvertKeyTest { [SetUp] public void Setup() { arguments.PublicKeyPath = "public.key"; provider.ConvertKeyPair(arguments); } [Test] public void ShouldReadPublicKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<ReadKeyFromFileCommand>(c => !c.IsPrivateKey && c.FilePath == "public.key"))); } [Test] public void ShouldNotReadPrivateKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<ReadKeyFromFileCommand>(c => c.IsPrivateKey)), Times.Never()); } [Test] public void ShouldWritePublicKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(c => c.FilePath == "public.key.der" && c.Out == publicKey && c.ContentType == ContentType.Der))); } [Test] public void ShouldThrowExceptionWhenKeyIsAlreadyInTheGivenType() { arguments.ContentType = ContentType.Pem; Assert.Throws<InvalidOperationException>(() => { provider.ConvertKeyPair(arguments); }); } } [TestFixture] public class ConvertPrivateKey : ConvertKeyTest { [SetUp] public void Setup() { arguments.PrivateKeyPath = "private.key"; arguments.Password = "kensentme"; provider.ConvertKeyPair(arguments); } [Test] public void ShouldReadPrivateKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<ReadKeyFromFileCommand>(c => c.IsPrivateKey && c.FilePath == "private.key"))); } [Test] public void ShouldNotReadPublicKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<ReadKeyFromFileCommand>(c => !c.IsPrivateKey)), Times.Never); } [Test] public void ShouldWritePrivateKey() { commandExecutor.Verify(ce => ce.Execute(It.Is<WriteFileCommand<IAsymmetricKey>>(c => c.FilePath == "private.key.der" && c.Out == privateKey && c.ContentType == ContentType.Der))); } [Test] public void ShouldThrowExceptionWhenKeyIsAlreadyInTheGivenType() { arguments.ContentType = ContentType.Pem; Assert.Throws<InvalidOperationException>(() => { provider.ConvertKeyPair(arguments); }); } [Test] public void ShouldThrowExceptionWhenPrivateKeyIsConvertedToSsh() { arguments.ContentType = ContentType.Ssh2; Assert.Throws<InvalidOperationException>(() => provider.ConvertKeyPair(arguments)); } } } } }
// 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.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Sse2.IsSupported) { using (TestTable<double> doubleTable = new TestTable<double>(new double[2] { 1, -5 }, new double[2])) { var vf = Sse2.LoadVector128((double*)(doubleTable.inArrayPtr)); Unsafe.Write(doubleTable.outArrayPtr, vf); if (!doubleTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y))) { Console.WriteLine("Sse2 LoadVector128 failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<int> intTable = new TestTable<int>(new int[4] { 1, -5, 100, 0 }, new int[4])) { var vf = Sse2.LoadVector128((int*)(intTable.inArrayPtr)); Unsafe.Write(intTable.outArrayPtr, vf); if (!intTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on int:"); foreach (var item in intTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<long> longTable = new TestTable<long>(new long[2] { 1, -5 }, new long[2])) { var vf = Sse2.LoadVector128((long*)(longTable.inArrayPtr)); Unsafe.Write(longTable.outArrayPtr, vf); if (!longTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on long:"); foreach (var item in longTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<uint> uintTable = new TestTable<uint>(new uint[4] { 1, 5, 100, 0 }, new uint[4])) { var vf = Sse2.LoadVector128((uint*)(uintTable.inArrayPtr)); Unsafe.Write(uintTable.outArrayPtr, vf); if (!uintTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on uint:"); foreach (var item in uintTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ulong> ulongTable = new TestTable<ulong>(new ulong[2] { 1, 5 }, new ulong[2])) { var vf = Sse2.LoadVector128((ulong*)(ulongTable.inArrayPtr)); Unsafe.Write(ulongTable.outArrayPtr, vf); if (!ulongTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on ulong:"); foreach (var item in ulongTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<short> shortTable = new TestTable<short>(new short[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new short[8])) { var vf = Sse2.LoadVector128((short*)(shortTable.inArrayPtr)); Unsafe.Write(shortTable.outArrayPtr, vf); if (!shortTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on short:"); foreach (var item in shortTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<ushort> ushortTable = new TestTable<ushort>(new ushort[8] { 1, 5, 100, 0, 1, 5, 100, 0 }, new ushort[8])) { var vf = Sse2.LoadVector128((ushort*)(ushortTable.inArrayPtr)); Unsafe.Write(ushortTable.outArrayPtr, vf); if (!ushortTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on ushort:"); foreach (var item in ushortTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<sbyte> sbyteTable = new TestTable<sbyte>(new sbyte[16] { 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0, 1, -5, 100, 0 }, new sbyte[16])) { var vf = Sse2.LoadVector128((sbyte*)(sbyteTable.inArrayPtr)); Unsafe.Write(sbyteTable.outArrayPtr, vf); if (!sbyteTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on sbyte:"); foreach (var item in sbyteTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<byte> byteTable = new TestTable<byte>(new byte[16] { 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0, 1, 5, 100, 0 }, new byte[16])) { var vf = Sse2.LoadVector128((byte*)(byteTable.inArrayPtr)); Unsafe.Write(byteTable.outArrayPtr, vf); if (!byteTable.CheckResult((x, y) => x == y)) { Console.WriteLine("Sse2 LoadVector128 failed on byte:"); foreach (var item in byteTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray; public T[] outArray; public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle; GCHandle outHandle; public TestTable(T[] a, T[] b) { this.inArray = a; this.outArray = b; inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, bool> check) { for (int i = 0; i < inArray.Length; i++) { if (!check(inArray[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle.Free(); outHandle.Free(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk.Security.Cryptographic; namespace Microsoft.Protocols.TestTools.StackSdk.Security.Pac { /// <summary> /// The PAC_CREDENTIAL_INFO structure serves as the header /// for the credential information. The PAC_CREDENTIAL_INFO /// header indicates the encryption algorithm that was /// used to encrypt the data that follows it. The data /// that follows is an encrypted, IDL-serialized PAC_CREDENTIAL_DATA /// structure that contains the user's actual credentials. /// Note that this structure cannot be used by protocols /// other than the Kerberos protocol; the encryption method /// relies on the encryption key currently in use by the /// Kerberos AS-REQ ([RFC4120] section 3.1 and [MS-KILE]) /// message.This buffer is inserted into the PAC only when /// initial authentication is done through the PKINIT protocol /// (as specified in [RFC4556]) and is inserted only during /// initial logon; it is not included when the ticket-granting /// ticket (TGT) is used for further authentication.A PAC_CREDENTIAL_INFO /// structure contains the encrypted user's credentials. /// The encryption key usage number [RFC4120] used in /// the encryption is KERB_NON_KERB_SALT (16). The encryption /// key used is the AS reply key. The PAC credentials buffer /// SHOULD be included only when PKINIT [RFC4556] is used. /// Therefore, the AS reply key is derived based on PKINIT.The /// byte array of encrypted data is computed per the procedures /// specified in [RFC3961]. /// </summary> public class PacCredentialInfo : PacInfoBuffer { /// <summary> /// The Key Usage Number used in credential, /// defined in TD section 2.6.1: /// "Key Usage Number ([RFC4120] sections 4 and 7.5.1) is KERB_NON_KERB_SALT (16)" /// </summary> private const int KerbNonKerbSalt = 16; /// <summary> /// The native PAC_CREDENTIAL_INFO object. /// </summary> public PAC_CREDENTIAL_INFO NativePacCredentialInfo; /// <summary> /// Encrypt a PacCredentialData instance. The encrypted data /// can be accessed from SerializedData property. /// </summary> /// <param name="credentialData">The _PAC_CREDENTIAL_DATA instance to be encrypted.</param> /// <param name="key">The encrypt key.</param> public void Encrypt(_PAC_CREDENTIAL_DATA credentialData, byte[] key) { if (key == null) { throw new ArgumentNullException("key"); } byte[] plain = null; using (SafeIntPtr ptr = TypeMarshal.ToIntPtr(credentialData)) { plain = PacUtility.NdrMarshal(ptr, FormatString.OffsetCredentialData); } NativePacCredentialInfo.SerializedData = Encrypt(key, plain, NativePacCredentialInfo.EncryptionType); } /// <summary> /// Decrypt the data of SerializedData property into /// a PacCredentialData instance. /// </summary> /// <param name="key">The decrypt key.</param> /// <returns>The decrypted _PAC_CREDENTIAL_DATA instance.</returns> public _PAC_CREDENTIAL_DATA Decrypt(byte[] key) { if (key == null) { throw new ArgumentNullException("key"); } byte[] plain = Decrypt( key, NativePacCredentialInfo.SerializedData, NativePacCredentialInfo.EncryptionType); return PacUtility.NdrUnmarshal<_PAC_CREDENTIAL_DATA>(plain, 0, plain.Length, FormatString.OffsetCredentialData); } /// <summary> /// Decode specified buffer from specified index, with specified count /// of bytes, into the instance of current class. /// </summary> /// <param name="buffer">The specified buffer.</param> /// <param name="index">The specified index from beginning of buffer.</param> /// <param name="count">The specified count of bytes to be decoded.</param> internal override void DecodeBuffer(byte[] buffer, int index, int count) { NativePacCredentialInfo = PacUtility.MemoryToObject<PAC_CREDENTIAL_INFO>(buffer, index, count); int headerLength = sizeof(uint) + sizeof(uint); // This is vary length member without pre-defined calculate method. // Need to decode manually. NativePacCredentialInfo.SerializedData = new byte[count - headerLength]; Buffer.BlockCopy(buffer, index + headerLength, NativePacCredentialInfo.SerializedData, 0, count - headerLength); } /// <summary> /// Encode the instance of current class into byte array, /// according to TD specification. /// </summary> /// <returns>The encoded byte array</returns> internal override byte[] EncodeBuffer() { byte[] version = BitConverter.GetBytes((int)NativePacCredentialInfo.Version); byte[] type = BitConverter.GetBytes((int)NativePacCredentialInfo.EncryptionType); byte[] data = NativePacCredentialInfo.SerializedData; byte[] result = new byte[version.Length + type.Length + data.Length]; Buffer.BlockCopy(version, 0, result, 0, version.Length); Buffer.BlockCopy(type, 0, result, version.Length, type.Length); Buffer.BlockCopy(data, 0, result, version.Length + type.Length, data.Length); return result; } /// <summary> /// Calculate size of current instance's encoded buffer, in bytes. /// </summary> /// <returns>The size of current instance's encoded buffer, in bytes.</returns> internal override int CalculateSize() { int dataLength = NativePacCredentialInfo.SerializedData.Length; // The structure contains following part: // Version (4 bytes) // EncryptionType (4 bytes) // SerializedData (variable) return sizeof(uint) + sizeof(uint) + dataLength; } /// <summary> /// Get the ulType of current instance's PAC_INFO_BUFFER. /// </summary> /// <returns>The ulType of current instance's PAC_INFO_BUFFER.</returns> internal override PAC_INFO_BUFFER_Type_Values GetBufferInfoType() { return PAC_INFO_BUFFER_Type_Values.CredentialsInformation; } /// <summary> /// Encrypt specified plain text to cypher, according to specified encryption type. /// </summary> /// <param name="key">The encrypt key.</param> /// <param name="plain">The specified plain text.</param> /// <param name="type">The specified encryption type.</param> /// <returns>The encrypted cypher.</returns> private static byte[] Encrypt(byte[] key, byte[] plain, EncryptionType_Values type) { switch (type) { case EncryptionType_Values.DES_CBC_CRC: return DesCbcCrypto.Encrypt(key, plain, EncryptionType.DES_CBC_CRC); case EncryptionType_Values.DES_CBC_MD5: return DesCbcCrypto.Encrypt(key, plain, EncryptionType.DES_CBC_MD5); case EncryptionType_Values.AES128_CTS_HMAC_SHA1_96: return AesCtsHmacSha1Crypto.Encrypt(key, plain, KerbNonKerbSalt, AesKeyType.Aes128BitsKey); case EncryptionType_Values.AES256_CTS_HMAC_SHA1_96: return AesCtsHmacSha1Crypto.Encrypt(key, plain, KerbNonKerbSalt, AesKeyType.Aes256BitsKey); case EncryptionType_Values.RC4_HMAC: return Rc4HmacCrypto.Encrypt(key, plain, KerbNonKerbSalt, EncryptionType.RC4_HMAC); default: throw new ArgumentOutOfRangeException("type"); } } /// <summary> /// Decrypt specified cypher to plain text, according to specified encryption type. /// </summary> /// <param name="key">The decrypt key.</param> /// <param name="cypher">The specified cypher.</param> /// <param name="type">The specified encryption type.</param> /// <returns>Yhe decrypted plain text.</returns> private static byte[] Decrypt(byte[] key, byte[] cypher, EncryptionType_Values type) { switch (type) { case EncryptionType_Values.DES_CBC_CRC: return DesCbcCrypto.Decrypt(key, cypher, EncryptionType.DES_CBC_CRC); case EncryptionType_Values.DES_CBC_MD5: return DesCbcCrypto.Decrypt(key, cypher, EncryptionType.DES_CBC_MD5); case EncryptionType_Values.AES128_CTS_HMAC_SHA1_96: return AesCtsHmacSha1Crypto.Decrypt(key, cypher, KerbNonKerbSalt, AesKeyType.Aes128BitsKey); case EncryptionType_Values.AES256_CTS_HMAC_SHA1_96: return AesCtsHmacSha1Crypto.Decrypt(key, cypher, KerbNonKerbSalt, AesKeyType.Aes256BitsKey); case EncryptionType_Values.RC4_HMAC: return Rc4HmacCrypto.Decrypt(key, cypher, KerbNonKerbSalt, EncryptionType.RC4_HMAC); default: throw new ArgumentOutOfRangeException("type"); } } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonEditor.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // MenuItems and in-Editor scripts for PhotonNetwork. // </summary> // <author>[email protected]</author> // ---------------------------------------------------------------------------- //#define PHOTON_VOICE using System; using System.Collections.Generic; using System.IO; using System.Reflection; using UnityEditor; using UnityEditorInternal; using UnityEngine; public class PunWizardText { public string WindowTitle = "PUN Wizard"; public string SetupWizardWarningTitle = "Warning"; public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking."; public string MainMenuButton = "Main Menu"; public string SetupWizardTitle = "PUN Setup"; public string SetupWizardInfo = "Thanks for importing Photon Unity Networking.\nThis window should set you up.\n\n<b>-</b> To use an existing Photon Cloud App, enter your AppId.\n<b>-</b> To register an account or access an existing one, enter the account's mail address.\n<b>-</b> To use Photon OnPremise, skip this step."; public string EmailOrAppIdLabel = "AppId or Email"; public string AlreadyRegisteredInfo = "The email is registered so we can't fetch your AppId (without password).\n\nPlease login online to get your AppId and paste it above."; public string SkipRegistrationInfo = "Skipping? No problem:\nEdit your server settings in the PhotonServerSettings file."; public string RegisteredNewAccountInfo = "We created a (free) account and fetched you an AppId.\nWelcome. Your PUN project is setup."; public string AppliedToSettingsInfo = "Your AppId is now applied to this project."; public string SetupCompleteInfo = "<b>Done!</b>\nAll connection settings can be edited in the <b>PhotonServerSettings</b> now.\nHave a look."; public string CloseWindowButton = "Close"; public string SkipButton = "Skip"; public string SetupButton = "Setup Project"; public string MobileExportNoteLabel = "Build for mobiles impossible. Get PUN+ or Unity Pro for mobile or use Unity 5."; public string MobilePunPlusExportNoteLabel = "PUN+ available. Using native sockets for iOS/Android."; public string CancelButton = "Cancel"; public string PUNWizardLabel = "PUN Wizard"; public string SettingsButton = "Settings"; public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud."; public string WarningPhotonDisconnect = ""; public string ConverterLabel = "Converter"; public string StartButton = "Start"; public string UNtoPUNLabel = "Converts pure Unity Networking to Photon Unity Networking."; public string LocateSettingsButton = "Locate PhotonServerSettings"; public string SettingsHighlightLabel = "Highlights the used photon settings file in the project."; public string DocumentationLabel = "Documentation"; public string OpenPDFText = "Reference PDF"; public string OpenPDFTooltip = "Opens the local documentation pdf."; public string OpenDevNetText = "DevNet / Manual"; public string OpenDevNetTooltip = "Online documentation for Photon."; public string OpenCloudDashboardText = "Cloud Dashboard Login"; public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics."; public string OpenForumText = "Open Forum"; public string OpenForumTooltip = "Online support for Photon."; public string OkButton = "Ok"; public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'."; public string ComparisonPageButton = "Cloud versus OnPremise"; public string ConnectionTitle = "Connecting"; public string ConnectionInfo = "Connecting to the account service..."; public string ErrorTextTitle = "Error"; public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!"; public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs"; public string FullRPCListTitle = "Warning: RPC-list is full!"; public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings()."; public string SkipRPCListUpdateLabel = "Skip RPC-list update"; public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility"; public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients."; public string RPCListCleared = "Clear RPC-list"; public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings()."; public string RpcFoundMessage = "Some code uses the obsolete RPC attribute. PUN now requires the PunRPC attribute to mark remote-callable methods.\nThe Editor can search and replace that code which will modify your source."; public string RpcFoundDialogTitle = "RPC Attribute Outdated"; public string RpcReplaceButton = "Replace. I got a backup."; public string RpcSkipReplace = "Not now."; public string WizardMainWindowInfo = "This window should help you find important settings for PUN, as well as documentation."; } [InitializeOnLoad] public class PhotonEditor : EditorWindow { protected static Type WindowType = typeof (PhotonEditor); protected Vector2 scrollPos = Vector2.zero; private readonly Vector2 preferredSize = new Vector2(350, 400); private static Texture2D BackgroundImage; public static PunWizardText CurrentLang = new PunWizardText(); protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun; protected static string DocumentationLocation = "Assets/Photon Unity Networking/PhotonNetwork-Documentation.pdf"; protected static string UrlFreeLicense = "https://www.photonengine.com/en/OnPremise/Dashboard"; protected static string UrlDevNet = "http://doc.photonengine.com/en/pun/current"; protected static string UrlForum = "http://forum.exitgames.com"; protected static string UrlCompare = "http://doc.photonengine.com/en/realtime/current/getting-started/onpremise-or-saas"; protected static string UrlHowToSetup = "http://doc.photonengine.com/en/onpremise/current/getting-started/photon-server-in-5min"; protected static string UrlAppIDExplained = "http://doc.photonengine.com/en/realtime/current/getting-started/obtain-your-app-id"; protected static string UrlAccountPage = "https://www.photonengine.com/Account/SignIn?email="; // opened in browser protected static string UrlCloudDashboard = "https://www.photonengine.com/Dashboard?email="; private enum PhotonSetupStates { MainUi, RegisterForPhotonCloud, EmailAlreadyRegistered, GoEditPhotonServerSettings } private bool isSetupWizard = false; private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; private bool minimumInput = false; private bool useMail = false; private bool useAppId = false; private bool useSkip = false; private bool highlightedSettings = false; private bool close = false; private string mailOrAppId = string.Empty; private static double lastWarning = 0; private static bool postCompileActionsDone; private static bool isPunPlus; private static bool androidLibExists; private static bool iphoneLibExists; // setup once on load static PhotonEditor() { EditorApplication.projectWindowChanged += EditorUpdate; EditorApplication.hierarchyWindowChanged += EditorUpdate; EditorApplication.playmodeStateChanged += PlaymodeStateChanged; EditorApplication.update += OnUpdate; // detect optional packages PhotonEditor.CheckPunPlus(); } // setup per window public PhotonEditor() { minSize = this.preferredSize; } [MenuItem("Window/Photon Unity Networking/PUN Wizard &p", false, 0)] protected static void MenuItemOpenWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.photonSetupState = PhotonSetupStates.MainUi; win.isSetupWizard = false; } [MenuItem("Window/Photon Unity Networking/Highlight Server Settings %#&p", false, 1)] protected static void MenuItemHighlightSettings() { HighlightSettings(); } /// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary> protected static void ShowRegistrationWizard() { PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor; win.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; win.isSetupWizard = true; } // called 100 times / sec private static void OnUpdate() { // after a compile, check RPCs to create a cache-list if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode && PhotonNetwork.PhotonServerSettings != null) { #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 if (EditorApplication.isUpdating) { return; } #endif PhotonEditor.UpdateRpcList(); postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything) #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 PhotonEditor.ImportWin8Support(); #endif } } // called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues) private static void EditorUpdate() { if (PhotonNetwork.PhotonServerSettings == null) { PhotonNetwork.CreateSettings(); } if (PhotonNetwork.PhotonServerSettings == null) { return; } // serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set if (!PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard && PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet) { ShowRegistrationWizard(); PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard = true; PhotonEditor.SaveSettings(); } // Workaround for TCP crash. Plus this surpresses any other recompile errors. if (EditorApplication.isCompiling) { if (PhotonNetwork.connected) { if (lastWarning > EditorApplication.timeSinceStartup - 3) { // Prevent error spam Debug.LogWarning(CurrentLang.WarningPhotonDisconnect); lastWarning = EditorApplication.timeSinceStartup; } PhotonNetwork.Disconnect(); } } } // called in editor on change of play-mode (used to show a message popup that connection settings are incomplete) private static void PlaymodeStateChanged() { if (EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode) { return; } if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet) { EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton); } } #region GUI and Wizard // Window Update() callback. On-demand, when Window is open protected void Update() { if (this.close) { Close(); } } protected virtual void OnGUI() { if (BackgroundImage == null) { BackgroundImage = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/Editor/PhotonNetwork/background.jpg", typeof(Texture2D)) as Texture2D; } PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed. GUI.SetNextControlName(""); this.scrollPos = GUILayout.BeginScrollView(this.scrollPos); if (this.photonSetupState == PhotonSetupStates.MainUi) { UiMainWizard(); } else { UiSetupApp(); } GUILayout.EndScrollView(); if (oldGuiState != this.photonSetupState) { GUI.FocusControl(""); } } protected virtual void UiSetupApp() { GUI.skin.label.wordWrap = true; if (!this.isSetupWizard) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false))) { this.photonSetupState = PhotonSetupStates.MainUi; } GUILayout.EndHorizontal(); } // setup header UiTitleBox(CurrentLang.SetupWizardTitle, BackgroundImage); // setup info text GUI.skin.label.richText = true; GUILayout.Label(CurrentLang.SetupWizardInfo); // input of appid or mail EditorGUILayout.Separator(); GUILayout.Label(CurrentLang.EmailOrAppIdLabel); this.mailOrAppId = EditorGUILayout.TextField(this.mailOrAppId).Trim(); // note: we trim all input if (this.mailOrAppId.Contains("@")) { // this should be a mail address this.minimumInput = (this.mailOrAppId.Length >= 5 && this.mailOrAppId.Contains(".")); this.useMail = this.minimumInput; this.useAppId = false; } else { // this should be an appId this.minimumInput = ServerSettingsInspector.IsAppId(this.mailOrAppId); this.useMail = false; this.useAppId = this.minimumInput; } // button to skip setup GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.SkipButton, GUILayout.Width(100))) { this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; this.useSkip = true; this.useMail = false; this.useAppId = false; } // SETUP button EditorGUI.BeginDisabledGroup(!this.minimumInput); if (GUILayout.Button(CurrentLang.SetupButton, GUILayout.Width(100))) { this.useSkip = false; GUIUtility.keyboardControl = 0; if (this.useMail) { RegisterWithEmail(this.mailOrAppId); // sets state } if (this.useAppId) { this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PhotonServerSettings for PUN"); PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId); PhotonEditor.SaveSettings(); } } EditorGUI.EndDisabledGroup(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); // existing account needs to fetch AppId online if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered) { // button to open dashboard and get the AppId GUILayout.Space(15); GUILayout.Label(CurrentLang.AlreadyRegisteredInfo); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip), GUILayout.Width(205))) { Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId)); this.mailOrAppId = ""; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } if (this.photonSetupState == PhotonSetupStates.GoEditPhotonServerSettings) { if (!this.highlightedSettings) { this.highlightedSettings = true; HighlightSettings(); } GUILayout.Space(15); if (this.useSkip) { GUILayout.Label(CurrentLang.SkipRegistrationInfo); } else if (this.useMail) { GUILayout.Label(CurrentLang.RegisteredNewAccountInfo); } else if (this.useAppId) { GUILayout.Label(CurrentLang.AppliedToSettingsInfo); } // setup-complete info GUILayout.Space(15); GUILayout.Label(CurrentLang.SetupCompleteInfo); // close window (done) GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(CurrentLang.CloseWindowButton, GUILayout.Width(205))) { this.close = true; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } GUI.skin.label.richText = false; } private void UiTitleBox(string title, Texture2D bgIcon) { GUIStyle bgStyle = new GUIStyle(GUI.skin.GetStyle("Label")); bgStyle.normal.background = bgIcon; bgStyle.fontSize = 22; bgStyle.fontStyle = FontStyle.Bold; EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); Rect scale = GUILayoutUtility.GetLastRect(); scale.height = 30; GUI.Label(scale, title, bgStyle); GUILayout.Space(scale.height+5); } protected virtual void UiMainWizard() { GUILayout.Space(15); // title UiTitleBox(CurrentLang.PUNWizardLabel, BackgroundImage); // wizard info text GUILayout.Label(CurrentLang.WizardMainWindowInfo); GUILayout.Space(15); // pun+ info if (isPunPlus) { GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel); GUILayout.Space(15); } #if !(UNITY_5_0 || UNITY_5) else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iPhone)) { GUILayout.Label(CurrentLang.MobileExportNoteLabel); GUILayout.Space(15); } #endif // settings button GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel))) { HighlightSettings(); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip))) { Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId)); } if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel))) { this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } GUILayout.EndVertical(); GUILayout.EndHorizontal(); GUILayout.Space(15); // converter GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.ConverterLabel, EditorStyles.boldLabel, GUILayout.Width(100)); if (GUILayout.Button(new GUIContent(CurrentLang.StartButton, CurrentLang.UNtoPUNLabel))) { PhotonConverter.RunConversion(); } GUILayout.EndHorizontal(); EditorGUILayout.Separator(); // documentation GUILayout.BeginHorizontal(); GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100)); GUILayout.BeginVertical(); if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip))) { EditorUtility.OpenWithDefaultApp(DocumentationLocation); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip))) { Application.OpenURL(UrlDevNet); } GUI.skin.label.wordWrap = true; GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel); if (GUILayout.Button(CurrentLang.ComparisonPageButton)) { Application.OpenURL(UrlCompare); } if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip))) { Application.OpenURL(UrlForum); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); } #endregion protected virtual void RegisterWithEmail(string email) { EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f); string accountServiceType = string.Empty; #if PHOTON_VOICE accountServiceType = "voice"; #endif AccountService client = new AccountService(); client.RegisterByEmail(email, RegisterOrigin, accountServiceType); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client EditorUtility.ClearProgressBar(); if (client.ReturnCode == 0) { this.mailOrAppId = client.AppId; PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId, 0); #if PHOTON_VOICE PhotonNetwork.PhotonServerSettings.VoiceAppID = client.AppId2; #endif PhotonEditor.SaveSettings(); this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings; } else { PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.PhotonCloud; PhotonEditor.SaveSettings(); Debug.LogWarning(client.Message + " ReturnCode: " + client.ReturnCode); if (client.Message.Contains("registered")) { this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered; } else { EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton); this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud; } } } protected internal static bool CheckPunPlus() { androidLibExists = File.Exists("Assets/Plugins/Android/libPhotonSocketPlugin.so"); iphoneLibExists = File.Exists("Assets/Plugins/IPhone/libPhotonSocketPlugin.a"); isPunPlus = androidLibExists || iphoneLibExists; return isPunPlus; } private static void ImportWin8Support() { if (EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode) { return; // don't import while compiling } #if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0 const string win8Package = "Assets/Plugins/Photon3Unity3D-Win8.unitypackage"; bool win8LibsExist = File.Exists("Assets/Plugins/WP8/Photon3Unity3D.dll") && File.Exists("Assets/Plugins/Metro/Photon3Unity3D.dll"); if (!win8LibsExist && File.Exists(win8Package)) { AssetDatabase.ImportPackage(win8Package, false); } #endif } // Pings PhotonServerSettings and makes it selected (show in Inspector) private static void HighlightSettings() { Selection.objects = new UnityEngine.Object[] { PhotonNetwork.PhotonServerSettings }; EditorGUIUtility.PingObject(PhotonNetwork.PhotonServerSettings); } // Marks settings object as dirty, so it gets saved. // unity 5.3 changes the usecase for SetDirty(). but here we don't modify a scene object! so it's ok to use private static void SaveSettings() { EditorUtility.SetDirty(PhotonNetwork.PhotonServerSettings); } #region RPC List Handling public static void UpdateRpcList() { List<string> additionalRpcs = new List<string>(); HashSet<string> currentRpcs = new HashSet<string>(); var types = GetAllSubTypesInScripts(typeof(MonoBehaviour)); int countOldRpcs = 0; foreach (var mono in types) { MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (MethodInfo method in methods) { bool isOldRpc = false; #pragma warning disable 618 // we let the Editor check for outdated RPC attributes in code. that should not cause a compile warning if (method.IsDefined(typeof (RPC), false)) { countOldRpcs++; isOldRpc = true; } #pragma warning restore 618 if (isOldRpc || method.IsDefined(typeof(PunRPC), false)) { currentRpcs.Add(method.Name); if (!additionalRpcs.Contains(method.Name) && !PhotonNetwork.PhotonServerSettings.RpcList.Contains(method.Name)) { additionalRpcs.Add(method.Name); } } } } if (additionalRpcs.Count > 0) { // LIMITS RPC COUNT if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue) { if (currentRpcs.Count <= byte.MaxValue) { bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(currentRpcs); } else { return; } } else { EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel); return; } } additionalRpcs.Sort(); Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PUN RPC-list"); PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs); PhotonEditor.SaveSettings(); } if (countOldRpcs > 0) { bool convertRPCs = EditorUtility.DisplayDialog(CurrentLang.RpcFoundDialogTitle, CurrentLang.RpcFoundMessage, CurrentLang.RpcReplaceButton, CurrentLang.RpcSkipReplace); if (convertRPCs) { PhotonConverter.ConvertRpcAttribute(""); } } } public static void ClearRpcList() { bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton); if (clearList) { PhotonNetwork.PhotonServerSettings.RpcList.Clear(); Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning); } } public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass) { var result = new System.Collections.Generic.List<System.Type>(); System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies(); foreach (var A in AS) { // this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project if (!A.FullName.StartsWith("Assembly-")) { // Debug.Log("Skipping Assembly: " + A); continue; } //Debug.Log("Assembly: " + A.FullName); System.Type[] types = A.GetTypes(); foreach (var T in types) { if (T.IsSubclassOf(aBaseClass)) { result.Add(T); } } } return result.ToArray(); } #endregion }
// // Copyright (c) 2008-2011, Kenneth Bell // // 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. // namespace DiscUtils.Registry { using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; /// <summary> /// A registry hive. /// </summary> public sealed class RegistryHive : IDisposable { private const long BinStart = 4 * Sizes.OneKiB; private Stream _fileStream; private Ownership _ownsStream; private HiveHeader _header; private List<BinHeader> _bins; /// <summary> /// Initializes a new instance of the RegistryHive class. /// </summary> /// <param name="hive">The stream containing the registry hive</param> /// <remarks> /// The created object does not assume ownership of the stream. /// </remarks> public RegistryHive(Stream hive) : this(hive, Ownership.None) { } /// <summary> /// Initializes a new instance of the RegistryHive class. /// </summary> /// <param name="hive">The stream containing the registry hive</param> /// <param name="ownership">Whether the new object assumes object of the stream</param> public RegistryHive(Stream hive, Ownership ownership) { _fileStream = hive; _fileStream.Position = 0; _ownsStream = ownership; byte[] buffer = Utilities.ReadFully(_fileStream, HiveHeader.HeaderSize); _header = new HiveHeader(); _header.ReadFrom(buffer, 0); _bins = new List<BinHeader>(); int pos = 0; while (pos < _header.Length) { _fileStream.Position = BinStart + pos; byte[] headerBuffer = Utilities.ReadFully(_fileStream, BinHeader.HeaderSize); BinHeader header = new BinHeader(); header.ReadFrom(headerBuffer, 0); _bins.Add(header); pos += header.BinSize; } } /// <summary> /// Gets the root key in the registry hive. /// </summary> public RegistryKey Root { get { return new RegistryKey(this, GetCell<KeyNodeCell>(_header.RootCell)); } } /// <summary> /// Creates a new (empty) registry hive. /// </summary> /// <param name="stream">The stream to contain the new hive</param> /// <returns>The new hive</returns> /// <remarks> /// The returned object does not assume ownership of the stream. /// </remarks> public static RegistryHive Create(Stream stream) { return Create(stream, Ownership.None); } /// <summary> /// Creates a new (empty) registry hive. /// </summary> /// <param name="stream">The stream to contain the new hive</param> /// <param name="ownership">Whether the returned object owns the stream</param> /// <returns>The new hive</returns> public static RegistryHive Create(Stream stream, Ownership ownership) { if (stream == null) { throw new ArgumentNullException("stream", "Attempt to create registry hive in null stream"); } // Construct a file with minimal structure - hive header, plus one (empty) bin BinHeader binHeader = new BinHeader(); binHeader.FileOffset = 0; binHeader.BinSize = (int)(4 * Sizes.OneKiB); HiveHeader hiveHeader = new HiveHeader(); hiveHeader.Length = binHeader.BinSize; stream.Position = 0; byte[] buffer = new byte[hiveHeader.Size]; hiveHeader.WriteTo(buffer, 0); stream.Write(buffer, 0, buffer.Length); buffer = new byte[binHeader.Size]; binHeader.WriteTo(buffer, 0); stream.Position = BinStart; stream.Write(buffer, 0, buffer.Length); buffer = new byte[4]; Utilities.WriteBytesLittleEndian(binHeader.BinSize - binHeader.Size, buffer, 0); stream.Write(buffer, 0, buffer.Length); // Make sure the file is initialized out to the end of the firs bin stream.Position = BinStart + binHeader.BinSize - 1; stream.WriteByte(0); // Temporary hive to perform construction of higher-level structures RegistryHive newHive = new RegistryHive(stream); KeyNodeCell rootCell = new KeyNodeCell("root", -1); rootCell.Flags = RegistryKeyFlags.Normal | RegistryKeyFlags.Root; newHive.UpdateCell(rootCell, true); RegistrySecurity sd = new RegistrySecurity(); sd.SetSecurityDescriptorSddlForm("O:BAG:BAD:PAI(A;;KA;;;SY)(A;CI;KA;;;BA)", AccessControlSections.All); SecurityCell secCell = new SecurityCell(sd); newHive.UpdateCell(secCell, true); secCell.NextIndex = secCell.Index; secCell.PreviousIndex = secCell.Index; newHive.UpdateCell(secCell, false); rootCell.SecurityIndex = secCell.Index; newHive.UpdateCell(rootCell, false); // Ref the root cell from the hive header hiveHeader.RootCell = rootCell.Index; buffer = new byte[hiveHeader.Size]; hiveHeader.WriteTo(buffer, 0); stream.Position = 0; stream.Write(buffer, 0, buffer.Length); // Finally, return the new hive return new RegistryHive(stream, ownership); } /// <summary> /// Creates a new (empty) registry hive. /// </summary> /// <param name="path">The file to create the new hive in</param> /// <returns>The new hive</returns> public static RegistryHive Create(string path) { return Create(new FileStream(path, FileMode.Create, FileAccess.ReadWrite), Ownership.Dispose); } /// <summary> /// Disposes of this instance, freeing any underlying stream (if any). /// </summary> public void Dispose() { if (_fileStream != null && _ownsStream == Ownership.Dispose) { _fileStream.Dispose(); _fileStream = null; } } internal K GetCell<K>(int index) where K : Cell { Bin bin = GetBin(index); if (bin != null) { return (K)bin.TryGetCell(index); } else { return null; } } internal void FreeCell(int index) { Bin bin = GetBin(index); if (bin != null) { bin.FreeCell(index); } } internal int UpdateCell(Cell cell, bool canRelocate) { if (cell.Index == -1 && canRelocate) { cell.Index = AllocateRawCell(cell.Size); } Bin bin = GetBin(cell.Index); if (bin != null) { if (bin.UpdateCell(cell)) { return cell.Index; } else if (canRelocate) { int oldCell = cell.Index; cell.Index = AllocateRawCell(cell.Size); bin = GetBin(cell.Index); if (!bin.UpdateCell(cell)) { cell.Index = oldCell; throw new RegistryCorruptException("Failed to migrate cell to new location"); } FreeCell(oldCell); return cell.Index; } else { throw new ArgumentException("Can't update cell, needs relocation but relocation disabled", "canRelocate"); } } else { throw new RegistryCorruptException("No bin found containing index: " + cell.Index); } } internal byte[] RawCellData(int index, int maxBytes) { Bin bin = GetBin(index); if (bin != null) { return bin.ReadRawCellData(index, maxBytes); } else { return null; } } internal bool WriteRawCellData(int index, byte[] data, int offset, int count) { Bin bin = GetBin(index); if (bin != null) { return bin.WriteRawCellData(index, data, offset, count); } else { throw new RegistryCorruptException("No bin found containing index: " + index); } } internal int AllocateRawCell(int capacity) { int minSize = Utilities.RoundUp(capacity + 4, 8); // Allow for size header and ensure multiple of 8 // Incredibly inefficient algorithm... foreach (var binHeader in _bins) { Bin bin = LoadBin(binHeader); int cellIndex = bin.AllocateCell(minSize); if (cellIndex >= 0) { return cellIndex; } } BinHeader newBinHeader = AllocateBin(minSize); Bin newBin = LoadBin(newBinHeader); return newBin.AllocateCell(minSize); } private BinHeader FindBin(int index) { int binsIdx = _bins.BinarySearch(null, new BinFinder(index)); if (binsIdx >= 0) { return _bins[binsIdx]; } return null; } private Bin GetBin(int cellIndex) { BinHeader binHeader = FindBin(cellIndex); if (binHeader != null) { return LoadBin(binHeader); } return null; } private Bin LoadBin(BinHeader binHeader) { _fileStream.Position = BinStart + binHeader.FileOffset; return new Bin(this, _fileStream); } private BinHeader AllocateBin(int minSize) { BinHeader lastBin = _bins[_bins.Count - 1]; BinHeader newBinHeader = new BinHeader(); newBinHeader.FileOffset = lastBin.FileOffset + lastBin.BinSize; newBinHeader.BinSize = Utilities.RoundUp(minSize + newBinHeader.Size, 4 * (int)Sizes.OneKiB); byte[] buffer = new byte[newBinHeader.Size]; newBinHeader.WriteTo(buffer, 0); _fileStream.Position = BinStart + newBinHeader.FileOffset; _fileStream.Write(buffer, 0, buffer.Length); byte[] cellHeader = new byte[4]; Utilities.WriteBytesLittleEndian(newBinHeader.BinSize - newBinHeader.Size, cellHeader, 0); _fileStream.Write(cellHeader, 0, 4); // Update hive with new length _header.Length = newBinHeader.FileOffset + newBinHeader.BinSize; _header.Timestamp = DateTime.UtcNow; _header.Sequence1++; _header.Sequence2++; _fileStream.Position = 0; byte[] hiveHeader = Utilities.ReadFully(_fileStream, _header.Size); _header.WriteTo(hiveHeader, 0); _fileStream.Position = 0; _fileStream.Write(hiveHeader, 0, hiveHeader.Length); // Make sure the file is initialized to desired position _fileStream.Position = BinStart + _header.Length - 1; _fileStream.WriteByte(0); _bins.Add(newBinHeader); return newBinHeader; } private class BinFinder : IComparer<BinHeader> { private int _index; public BinFinder(int index) { _index = index; } #region IComparer<BinHeader> Members public int Compare(BinHeader x, BinHeader y) { if (x.FileOffset + x.BinSize < _index) { return -1; } else if (x.FileOffset > _index) { return 1; } else { return 0; } } #endregion } } }
// 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.ComponentModel; using System.ComponentModel.Composition; using System.ComponentModel.Design; using System.IO; using System.Linq; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Notification; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.SolutionExplorer; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using VSLangProj140; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export] internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents { private readonly AnalyzerItemsTracker _tracker; private readonly AnalyzerReferenceManager _analyzerReferenceManager; private readonly IServiceProvider _serviceProvider; private ContextMenuController _analyzerFolderContextMenuController; private ContextMenuController _analyzerContextMenuController; private ContextMenuController _diagnosticContextMenuController; // Analyzers folder context menu items private MenuCommand _addMenuItem; private MenuCommand _openRuleSetMenuItem; // Analyzer context menu items private MenuCommand _removeMenuItem; // Diagnostic context menu items private MenuCommand _setSeverityErrorMenuItem; private MenuCommand _setSeverityWarningMenuItem; private MenuCommand _setSeverityInfoMenuItem; private MenuCommand _setSeverityHiddenMenuItem; private MenuCommand _setSeverityNoneMenuItem; private MenuCommand _openHelpLinkMenuItem; // Other menu items private MenuCommand _projectAddMenuItem; private MenuCommand _projectContextAddMenuItem; private MenuCommand _referencesContextAddMenuItem; private MenuCommand _setActiveRuleSetMenuItem; private Workspace _workspace; private bool _allowProjectSystemOperations = true; [ImportingConstructor] public AnalyzersCommandHandler( AnalyzerItemsTracker tracker, AnalyzerReferenceManager analyzerReferenceManager, [Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider) { _tracker = tracker; _analyzerReferenceManager = analyzerReferenceManager; _serviceProvider = serviceProvider; } /// <summary> /// Hook up the context menu handlers. /// </summary> public void Initialize(IMenuCommandService menuCommandService) { if (menuCommandService != null) { // Analyzers folder context menu items _addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler); _openRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler); // Analyzer context menu items _removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler); // Diagnostic context menu items _setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler); _setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler); _setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler); _setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler); _setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler); _openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler); // Other menu items _projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler); _projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler); _referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler); _setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler); UpdateOtherMenuItemsVisibility(); if (_tracker != null) { _tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler; } var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager)); uint cookie; buildManager.AdviseUpdateSolutionEvents(this, out cookie); } } public IContextMenuController AnalyzerFolderContextMenuController { get { if (_analyzerFolderContextMenuController == null) { _analyzerFolderContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerFolderContextMenu, ShouldShowAnalyzerFolderContextMenu, UpdateAnalyzerFolderContextMenu); } return _analyzerFolderContextMenuController; } } private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items) { return items.Count() == 1; } private void UpdateAnalyzerFolderContextMenu() { _addMenuItem.Visible = SelectedProjectSupportsAnalyzers(); _addMenuItem.Enabled = _allowProjectSystemOperations; } public IContextMenuController AnalyzerContextMenuController { get { if (_analyzerContextMenuController == null) { _analyzerContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerContextMenu, ShouldShowAnalyzerContextMenu, UpdateAnalyzerContextMenu); } return _analyzerContextMenuController; } } private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items) { return items.All(item => item is AnalyzerItem); } private void UpdateAnalyzerContextMenu() { _removeMenuItem.Enabled = _allowProjectSystemOperations; } public IContextMenuController DiagnosticContextMenuController { get { if (_diagnosticContextMenuController == null) { _diagnosticContextMenuController = new ContextMenuController( ID.RoslynCommands.DiagnosticContextMenu, ShouldShowDiagnosticContextMenu, UpdateDiagnosticContextMenu); } return _diagnosticContextMenuController; } } private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items) { return items.All(item => item is DiagnosticItem); } private void UpdateDiagnosticContextMenu() { UpdateSeverityMenuItemsChecked(); UpdateSeverityMenuItemsEnabled(); UpdateOpenHelpLinkMenuItemVisibility(); } private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler) { var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand); var menuCommand = new MenuCommand(handler, commandID); menuCommandService.AddCommand(menuCommand); return menuCommand; } private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e) { UpdateOtherMenuItemsVisibility(); } private void UpdateOtherMenuItemsVisibility() { bool selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers(); _projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT; _referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers; string itemName; _setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out itemName) && Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase); } private void UpdateOtherMenuItemsEnabled() { _projectAddMenuItem.Enabled = _allowProjectSystemOperations; _projectContextAddMenuItem.Enabled = _allowProjectSystemOperations; _referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations; _removeMenuItem.Enabled = _allowProjectSystemOperations; } private void UpdateOpenHelpLinkMenuItemVisibility() { _openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 && !string.IsNullOrWhiteSpace(_tracker.SelectedDiagnosticItems[0].Descriptor.HelpLinkUri); } private void UpdateSeverityMenuItemsChecked() { _setSeverityErrorMenuItem.Checked = false; _setSeverityWarningMenuItem.Checked = false; _setSeverityInfoMenuItem.Checked = false; _setSeverityHiddenMenuItem.Checked = false; _setSeverityNoneMenuItem.Checked = false; var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } HashSet<ReportDiagnostic> selectedItemSeverities = new HashSet<ReportDiagnostic>(); var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.AnalyzerItem.AnalyzersFolder.ProjectId); foreach (var group in groups) { var project = (AbstractProject)workspace.GetHostProject(group.Key); IRuleSetFile ruleSet = project.RuleSetFile; if (ruleSet != null) { var specificOptions = ruleSet.GetSpecificDiagnosticOptions(); foreach (var diagnosticItem in group) { ReportDiagnostic ruleSetSeverity; if (specificOptions.TryGetValue(diagnosticItem.Descriptor.Id, out ruleSetSeverity)) { selectedItemSeverities.Add(ruleSetSeverity); } else { // The rule has no setting. selectedItemSeverities.Add(ReportDiagnostic.Default); } } } } if (selectedItemSeverities.Count != 1) { return; } switch (selectedItemSeverities.Single()) { case ReportDiagnostic.Default: break; case ReportDiagnostic.Error: _setSeverityErrorMenuItem.Checked = true; break; case ReportDiagnostic.Warn: _setSeverityWarningMenuItem.Checked = true; break; case ReportDiagnostic.Info: _setSeverityInfoMenuItem.Checked = true; break; case ReportDiagnostic.Hidden: _setSeverityHiddenMenuItem.Checked = true; break; case ReportDiagnostic.Suppress: _setSeverityNoneMenuItem.Checked = true; break; default: break; } } private bool AnyDiagnosticsWithSeverity(ReportDiagnostic severity) { return _tracker.SelectedDiagnosticItems.Any(item => item.EffectiveSeverity == severity); } private void UpdateSeverityMenuItemsEnabled() { bool configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable)); _setSeverityErrorMenuItem.Enabled = configurable; _setSeverityWarningMenuItem.Enabled = configurable; _setSeverityInfoMenuItem.Enabled = configurable; _setSeverityHiddenMenuItem.Enabled = configurable; _setSeverityNoneMenuItem.Enabled = configurable; } private bool SelectedProjectSupportsAnalyzers() { EnvDTE.Project project; return _tracker != null && _tracker.SelectedHierarchy != null && _tracker.SelectedHierarchy.TryGetProject(out project) && project.Object is VSProject3; } /// <summary> /// Handler for "Add Analyzer..." context menu on Analyzers folder node. /// </summary> internal void AddAnalyzerHandler(object sender, EventArgs args) { if (_analyzerReferenceManager != null) { _analyzerReferenceManager.ShowDialog(); } } /// <summary> /// Handler for "Remove" context menu on individual Analyzer items. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void RemoveAnalyzerHandler(object sender, EventArgs args) { foreach (var item in _tracker.SelectedAnalyzerItems) { item.Remove(); } } internal void OpenRuleSetHandler(object sender, EventArgs args) { if (_tracker.SelectedFolder != null && _serviceProvider != null) { var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspaceImpl; var projectId = _tracker.SelectedFolder.ProjectId; if (workspace != null) { var project = (AbstractProject)workspace.GetHostProject(projectId); if (project == null) { SendUnableToOpenRuleSetNotification(workspace, string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CouldNotFindProject, projectId)); return; } if (project.RuleSetFile == null) { SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.AnalyzersCommandHandler_NoRuleSetFile); return; } try { EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(project.RuleSetFile.FilePath); } catch (Exception e) { SendUnableToOpenRuleSetNotification(workspace, e.Message); } } } } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; ReportDiagnostic? selectedAction = MapSelectedItemToReportDiagnostic(selectedItem); if (!selectedAction.HasValue) { return; } var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems) { var projectId = selectedDiagnostic.AnalyzerItem.AnalyzersFolder.ProjectId; var project = (AbstractProject)workspace.GetHostProject(projectId); if (project == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CouldNotFindProject, projectId)); continue; } var pathToRuleSet = project.RuleSetFile?.FilePath; if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.AnalyzersCommandHandler_NoRuleSetFile); continue; } try { EnvDTE.Project envDteProject; project.Hierarchy.TryGetProject(out envDteProject); if (SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider)) { pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject); if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CouldNotCreateRuleSetFile, envDteProject.Name)); continue; } var fileInfo = new FileInfo(pathToRuleSet); fileInfo.IsReadOnly = false; } var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var waitIndicator = componentModel.GetService<IWaitIndicator>(); waitIndicator.Wait( title: SolutionExplorerShim.AnalyzersCommandHandler_RuleSet, message: string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CheckingOutRuleSet, Path.GetFileName(pathToRuleSet)), allowCancel: false, action: c => { if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet)) { envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet); } }); selectedDiagnostic.SetSeverity(selectedAction.Value, pathToRuleSet); } catch (Exception e) { SendUnableToUpdateRuleSetNotification(workspace, e.Message); } } } private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e) { if (_tracker.SelectedDiagnosticItems.Length != 1 || string.IsNullOrWhiteSpace(_tracker.SelectedDiagnosticItems[0].Descriptor.HelpLinkUri)) { return; } string link = _tracker.SelectedDiagnosticItems[0].Descriptor.HelpLinkUri; Uri uri; if (BrowserHelper.TryGetUri(link, out uri)) { BrowserHelper.StartBrowser(_serviceProvider, uri); } } private void SetActiveRuleSetHandler(object sender, EventArgs e) { EnvDTE.Project project; string ruleSetFileFullPath; if (_tracker.SelectedHierarchy.TryGetProject(out project) && _tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out ruleSetFileFullPath)) { string projectDirectoryFullPath = Path.GetDirectoryName(project.FullName); string ruleSetFileRelativePath = FilePathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath); UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath); } } private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject) { string fileName = GetNewRuleSetFileNameForProject(envDteProject); string projectDirectory = Path.GetDirectoryName(envDteProject.FullName); string fullFilePath = Path.Combine(projectDirectory, fileName); File.Copy(pathToRuleSet, fullFilePath); UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName); envDteProject.ProjectItems.AddFromFile(fullFilePath); return fullFilePath; } private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName) { foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager) { EnvDTE.Properties properties = config.Properties; try { EnvDTE.Property codeAnalysisRuleSetFileProperty = properties.Item("CodeAnalysisRuleSet"); if (codeAnalysisRuleSetFileProperty != null) { codeAnalysisRuleSetFileProperty.Value = fileName; } } catch (ArgumentException) { // Unfortunately the properties collection sometimes throws an ArgumentException // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet. // Ignore it and move on. } } } private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject) { string projectName = envDteProject.Name; HashSet<string> projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (ProjectItem item in envDteProject.ProjectItems) { projectItemNames.Add(item.Name); } string ruleSetName = projectName + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } for (int i = 1; i < int.MaxValue; i++) { ruleSetName = projectName + i + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } } return null; } private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { ReportDiagnostic? selectedAction = null; if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { switch (selectedItem.CommandID.ID) { case ID.RoslynCommands.SetSeverityError: selectedAction = ReportDiagnostic.Error; break; case ID.RoslynCommands.SetSeverityWarning: selectedAction = ReportDiagnostic.Warn; break; case ID.RoslynCommands.SetSeverityInfo: selectedAction = ReportDiagnostic.Info; break; case ID.RoslynCommands.SetSeverityHidden: selectedAction = ReportDiagnostic.Hidden; break; case ID.RoslynCommands.SetSeverityNone: selectedAction = ReportDiagnostic.Suppress; break; default: selectedAction = null; break; } } return selectedAction; } private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.AnalyzersCommandHandler_RuleSetFileCouldNotBeOpened, message); } private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.AnalyzersCommandHandler_RuleSetFileCouldNotBeUpdated, message); } private void SendErrorNotification(Workspace workspace, string title, string message) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(message, title, NotificationSeverity.Error); } int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate) { _allowProjectSystemOperations = false; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate) { return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Cancel() { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy) { return VSConstants.S_OK; } private Workspace TryGetWorkspace() { if (_workspace == null) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var provider = componentModel.DefaultExportProvider.GetExportedValueOrDefault<ISolutionExplorerWorkspaceProvider>(); if (provider != null) { _workspace = provider.GetWorkspace(); } } return _workspace; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateType { internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax> { internal abstract IMethodSymbol GetDelegatingConstructor( SemanticDocument document, TObjectCreationExpressionSyntax objectCreation, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken); private partial class Editor { private INamedTypeSymbol GenerateNamedType() { return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( DetermineAttributes(), DetermineAccessibility(), DetermineModifiers(), DetermineTypeKind(), DetermineName(), DetermineTypeParameters(), DetermineBaseType(), DetermineInterfaces(), members: DetermineMembers()); } private INamedTypeSymbol GenerateNamedType(GenerateTypeOptionsResult options) { if (options.TypeKind == TypeKind.Delegate) { return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( DetermineAttributes(), options.Accessibility, DetermineModifiers(), DetermineReturnType(options), returnsByRef: false, name: options.TypeName, typeParameters: DetermineTypeParameters(options), parameters: DetermineParameters(options)); } return CodeGenerationSymbolFactory.CreateNamedTypeSymbol( DetermineAttributes(), options.Accessibility, DetermineModifiers(), options.TypeKind, options.TypeName, DetermineTypeParameters(), DetermineBaseType(), DetermineInterfaces(), members: DetermineMembers(options)); } private ITypeSymbol DetermineReturnType(GenerateTypeOptionsResult options) { if (_state.DelegateMethodSymbol == null || _state.DelegateMethodSymbol.ReturnType == null || _state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol) { // Since we cannot determine the return type, we are returning void return _state.Compilation.GetSpecialType(SpecialType.System_Void); } else { return _state.DelegateMethodSymbol.ReturnType; } } private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters(GenerateTypeOptionsResult options) { if (_state.DelegateMethodSymbol != null) { return _state.DelegateMethodSymbol.TypeParameters; } // If the delegate symbol cannot be determined then return DetermineTypeParameters(); } private ImmutableArray<IParameterSymbol> DetermineParameters(GenerateTypeOptionsResult options) { if (_state.DelegateMethodSymbol != null) { return _state.DelegateMethodSymbol.Parameters; } return default(ImmutableArray<IParameterSymbol>); } private ImmutableArray<ISymbol> DetermineMembers(GenerateTypeOptionsResult options = null) { var members = ArrayBuilder<ISymbol>.GetInstance(); AddMembers(members, options); if (_state.IsException) { AddExceptionConstructors(members); } return members.ToImmutableAndFree(); } private void AddMembers(ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null) { AddProperties(members); if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out var argumentList)) { return; } var parameterTypes = GetArgumentTypes(argumentList); // Don't generate this constructor if it would conflict with a default exception // constructor. Default exception constructors will be added automatically by our // caller. if (_state.IsException && _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any( c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes))) { return; } // If there's an accessible base constructor that would accept these types, then // just call into that instead of generating fields. if (_state.BaseTypeOrInterfaceOpt != null) { if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface && argumentList.Count == 0) { // No need to add the default constructor if our base type is going to be // 'object'. We get that constructor for free. return; } var accessibleInstanceConstructors = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.Where( IsSymbolAccessible).ToSet(); if (accessibleInstanceConstructors.Any()) { var delegatedConstructor = _service.GetDelegatingConstructor( _document, _state.ObjectCreationExpressionOpt, _state.BaseTypeOrInterfaceOpt, accessibleInstanceConstructors, _cancellationToken); if (delegatedConstructor != null) { // There was a best match. Call it directly. AddBaseDelegatingConstructor(delegatedConstructor, members); return; } } } // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. AddFieldDelegatingConstructor(argumentList, members, options); } private void AddProperties(ArrayBuilder<ISymbol> members) { var typeInference = _document.Project.LanguageServices.GetService<ITypeInferenceService>(); foreach (var property in _state.PropertiesToGenerate) { if (_service.TryGenerateProperty(property, _document.SemanticModel, typeInference, _cancellationToken, out var generatedProperty)) { members.Add(generatedProperty); } } } private void AddBaseDelegatingConstructor( IMethodSymbol methodSymbol, ArrayBuilder<ISymbol> members) { // If we're generating a constructor to delegate into the no-param base constructor // then we can just elide the constructor entirely. if (methodSymbol.Parameters.Length == 0) { return; } var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>(); members.Add(factory.CreateBaseDelegatingConstructor( methodSymbol, DetermineName())); } private void AddFieldDelegatingConstructor( IList<TArgumentSyntax> argumentList, ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null) { var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>(); var syntaxFactsService = _document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _document.SemanticModel, _intoNamespace, _cancellationToken); var parameterTypes = GetArgumentTypes(argumentList); var parameterNames = _service.GenerateParameterNames(_document.SemanticModel, argumentList); var parameters = ArrayBuilder<IParameterSymbol>.GetInstance(); var parameterToExistingFieldMap = new Dictionary<string, ISymbol>(); var parameterToNewFieldMap = new Dictionary<string, string>(); var syntaxFacts = _document.Project.LanguageServices.GetService<ISyntaxFactsService>(); for (var i = 0; i < parameterNames.Count; i++) { var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]); var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; parameterType = parameterType.RemoveUnavailableTypeParameters( _document.SemanticModel.Compilation, availableTypeParameters); if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: true)) { if (!TryFindMatchingField(parameterName, parameterType, parameterToExistingFieldMap, caseSensitive: false)) { parameterToNewFieldMap[parameterName.BestNameForParameter] = parameterName.NameBasedOnArgument; } } parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default(ImmutableArray<AttributeData>), refKind: refKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } // Empty Constructor for Struct is not allowed if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure))) { members.AddRange(factory.CreateFieldDelegatingConstructor( DetermineName(), null, parameters.ToImmutable(), parameterToExistingFieldMap, parameterToNewFieldMap, _cancellationToken)); } parameters.Free(); } private void AddExceptionConstructors(ArrayBuilder<ISymbol> members) { var factory = _document.Project.LanguageServices.GetService<SyntaxGenerator>(); var exceptionType = _document.SemanticModel.Compilation.ExceptionType(); var constructors = exceptionType.InstanceConstructors .Where(c => c.DeclaredAccessibility == Accessibility.Public || c.DeclaredAccessibility == Accessibility.Protected) .Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: c.DeclaredAccessibility, modifiers: default(DeclarationModifiers), typeName: DetermineName(), parameters: c.Parameters, statements: default(ImmutableArray<SyntaxNode>), baseConstructorArguments: c.Parameters.Length == 0 ? default(ImmutableArray<SyntaxNode>) : factory.CreateArguments(c.Parameters))); members.AddRange(constructors); } private ImmutableArray<AttributeData> DetermineAttributes() { if (_state.IsException) { var serializableType = _document.SemanticModel.Compilation.SerializableAttributeType(); if (serializableType != null) { var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType); return ImmutableArray.Create(attribute); } } return default(ImmutableArray<AttributeData>); } private Accessibility DetermineAccessibility() { return _service.GetAccessibility(_state, _document.SemanticModel, _intoNamespace, _cancellationToken); } private DeclarationModifiers DetermineModifiers() { return default(DeclarationModifiers); } private INamedTypeSymbol DetermineBaseType() { if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) { return null; } return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt); } private ImmutableArray<INamedTypeSymbol> DetermineInterfaces() { if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface) { var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt); if (type != null) { return ImmutableArray.Create(type); } } return ImmutableArray<INamedTypeSymbol>.Empty; } private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type) { return type.RemoveUnavailableTypeParameters( _document.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol; } private string DetermineName() { return GetTypeName(_state); } private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters() => _service.GetTypeParameters(_state, _document.SemanticModel, _cancellationToken); private TypeKind DetermineTypeKind() { return _state.IsStruct ? TypeKind.Struct : _state.IsInterface ? TypeKind.Interface : TypeKind.Class; } protected IList<ITypeParameterSymbol> GetAvailableTypeParameters() { var availableInnerTypeParameters = _service.GetTypeParameters(_state, _document.SemanticModel, _cancellationToken); var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null ? _state.TypeToGenerateInOpt.GetAllTypeParameters() : SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList(); } } internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property); } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Threading; namespace Tiraggo.Interfaces { /// <summary> /// This is the EntitySpaces ADO.NET connection based transaction class that mimics the System.Transactions.TransactionScope class. /// </summary> /// <remarks> /// EntitySpaces supports two transactions models, connection based via this class (tgTransactionScope) and the /// new System.Transactions.TransactionScope. Some databases such as Microsoft Access don't support the new System.Transactions.TransactionScope /// class. And still there are other cases where the System.Transactions.TransactionScope class cannot be used as is the case with a lot /// of hosting companies. Thus EntitySpaces provides a very nice ADO.NET connection based transaction handler. /// /// The Syntax should be as follows: /// <code> /// using (tgTransactionScope scope = new tgTransactionScope()) /// { /// // Logic here ... /// /// scope.Complete(); // last line of using statement /// } /// </code> /// Note that if an exception is thrown scope.Complete will not be called, and the transaction upon leaving the using statement /// will be rolled back. You indicate whether you want the provider to use the tgTransactionScope or the System.Transactions.TransactionScope /// class in your .config file. Notice in the config file setting below that providerClass="DataProvider". This indicates that you want to use /// the tgTransactionScope class, use providerClass="DataProviderEnterprise" to use System.Transactions.TransactionScope. /// <code> /// &lt;add name="SQL" /// providerMetadataKey="esDefault" /// sqlAccessType="DynamicSQL" /// provider="Tiraggo.SqlClientProvider" /// providerClass="DataProvider" /// connectionString="User ID=sa;Password=griffinski;Initial Catalog=Northwind;Data Source=localhost" /// databaseVersion="2005"/&gt; /// </code> /// /// /// </remarks> public class tgTransactionScope : IDisposable { /// <summary> /// The default constructor, this transactions <see cref="tgTransactionScopeOption"/> will be /// set to Required. The IsolationLevel is set to Unspecified. /// <code> /// using (tgTransactionScope scope = new tgTransactionScope()) /// { /// // Do your work here /// scope.Complete(); /// } /// </code> /// </summary> public tgTransactionScope() { this.option = tgTransactionScopeOption.Required; this.level = tgTransactionScope.IsolationLevel; CommonInit(this); this.root.count++; } /// <summary> /// Use this constructor to control the tgTransactionScopeOption as it applies /// to this transaction. /// <code> /// using (tgTransactionScope scope = new tgTransactionScope(tgTransactionScopeOption.RequiresNew)) /// { /// // Do your work here /// scope.Complete(); /// } /// </code> /// </summary> /// <param name="option">See <see cref="tgTransactionScopeOption"/></param> public tgTransactionScope(tgTransactionScopeOption option) { if (option == tgTransactionScopeOption.None) throw new ArgumentException("'None' cannot be passed"); this.option = option; this.level = tgTransactionScope.IsolationLevel; CommonInit(this); this.root.count++; } /// <summary> /// Use this constructor to control the tgTransactionScopeOption as it applies /// to this transaction. /// <code> /// using (tgTransactionScope scope = new /// tgTransactionScope(tgTransactionScopeOption.RequiresNew, IsolationLevel.ReadCommitted)) /// { /// // Do your work here /// scope.Complete(); /// } /// </code> /// </summary> /// <param name="option">See <see cref="tgTransactionScopeOption"/></param> /// <param name="level">See IsolationLevel in the System.Data namespace</param> public tgTransactionScope(tgTransactionScopeOption option, IsolationLevel level) { this.option = option; this.level = level; CommonInit(this); this.root.count++; } /// <summary> /// You must call Complete to commit the transaction. Calls and transactions can be nested, only the final outer call to /// Complete will commit the transaction. /// </summary> public void Complete() { this.root.count--; if (this.root == this && this.root.count == 0 && this.option != tgTransactionScopeOption.Suppress) { foreach (Transaction tx in this.root.transactions.Values) { IDbConnection cn = tx.sqlTx.Connection; tx.sqlTx.Commit(); tx.sqlTx.Dispose(); tx.sqlTx = null; if (cn != null && cn.State == ConnectionState.Open) { cn.Close(); } tx.sqlCn = null; } this.root.transactions.Clear(); if (this.commitList != null) { foreach (ICommittable commit in this.commitList) { commit.Commit(); } commitList.Clear(); } } } #region IDisposable Members /// <summary> /// Internal. Called when the "using" statement is exited. /// </summary> void IDisposable.Dispose() { try { if (this.root == this && this.count > 0) { // Somebody didn't call Complete, we must roll back ... if (this.root.transactions.Count > 0) { Rollback(); return; } } } finally { if (this.commitList != null) { commitList.Clear(); this.commitList = null; } Stack<tgTransactionScope> stack = (Stack<tgTransactionScope>)Thread.GetData(txSlot); stack.Pop(); } } #endregion /// <summary> /// Internal method, called if the "using" statement is left without calling scope.Complete() /// </summary> private void Rollback() { if (false == this.root.hasRolledBack && this.root.count > 0) { this.root.hasRolledBack = true; foreach (Transaction tx in this.root.transactions.Values) { IDbConnection cn = tx.sqlTx.Connection; try { // It may look as though we are eating an exception here // but this method is private and only called when we // have already received an error, we don't want our cleanup // code to cloud the issue. cn = tx.sqlTx.Connection; tx.sqlTx.Rollback(); tx.sqlTx.Dispose(); } catch { } tx.sqlTx = null; tx.sqlCn = null; if (cn != null && cn.State == ConnectionState.Open) { cn.Close(); } } this.root.transactions.Clear(); this.root.count = 0; } } // We might have multple transactions going at the same time. // There's one per connnection string private class Transaction { public IDbTransaction sqlTx = null; public IDbConnection sqlCn = null; } private Dictionary<string, Transaction> transactions; private List<ICommittable> commitList; private bool hasRolledBack; private int count; private tgTransactionScope root; private tgTransactionScopeOption option; private IsolationLevel level; #region "static" /// <summary> /// EntitySpaces providers register this callback so that the tgTransactionScope class can ask it to create the proper /// type of connection, ie, SqlConnection, OracleConnection, OleDbConnection and so on ... /// </summary> /// <returns></returns> public delegate IDbConnection CreateIDbConnectionDelegate(); /// <summary> /// This can be used to get the tgTransactionScopeOption from the current tgTransactionScope (remember transactions can be nested). /// If there is no on-going transaction then tgTransactionScopeOption.None is returned. /// </summary> /// <returns></returns> static public tgTransactionScopeOption GetCurrentTransactionScopeOption() { tgTransactionScope currentTx = GetCurrentTx(); if (currentTx == null) return tgTransactionScopeOption.None; else return currentTx.option; } /// <summary> /// You should never call this directly, the providers call this method. /// </summary> /// <param name="cmd">The command to enlist into a transaction</param> /// <param name="connectionString">The connection string passed to the CreateIDbConnectionDelegate delegate</param> /// <param name="creator">The delegate previously registered by the provider</param> static public void Enlist(IDbCommand cmd, string connectionString, CreateIDbConnectionDelegate creator) { tgTransactionScope currentTx = GetCurrentTx(); if (currentTx == null || currentTx.option == tgTransactionScopeOption.Suppress) { cmd.Connection = creator(); cmd.Connection.ConnectionString = connectionString; cmd.Connection.Open(); } else { Transaction tx = null; if (currentTx.root.transactions.ContainsKey(connectionString)) { tx = currentTx.root.transactions[connectionString] as Transaction; } else { tx = new Transaction(); IDbConnection cn = creator(); cn.ConnectionString = connectionString; cn.Open(); // The .NET framework has a bug in that the IDbTransaction only maintains // a weak reference to the Connection, thus, we put a strong reference // on it. tx.sqlCn = cn; if (_isolationLevel != IsolationLevel.Unspecified) { tx.sqlTx = cn.BeginTransaction(_isolationLevel); } else { tx.sqlTx = cn.BeginTransaction(); } currentTx.root.transactions[connectionString] = tx; } cmd.Connection = tx.sqlTx.Connection; cmd.Transaction = tx.sqlTx; } } /// <summary> /// You should never call this directly, the providers call this method. /// </summary> /// <param name="cmd">The command to enlist into a transaction</param> static public void DeEnlist(IDbCommand cmd) { tgTransactionScope current = GetCurrentTx(); if (current == null || current.option == tgTransactionScopeOption.Suppress) { cmd.Connection.Close(); } } /// <summary> /// You should never call this directly, EntitySpaces calls this internally. /// </summary> /// <param name="commit">Any class that implements ICommittable</param> /// <returns>True if successful</returns> static public bool AddForCommit(ICommittable commit) { tgTransactionScope current = GetCurrentTx(); if (current != null) { if (current.commitList == null) { current.commitList = new List<ICommittable>(); } current.commitList.Add(commit); return true; } else { return false; } } /// <summary> /// This is the common constructor logic, tx is "this" from the constructor /// </summary> /// <param name="tx"></param> static protected void CommonInit(tgTransactionScope tx) { Stack<tgTransactionScope> stack; // See if our stack is already created (there is only one per thread) object obj = Thread.GetData(txSlot); if (obj == null) { stack = new Stack<tgTransactionScope>(); Thread.SetData(txSlot, stack); } else { stack = (Stack<tgTransactionScope>)obj; } // If this transaction is required we need to set it's root if (tx.option == tgTransactionScopeOption.Required) { foreach (tgTransactionScope esTrans in stack) { // The root can be either a Requires or RequiresNew, and a root always points to // itself, therefore, as long as it's not a Suppress and it's pointing to itself // then we know this the next root up on the stack if (esTrans.option != tgTransactionScopeOption.Suppress && esTrans == esTrans.root) { tx.root = esTrans; break; } } } // If we didn't find a root, then we are by definition the root if (tx.root == null) { tx.root = tx; tx.transactions = new Dictionary<string, Transaction>(); } stack.Push(tx); } /// <summary> /// Internal method. /// </summary> /// <returns></returns> static private tgTransactionScope GetCurrentTx() { tgTransactionScope tx = null; object o = Thread.GetData(txSlot); if(o != null) { Stack<tgTransactionScope> stack = o as Stack<tgTransactionScope>; if (stack.Count > 0) { tx = stack.Peek(); } } return tx; } /// <summary> /// This is the Transaction's strength. The default is "IsolationLevel.Unspecified, the strongest is "IsolationLevel.Serializable" which is what /// is recommended for serious enterprize level projects. /// </summary> public static IsolationLevel IsolationLevel { get { return _isolationLevel; } set { _isolationLevel = value; } } private static IsolationLevel _isolationLevel = IsolationLevel.Unspecified; private static LocalDataStoreSlot txSlot = Thread.AllocateDataSlot(); #endregion } }
namespace DockSample { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.mainMenu = new System.Windows.Forms.MenuStrip(); this.menuItemFile = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemNew = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemOpen = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemClose = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemCloseAll = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemCloseAllButThisOne = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem4 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemExit = new System.Windows.Forms.ToolStripMenuItem(); this.exitWithoutSavingLayout = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemView = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSolutionExplorer = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemPropertyWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemToolbox = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemOutputWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemTaskList = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemToolBar = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemStatusBar = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem2 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemLayoutByCode = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemLayoutByXml = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemTools = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemLockLayout = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemShowDocumentIcon = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem3 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemSchemaVS2015Light = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2015Blue = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2015Dark = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2013Light = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2013Blue = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2013Dark = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2012Light = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2012Blue = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2012Dark = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2010Blue = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2005 = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSchemaVS2003 = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem6 = new System.Windows.Forms.ToolStripSeparator(); this.menuItemDockingMdi = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemDockingSdi = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemDockingWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemSystemMdi = new System.Windows.Forms.ToolStripMenuItem(); this.menuItem5 = new System.Windows.Forms.ToolStripSeparator(); this.showRightToLeft = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemNewWindow = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemHelp = new System.Windows.Forms.ToolStripMenuItem(); this.menuItemAbout = new System.Windows.Forms.ToolStripMenuItem(); this.statusBar = new System.Windows.Forms.StatusStrip(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.toolBar = new System.Windows.Forms.ToolStrip(); this.toolBarButtonNew = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonOpen = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolBarButtonSolutionExplorer = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonPropertyWindow = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonToolbox = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonOutputWindow = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonTaskList = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolBarButtonLayoutByCode = new System.Windows.Forms.ToolStripButton(); this.toolBarButtonLayoutByXml = new System.Windows.Forms.ToolStripButton(); this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel(); this.vS2005Theme1 = new WeifenLuo.WinFormsUI.Docking.VS2005Theme(); this.vS2003Theme1 = new WeifenLuo.WinFormsUI.Docking.VS2003Theme(); this.vS2015LightTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2015LightTheme(); this.vS2015BlueTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2015BlueTheme(); this.vS2015DarkTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2015DarkTheme(); this.vS2013LightTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2013LightTheme(); this.vS2013BlueTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2013BlueTheme(); this.vS2013DarkTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2013DarkTheme(); this.vS2012LightTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2012LightTheme(); this.vS2012BlueTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2012BlueTheme(); this.vS2012DarkTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2012DarkTheme(); this.vS2010BlueTheme1 = new WeifenLuo.WinFormsUI.Docking.VS2010BlueTheme(); this.vsToolStripExtender1 = new WeifenLuo.WinFormsUI.Docking.VisualStudioToolStripExtender(this.components); this.mainMenu.SuspendLayout(); this.toolBar.SuspendLayout(); this.SuspendLayout(); // // mainMenu // this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemFile, this.menuItemView, this.menuItemTools, this.menuItemWindow, this.menuItemHelp}); this.mainMenu.Location = new System.Drawing.Point(0, 0); this.mainMenu.MdiWindowListItem = this.menuItemWindow; this.mainMenu.Name = "mainMenu"; this.mainMenu.Size = new System.Drawing.Size(579, 24); this.mainMenu.TabIndex = 7; // // menuItemFile // this.menuItemFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemNew, this.menuItemOpen, this.menuItemClose, this.menuItemCloseAll, this.menuItemCloseAllButThisOne, this.menuItem4, this.menuItemExit, this.exitWithoutSavingLayout}); this.menuItemFile.Name = "menuItemFile"; this.menuItemFile.Size = new System.Drawing.Size(37, 20); this.menuItemFile.Text = "&File"; this.menuItemFile.DropDownOpening += new System.EventHandler(this.menuItemFile_Popup); // // menuItemNew // this.menuItemNew.Name = "menuItemNew"; this.menuItemNew.Size = new System.Drawing.Size(215, 22); this.menuItemNew.Text = "&New"; this.menuItemNew.Click += new System.EventHandler(this.menuItemNew_Click); // // menuItemOpen // this.menuItemOpen.Name = "menuItemOpen"; this.menuItemOpen.Size = new System.Drawing.Size(215, 22); this.menuItemOpen.Text = "&Open..."; this.menuItemOpen.Click += new System.EventHandler(this.menuItemOpen_Click); // // menuItemClose // this.menuItemClose.Name = "menuItemClose"; this.menuItemClose.Size = new System.Drawing.Size(215, 22); this.menuItemClose.Text = "&Close"; this.menuItemClose.Click += new System.EventHandler(this.menuItemClose_Click); // // menuItemCloseAll // this.menuItemCloseAll.Name = "menuItemCloseAll"; this.menuItemCloseAll.Size = new System.Drawing.Size(215, 22); this.menuItemCloseAll.Text = "Close &All"; this.menuItemCloseAll.Click += new System.EventHandler(this.menuItemCloseAll_Click); // // menuItemCloseAllButThisOne // this.menuItemCloseAllButThisOne.Name = "menuItemCloseAllButThisOne"; this.menuItemCloseAllButThisOne.Size = new System.Drawing.Size(215, 22); this.menuItemCloseAllButThisOne.Text = "Close All &But This One"; this.menuItemCloseAllButThisOne.Click += new System.EventHandler(this.menuItemCloseAllButThisOne_Click); // // menuItem4 // this.menuItem4.Name = "menuItem4"; this.menuItem4.Size = new System.Drawing.Size(212, 6); // // menuItemExit // this.menuItemExit.Name = "menuItemExit"; this.menuItemExit.Size = new System.Drawing.Size(215, 22); this.menuItemExit.Text = "&Exit"; this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click); // // exitWithoutSavingLayout // this.exitWithoutSavingLayout.Name = "exitWithoutSavingLayout"; this.exitWithoutSavingLayout.Size = new System.Drawing.Size(215, 22); this.exitWithoutSavingLayout.Text = "Exit &Without Saving Layout"; this.exitWithoutSavingLayout.Click += new System.EventHandler(this.exitWithoutSavingLayout_Click); // // menuItemView // this.menuItemView.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemSolutionExplorer, this.menuItemPropertyWindow, this.menuItemToolbox, this.menuItemOutputWindow, this.menuItemTaskList, this.menuItem1, this.menuItemToolBar, this.menuItemStatusBar, this.menuItem2, this.menuItemLayoutByCode, this.menuItemLayoutByXml}); this.menuItemView.MergeIndex = 1; this.menuItemView.Name = "menuItemView"; this.menuItemView.Size = new System.Drawing.Size(44, 20); this.menuItemView.Text = "&View"; // // menuItemSolutionExplorer // this.menuItemSolutionExplorer.Name = "menuItemSolutionExplorer"; this.menuItemSolutionExplorer.Size = new System.Drawing.Size(185, 22); this.menuItemSolutionExplorer.Text = "&Solution Explorer"; this.menuItemSolutionExplorer.Click += new System.EventHandler(this.menuItemSolutionExplorer_Click); // // menuItemPropertyWindow // this.menuItemPropertyWindow.Name = "menuItemPropertyWindow"; this.menuItemPropertyWindow.ShortcutKeys = System.Windows.Forms.Keys.F4; this.menuItemPropertyWindow.Size = new System.Drawing.Size(185, 22); this.menuItemPropertyWindow.Text = "&Property Window"; this.menuItemPropertyWindow.Click += new System.EventHandler(this.menuItemPropertyWindow_Click); // // menuItemToolbox // this.menuItemToolbox.Name = "menuItemToolbox"; this.menuItemToolbox.Size = new System.Drawing.Size(185, 22); this.menuItemToolbox.Text = "&Toolbox"; this.menuItemToolbox.Click += new System.EventHandler(this.menuItemToolbox_Click); // // menuItemOutputWindow // this.menuItemOutputWindow.Name = "menuItemOutputWindow"; this.menuItemOutputWindow.Size = new System.Drawing.Size(185, 22); this.menuItemOutputWindow.Text = "&Output Window"; this.menuItemOutputWindow.Click += new System.EventHandler(this.menuItemOutputWindow_Click); // // menuItemTaskList // this.menuItemTaskList.Name = "menuItemTaskList"; this.menuItemTaskList.Size = new System.Drawing.Size(185, 22); this.menuItemTaskList.Text = "Task &List"; this.menuItemTaskList.Click += new System.EventHandler(this.menuItemTaskList_Click); // // menuItem1 // this.menuItem1.Name = "menuItem1"; this.menuItem1.Size = new System.Drawing.Size(182, 6); // // menuItemToolBar // this.menuItemToolBar.Checked = true; this.menuItemToolBar.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemToolBar.Name = "menuItemToolBar"; this.menuItemToolBar.Size = new System.Drawing.Size(185, 22); this.menuItemToolBar.Text = "Tool &Bar"; this.menuItemToolBar.Click += new System.EventHandler(this.menuItemToolBar_Click); // // menuItemStatusBar // this.menuItemStatusBar.Checked = true; this.menuItemStatusBar.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemStatusBar.Name = "menuItemStatusBar"; this.menuItemStatusBar.Size = new System.Drawing.Size(185, 22); this.menuItemStatusBar.Text = "Status B&ar"; this.menuItemStatusBar.Click += new System.EventHandler(this.menuItemStatusBar_Click); // // menuItem2 // this.menuItem2.Name = "menuItem2"; this.menuItem2.Size = new System.Drawing.Size(182, 6); // // menuItemLayoutByCode // this.menuItemLayoutByCode.Name = "menuItemLayoutByCode"; this.menuItemLayoutByCode.Size = new System.Drawing.Size(185, 22); this.menuItemLayoutByCode.Text = "Layout By &Code"; this.menuItemLayoutByCode.Click += new System.EventHandler(this.menuItemLayoutByCode_Click); // // menuItemLayoutByXml // this.menuItemLayoutByXml.Name = "menuItemLayoutByXml"; this.menuItemLayoutByXml.Size = new System.Drawing.Size(185, 22); this.menuItemLayoutByXml.Text = "Layout By &XML"; this.menuItemLayoutByXml.Click += new System.EventHandler(this.menuItemLayoutByXml_Click); // // menuItemTools // this.menuItemTools.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemLockLayout, this.menuItemShowDocumentIcon, this.menuItem3, this.menuItemSchemaVS2015Light, this.menuItemSchemaVS2015Blue, this.menuItemSchemaVS2015Dark, this.menuItemSchemaVS2013Light, this.menuItemSchemaVS2013Blue, this.menuItemSchemaVS2013Dark, this.menuItemSchemaVS2012Light, this.menuItemSchemaVS2012Blue, this.menuItemSchemaVS2012Dark, this.menuItemSchemaVS2010Blue, this.menuItemSchemaVS2005, this.menuItemSchemaVS2003, this.menuItem6, this.menuItemDockingMdi, this.menuItemDockingSdi, this.menuItemDockingWindow, this.menuItemSystemMdi, this.menuItem5, this.showRightToLeft}); this.menuItemTools.MergeIndex = 2; this.menuItemTools.Name = "menuItemTools"; this.menuItemTools.Size = new System.Drawing.Size(48, 20); this.menuItemTools.Text = "&Tools"; this.menuItemTools.DropDownOpening += new System.EventHandler(this.menuItemTools_Popup); // // menuItemLockLayout // this.menuItemLockLayout.Name = "menuItemLockLayout"; this.menuItemLockLayout.Size = new System.Drawing.Size(255, 22); this.menuItemLockLayout.Text = "&Lock Layout"; this.menuItemLockLayout.Click += new System.EventHandler(this.menuItemLockLayout_Click); // // menuItemShowDocumentIcon // this.menuItemShowDocumentIcon.Name = "menuItemShowDocumentIcon"; this.menuItemShowDocumentIcon.Size = new System.Drawing.Size(255, 22); this.menuItemShowDocumentIcon.Text = "&Show Document Icon"; this.menuItemShowDocumentIcon.Click += new System.EventHandler(this.menuItemShowDocumentIcon_Click); // // menuItem3 // this.menuItem3.Name = "menuItem3"; this.menuItem3.Size = new System.Drawing.Size(252, 6); // // menuItemSchemaVS2015Light // this.menuItemSchemaVS2015Light.Name = "menuItemSchemaVS2015Light"; this.menuItemSchemaVS2015Light.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2015Light.Text = "Schema: VS2015 Light"; this.menuItemSchemaVS2015Light.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2015Blue // this.menuItemSchemaVS2015Blue.Name = "menuItemSchemaVS2015Blue"; this.menuItemSchemaVS2015Blue.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2015Blue.Text = "Schema: VS2015 Blue"; this.menuItemSchemaVS2015Blue.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2015Dark // this.menuItemSchemaVS2015Dark.Name = "menuItemSchemaVS2015Dark"; this.menuItemSchemaVS2015Dark.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2015Dark.Text = "Schema: VS2015 Dark"; this.menuItemSchemaVS2015Dark.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2013Light // this.menuItemSchemaVS2013Light.Name = "menuItemSchemaVS2013Light"; this.menuItemSchemaVS2013Light.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2013Light.Text = "Schema: VS2013 Light"; this.menuItemSchemaVS2013Light.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2013Blue // this.menuItemSchemaVS2013Blue.Name = "menuItemSchemaVS2013Blue"; this.menuItemSchemaVS2013Blue.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2013Blue.Text = "Schema: VS2013 Blue"; this.menuItemSchemaVS2013Blue.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2013Dark // this.menuItemSchemaVS2013Dark.Name = "menuItemSchemaVS2013Dark"; this.menuItemSchemaVS2013Dark.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2013Dark.Text = "Schema: VS2013 Dark"; this.menuItemSchemaVS2013Dark.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2012Light // this.menuItemSchemaVS2012Light.Name = "menuItemSchemaVS2012Light"; this.menuItemSchemaVS2012Light.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2012Light.Text = "Schema: VS2012 Light"; this.menuItemSchemaVS2012Light.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2012Blue // this.menuItemSchemaVS2012Blue.Name = "menuItemSchemaVS2012Blue"; this.menuItemSchemaVS2012Blue.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2012Blue.Text = "Schema: VS2012 Blue"; this.menuItemSchemaVS2012Blue.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2012Dark // this.menuItemSchemaVS2012Dark.Name = "menuItemSchemaVS2012Dark"; this.menuItemSchemaVS2012Dark.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2012Dark.Text = "Schema: VS2012 Dark"; this.menuItemSchemaVS2012Dark.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2010Blue // this.menuItemSchemaVS2010Blue.Name = "menuItemSchemaVS2010Blue"; this.menuItemSchemaVS2010Blue.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2010Blue.Text = "Schema: VS2010 Blue"; this.menuItemSchemaVS2010Blue.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2005 // this.menuItemSchemaVS2005.Checked = true; this.menuItemSchemaVS2005.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemSchemaVS2005.Name = "menuItemSchemaVS2005"; this.menuItemSchemaVS2005.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2005.Text = "Schema: VS200&5"; this.menuItemSchemaVS2005.Click += new System.EventHandler(this.SetSchema); // // menuItemSchemaVS2003 // this.menuItemSchemaVS2003.Name = "menuItemSchemaVS2003"; this.menuItemSchemaVS2003.Size = new System.Drawing.Size(255, 22); this.menuItemSchemaVS2003.Text = "Schema: VS200&3"; this.menuItemSchemaVS2003.Click += new System.EventHandler(this.SetSchema); // // menuItem6 // this.menuItem6.Name = "menuItem6"; this.menuItem6.Size = new System.Drawing.Size(252, 6); // // menuItemDockingMdi // this.menuItemDockingMdi.Checked = true; this.menuItemDockingMdi.CheckState = System.Windows.Forms.CheckState.Checked; this.menuItemDockingMdi.Name = "menuItemDockingMdi"; this.menuItemDockingMdi.Size = new System.Drawing.Size(255, 22); this.menuItemDockingMdi.Text = "Document Style: Docking &MDI"; this.menuItemDockingMdi.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItemDockingSdi // this.menuItemDockingSdi.Name = "menuItemDockingSdi"; this.menuItemDockingSdi.Size = new System.Drawing.Size(255, 22); this.menuItemDockingSdi.Text = "Document Style: Docking &SDI"; this.menuItemDockingSdi.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItemDockingWindow // this.menuItemDockingWindow.Name = "menuItemDockingWindow"; this.menuItemDockingWindow.Size = new System.Drawing.Size(255, 22); this.menuItemDockingWindow.Text = "Document Style: Docking &Window"; this.menuItemDockingWindow.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItemSystemMdi // this.menuItemSystemMdi.Name = "menuItemSystemMdi"; this.menuItemSystemMdi.Size = new System.Drawing.Size(255, 22); this.menuItemSystemMdi.Text = "Document Style: S&ystem MDI"; this.menuItemSystemMdi.Click += new System.EventHandler(this.SetDocumentStyle); // // menuItem5 // this.menuItem5.Name = "menuItem5"; this.menuItem5.Size = new System.Drawing.Size(252, 6); // // showRightToLeft // this.showRightToLeft.Name = "showRightToLeft"; this.showRightToLeft.Size = new System.Drawing.Size(255, 22); this.showRightToLeft.Text = "Show &Right-To-Left"; this.showRightToLeft.Click += new System.EventHandler(this.showRightToLeft_Click); // // menuItemWindow // this.menuItemWindow.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemNewWindow}); this.menuItemWindow.MergeIndex = 2; this.menuItemWindow.Name = "menuItemWindow"; this.menuItemWindow.Size = new System.Drawing.Size(63, 20); this.menuItemWindow.Text = "&Window"; // // menuItemNewWindow // this.menuItemNewWindow.Name = "menuItemNewWindow"; this.menuItemNewWindow.Size = new System.Drawing.Size(145, 22); this.menuItemNewWindow.Text = "&New Window"; this.menuItemNewWindow.Click += new System.EventHandler(this.menuItemNewWindow_Click); // // menuItemHelp // this.menuItemHelp.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuItemAbout}); this.menuItemHelp.MergeIndex = 3; this.menuItemHelp.Name = "menuItemHelp"; this.menuItemHelp.Size = new System.Drawing.Size(44, 20); this.menuItemHelp.Text = "&Help"; // // menuItemAbout // this.menuItemAbout.Name = "menuItemAbout"; this.menuItemAbout.Size = new System.Drawing.Size(185, 22); this.menuItemAbout.Text = "&About DockSample..."; this.menuItemAbout.Click += new System.EventHandler(this.menuItemAbout_Click); // // statusBar // this.statusBar.BackColor = System.Drawing.Color.Black; this.statusBar.Location = new System.Drawing.Point(0, 387); this.statusBar.Name = "statusBar"; this.statusBar.Size = new System.Drawing.Size(579, 22); this.statusBar.TabIndex = 4; // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, ""); this.imageList.Images.SetKeyName(1, ""); this.imageList.Images.SetKeyName(2, ""); this.imageList.Images.SetKeyName(3, ""); this.imageList.Images.SetKeyName(4, ""); this.imageList.Images.SetKeyName(5, ""); this.imageList.Images.SetKeyName(6, ""); this.imageList.Images.SetKeyName(7, ""); this.imageList.Images.SetKeyName(8, ""); // // toolBar // this.toolBar.ImageList = this.imageList; this.toolBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolBarButtonNew, this.toolBarButtonOpen, this.toolBarButtonSeparator1, this.toolBarButtonSolutionExplorer, this.toolBarButtonPropertyWindow, this.toolBarButtonToolbox, this.toolBarButtonOutputWindow, this.toolBarButtonTaskList, this.toolBarButtonSeparator2, this.toolBarButtonLayoutByCode, this.toolBarButtonLayoutByXml}); this.toolBar.Location = new System.Drawing.Point(0, 24); this.toolBar.Name = "toolBar"; this.toolBar.Size = new System.Drawing.Size(579, 25); this.toolBar.TabIndex = 6; this.toolBar.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolBar_ButtonClick); // // toolBarButtonNew // this.toolBarButtonNew.ImageIndex = 0; this.toolBarButtonNew.Name = "toolBarButtonNew"; this.toolBarButtonNew.Size = new System.Drawing.Size(23, 22); this.toolBarButtonNew.ToolTipText = "Show Layout From XML"; // // toolBarButtonOpen // this.toolBarButtonOpen.ImageIndex = 1; this.toolBarButtonOpen.Name = "toolBarButtonOpen"; this.toolBarButtonOpen.Size = new System.Drawing.Size(23, 22); this.toolBarButtonOpen.ToolTipText = "Open"; // // toolBarButtonSeparator1 // this.toolBarButtonSeparator1.Name = "toolBarButtonSeparator1"; this.toolBarButtonSeparator1.Size = new System.Drawing.Size(6, 25); // // toolBarButtonSolutionExplorer // this.toolBarButtonSolutionExplorer.ImageIndex = 2; this.toolBarButtonSolutionExplorer.Name = "toolBarButtonSolutionExplorer"; this.toolBarButtonSolutionExplorer.Size = new System.Drawing.Size(23, 22); this.toolBarButtonSolutionExplorer.ToolTipText = "Solution Explorer"; // // toolBarButtonPropertyWindow // this.toolBarButtonPropertyWindow.ImageIndex = 3; this.toolBarButtonPropertyWindow.Name = "toolBarButtonPropertyWindow"; this.toolBarButtonPropertyWindow.Size = new System.Drawing.Size(23, 22); this.toolBarButtonPropertyWindow.ToolTipText = "Property Window"; // // toolBarButtonToolbox // this.toolBarButtonToolbox.ImageIndex = 4; this.toolBarButtonToolbox.Name = "toolBarButtonToolbox"; this.toolBarButtonToolbox.Size = new System.Drawing.Size(23, 22); this.toolBarButtonToolbox.ToolTipText = "Tool Box"; // // toolBarButtonOutputWindow // this.toolBarButtonOutputWindow.ImageIndex = 5; this.toolBarButtonOutputWindow.Name = "toolBarButtonOutputWindow"; this.toolBarButtonOutputWindow.Size = new System.Drawing.Size(23, 22); this.toolBarButtonOutputWindow.ToolTipText = "Output Window"; // // toolBarButtonTaskList // this.toolBarButtonTaskList.ImageIndex = 6; this.toolBarButtonTaskList.Name = "toolBarButtonTaskList"; this.toolBarButtonTaskList.Size = new System.Drawing.Size(23, 22); this.toolBarButtonTaskList.ToolTipText = "Task List"; // // toolBarButtonSeparator2 // this.toolBarButtonSeparator2.Name = "toolBarButtonSeparator2"; this.toolBarButtonSeparator2.Size = new System.Drawing.Size(6, 25); // // toolBarButtonLayoutByCode // this.toolBarButtonLayoutByCode.ImageIndex = 7; this.toolBarButtonLayoutByCode.Name = "toolBarButtonLayoutByCode"; this.toolBarButtonLayoutByCode.Size = new System.Drawing.Size(23, 22); this.toolBarButtonLayoutByCode.ToolTipText = "Show Layout By Code"; // // toolBarButtonLayoutByXml // this.toolBarButtonLayoutByXml.ImageIndex = 8; this.toolBarButtonLayoutByXml.Name = "toolBarButtonLayoutByXml"; this.toolBarButtonLayoutByXml.Size = new System.Drawing.Size(23, 22); this.toolBarButtonLayoutByXml.ToolTipText = "Show layout by predefined XML file"; // // dockPanel // this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.dockPanel.DockBackColor = System.Drawing.SystemColors.AppWorkspace; this.dockPanel.DockBottomPortion = 150D; this.dockPanel.DockLeftPortion = 200D; this.dockPanel.DockRightPortion = 200D; this.dockPanel.DockTopPortion = 150D; this.dockPanel.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.World, ((byte)(0))); this.dockPanel.Location = new System.Drawing.Point(0, 49); this.dockPanel.Name = "dockPanel"; this.dockPanel.RightToLeftLayout = true; this.dockPanel.Size = new System.Drawing.Size(579, 338); this.dockPanel.TabIndex = 0; // // vsToolStripExtender1 // this.vsToolStripExtender1.DefaultRenderer = null; // // MainForm // this.ClientSize = new System.Drawing.Size(579, 409); this.Controls.Add(this.dockPanel); this.Controls.Add(this.toolBar); this.Controls.Add(this.mainMenu); this.Controls.Add(this.statusBar); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.IsMdiContainer = true; this.MainMenuStrip = this.mainMenu; this.Name = "MainForm"; this.Text = "DockSample"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Closing += new System.ComponentModel.CancelEventHandler(this.MainForm_Closing); this.Load += new System.EventHandler(this.MainForm_Load); this.SizeChanged += new System.EventHandler(this.MainForm_SizeChanged); this.mainMenu.ResumeLayout(false); this.mainMenu.PerformLayout(); this.toolBar.ResumeLayout(false); this.toolBar.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel; private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.ToolStrip toolBar; private System.Windows.Forms.ToolStripButton toolBarButtonNew; private System.Windows.Forms.ToolStripButton toolBarButtonOpen; private System.Windows.Forms.ToolStripSeparator toolBarButtonSeparator1; private System.Windows.Forms.ToolStripButton toolBarButtonSolutionExplorer; private System.Windows.Forms.ToolStripButton toolBarButtonPropertyWindow; private System.Windows.Forms.ToolStripButton toolBarButtonToolbox; private System.Windows.Forms.ToolStripButton toolBarButtonOutputWindow; private System.Windows.Forms.ToolStripButton toolBarButtonTaskList; private System.Windows.Forms.ToolStripSeparator toolBarButtonSeparator2; private System.Windows.Forms.ToolStripButton toolBarButtonLayoutByCode; private System.Windows.Forms.ToolStripButton toolBarButtonLayoutByXml; private System.Windows.Forms.MenuStrip mainMenu; private System.Windows.Forms.ToolStripMenuItem menuItemFile; private System.Windows.Forms.ToolStripMenuItem menuItemNew; private System.Windows.Forms.ToolStripMenuItem menuItemOpen; private System.Windows.Forms.ToolStripMenuItem menuItemClose; private System.Windows.Forms.ToolStripMenuItem menuItemCloseAll; private System.Windows.Forms.ToolStripMenuItem menuItemCloseAllButThisOne; private System.Windows.Forms.ToolStripSeparator menuItem4; private System.Windows.Forms.ToolStripMenuItem menuItemExit; private System.Windows.Forms.ToolStripMenuItem menuItemView; private System.Windows.Forms.ToolStripMenuItem menuItemSolutionExplorer; private System.Windows.Forms.ToolStripMenuItem menuItemPropertyWindow; private System.Windows.Forms.ToolStripMenuItem menuItemToolbox; private System.Windows.Forms.ToolStripMenuItem menuItemOutputWindow; private System.Windows.Forms.ToolStripMenuItem menuItemTaskList; private System.Windows.Forms.ToolStripSeparator menuItem1; private System.Windows.Forms.ToolStripMenuItem menuItemToolBar; private System.Windows.Forms.ToolStripMenuItem menuItemStatusBar; private System.Windows.Forms.ToolStripSeparator menuItem2; private System.Windows.Forms.ToolStripMenuItem menuItemLayoutByCode; private System.Windows.Forms.ToolStripMenuItem menuItemLayoutByXml; private System.Windows.Forms.ToolStripMenuItem menuItemTools; private System.Windows.Forms.ToolStripMenuItem menuItemLockLayout; private System.Windows.Forms.ToolStripSeparator menuItem3; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2005; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2003; private System.Windows.Forms.ToolStripSeparator menuItem6; private System.Windows.Forms.ToolStripMenuItem menuItemDockingMdi; private System.Windows.Forms.ToolStripMenuItem menuItemDockingSdi; private System.Windows.Forms.ToolStripMenuItem menuItemDockingWindow; private System.Windows.Forms.ToolStripMenuItem menuItemSystemMdi; private System.Windows.Forms.ToolStripSeparator menuItem5; private System.Windows.Forms.ToolStripMenuItem menuItemShowDocumentIcon; private System.Windows.Forms.ToolStripMenuItem menuItemWindow; private System.Windows.Forms.ToolStripMenuItem menuItemNewWindow; private System.Windows.Forms.ToolStripMenuItem menuItemHelp; private System.Windows.Forms.ToolStripMenuItem menuItemAbout; private System.Windows.Forms.StatusStrip statusBar; private System.Windows.Forms.ToolStripMenuItem showRightToLeft; private System.Windows.Forms.ToolStripMenuItem exitWithoutSavingLayout; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2010Blue; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2012Light; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2012Blue; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2012Dark; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2013Light; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2013Blue; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2013Dark; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2015Light; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2015Blue; private System.Windows.Forms.ToolStripMenuItem menuItemSchemaVS2015Dark; private WeifenLuo.WinFormsUI.Docking.VS2015LightTheme vS2015LightTheme1; private WeifenLuo.WinFormsUI.Docking.VS2015BlueTheme vS2015BlueTheme1; private WeifenLuo.WinFormsUI.Docking.VS2015DarkTheme vS2015DarkTheme1; private WeifenLuo.WinFormsUI.Docking.VS2013LightTheme vS2013LightTheme1; private WeifenLuo.WinFormsUI.Docking.VS2013BlueTheme vS2013BlueTheme1; private WeifenLuo.WinFormsUI.Docking.VS2013DarkTheme vS2013DarkTheme1; private WeifenLuo.WinFormsUI.Docking.VS2012LightTheme vS2012LightTheme1; private WeifenLuo.WinFormsUI.Docking.VS2012BlueTheme vS2012BlueTheme1; private WeifenLuo.WinFormsUI.Docking.VS2012DarkTheme vS2012DarkTheme1; private WeifenLuo.WinFormsUI.Docking.VS2010BlueTheme vS2010BlueTheme1; private WeifenLuo.WinFormsUI.Docking.VS2003Theme vS2003Theme1; private WeifenLuo.WinFormsUI.Docking.VS2005Theme vS2005Theme1; private WeifenLuo.WinFormsUI.Docking.VisualStudioToolStripExtender vsToolStripExtender1; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using System.Xml; using SIL.IO; using SIL.PlatformUtilities; using SIL.Threading; using SIL.WritingSystems.Migration; namespace SIL.WritingSystems { ///<summary> /// A system wide writing system repository. ///</summary> public class GlobalWritingSystemRepository : GlobalWritingSystemRepository<WritingSystemDefinition> { ///<summary> /// Initializes the global writing system repository. Migrates any ldml files if required, /// notifying of any changes of writing system id that occured during migration. ///</summary> public static GlobalWritingSystemRepository Initialize(Action<int, IEnumerable<LdmlMigrationInfo>> migrationHandler = null) { return InitializeWithBasePath(DefaultBasePath, migrationHandler); } ///<summary> /// This initializer is intended for tests as it allows setting of the basePath explicitly. ///</summary> internal static GlobalWritingSystemRepository InitializeWithBasePath(string basePath, Action<int, IEnumerable<LdmlMigrationInfo>> migrationHandler) { var migrator = new GlobalWritingSystemRepositoryMigrator(basePath, migrationHandler); if (migrator.NeedsMigration()) migrator.Migrate(); var globalRepo = new GlobalWritingSystemRepository(basePath); migrator.ResetRemovedProperties(globalRepo); return globalRepo; } protected internal GlobalWritingSystemRepository(string basePath) : base(basePath) { } protected override IWritingSystemFactory<WritingSystemDefinition> CreateWritingSystemFactory() { return new SldrWritingSystemFactory(); } } ///<summary> /// A system wide writing system repository. ///</summary> public abstract class GlobalWritingSystemRepository<T> : WritingSystemRepositoryBase<T>, IDisposable where T : WritingSystemDefinition { private const string Extension = ".ldml"; private readonly string _path; private readonly GlobalMutex _mutex; private readonly Dictionary<string, Tuple<DateTime, long>> _lastFileStats; protected internal GlobalWritingSystemRepository(string basePath) { _lastFileStats = new Dictionary<string, Tuple<DateTime, long>>(); _path = CurrentVersionPath(basePath); if (!Directory.Exists(_path)) CreateGlobalWritingSystemRepositoryDirectory(_path); _mutex = new GlobalMutex(_path.Replace('\\', '_').Replace('/', '_')); _mutex.Initialize(); } private void UpdateDefinitions() { var ldmlDataMapper = new LdmlDataMapper(WritingSystemFactory); var removedIds = new HashSet<string>(WritingSystems.Keys); foreach (string file in Directory.GetFiles(_path, "*.ldml")) { var fi = new FileInfo(file); string id = Path.GetFileNameWithoutExtension(file); Debug.Assert(id != null); T ws; if (WritingSystems.TryGetValue(id, out ws)) { // existing writing system // preserve this repo's changes if (!ws.IsChanged) { // for performance purposes, we check the last modified timestamp and file size to see if the file has changed // hopefully that is good enough for our purposes here if (_lastFileStats[id].Item1 != fi.LastWriteTime || _lastFileStats[id].Item2 != fi.Length) { // modified writing system ldmlDataMapper.Read(file, ws); if(string.IsNullOrEmpty(ws.Id)) ws.Id = ws.LanguageTag; ws.AcceptChanges(); _lastFileStats[id] = Tuple.Create(fi.LastWriteTime, fi.Length); } } removedIds.Remove(id); } else { // new writing system try { ws = WritingSystemFactory.Create(); ldmlDataMapper.Read(file, ws); ws.Id = ws.LanguageTag; ws.AcceptChanges(); WritingSystems[id] = ws; _lastFileStats[id] = Tuple.Create(fi.LastWriteTime, fi.Length); } catch (XmlException) { // ldml file is not valid, rename it so it is no longer used RobustFile.Move(file, file + ".bad"); } } } foreach (string id in removedIds) { // preserve this repo's changes if (!WritingSystems[id].IsChanged) base.Remove(id); } } ///<summary> /// The DefaultBasePath is %CommonApplicationData%\SIL\WritingSystemRepository /// On Windows 7 this is \ProgramData\SIL\WritingSystemRepository\ /// On Linux this must be in ~/.local/share so that it may be edited ///</summary> public static string DefaultBasePath { get { string basePath = Platform.IsLinux ? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) : Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); return Path.Combine(basePath, "SIL", "WritingSystemRepository"); } } ///<summary> /// The CurrentVersionPath is %CommonApplicationData%\SIL\WritingSystemRepository\[CurrentLdmlVersion] /// e.g. On Windows 7 this is \ProgramData\SIL\WritingSystemRepository\1 ///</summary> public static string CurrentVersionPath(string basePath) { return Path.Combine(basePath, LdmlDataMapper.CurrentLdmlLibraryVersion.ToString(CultureInfo.InvariantCulture)); } public static void CreateGlobalWritingSystemRepositoryDirectory(string path) { DirectoryInfo di = Directory.CreateDirectory(path); if (!Platform.IsLinux && !path.StartsWith(Path.GetTempPath())) { // NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono DirectorySecurity ds = di.GetAccessControl(); var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); AccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); bool modified; ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified); di.SetAccessControl(ds); } } public string PathToWritingSystems { get { return _path; } } /// <summary> /// Adds the writing system to the store or updates the store information about /// an already-existing writing system. Set should be called when there is a change /// that updates the IETF language tag information. /// </summary> public override void Set(T ws) { using (_mutex.Lock()) { UpdateDefinitions(); string oldStoreId = ws.Id; base.Set(ws); //Renaming the file here is a bit ugly as the content has not yet been updated. Thus there //may be a mismatch between the filename and the contained rfc5646 tag. Doing it here however //helps us avoid having to deal with situations where a writing system id is changed to be //identical with the old id of another writing sytsem. This could otherwise lead to dataloss. //The inconsistency is resolved on Save() if (oldStoreId != ws.Id && File.Exists(GetFilePathFromLanguageTag(oldStoreId))) File.Move(GetFilePathFromLanguageTag(oldStoreId), GetFilePathFromLanguageTag(ws.Id)); } } /// <summary> /// Gets the writing system object for the given Store ID /// </summary> public override T Get(string id) { using (_mutex.Lock()) { UpdateDefinitions(); return base.Get(id); } } /// <summary> /// This method will save the global store file in a temporary location while doing the base /// Replace (Remove/Set). This will leave the old file content available during the Save method so that /// it will round trip correctly. /// </summary> public override void Replace(string languageTag, T newWs) { using (new WsStasher(Path.Combine(_path, languageTag + Extension))) { base.Replace(languageTag, newWs); } } /// <summary> /// Returns true if a writing system with the given Store ID exists in the store /// </summary> public override bool Contains(string id) { using (_mutex.Lock()) { UpdateDefinitions(); return base.Contains(id); } } /// <summary> /// Gives the total number of writing systems in the store /// </summary> public override int Count { get { using (_mutex.Lock()) { UpdateDefinitions(); return base.Count; } } } /// <summary> /// This is a new required interface member. We don't use it, and I hope we don't use anything which uses it! /// </summary> /// <param name="wsToConflate"></param> /// <param name="wsToConflateWith"></param> public override void Conflate(string wsToConflate, string wsToConflateWith) { using (_mutex.Lock()) { UpdateDefinitions(); base.Conflate(wsToConflate, wsToConflateWith); } } /// <summary> /// Removes the writing system with the specified Store ID from the store. /// </summary> public override void Remove(string id) { using (_mutex.Lock()) { UpdateDefinitions(); base.Remove(id); } } /// <summary> /// Returns a list of all writing system definitions in the store. /// </summary> public override IEnumerable<T> AllWritingSystems { get { using (_mutex.Lock()) { UpdateDefinitions(); return base.AllWritingSystems; } } } /// <summary> /// This is used by the orphan finder, which we don't use (yet). It tells whether, typically in the scope of some /// current change log, a writing system ID has changed to something else...call WritingSystemIdHasChangedTo /// to find out what. /// </summary> public override bool WritingSystemIdHasChanged(string id) { throw new NotImplementedException(); } /// <summary> /// This is used by the orphan finder, which we don't use (yet). It tells what, typically in the scope of some /// current change log, a writing system ID has changed to. /// </summary> public override string WritingSystemIdHasChangedTo(string id) { throw new NotImplementedException(); } protected override void RemoveDefinition(T ws) { string file = GetFilePathFromLanguageTag(ws.LanguageTag); if (File.Exists(file)) File.Delete(file); base.RemoveDefinition(ws); } private void SaveDefinition(T ws) { base.Set(ws); string writingSystemFilePath = GetFilePathFromLanguageTag(ws.LanguageTag); if (!File.Exists(writingSystemFilePath) && !string.IsNullOrEmpty(ws.Template)) { // this is a new writing system that was generated from a template, so copy the template over before saving File.Copy(ws.Template, writingSystemFilePath); ws.Template = null; } if (!ws.IsChanged && File.Exists(writingSystemFilePath)) return; // no need to save (better to preserve the modified date) ws.DateModified = DateTime.UtcNow; MemoryStream oldData = null; if (File.Exists(writingSystemFilePath)) { // load old data to preserve stuff in LDML that we don't use, but don't throw up an error if it fails try { oldData = new MemoryStream(File.ReadAllBytes(writingSystemFilePath), false); } catch {} // What to do? Assume that the UI has already checked for existing, asked, and allowed the overwrite. File.Delete(writingSystemFilePath); //!!! Should this be move to trash? } var ldmlDataMapper = new LdmlDataMapper(WritingSystemFactory); try { // Provides FW on Linux multi-user access. Overrides the system // umask and creates the files with the permissions "775". // The "fieldworks" group was created outside the app during // configuration of the package which allows group access. using (new FileModeOverride()) { ldmlDataMapper.Write(writingSystemFilePath, ws, oldData); } var fi = new FileInfo(writingSystemFilePath); _lastFileStats[ws.Id] = Tuple.Create(fi.LastWriteTime, fi.Length); } catch (UnauthorizedAccessException) { // If we can't save the changes, too bad. Inability to save locally is typically caught // when we go to open the modify dialog. If we can't make the global store consistent, // as we well may not be able to in a client-server mode, too bad. } ws.AcceptChanges(); } /// <summary> /// Writes the store to a persistable medium, if applicable. /// </summary> public override void Save() { using (_mutex.Lock()) { UpdateDefinitions(); //delete anything we're going to delete first, to prevent losing //a WS we want by having it deleted by an old WS we don't want //(but which has the same identifier) foreach (string id in AllWritingSystems.Where(ws => ws.MarkedForDeletion).Select(ws => ws.Id).ToArray()) base.Remove(id); // make a copy and then go through that list - SaveDefinition calls Set which // may delete and then insert the same writing system - which would change WritingSystemDefinitions // and not be allowed in a foreach loop foreach (T ws in AllWritingSystems.Where(CanSet).ToArray()) SaveDefinition(ws); } } /// <summary> /// Since the current implementation of Save does nothing, it's always possible. /// </summary> public override bool CanSave(T ws) { using (_mutex.Lock()) { string filePath = GetFilePathFromLanguageTag(ws.Id); if (File.Exists(filePath)) { try { using (FileStream stream = File.Open(filePath, FileMode.Open)) stream.Close(); // don't really want to change anything } catch (UnauthorizedAccessException) { return false; } } else if (Directory.Exists(PathToWritingSystems)) { try { // See whether we're allowed to create the file (but if so, get rid of it). // Pathologically we might have create but not delete permission...if so, // we'll create an empty file and report we can't save. I don't see how to // do better. using (FileStream stream = File.Create(filePath)) stream.Close(); File.Delete(filePath); } catch (UnauthorizedAccessException) { return false; } } else { try { Directory.CreateDirectory(PathToWritingSystems); // Don't try to clean it up again. This is a vanishingly rare case, // I don't think it's even possible to create a writing system store without // the directory existing. } catch (UnauthorizedAccessException) { return false; } } return true; } } /// <summary> /// Gets the specified writing system if it exists. /// </summary> /// <param name="id">The identifier.</param> /// <param name="ws">The writing system.</param> /// <returns></returns> public override bool TryGet(string id, out T ws) { using (_mutex.Lock()) { UpdateDefinitions(); return WritingSystems.TryGetValue(id, out ws); } } ///<summary> /// Returns the full path to the underlying store for this writing system. ///</summary> public string GetFilePathFromLanguageTag(string langTag) { return Path.Combine(PathToWritingSystems, GetFileNameFromLanguageTag(langTag)); } /// <summary> /// Gets the file name from the specified identifier. /// </summary> protected static string GetFileNameFromLanguageTag(string langTag) { return langTag + Extension; } ~GlobalWritingSystemRepository() { Dispose(false); // The base class finalizer is called automatically. } public bool IsDisposed { get; private set; } public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****** Missing Dispose() call for " + GetType().Name + ". ****** "); // Must not be run more than once. if (IsDisposed) return; if (disposing) _mutex.Dispose(); IsDisposed = true; } private class WsStasher : IDisposable { private string _wsFile; private const string _localrepoupdate = ".localrepoupdate"; public WsStasher(string wsFile) { _wsFile = wsFile; RobustFile.Copy(wsFile, wsFile + _localrepoupdate); } public void Dispose() { RobustFile.Move($"{_wsFile}{_localrepoupdate}", _wsFile); } } } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Ocsp; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.X509; using Org.BouncyCastle.X509.Store; namespace Org.BouncyCastle.Ocsp { /** * <pre> * OcspRequest ::= SEQUENCE { * tbsRequest TBSRequest, * optionalSignature [0] EXPLICIT Signature OPTIONAL } * * TBSRequest ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * requestorName [1] EXPLICIT GeneralName OPTIONAL, * requestList SEQUENCE OF Request, * requestExtensions [2] EXPLICIT Extensions OPTIONAL } * * Signature ::= SEQUENCE { * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING, * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL} * * Version ::= INTEGER { v1(0) } * * Request ::= SEQUENCE { * reqCert CertID, * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } * * CertID ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * issuerNameHash OCTET STRING, -- Hash of Issuer's DN * issuerKeyHash OCTET STRING, -- Hash of Issuers public key * serialNumber CertificateSerialNumber } * </pre> */ public class OcspReq : X509ExtensionBase { private OcspRequest req; public OcspReq( OcspRequest req) { this.req = req; } public OcspReq( byte[] req) : this(new Asn1InputStream(req)) { } public OcspReq( Stream inStr) : this(new Asn1InputStream(inStr)) { } private OcspReq( Asn1InputStream aIn) { try { this.req = OcspRequest.GetInstance(aIn.ReadObject()); } catch (ArgumentException e) { throw new IOException("malformed request: " + e.Message); } catch (InvalidCastException e) { throw new IOException("malformed request: " + e.Message); } } /** * Return the DER encoding of the tbsRequest field. * @return DER encoding of tbsRequest * @throws OcspException in the event of an encoding error. */ public byte[] GetTbsRequest() { try { return req.TbsRequest.GetEncoded(); } catch (IOException e) { throw new OcspException("problem encoding tbsRequest", e); } } public int Version { get { return req.TbsRequest.Version.Value.IntValue + 1; } } public GeneralName RequestorName { get { return GeneralName.GetInstance(req.TbsRequest.RequestorName); } } public Req[] GetRequestList() { Asn1Sequence seq = req.TbsRequest.RequestList; Req[] requests = new Req[seq.Count]; for (int i = 0; i != requests.Length; i++) { requests[i] = new Req(Request.GetInstance(seq[i])); } return requests; } public X509Extensions RequestExtensions { get { return X509Extensions.GetInstance(req.TbsRequest.RequestExtensions); } } protected override X509Extensions GetX509Extensions() { return RequestExtensions; } /** * return the object identifier representing the signature algorithm */ public string SignatureAlgOid { get { if (!this.IsSigned) return null; return req.OptionalSignature.SignatureAlgorithm.ObjectID.Id; } } public byte[] GetSignature() { if (!this.IsSigned) return null; return req.OptionalSignature.SignatureValue.GetBytes(); } private ArrayList GetCertList() { // load the certificates if we have any ArrayList certs = new ArrayList(); Asn1Sequence s = req.OptionalSignature.Certs; if (s != null) { foreach (Asn1Encodable ae in s) { try { certs.Add(new X509CertificateParser().ReadCertificate(ae.GetEncoded())); } catch (Exception e) { throw new OcspException("can't re-encode certificate!", e); } } } return certs; } public X509Certificate[] GetCerts() { if (!this.IsSigned) return null; ArrayList certs = this.GetCertList(); return (X509Certificate[]) certs.ToArray(typeof(X509Certificate)); } /** * If the request is signed return a possibly empty CertStore containing the certificates in the * request. If the request is not signed the method returns null. * * @return null if not signed, a CertStore otherwise * @throws OcspException */ public IX509Store GetCertificates( string type) { if (!this.IsSigned) return null; try { return X509StoreFactory.Create( "Certificate/" + type, new X509CollectionStoreParameters(this.GetCertList())); } catch (Exception e) { throw new OcspException("can't setup the CertStore", e); } } /** * Return whether or not this request is signed. * * @return true if signed false otherwise. */ public bool IsSigned { get { return req.OptionalSignature != null; } } /** * Verify the signature against the TBSRequest object we contain. */ public bool Verify( AsymmetricKeyParameter publicKey) { if (!this.IsSigned) throw new OcspException("attempt to Verify signature on unsigned object"); try { ISigner signature = SignerUtilities.GetSigner(this.SignatureAlgOid); signature.Init(false, publicKey); byte[] encoded = req.TbsRequest.GetEncoded(); signature.BlockUpdate(encoded, 0, encoded.Length); return signature.VerifySignature(this.GetSignature()); } catch (Exception e) { throw new OcspException("exception processing sig: " + e, e); } } /** * return the ASN.1 encoded representation of this object. */ public byte[] GetEncoded() { return req.GetEncoded(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; using System.Reflection; using Aurora.Simulation.Base; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Services.Connectors.Simulation { public class LocalSimulationServiceConnector : IService, ISimulationService { private readonly List<IScene> m_sceneList = new List<IScene>(); public string Name { get { return GetType().Name; } } #region ISimulation public IScene GetScene(ulong regionhandle) { #if (!ISWIN) foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionhandle) return s; } return null; #else return m_sceneList.FirstOrDefault(s => s.RegionInfo.RegionHandle == regionhandle); #endif // ? weird. should not happen } public ISimulationService GetInnerService() { return this; } /// <summary> /// Can be called from other modules. /// </summary> /// <param name = "scene"></param> public void RemoveScene(IScene scene) { lock (m_sceneList) { m_sceneList.Remove(scene); } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name = "scene"></param> public void Init(IScene scene) { lock (m_sceneList) { m_sceneList.Add(scene); } } /** * Agent-related communications */ public bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, AgentData data, out int requestedUDPPort, out string reason) { requestedUDPPort = 0; if (destination == null) { reason = "Given destination was null"; MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination"); return false; } if (destination.ExternalEndPoint != null) requestedUDPPort = destination.ExternalEndPoint.Port; #if (!ISWIN) foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionID == destination.RegionID) { //MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); if (data != null) UpdateAgent(destination, data); IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) return transferModule.NewUserConnection(s, aCircuit, teleportFlags, out requestedUDPPort, out reason); } } #else foreach (IScene s in m_sceneList.Where(s => s.RegionInfo.RegionID == destination.RegionID)) { //MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); if (data != null) UpdateAgent(destination, data); IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) return transferModule.NewUserConnection(s, aCircuit, teleportFlags, out requestedUDPPort, out reason); } #endif MainConsole.Instance.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Did not find region {0} for CreateAgent", destination.RegionName); OSDMap map = new OSDMap(); map["Reason"] = "Did not find region " + destination.RegionName; map["Success"] = false; reason = OSDParser.SerializeJsonString(map); return false; } public bool UpdateAgent(GridRegion destination, AgentData cAgentData) { if (destination == null || m_sceneList.Count == 0 || cAgentData == null) return false; bool retVal = false; IEntityTransferModule transferModule = m_sceneList[0].RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) { #if (!ISWIN) foreach (IScene s in m_sceneList) { if (destination.RegionID == s.RegionInfo.RegionID) { retVal = transferModule.IncomingChildAgentDataUpdate(s, cAgentData); } } #else foreach (IScene s in m_sceneList.Where(s => destination.RegionID == s.RegionInfo.RegionID)) { retVal = transferModule.IncomingChildAgentDataUpdate(s, cAgentData); } #endif } // MainConsole.Instance.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle); return retVal; } public bool UpdateAgent(GridRegion destination, AgentPosition cAgentData) { if (destination == null) return false; bool retVal = false; foreach (IScene s in m_sceneList) { //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) if (retVal) transferModule.IncomingChildAgentDataUpdate(s, cAgentData); else retVal = transferModule.IncomingChildAgentDataUpdate(s, cAgentData); } //MainConsole.Instance.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return retVal; } public bool FailedToMoveAgentIntoNewRegion(UUID AgentID, UUID RegionID) { #if (!ISWIN) foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionID == RegionID) { IScenePresence sp = s.GetScenePresence(AgentID); if (sp != null) { sp.AgentFailedToLeave(); } } } #else foreach (IScenePresence sp in m_sceneList.Where(s => s.RegionInfo.RegionID == RegionID).Select(s => s.GetScenePresence(AgentID)).Where(sp => sp != null)) { sp.AgentFailedToLeave(); } #endif return false; } public bool MakeChildAgent(UUID AgentID, UUID leavingRegion, GridRegion destination, bool markAgentAsLeaving) { foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionID != leavingRegion) continue; //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (transferModule == null) continue; transferModule.MakeChildAgent(s.GetScenePresence(AgentID), destination, markAgentAsLeaving); return true; } return false; } public bool RetrieveAgent(GridRegion destination, UUID id, bool agentIsLeaving, out AgentData agent, out AgentCircuitData circuitData) { agent = null; circuitData = null; if (destination == null) return false; foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionID == destination.RegionID) { //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) return transferModule.IncomingRetrieveRootAgent(s, id, agentIsLeaving, out agent, out circuitData); } } return false; //MainConsole.Instance.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); } public bool CloseAgent(GridRegion destination, UUID id) { if (destination == null) return false; foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionID == destination.RegionID) { //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to SendCloseAgent"); IEntityTransferModule transferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (transferModule != null) return transferModule.IncomingCloseAgent(s, id); } } MainConsole.Instance.Debug("[LOCAL SIMULATION COMMS]: region not found in CloseAgent"); return false; } /** * Object-related communications */ public bool CreateObject(GridRegion destination, ISceneObject sog) { if (destination == null) return false; foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionHandle != destination.RegionHandle) continue; //MainConsole.Instance.Debug("[LOCAL COMMS]: Found region to SendCreateObject"); IEntityTransferModule AgentTransferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (AgentTransferModule != null) { return AgentTransferModule.IncomingCreateObject(s.RegionInfo.RegionID, sog); } } MainConsole.Instance.Warn("[LOCAL SIMULATION COMMS]: region not found in CreateObject"); return false; } public bool CreateObject(GridRegion destination, UUID userID, UUID itemID) { if (destination == null) return false; foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionHandle == destination.RegionHandle) { IEntityTransferModule AgentTransferModule = s.RequestModuleInterface<IEntityTransferModule>(); if (AgentTransferModule != null) { return AgentTransferModule.IncomingCreateObject(s.RegionInfo.RegionID, userID, itemID); } } } MainConsole.Instance.Warn("[LOCAL SIMULATION COMMS]: region not found in CreateObject"); return false; } #endregion /* ISimulationService */ #region Misc public bool IsLocalRegion(ulong regionhandle) { #if (!ISWIN) foreach (IScene s in m_sceneList) if (s.RegionInfo.RegionHandle == regionhandle) return true; return false; #else if (m_sceneList.Any(s => s.RegionInfo.RegionHandle == regionhandle)) { return true; } return false; #endif } public bool IsLocalRegion(UUID id) { #if (!ISWIN) foreach (IScene s in m_sceneList) { if (s.RegionInfo.RegionID == id) return true; } return false; #else return m_sceneList.Any(s => s.RegionInfo.RegionID == id); #endif } #endregion #region IService Members public void Initialize(IConfigSource config, IRegistryCore registry) { IConfig handlers = config.Configs["Handlers"]; if (handlers.GetString("SimulationHandler", "") == Name) registry.RegisterModuleInterface<ISimulationService>(this); } public void Start(IConfigSource config, IRegistryCore registry) { ISceneManager man = registry.RequestModuleInterface<ISceneManager>(); if (man != null) { man.OnAddedScene += Init; man.OnCloseScene += RemoveScene; } } public void FinishedStartup() { } #endregion } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; #if SILVERLIGHT using Mono.Diagnostics; #endif using MsgPack.Rpc.Protocols; namespace MsgPack.Rpc.Client.Protocols { /// <summary> /// Represents context information for the client side request including notification. /// </summary> public sealed class ClientRequestContext : OutboundMessageContext { /// <summary> /// Constant part of the request header. /// </summary> private static readonly ArraySegment<byte> _requestHeader = new ArraySegment<byte>( new byte[] { 0x94, 0x00 } ); // [FixArray4], [Request:0] /// <summary> /// Constant part of the request header. /// </summary> private static readonly ArraySegment<byte> _notificationHeader = new ArraySegment<byte>( new byte[] { 0x94, 0x02 } ); // [FixArray4], [Notification:2] /// <summary> /// Empty array of <see cref="ArraySegment{T}"/> of <see cref="Byte"/>. /// </summary> private static readonly ArraySegment<byte> _emptyBuffer = new ArraySegment<byte>( new byte[ 0 ], 0, 0 ); private MessageType _messageType; /// <summary> /// Gets the type of the message. /// </summary> /// <value> /// The type of the message. /// </value> /// <remarks> /// This value can be set via <see cref="SetRequest"/> or <see cref="SetNotification"/> method. /// </remarks> public MessageType MessageType { get { Contract.Ensures( Contract.Result<MessageType>() == Rpc.Protocols.MessageType.Request || Contract.Result<MessageType>() == Rpc.Protocols.MessageType.Notification ); return this._messageType; } } private Packer _argumentsPacker; /// <summary> /// Gets the <see cref="Packer"/> to pack arguments array. /// </summary> /// <value> /// The <see cref="Packer"/> to pack arguments array. /// This value will not be <c>null</c>. /// </value> public Packer ArgumentsPacker { get { Contract.Ensures( Contract.Result<Packer>() != null ); return this._argumentsPacker; } } private string _methodName; /// <summary> /// Gets the name of the calling method. /// </summary> /// <value> /// The name of the calling method. /// This value will be <c>null</c> if both of <see cref="SetRequest"/> and <see cref="SetNotification"/> have not been called after previous cleanup or initialization. /// </value> /// <remarks> /// This value can be set via <see cref="SetRequest"/> or <see cref="SetNotification"/> method. /// </remarks> public string MethodName { get { return this._methodName; } } /// <summary> /// The reusable buffer to pack method name. /// This value will not be <c>null</c>. /// </summary> private readonly MemoryStream _methodNameBuffer; /// <summary> /// The reusable buffer to pack arguments. /// This value will not be <c>null</c>. /// </summary> private readonly MemoryStream _argumentsBuffer; /// <summary> /// The resusable buffer to hold sending response data. /// </summary> /// <remarks> /// Each segment corresponds to the message segment. /// <list type="table"> /// <listheader> /// <term>Index</term> /// <description>Content</description> /// </listheader> /// <item> /// <term>0</term> /// <description> /// Common response header, namely array header and message type. /// Do not change this element. /// </description> /// </item> /// <item> /// <term>1</term> /// <description> /// Message ID to correpond the response to the request. /// </description> /// </item> /// <item> /// <term>2</term> /// <description> /// Error identifier. /// </description> /// </item> /// <item> /// <term>3</term> /// <description> /// Return value. /// </description> /// </item> /// </list> /// </remarks> internal readonly ArraySegment<byte>[] SendingBuffer; #if MONO private readonly MemoryStream _unifiedSendingBuffer; #endif private Action<Exception, bool> _notificationCompletionCallback; /// <summary> /// Gets the callback delegate which will be called when the notification is sent. /// </summary> /// <value> /// The callback delegate which will be called when the notification is sent. /// The 1st argument is an <see cref="Exception"/> which represents sending error, or <c>null</c> for success. /// The 2nd argument indicates that the operation is completed synchronously. /// This value will be <c>null</c> if both of <see cref="SetRequest"/> and <see cref="SetNotification"/> have not been called after previous cleanup or initialization. /// </value> /// <remarks> /// This value can be set via <see cref="SetNotification"/> method. /// </remarks> public Action<Exception, bool> NotificationCompletionCallback { get { return this._notificationCompletionCallback; } } private Action<ClientResponseContext, Exception, bool> _requestCompletionCallback; /// <summary> /// Gets the callback delegate which will be called when the response is received. /// </summary> /// <value> /// The callback delegate which will be called when the notification sent. /// The 1st argument is a <see cref="ClientResponseContext"/> which stores any information of the response, it will not be <c>null</c>. /// The 2nd argument is an <see cref="Exception"/> which represents sending error, or <c>null</c> for success. /// The 3rd argument indicates that the operation is completed synchronously. /// This value will be <c>null</c> if both of <see cref="SetRequest"/> and <see cref="SetNotification"/> have not been called after previous cleanup or initialization. /// </value> /// <remarks> /// This value can be set via <see cref="SetRequest"/> method. /// </remarks> public Action<ClientResponseContext, Exception, bool> RequestCompletionCallback { get { return this._requestCompletionCallback; } } private readonly Stopwatch _stopwatch; internal TimeSpan ElapsedTime { get { return this._stopwatch.Elapsed; } } /// <summary> /// Initializes a new instance of the <see cref="ClientRequestContext"/> class with default settings. /// </summary> public ClientRequestContext() : this( null ) { } /// <summary> /// Initializes a new instance of the <see cref="ClientRequestContext"/> class with specified configuration. /// </summary> /// <param name="configuration"> /// An <see cref="RpcClientConfiguration"/> to tweak this instance initial state. /// </param> public ClientRequestContext( RpcClientConfiguration configuration ) { this._methodNameBuffer = new MemoryStream( ( configuration ?? RpcClientConfiguration.Default ).InitialMethodNameBufferLength ); this._argumentsBuffer = new MemoryStream( ( configuration ?? RpcClientConfiguration.Default ).InitialArgumentsBufferLength ); this.SendingBuffer = new ArraySegment<byte>[ 4 ]; #if MONO this._unifiedSendingBuffer = new MemoryStream( ( configuration ?? RpcClientConfiguration.Default ).InitialReceiveBufferLength ); #endif this._argumentsPacker = Packer.Create( this._argumentsBuffer, false ); this._messageType = MessageType.Response; this._stopwatch = new Stopwatch(); } internal override void StartWatchTimeout( TimeSpan timeout ) { base.StartWatchTimeout( timeout ); this._stopwatch.Restart(); } internal override void StopWatchTimeout() { this._stopwatch.Stop(); base.StopWatchTimeout(); } /// <summary> /// Set ups this context for request message. /// </summary> /// <param name="messageId">The message id which identifies request/response and associates request and response.</param> /// <param name="methodName">Name of the method to be called.</param> /// <param name="completionCallback"> /// The callback which will be called when the response is received. /// For details, see <see cref="RequestCompletionCallback"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="methodName"/> is <c>null</c>. /// Or <paramref name="completionCallback"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="methodName"/> is empty. /// </exception> public void SetRequest( int messageId, string methodName, Action<ClientResponseContext, Exception, bool> completionCallback ) { if ( methodName == null ) { throw new ArgumentNullException( "methodName" ); } if ( methodName.Length == 0 ) { throw new ArgumentException( "Method name cannot be empty.", "methodName" ); } if ( completionCallback == null ) { throw new ArgumentNullException( "completionCallback" ); } Contract.Ensures( this.MessageType == Rpc.Protocols.MessageType.Request ); Contract.Ensures( this.MessageId != null ); Contract.Ensures( !String.IsNullOrEmpty( this.MethodName ) ); Contract.Ensures( this.RequestCompletionCallback != null ); Contract.Ensures( this.NotificationCompletionCallback == null ); this._messageType = Rpc.Protocols.MessageType.Request; this.MessageId = messageId; this._methodName = methodName; this._requestCompletionCallback = completionCallback; this._notificationCompletionCallback = null; } /// <summary> /// Set ups this context for notification message. /// </summary> /// <param name="methodName">Name of the method to be called.</param> /// <param name="completionCallback"> /// The callback which will be called when the response is received. /// For details, see <see cref="NotificationCompletionCallback"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="methodName"/> is <c>null</c>. /// Or <paramref name="completionCallback"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="methodName"/> is empty. /// </exception> public void SetNotification( string methodName, Action<Exception, bool> completionCallback ) { if ( methodName == null ) { throw new ArgumentNullException( "methodName" ); } if ( methodName.Length == 0 ) { throw new ArgumentException( "Method name cannot be empty.", "methodName" ); } if ( completionCallback == null ) { throw new ArgumentNullException( "completionCallback" ); } Contract.Ensures( this.MessageType == Rpc.Protocols.MessageType.Notification ); Contract.Ensures( this.MessageId == null ); Contract.Ensures( !String.IsNullOrEmpty( this.MethodName ) ); Contract.Ensures( this.RequestCompletionCallback == null ); Contract.Ensures( this.NotificationCompletionCallback != null ); this._messageType = Rpc.Protocols.MessageType.Notification; this.MessageId = null; this._methodName = methodName; this._notificationCompletionCallback = completionCallback; this._requestCompletionCallback = null; } /// <summary> /// Prepares this instance to send request or notification message. /// </summary> internal void Prepare( bool canUseChunkedBuffer ) { if ( this._messageType == MessageType.Response ) { throw new InvalidOperationException( "MessageType is not set." ); } Contract.Assert( this._methodName != null ); using ( var packer = Packer.Create( this._methodNameBuffer, false ) ) { packer.Pack( this._methodName ); } if ( this._messageType == MessageType.Request ) { Contract.Assert( this.MessageId != null ); Contract.Assert( this._requestCompletionCallback != null ); this.SendingBuffer[ 0 ] = _requestHeader; this.SendingBuffer[ 1 ] = this.GetPackedMessageId(); this.SendingBuffer[ 2 ] = new ArraySegment<byte>( this._methodNameBuffer.GetBuffer(), 0, unchecked( ( int )this._methodNameBuffer.Length ) ); this.SendingBuffer[ 3 ] = new ArraySegment<byte>( this._argumentsBuffer.GetBuffer(), 0, unchecked( ( int )this._argumentsBuffer.Length ) ); } else { Contract.Assert( this._notificationCompletionCallback != null ); this.SendingBuffer[ 0 ] = _notificationHeader; this.SendingBuffer[ 1 ] = new ArraySegment<byte>( this._methodNameBuffer.GetBuffer(), 0, unchecked( ( int )this._methodNameBuffer.Length ) ); this.SendingBuffer[ 2 ] = new ArraySegment<byte>( this._argumentsBuffer.GetBuffer(), 0, unchecked( ( int )this._argumentsBuffer.Length ) ); this.SendingBuffer[ 3 ] = _emptyBuffer; } #if MONO if ( !canUseChunkedBuffer ) { this._unifiedSendingBuffer.Position = 0; this._unifiedSendingBuffer.SetLength( 0 ); this._unifiedSendingBuffer.Write( this.SendingBuffer[ 0 ].Array, this.SendingBuffer[ 0 ].Offset, this.SendingBuffer[ 0 ].Count ); this._unifiedSendingBuffer.Write( this.SendingBuffer[ 1 ].Array, this.SendingBuffer[ 1 ].Offset, this.SendingBuffer[ 1 ].Count ); this._unifiedSendingBuffer.Write( this.SendingBuffer[ 2 ].Array, this.SendingBuffer[ 2 ].Offset, this.SendingBuffer[ 2 ].Count ); this._unifiedSendingBuffer.Write( this.SendingBuffer[ 3 ].Array, this.SendingBuffer[ 3 ].Offset, this.SendingBuffer[ 3 ].Count ); this.SocketContext.SetBuffer( this._unifiedSendingBuffer.GetBuffer(), 0, unchecked( ( int )this._unifiedSendingBuffer.Length ) ); this.SocketContext.BufferList = null; return; } #endif this.SocketContext.SetBuffer( null, 0, 0 ); this.SocketContext.BufferList = this.SendingBuffer; } internal override void ClearBuffers() { this._methodNameBuffer.SetLength( 0 ); this._argumentsBuffer.SetLength( 0 ); this.SocketContext.BufferList = null; this._argumentsPacker.Dispose(); this._argumentsPacker = Packer.Create( this._argumentsBuffer, false ); this.SendingBuffer[ 0 ] = new ArraySegment<byte>(); this.SendingBuffer[ 1 ] = new ArraySegment<byte>(); this.SendingBuffer[ 2 ] = new ArraySegment<byte>(); this.SendingBuffer[ 3 ] = new ArraySegment<byte>(); base.ClearBuffers(); } /// <summary> /// Clears this instance internal buffers for reuse. /// </summary> internal sealed override void Clear() { this.ClearBuffers(); this._methodName = null; this._messageType = MessageType.Response; // Invalid. this._requestCompletionCallback = null; this._notificationCompletionCallback = null; base.Clear(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Globalization; using Machine.Specifications.Annotations; using Machine.Specifications.Utility; using Machine.Specifications.Utility.Internal; namespace Machine.Specifications { public static class ShouldExtensionMethods { static bool SafeEquals<T>(this T left, T right) { var comparer = new AssertComparer<T>(); return comparer.Compare(left, right) == 0; } [AssertionMethod] public static void ShouldBeFalse([AssertionCondition(AssertionConditionType.IS_FALSE)] this bool condition) { if (condition) throw new SpecificationException("Should be [false] but is [true]"); } [AssertionMethod] public static void ShouldBeTrue([AssertionCondition(AssertionConditionType.IS_TRUE)] this bool condition) { if (!condition) throw new SpecificationException("Should be [true] but is [false]"); } public static T ShouldEqual<T>(this T actual, T expected) { if (!actual.SafeEquals(expected)) { throw new SpecificationException(PrettyPrintingExtensions.FormatErrorMessage(actual, expected)); } return actual; } public static object ShouldNotEqual<T>(this T actual, T expected) { if (actual.SafeEquals(expected)) { throw new SpecificationException(string.Format("Should not equal {0} but does: {1}", expected.ToUsefulString(), actual.ToUsefulString())); } return actual; } [AssertionMethod] public static void ShouldBeNull([AssertionCondition(AssertionConditionType.IS_NULL)] this object anObject) { if (anObject != null) { throw new SpecificationException(string.Format((string)"Should be [null] but is {0}", (object)anObject.ToUsefulString())); } } [AssertionMethod] public static void ShouldNotBeNull([AssertionCondition(AssertionConditionType.IS_NOT_NULL)] this object anObject) { if (anObject == null) { throw new SpecificationException(string.Format("Should be [not null] but is [null]")); } } public static object ShouldBeTheSameAs(this object actual, object expected) { if (!ReferenceEquals(actual, expected)) { throw new SpecificationException(string.Format("Should be the same as {0} but is {1}", expected, actual)); } return expected; } public static object ShouldNotBeTheSameAs(this object actual, object expected) { if (ReferenceEquals(actual, expected)) { throw new SpecificationException(string.Format("Should not be the same as {0} but is {1}", expected, actual)); } return expected; } public static void ShouldBeOfExactType(this object actual, Type expected) { if (actual == null) { throw new SpecificationException(string.Format("Should be of type {0} but is [null]", expected)); } if (actual.GetType() != expected) { throw new SpecificationException(string.Format("Should be of type {0} but is of type {1}", expected, actual.GetType())); } } public static void ShouldNotBeOfExactType(this object actual, Type expected) { if (actual == null) { throw new SpecificationException(string.Format("Should not be of type {0} but is [null]", expected)); } if (actual.GetType() == expected) { throw new SpecificationException(string.Format("Should not be of type {0} but is of type {1}", expected, actual.GetType())); } } public static void ShouldBeOfExactType<T>(this object actual) { actual.ShouldBeOfExactType(typeof(T)); } public static void ShouldNotBeOfExactType<T>(this object actual) { actual.ShouldNotBeOfExactType(typeof(T)); } public static void ShouldBeAssignableTo(this object actual, Type expected) { if (actual == null) { throw new SpecificationException(string.Format("Should be assignable to type {0} but is [null]", expected)); } if (!expected.IsAssignableFrom(actual.GetType())) { throw new SpecificationException(string.Format("Should be assignable to type {0} but is not. Actual type is {1}", expected, actual.GetType())); } } public static void ShouldNotBeAssignableTo(this object actual, Type expected) { if (actual == null) { throw new SpecificationException(string.Format("Should not be assignable to type {0} but is [null]", expected)); } if (expected.IsAssignableFrom(actual.GetType())) { throw new SpecificationException(string.Format("Should not be assignable to type {0} but is. Actual type is {1}", expected, actual.GetType())); } } public static void ShouldBeAssignableTo<T>(this object actual) { actual.ShouldBeAssignableTo(typeof(T)); } public static void ShouldNotBeAssignableTo<T>(this object actual) { actual.ShouldNotBeAssignableTo(typeof(T)); } public static void ShouldMatch<T>(this T actual, Expression<Func<T, bool>> condition) { var matches = condition.Compile().Invoke(actual); if (matches) return; throw new SpecificationException(string.Format("Should match expression [{0}], but does not.", condition)); } public static void ShouldEachConformTo<T>(this IEnumerable<T> list, Expression<Func<T, bool>> condition) { var source = new List<T>(list); var func = condition.Compile(); var failingItems = source.Where(x => func(x) == false); if (failingItems.Any()) { throw new SpecificationException(string.Format( @"Should contain only elements conforming to: {0} the following items did not meet the condition: {1}", condition, failingItems.EachToUsefulString())); } } public static void ShouldContain(this IEnumerable list, params object[] items) { var actualList = list.Cast<object>(); var expectedList = items.Cast<object>(); actualList.ShouldContain(expectedList); } public static void ShouldContain<T>(this IEnumerable<T> list, params T[] items) { list.ShouldContain((IEnumerable<T>)items); } public static void ShouldContain<T>(this IEnumerable<T> list, IEnumerable<T> items) { var noContain = new List<T>(); var comparer = new AssertComparer<T>(); foreach (var item in items) { if (!list.Contains<T>(item, comparer)) { noContain.Add(item); } } if (noContain.Any()) { throw new SpecificationException(string.Format( @"Should contain: {0} entire list: {1} does not contain: {2}", items.EachToUsefulString(), list.EachToUsefulString(), noContain.EachToUsefulString())); } } public static void ShouldContain<T>(this IEnumerable<T> list, Expression<Func<T, bool>> condition) { var func = condition.Compile(); if (!list.Any(func)) { throw new SpecificationException(string.Format( @"Should contain elements conforming to: {0} entire list: {1}", condition, list.EachToUsefulString())); } } public static void ShouldNotContain(this IEnumerable list, params object[] items) { var actualList = list.Cast<object>(); var expectedList = items.Cast<object>(); actualList.ShouldNotContain(expectedList); } public static void ShouldNotContain<T>(this IEnumerable<T> list, params T[] items) { list.ShouldNotContain((IEnumerable<T>)items); } public static void ShouldNotContain<T>(this IEnumerable<T> list, IEnumerable<T> items) { var contains = new List<T>(); var comparer = new AssertComparer<T>(); foreach (var item in items) { if (list.Contains<T>(item, comparer)) { contains.Add(item); } } if (contains.Any()) { throw new SpecificationException(string.Format( @"Should not contain: {0} entire list: {1} does contain: {2}", items.EachToUsefulString(), list.EachToUsefulString(), contains.EachToUsefulString())); } } public static void ShouldNotContain<T>(this IEnumerable<T> list, Expression<Func<T, bool>> condition) { var func = condition.Compile(); var contains = list.Where(func); if (contains.Any()) { throw new SpecificationException(string.Format( @"No elements should conform to: {0} entire list: {1} does contain: {2}", condition, list.EachToUsefulString(), contains.EachToUsefulString())); } } static SpecificationException NewException(string message, params object[] parameters) { if (parameters.Any()) { return new SpecificationException(string.Format(message.EnsureSafeFormat(), parameters.Select<object, string>(x => x.ToUsefulString()).Cast<object>().ToArray())); } return new SpecificationException(message); } public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2) { if (arg2 == null) throw new ArgumentNullException("arg2"); if (arg1 == null) throw NewException("Should be greater than {0} but is [null]", arg2); if (arg1.CompareTo(arg2.TryToChangeType(arg1.GetType())) <= 0) throw NewException("Should be greater than {0} but is {1}", arg2, arg1); return arg1; } public static IComparable ShouldBeGreaterThanOrEqualTo(this IComparable arg1, IComparable arg2) { if (arg2 == null) throw new ArgumentNullException("arg2"); if (arg1 == null) throw NewException("Should be greater than or equal to {0} but is [null]", arg2); if (arg1.CompareTo(arg2.TryToChangeType(arg1.GetType())) < 0) throw NewException("Should be greater than or equal to {0} but is {1}", arg2, arg1); return arg1; } static object TryToChangeType(this object original, Type type) { try { return Convert.ChangeType(original, type); } catch { return original; } } public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2) { if (arg2 == null) throw new ArgumentNullException("arg2"); if (arg1 == null) throw NewException("Should be less than {0} but is [null]", arg2); if (arg1.CompareTo(arg2.TryToChangeType(arg1.GetType())) >= 0) throw NewException("Should be less than {0} but is {1}", arg2, arg1); return arg1; } public static IComparable ShouldBeLessThanOrEqualTo(this IComparable arg1, IComparable arg2) { if (arg2 == null) throw new ArgumentNullException("arg2"); if (arg1 == null) throw NewException("Should be less than or equal to {0} but is [null]", arg2); if (arg1.CompareTo(arg2.TryToChangeType(arg1.GetType())) > 0) throw NewException("Should be less than or equal to {0} but is {1}", arg2, arg1); return arg1; } public static void ShouldBeCloseTo(this float actual, float expected) { ShouldBeCloseTo(actual, expected, 0.0000001f); } public static void ShouldBeCloseTo(this float actual, float expected, float tolerance) { if (Math.Abs(actual - expected) > tolerance) { throw new SpecificationException(string.Format("Should be within {0} of {1} but is {2}", tolerance.ToUsefulString(), expected.ToUsefulString(), actual.ToUsefulString())); } } public static void ShouldBeCloseTo(this double actual, double expected) { ShouldBeCloseTo(actual, expected, 0.0000001f); } public static void ShouldBeCloseTo(this double actual, double expected, double tolerance) { if (Math.Abs(actual - expected) > tolerance) { throw new SpecificationException(string.Format("Should be within {0} of {1} but is {2}", tolerance.ToUsefulString(), expected.ToUsefulString(), actual.ToUsefulString())); } } public static void ShouldBeCloseTo(this TimeSpan actual, TimeSpan expected, TimeSpan tolerance) { if (Math.Abs(actual.Ticks - expected.Ticks) > tolerance.Ticks) { throw new SpecificationException(string.Format("Should be within {0} of {1} but is {2}", tolerance.ToUsefulString(), expected.ToUsefulString(), actual.ToUsefulString())); } } public static void ShouldBeCloseTo(this DateTime actual, DateTime expected, TimeSpan tolerance) { var difference = expected - actual; if (Math.Abs(difference.Ticks) > tolerance.Ticks) { throw new SpecificationException(string.Format("Should be within {0} of {1} but is {2}", tolerance.ToUsefulString(), expected.ToUsefulString(), actual.ToUsefulString())); } } public static void ShouldBeEmpty(this IEnumerable collection) { if (collection.Cast<object>().Any()) { throw NewException("Should be empty but contains:\n" + collection.Cast<object>().EachToUsefulString()); } } public static void ShouldBeEmpty(this string aString) { if (aString == null) { throw new SpecificationException("Should be empty but is [null]"); } if (!string.IsNullOrEmpty(aString)) { throw NewException("Should be empty but is {0}", aString); } } public static void ShouldNotBeEmpty(this IEnumerable collection) { if (!collection.Cast<object>().Any()) { throw NewException("Should not be empty but is"); } } public static void ShouldNotBeEmpty(this string aString) { if (string.IsNullOrEmpty(aString)) { throw NewException("Should not be empty but is"); } } public static void ShouldMatch(this string actual, string pattern) { if (pattern == null) throw new ArgumentNullException("pattern"); if (actual == null) throw NewException("Should match regex {0} but is [null]", pattern); ShouldMatch(actual, new Regex(pattern)); } public static void ShouldMatch(this string actual, Regex pattern) { if (pattern == null) throw new ArgumentNullException("pattern"); if (actual == null) throw NewException("Should match regex {0} but is [null]", pattern); if (!pattern.IsMatch(actual)) { throw NewException("Should match {0} but is {1}", pattern, actual); } } public static void ShouldContain(this string actual, string expected) { if (expected == null) throw new ArgumentNullException("expected"); if (actual == null) throw NewException("Should contain {0} but is [null]", expected); if (!actual.Contains(expected)) { throw NewException("Should contain {0} but is {1}", expected, actual); } } public static void ShouldNotContain(this string actual, string notExpected) { if (notExpected == null) throw new ArgumentNullException("notExpected"); if (actual == null) return; if (actual.Contains(notExpected)) { throw NewException("Should not contain {0} but is {1}", notExpected, actual); } } public static string ShouldBeEqualIgnoringCase(this string actual, string expected) { if (expected == null) throw new ArgumentNullException("expected"); if (actual == null) throw NewException("Should be equal ignoring case to {0} but is [null]", expected); if (CultureInfo.InvariantCulture.CompareInfo.Compare(actual, expected, CompareOptions.IgnoreCase) != 0) { throw NewException("Should be equal ignoring case to {0} but is {1}", expected, actual); } return actual; } public static void ShouldStartWith(this string actual, string expected) { if (expected == null) throw new ArgumentNullException("expected"); if (actual == null) throw NewException("Should start with {0} but is [null]", expected); if (!actual.StartsWith(expected)) { throw NewException("Should start with {0} but is {1}", expected, actual); } } public static void ShouldEndWith(this string actual, string expected) { if (expected == null) throw new ArgumentNullException("expected"); if (actual == null) throw NewException("Should end with {0} but is [null]", expected); if (!actual.EndsWith(expected)) { throw NewException("Should end with {0} but is {1}", expected, actual); } } public static void ShouldBeSurroundedWith(this string actual, string expectedStartDelimiter, string expectedEndDelimiter) { actual.ShouldStartWith(expectedStartDelimiter); actual.ShouldEndWith(expectedEndDelimiter); } public static void ShouldBeSurroundedWith(this string actual, string expectedDelimiter) { actual.ShouldStartWith(expectedDelimiter); actual.ShouldEndWith(expectedDelimiter); } public static void ShouldContainErrorMessage(this Exception exception, string expected) { exception.Message.ShouldContain(expected); } public static void ShouldContainOnly<T>(this IEnumerable<T> list, params T[] items) { list.ShouldContainOnly((IEnumerable<T>)items); } public static void ShouldContainOnly<T>(this IEnumerable<T> list, IEnumerable<T> items) { var source = new List<T>(list); var noContain = new List<T>(); var comparer = new AssertComparer<T>(); foreach (var item in items) { if (!source.Contains<T>(item, comparer)) { noContain.Add(item); } else { source.Remove(item); } } if (noContain.Any() || source.Any()) { var message = string.Format(@"Should contain only: {0} entire list: {1}", items.EachToUsefulString(), list.EachToUsefulString()); if (noContain.Any()) { message += "\ndoes not contain: " + noContain.EachToUsefulString(); } if (source.Any()) { message += "\ndoes contain but shouldn't: " + source.EachToUsefulString(); } throw new SpecificationException(message); } } public static Exception ShouldBeThrownBy(this Type exceptionType, Action method) { var exception = Catch.Exception(method); ShouldNotBeNull(exception); ShouldBeAssignableTo(exception, exceptionType); return exception; } public static void ShouldBeLike(this object obj, object expected) { var exceptions = ShouldBeLikeInternal(obj, expected, "", new HashSet<ReferentialEqualityTuple>()).ToArray(); if (exceptions.Any()) { throw NewException(exceptions.Select(e => e.Message).Aggregate<string, string>("", (r, m) => r + m + Environment.NewLine + Environment.NewLine).TrimEnd()); } } static IEnumerable<SpecificationException> ShouldBeLikeInternal(object obj, object expected, string nodeName, HashSet<ReferentialEqualityTuple> visited) { // Stop at already checked <actual,expected>-pairs to prevent infinite loops (cycles in object graphs). Additionally // this also avoids re-equality-evaluation for already compared pairs. var objExpectedTuple = new ReferentialEqualityTuple(obj, expected); if (visited.Contains(objExpectedTuple)) return Enumerable.Empty<SpecificationException>(); else visited.Add(objExpectedTuple); ObjectGraphHelper.INode expectedNode = null; var nodeType = typeof(ObjectGraphHelper.LiteralNode); if (obj != null && expected != null) { expectedNode = ObjectGraphHelper.GetGraph(expected); nodeType = expectedNode.GetType(); } if (nodeType == typeof(ObjectGraphHelper.LiteralNode)) { try { obj.ShouldEqual(expected); } catch (SpecificationException ex) { return new[] { NewException(string.Format("{{0}}:{0}{1}", Environment.NewLine, ex.Message), nodeName) }; } return Enumerable.Empty<SpecificationException>(); } else if (nodeType == typeof(ObjectGraphHelper.SequenceNode)) { if (obj == null) { var errorMessage = PrettyPrintingExtensions.FormatErrorMessage(null, expected); return new[] { NewException(string.Format("{{0}}:{0}{1}", Environment.NewLine, errorMessage), nodeName) }; } var actualNode = ObjectGraphHelper.GetGraph(obj); if (actualNode.GetType() != typeof(ObjectGraphHelper.SequenceNode)) { var errorMessage = string.Format(" Expected: Array or Sequence{0} But was: {1}", Environment.NewLine, obj.GetType()); return new[] { NewException(string.Format("{{0}}:{0}{1}", Environment.NewLine, errorMessage), nodeName) }; } var expectedValues = ((ObjectGraphHelper.SequenceNode)expectedNode).ValueGetters; var actualValues = ((ObjectGraphHelper.SequenceNode)actualNode).ValueGetters; var expectedCount = Enumerable.Count<Func<object>>(expectedValues); var actualCount = Enumerable.Count<Func<object>>(actualValues); if (expectedCount != actualCount) { var errorMessage = string.Format(" Expected: Sequence length of {1}{0} But was: {2}", Environment.NewLine, expectedCount, actualCount); return new[] { NewException(string.Format("{{0}}:{0}{1}", Environment.NewLine, errorMessage), nodeName) }; } return Enumerable.Range(0, expectedCount) .SelectMany(i => ShouldBeLikeInternal(Enumerable.ElementAt<Func<object>>(actualValues, i)(), Enumerable.ElementAt<Func<object>>(expectedValues, i)(), string.Format("{0}[{1}]", nodeName, i), visited)); } else if (nodeType == typeof(ObjectGraphHelper.KeyValueNode)) { var actualNode = ObjectGraphHelper.GetGraph(obj); if (actualNode.GetType() != typeof(ObjectGraphHelper.KeyValueNode)) { var errorMessage = string.Format(" Expected: Class{0} But was: {1}", Environment.NewLine, obj.GetType()); return new[] { NewException(string.Format("{{0}}:{0}{1}", Environment.NewLine, errorMessage), nodeName) }; } var expectedKeyValues = ((ObjectGraphHelper.KeyValueNode)expectedNode).KeyValues; var actualKeyValues = ((ObjectGraphHelper.KeyValueNode)actualNode).KeyValues; return expectedKeyValues .SelectMany(kv => { var fullNodeName = string.IsNullOrEmpty(nodeName) ? kv.Name : string.Format("{0}.{1}", nodeName, kv.Name); var actualKeyValue = actualKeyValues.SingleOrDefault(k => k.Name == kv.Name); if (actualKeyValue == null) { var errorMessage = string.Format(" Expected: {1}{0} But was: Not Defined", Environment.NewLine, kv.ValueGetter().ToUsefulString()); return new[] { NewException(string.Format("{{0}}:{0}{1}", Environment.NewLine, errorMessage), fullNodeName) }; } return ShouldBeLikeInternal(actualKeyValue.ValueGetter(), kv.ValueGetter(), fullNodeName, visited); }); } else { throw new InvalidOperationException("Unknown node type"); } } // DTO for ShouldBeLikeInternal() loop detection's visited cache private class ReferentialEqualityTuple { private readonly object _obj; private readonly object _expected; public ReferentialEqualityTuple(object obj, object expected) { _obj = obj; _expected = expected; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode (_obj) * RuntimeHelpers.GetHashCode (_expected); } public override bool Equals(object other) { var otherSimpleTuple = other as ReferentialEqualityTuple; if (otherSimpleTuple == null) return false; return ReferenceEquals(_obj, otherSimpleTuple._obj) && ReferenceEquals(_expected, otherSimpleTuple._expected); } } } }
using System.Diagnostics; namespace dotless.Core.Parser { using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Exceptions; using Infrastructure.Nodes; using Utils; [DebuggerDisplay("{Remaining}")] public class Tokenizer { public int Optimization { get; set; } private string _input; // LeSS input string private List<Chunk> _chunks; // chunkified input private int _i; // current index in `input` private int _j; // current chunk private int _current; // index of current chunk, in `input` private int _lastCommentStart = -1; // the start of the last collection of comments private int _lastCommentEnd = -1; // the end of the last collection of comments private int _inputLength; private readonly string _commentRegEx = @"(//[^\n]*|(/\*(.|[\r\n])*?\*/))"; private readonly string _quotedRegEx = @"(""((?:[^""\\\r\n]|\\.)*)""|'((?:[^'\\\r\n]|\\.)*)')"; private string _fileName; //Increasing throughput through tracing of Regex private IDictionary<string, Regex> regexCache = new Dictionary<string, Regex>(); public Tokenizer(int optimization) { Optimization = optimization; } public void SetupInput(string input, string fileName) { _fileName = fileName; _i = _j = _current = 0; _chunks = new List<Chunk>(); _input = input.Replace("\r\n", "\n"); _inputLength = _input.Length; // Split the input into chunks, // Either delimited by /\n\n/ or // delmited by '\n}' (see rationale above), // depending on the level of optimization. if(Optimization == 0) _chunks.Add(new Chunk(_input)); else { var skip = new Regex(@"\G(@\{[a-zA-Z0-9_-]+\}|[^\""'{}/\\\(\)]+)"); var comment = GetRegex(this._commentRegEx, RegexOptions.None); var quotedstring = GetRegex(this._quotedRegEx, RegexOptions.None); var level = 0; var lastBlock = 0; var inParam = false; int i = 0; while(i < _inputLength) { var match = skip.Match(_input, i); if(match.Success) { Chunk.Append(match.Value, _chunks); i += match.Length; continue; } var c = _input[i]; if(i < _inputLength - 1 && c == '/') { var cc = _input[i + 1]; if ((!inParam && cc == '/') || cc == '*') { match = comment.Match(_input, i); if(match.Success) { i += match.Length; _chunks.Add(new Chunk(match.Value, ChunkType.Comment)); continue; } else { throw new ParsingException("Missing closing comment", GetNodeLocation(i)); } } } if(c == '"' || c == '\'') { match = quotedstring.Match(_input, i); if(match.Success) { i += match.Length; _chunks.Add(new Chunk(match.Value, ChunkType.QuotedString)); continue; } else { throw new ParsingException(string.Format("Missing closing quote ({0})", c), GetNodeLocation(i)); } } // we are not in a quoted string or comment - process '{' level if(!inParam && c == '{') { level++; lastBlock = i; } else if (!inParam && c == '}') { level--; if(level < 0) throw new ParsingException("Unexpected '}'", GetNodeLocation(i)); Chunk.Append(c, _chunks, true); i++; continue; } if (c == '(') { inParam = true; } else if (c == ')') { inParam = false; } Chunk.Append(c, _chunks); i++; } if(level > 0) throw new ParsingException("Missing closing '}'", GetNodeLocation(lastBlock)); _input = Chunk.CommitAll(_chunks); _inputLength = _input.Length; } Advance(0); // skip any whitespace characters at the start. } public string GetComment() { // if we've hit the end we might still be looking at a valid chunk, so return early if (_i == _inputLength) { return null; } string val; int startI = _i; int endI = 0; if (Optimization == 0) { if (this.CurrentChar != '/') return null; var comment = this.Match(this._commentRegEx); if (comment == null) { return null; } val = comment.Value; endI = startI + comment.Value.Length; } else { if (_chunks[_j].Type == ChunkType.Comment) { val = _chunks[_j].Value; endI = _i + _chunks[_j].Value.Length; Advance(_chunks[_j].Value.Length); } else { return null; } } if (_lastCommentEnd != startI) { _lastCommentStart = startI; } _lastCommentEnd = endI; return val; } public string GetQuotedString() { // if we've hit the end we might still be looking at a valid chunk, so return early if (_i == _inputLength) { return null; } if (Optimization == 0) { if (this.CurrentChar != '"' && this.CurrentChar != '\'') return null; var quotedstring = this.Match(this._quotedRegEx); return quotedstring.Value; } else { if (_chunks[_j].Type == ChunkType.QuotedString) { string val = _chunks[_j].Value; Advance(_chunks[_j].Value.Length); return val; } } return null; } public string MatchString(char tok) { var c = Match(tok); return c == null ? null : c.Value; } public string MatchString(string tok) { var match = Match(tok); return match == null ? null : match.Value; } // // Parse from a token, regexp or string, and move forward if match // public CharMatchResult Match(char tok) { if (_i == _inputLength || _chunks[_j].Type != ChunkType.Text) { return null; } if (_input[_i] == tok) { var index = _i; Advance(1); return new CharMatchResult(tok) { Location = GetNodeLocation(index) }; } return null; } public RegexMatchResult Match(string tok) { return Match(tok, false); } public RegexMatchResult Match(string tok, bool caseInsensitive) { if (_i == _inputLength || _chunks[_j].Type != ChunkType.Text) { return null; } var options = RegexOptions.None; if (caseInsensitive) options |= RegexOptions.IgnoreCase; var regex = GetRegex(tok, options); var match = regex.Match(_chunks[_j].Value, _i - _current); if (!match.Success) return null; var index = _i; Advance(match.Length); return new RegexMatchResult(match) {Location = GetNodeLocation(index)}; } // Match a string, but include the possibility of matching quoted and comments public RegexMatchResult MatchAny(string tok) { if (_i == _inputLength) { return null; } var regex = GetRegex(tok, RegexOptions.None); var match = regex.Match(_input, _i); if (!match.Success) return null; Advance(match.Length); if (_i > _current && _i < _current + _chunks[_j].Value.Length) { //If we absorbed the start of an inline comment then turn it into text so the rest can be absorbed if (_chunks[_j].Type == ChunkType.Comment && _chunks[_j].Value.StartsWith("//")) { _chunks[_j].Type = ChunkType.Text; } } return new RegexMatchResult(match); } public void Advance(int length) { if (_i == _inputLength) //only for empty cases as there may not be any chunks return; // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. _i += length; var endIndex = _current + _chunks[_j].Value.Length; while (true) { if(_i == _inputLength) break; if (_i >= endIndex) { if (_j < _chunks.Count - 1) { _current = endIndex; endIndex += _chunks[++_j].Value.Length; continue; // allow skipping multiple chunks } else break; } if (!char.IsWhiteSpace(_input[_i])) break; _i++; } } // Same as Match, but don't change the state of the parser, // just return the match. public bool Peek(char tok) { if (_i == _inputLength) return false; return _input[_i] == tok; } public bool Peek(string tok) { var regex = GetRegex(tok, RegexOptions.None); var match = regex.Match(_input, _i); return match.Success; } public bool PeekAfterComments(char tok) { var memo = this.Location; while(GetComment() != null); var peekSuccess = Peek(tok); this.Location = memo; return peekSuccess; } private Regex GetRegex(string pattern, RegexOptions options) { if (!regexCache.ContainsKey(pattern)) regexCache.Add(pattern, new Regex(@"\G" + pattern, options)); return regexCache[pattern]; } public char GetPreviousCharIgnoringComments() { if (_i == 0) { return '\0'; } if (_i != _lastCommentEnd) { return PreviousChar; } int i = _lastCommentStart - 1; if (i < 0) { return '\0'; } return _input[i]; } public char PreviousChar { get { return _i == 0 ? '\0' : _input[_i - 1]; } } public char CurrentChar { get { return _i == _inputLength ? '\0' : _input[_i]; } } public char NextChar { get { return _i + 1 == _inputLength ? '\0' : _input[_i + 1]; } } public bool HasCompletedParsing() { return _i == _inputLength; } public Location Location { get { return new Location { Index = _i, CurrentChunk = _j, CurrentChunkIndex = _current }; } set { _i = value.Index; _j = value.CurrentChunk; _current = value.CurrentChunkIndex; } } public NodeLocation GetNodeLocation(int index) { return new NodeLocation(index, this._input, this._fileName); } public NodeLocation GetNodeLocation() { return GetNodeLocation(this.Location.Index); } private enum ChunkType { Text, Comment, QuotedString } private class Chunk { private StringBuilder _builder; public Chunk(string val) { Value = val; Type = ChunkType.Text; } public Chunk(string val, ChunkType type) { Value = val; Type = type; } public Chunk() { _builder = new StringBuilder(); Type = ChunkType.Text; } public ChunkType Type { get; set; } public string Value { get; set; } private bool _final; public void Append(string str) { _builder.Append(str); } public void Append(char c) { _builder.Append(c); } private static Chunk ReadyForText(List<Chunk> chunks) { Chunk last = chunks.LastOrDefault(); if (last == null || last.Type != ChunkType.Text || last._final == true) { last = new Chunk(); chunks.Add(last); } return last; } public static void Append(char c, List<Chunk> chunks, bool final) { Chunk chunk = ReadyForText(chunks); chunk.Append(c); chunk._final = final; } public static void Append(char c, List<Chunk> chunks) { Chunk chunk = ReadyForText(chunks); chunk.Append(c); } public static void Append(string s, List<Chunk> chunks) { Chunk chunk = ReadyForText(chunks); chunk.Append(s); } public static string CommitAll(List<Chunk> chunks) { StringBuilder all = new StringBuilder(); foreach(Chunk chunk in chunks) { if (chunk._builder != null) { string val = chunk._builder.ToString(); chunk._builder = null; chunk.Value = val; } all.Append(chunk.Value); } return all.ToString(); } } private string Remaining { get { return _input.Substring(_i); } } } public class Location { public int Index { get; set; } public int CurrentChunk { get; set; } public int CurrentChunkIndex { get; set; } } }
#region Using directives using System; using System.Xml; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Web.Services.Description; using System.Web.Services.Discovery; using System.Xml.Schema; using System.IO; using Commanigy.Iquomi.Data; using Commanigy.Iquomi.Api; #endregion namespace Commanigy.Iquomi.Services { /// <summary> /// Builds WSDL/DISCO file based on Service definition. /// </summary> public class ServiceLocatorHandler : System.Web.IHttpHandler { public ServiceLocatorHandler() { ; } public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { string output = ""; string path = context.Request.Path.Trim(); string serviceName = path.Substring(1, path.Length-".service".Length-1); if (serviceName != null && serviceName.Length > 0) { if (context.Request.QueryString.ToString().ToLower().StartsWith("wsdl")) { output = GetWsdl(serviceName); context.Response.ContentType = "text/xml"; } else if (context.Request.QueryString.ToString().ToLower().StartsWith("disco")) { output = GetDisco(serviceName); context.Response.ContentType = "text/xml"; } else { output = @" <html> <head> <link type='text/xml' rel='alternate' href='" + path + @"?disco'/> </head> <body> <h1>Iquomi Web Service Generator</h1> Service: <b>" + serviceName + @"</b> </body> </html> "; } } // [~] why is it using utf16? this can't be displayed by browsers! output = output.Replace("utf-16", "utf-8"); if (context.Request["debug"] != null) { context.Response.ContentType = "text/html"; context.Response.Write(@"<html><head><link type='text/xml' rel='alternate' href='" + serviceName + ".service?disco'/></HEAD><body>"); context.Response.Write("<h1>Iquomi Dynamic WSDL Generator</h1>"); context.Response.Write("Requesting service: <b>" + serviceName + "</b>"); context.Response.Write("<pre style='font-size: 11px; background-color: #f3fff3; border: 1px solid #c3ffc3'>"); context.Response.Write(HttpUtility.HtmlEncode(output)); context.Response.Write("</pre>"); } else { context.Response.Write(output); } } protected DbService LookupService(string serviceName) { DbService service = new DbService(); service.Name = serviceName; return (DbService)service.DbFindByName(); } public void handler(object o, System.Xml.Schema.ValidationEventArgs args) { throw new Exception("uha, en fejl ved parsing af xsd"); } public string GetDisco(string serviceName) { DiscoveryDocument dd = new DiscoveryDocument(); // Get a ContractReference. ContractReference myContractReference = new ContractReference(); // Set the URL to the referenced service description. myContractReference.Ref = "http://services.iquomi.com/" + serviceName + ".service?wsdl"; // Set the URL for an XML Web service implementing the service // description. myContractReference.DocRef = "http://services.iquomi.com/" + serviceName + ".service"; System.Web.Services.Discovery.SoapBinding myBinding = new System.Web.Services.Discovery.SoapBinding(); myBinding.Binding = new XmlQualifiedName(serviceName + "Soap", "http://tempuri.org/"); myBinding.Address = "http://services.iquomi.com/" + serviceName + ".service"; // Add myContractReference to the list of references contained // in the discovery document. dd.References.Add(myContractReference); // Add Binding to the references collection. dd.References.Add(myBinding); System.IO.StringWriter writer = new System.IO.StringWriter(); dd.Write(writer); writer.Flush(); return writer.GetStringBuilder().ToString(); } public string GetWsdl(string serviceName) { DbService service = LookupService(serviceName); if (service == null || service.Xsd == null) { return "No xsd found"; } ServiceDescription sd = new ServiceDescription(); sd.TargetNamespace = "http://schemas.iquomi.com/2004/01/" + serviceName; string realPath = HttpContext.Current.Server.MapPath("~/2004/01/core/iqcommon.xsd"); System.IO.StreamReader sr = new System.IO.StreamReader(realPath, System.Text.Encoding.UTF8); XmlSchema core = System.Xml.Schema.XmlSchema.Read(sr ,null); core.Compile(null); //sd.Types.Schemas.Add(core); System.Xml.Schema.XmlSchema x = service.GetXmlSchema(); x.TargetNamespace = sd.TargetNamespace; System.Xml.Schema.XmlSchemaElement xso = new System.Xml.Schema.XmlSchemaElement(); xso.Name = "Create"; System.Xml.Schema.XmlSchemaComplexType xsoct = new System.Xml.Schema.XmlSchemaComplexType(); xso.SchemaType = xsoct; x.Items.Add(xso); sd.Types.Schemas.Add(x); Message m = new Message(); m.Name = "InsertRequest"; MessagePart mp = new MessagePart(); mp.Name = "parameters"; mp.Element = new XmlQualifiedName("Insert", sd.TargetNamespace); m.Parts.Add(mp); sd.Messages.Add(m); m = new Message(); m.Name = "InsertResponse"; mp = new MessagePart(); mp.Name = "parameters"; mp.Element = new XmlQualifiedName("Insert", sd.TargetNamespace); m.Parts.Add(mp); sd.Messages.Add(m); System.Web.Services.Description.PortType pt = new PortType(); pt.Name = serviceName + "Soap"; System.Web.Services.Description.Operation o = CreateOperation( "Insert", "InsertRequest", "InsertResponse", sd.TargetNamespace ); pt.Operations.Add(o); sd.PortTypes.Add(pt); Binding b = new Binding(); b.Name = serviceName + "Soap"; b.Type = new System.Xml.XmlQualifiedName(pt.Name, sd.TargetNamespace); System.Web.Services.Description.SoapBinding mySoapBinding = new System.Web.Services.Description.SoapBinding(); mySoapBinding.Transport = "http://schemas.xmlsoap.org/soap/http"; mySoapBinding.Style = SoapBindingStyle.Document; b.Extensions.Add(mySoapBinding); OperationBinding ob = new OperationBinding(); ob.Name = "Insert"; SoapOperationBinding soapo = new SoapOperationBinding(); soapo.SoapAction = "http://services.iquomi.com/Insert"; soapo.Style = SoapBindingStyle.Document; ob.Extensions.Add(soapo); SoapBodyBinding soapb = new SoapBodyBinding(); soapb.Use = SoapBindingUse.Literal; InputBinding ib = new InputBinding(); ib.Extensions.Add(soapb); ob.Input = ib; OutputBinding outb = new OutputBinding(); outb.Extensions.Add(soapb); ob.Output = outb; b.Operations.Add(ob); sd.Bindings.Add(b); System.Web.Services.Description.Service s = new System.Web.Services.Description.Service(); s.Name = serviceName; Port p = new Port(); p.Name = serviceName + "Soap"; p.Binding = b.Type; SoapAddressBinding soapab = new SoapAddressBinding(); soapab.Location = "http://services.iquomi.com/Service.asmx"; p.Extensions.Add(soapab); s.Ports.Add(p); sd.Services.Add(s); System.IO.StringWriter writer = new System.IO.StringWriter(); sd.Write(writer); writer.Flush(); return writer.GetStringBuilder().ToString(); } public static Operation CreateOperation(string operationName, string inputMessage, string outputMessage, string targetNamespace) { Operation myOperation = new Operation(); myOperation.Name = operationName; OperationMessage input = (OperationMessage) new OperationInput(); input.Message = new XmlQualifiedName(inputMessage, targetNamespace); OperationMessage output = (OperationMessage) new OperationOutput(); output.Message = new XmlQualifiedName(outputMessage, targetNamespace); myOperation.Messages.Add(input); myOperation.Messages.Add(output); return myOperation; } } }
using System; using System.Reflection; using System.Globalization; using System.Resources; using System.Text; using System.ComponentModel; using System.Workflow.Activities; using System.Drawing; using System.Workflow.ComponentModel.Design; [AttributeUsage(AttributeTargets.All)] internal sealed class SRDescriptionAttribute : DescriptionAttribute { public SRDescriptionAttribute(string description) { DescriptionValue = SR.GetString(description); } public SRDescriptionAttribute(string description, string resourceSet) { ResourceManager rm = new ResourceManager(resourceSet, Assembly.GetExecutingAssembly()); DescriptionValue = rm.GetString(description); System.Diagnostics.Debug.Assert(DescriptionValue != null, string.Format(CultureInfo.CurrentCulture, "String resource {0} not found.", description)); } } [AttributeUsage(AttributeTargets.All)] internal sealed class SRCategoryAttribute : CategoryAttribute { private string resourceSet = String.Empty; public SRCategoryAttribute(string category) : base(category) { } public SRCategoryAttribute(string category, string resourceSet) : base(category) { this.resourceSet = resourceSet; } protected override string GetLocalizedString(string value) { if (this.resourceSet.Length > 0) { ResourceManager rm = new ResourceManager(resourceSet, Assembly.GetExecutingAssembly()); String localizedString = rm.GetString(value); System.Diagnostics.Debug.Assert(localizedString != null, string.Format(CultureInfo.CurrentCulture, "String resource {0} not found.", value)); return localizedString; } else { return SR.GetString(value); } } } [AttributeUsage(AttributeTargets.All)] internal sealed class SRDisplayNameAttribute : DisplayNameAttribute { public SRDisplayNameAttribute(string name) { DisplayNameValue = SR.GetString(name); } public SRDisplayNameAttribute(string name, string resourceSet) { ResourceManager rm = new ResourceManager(resourceSet, Assembly.GetExecutingAssembly()); DisplayNameValue = rm.GetString(name); System.Diagnostics.Debug.Assert(DisplayNameValue != null, string.Format(CultureInfo.CurrentCulture, "String resource {0} not found.", name)); } } /// <summary> /// AutoGenerated resource class. Usage: /// /// string s = SR.GetString(SR.MyIdenfitier); /// </summary> internal sealed class SR { static SR loader = null; ResourceManager resources; internal SR() { resources = new System.Resources.ResourceManager("System.Workflow.Activities.StringResources", Assembly.GetExecutingAssembly()); } private static SR GetLoader() { if (loader == null) loader = new SR(); return loader; } private static CultureInfo Culture { get { return null/*use ResourceManager default, CultureInfo.CurrentUICulture*/; } } internal static string GetString(string name, params object[] args) { return GetString(SR.Culture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { SR sys = GetLoader(); if (sys == null) return null; string res = sys.resources.GetString(name, culture); System.Diagnostics.Debug.Assert(res != null, string.Format(CultureInfo.CurrentCulture, "String resource {0} not found.", name)); if (args != null && args.Length > 0) { return String.Format(CultureInfo.CurrentCulture, res, args); } else { return res; } } internal static string GetString(string name) { return GetString(SR.Culture, name); } internal static string GetString(CultureInfo culture, string name) { SR sys = GetLoader(); if (sys == null) return null; string res = sys.resources.GetString(name, culture); System.Diagnostics.Debug.Assert(res != null, string.Format(CultureInfo.CurrentCulture, "String resource {0} not found.", name)); return res; } // All these strings should be present in StringResources.resx internal const string Activity = "Activity"; internal const string Handlers = "Handlers"; internal const string Conditions = "Conditions"; internal const string ConditionedActivityConditions = "ConditionedActivityConditions"; internal const string CorrelationSet = "CorrelationSet"; internal const string NameDescr = "NameDescr"; internal const string UserCodeHandlerDescr = "UserCodeHandlerDescr"; internal const string ExpressionDescr = "ExpressionDescr"; internal const string ExecutionTypeDescr = "ExecutionTypeDescr"; internal const string InitialChildDataDescr = "InitialChildDataDescr"; internal const string ConditionDescr = "ConditionDescr"; internal const string UntilConditionDescr = "UntilConditionDescr"; internal const string WhenConditionDescr = "WhenConditionDescr"; internal const string TargetWorkflowDescr = "TargetWorkflowDescr"; internal const string InitializeCaleeDescr = "InitializeCaleeDescr"; internal const string ProxyClassDescr = "ProxyClassDescr"; internal const string MethodNameDescr = "MethodNameDescr"; internal const string URLDescr = "URLDescr"; internal const string ActivationDescr = "ActivationDescr"; internal const string OnAfterMethodInvokeDescr = "OnAfterMethodInvokeDescr"; internal const string OnBeforeMethodInvokeDescr = "OnBeforeMethodInvokeDescr"; internal const string TypeDescr = "TypeDescr"; internal const string WhileConditionDescr = "WhileConditionDescr"; internal const string ReplicatorUntilConditionDescr = "ReplicatorUntilConditionDescr"; internal const string DynamicUpdateConditionDescr = "DynamicUpdateConditionDescr"; internal const string CorrelationSetDescr = "CorrelationSetDescr"; internal const string RoleDescr = "RoleDescr"; internal const string ChangingVariable = "ChangingVariable"; internal const string OnInitializedDescr = "OnInitializedDescr"; internal const string OnCompletedDescr = "OnCompletedDescr"; internal const string Type = "Type"; internal const string InterfaceTypeDescription = "InterfaceTypeDescription"; internal const string InterfaceTypeFilterDescription = "InterfaceTypeFilterDescription"; internal const string WebServiceMethodDescription = "WebServiceMethodDescription"; internal const string ReceiveActivityNameDescription = "ReceiveActivityNameDescription"; internal const string WebServiceSessionIDDescr = "WebServiceSessionIDDescr"; internal const string OnAfterReceiveDescr = "OnAfterReceiveDescr"; internal const string OnBeforeResponseDescr = "OnBeforeResponseDescr"; internal const string OnBeforeFaultingDescr = "OnBeforeFaultingDescr"; internal const string TimeoutDurationDescription = "TimeoutDurationDescription"; internal const string TimeoutInitializerDescription = "TimeoutInitializerDescription"; internal const string StateMachineWorkflow = "StateMachineWorkflow"; internal const string SequentialWorkflow = "SequentialWorkflow"; internal const string EventSink = "EventSink"; internal const string RuleSetDescription = "RuleSetDescription"; internal const string RuleSetDefinitionDescription = "RuleSetDefinitionDescription"; internal const string ConnectorColorDescription = "ConnectorColorDescription"; internal const string InitialStateImagePathDescription = "InitialStateImagePathDescription"; internal const string CompletedStateImagePathDescription = "CompletedStateImagePathDescription"; internal const string Error_ConditionalBranchParentNotConditional = "Error_ConditionalBranchParentNotConditional"; internal const string Error_EventDrivenMultipleEventActivity = "Error_EventDrivenMultipleEventActivity"; internal const string Error_ParameterPropertyNotSet = "Error_ParameterPropertyNotSet"; internal const string Error_ListenNotAllEventDriven = "Error_ListenNotAllEventDriven"; internal const string Error_InterfaceTypeNotInterface = "Error_InterfaceTypeNotInterface"; internal const string Error_ParallelLessThanTwoChildren = "Error_ParallelLessThanTwoChildren"; internal const string Error_PropertyNotSet = "Error_PropertyNotSet"; internal const string Error_MissingCorrelationParameterAttribute = "Error_MissingCorrelationParameterAttribute"; internal const string Error_MissingCorrelationTokenProperty = "Error_MissingCorrelationTokenProperty"; internal const string Error_CorrelationTypeNotConsistent = "Error_CorrelationTypeNotConsistent"; internal const string Error_CorrelationInvalid = "Error_CorrelationInvalid"; internal const string Error_MissingMethodName = "Error_MissingMethodName"; internal const string Error_MissingEventName = "Error_MissingEventName"; internal const string Error_ListenLessThanTwoChildren = "Error_ListenLessThanTwoChildren"; internal const string Error_MethodNotExists = "Error_MethodNotExists"; internal const string General_MissingService = "General_MissingService"; internal const string Error_FieldNotExists = "Error_FieldNotExists"; internal const string Error_TypeNotResolved = "Error_TypeNotResolved"; internal const string Error_ParameterNotFound = "Error_ParameterNotFound"; internal const string Error_TypeNotExist = "Error_TypeNotExist"; internal const string Error_ParallelNotAllSequence = "Error_ParallelNotAllSequence"; internal const string Error_ActivationActivityNotFirst = "Error_ActivationActivityNotFirst"; internal const string Error_ActivationActivityInsideLoop = "Error_ActivationActivityInsideLoop"; internal const string Error_DuplicateCorrelation = "Error_DuplicateCorrelation"; internal const string Error_NegativeValue = "Error_NegativeValue"; internal const string Error_MustHaveParent = "Error_MustHaveParent"; internal const string Error_CanNotChangeAtRuntime = "Error_CanNotChangeAtRuntime"; internal const string Error_CannotNestThisActivity = "Error_CannotNestThisActivity"; internal const string Error_GetCalleeWorkflow = "Error_GetCalleeWorkflow"; internal const string Error_TypeIsNotRootActivity = "Error_TypeIsNotRootActivity"; internal const string Error_ContextStackItemMissing = "Error_ContextStackItemMissing"; internal const string Error_UnexpectedArgumentType = "Error_UnexpectedArgumentType"; internal const string OnGeneratorChildCompletedDescr = "OnGeneratorChildCompletedDescr"; internal const string OnGeneratorChildInitializedDescr = "OnGeneratorChildInitializedDescr"; internal const string Error_WebServiceResponseNotFound = "Error_WebServiceResponseNotFound"; internal const string Error_WebServiceReceiveNotFound = "Error_WebServiceReceiveNotFound"; internal const string Error_WebServiceResponseNotNeeded = "Error_WebServiceResponseNotNeeded"; internal const string Error_WebServiceFaultNotNeeded = "Error_WebServiceFaultNotNeeded"; internal const string Error_WebServiceReceiveNotConfigured = "Error_WebServiceReceiveNotConfigured"; internal const string Error_WebServiceReceiveNotMarkedActivate = "Error_WebServiceReceiveNotMarkedActivate"; internal const string Error_DuplicateWebServiceResponseFound = "Error_DuplicateWebServiceResponseFound"; internal const string Error_DuplicateWebServiceFaultFound = "Error_DuplicateWebServiceFaultFound"; internal const string Error_CAGChildNotFound = "Error_CAGChildNotFound"; internal const string Error_CAGNotExecuting = "Error_CAGNotExecuting"; internal const string Error_CAGQuiet = "Error_CAGQuiet"; internal const string Error_CAGDynamicUpdateNotAllowed = "Error_CAGDynamicUpdateNotAllowed"; internal const string Error_MissingValidationProperty = "Error_MissingValidationProperty"; internal const string Error_MissingConditionName = "Error_MissingConditionName"; internal const string Error_MissingRuleConditions = "Error_MissingRuleConditions"; internal const string Error_RoleProviderNotAvailableOrEnabled = "Error_RoleProviderNotAvailableOrEnabled"; internal const string Error_ExternalDataExchangeServiceExists = "Error_ExternalDataExchangeServiceExists"; internal const string Error_WorkflowTerminated = "Error_WorkflowTerminated"; internal const string Error_WorkflowCompleted = "Error_WorkflowCompleted"; internal const string Warning_AdditionalBindingsFound = "Warning_AdditionalBindingsFound"; internal const string Error_ConfigurationSectionNotFound = "Error_ConfigurationSectionNotFound"; internal const string Error_UnknownConfigurationParameter = "Error_UnknownConfigurationParameter"; internal const string Error_CannotConnectToRequest = "Error_CannotConnectToRequest"; // state machine errors internal const string Error_StateChildNotFound = "Error_StateChildNotFound"; private const string Error_InvalidStateActivityParent = "Error_InvalidStateActivityParent"; internal static string GetError_InvalidStateActivityParent() { return GetString(Error_InvalidStateActivityParent, typeof(StateActivity).Name); } private const string Error_BlackBoxCustomStateNotSupported = "Error_BlackBoxCustomStateNotSupported"; internal static string GetError_BlackBoxCustomStateNotSupported() { return GetString(Error_BlackBoxCustomStateNotSupported, typeof(StateActivity).Name); } private const string Error_InvalidLeafStateChild = "Error_InvalidLeafStateChild"; internal static string GetError_InvalidLeafStateChild() { return GetString(Error_InvalidLeafStateChild, typeof(StateActivity).Name, typeof(EventDrivenActivity).Name, typeof(StateInitializationActivity).Name, typeof(StateFinalizationActivity).Name); } private const string Error_InvalidCompositeStateChild = "Error_InvalidCompositeStateChild"; internal static string GetError_InvalidCompositeStateChild() { return GetString(Error_InvalidCompositeStateChild, typeof(StateMachineWorkflowActivity).Name, typeof(StateActivity).Name, typeof(EventDrivenActivity).Name); } private const string Error_SetStateOnlyWorksOnStateMachineWorkflow = "Error_SetStateOnlyWorksOnStateMachineWorkflow"; internal static string GetError_SetStateOnlyWorksOnStateMachineWorkflow() { return GetString(Error_SetStateOnlyWorksOnStateMachineWorkflow, typeof(SetStateActivity).Name, typeof(EventDrivenActivity).Name, typeof(StateInitializationActivity).Name, typeof(StateMachineWorkflowActivity).Name, typeof(StateActivity).Name); } private const string Error_SetStateMustPointToAState = "Error_SetStateMustPointToAState"; internal static string GetError_SetStateMustPointToAState() { return GetString(Error_SetStateMustPointToAState, SetStateActivity.TargetStateNameProperty, typeof(StateActivity).Name); } private const string Error_StateActivityMustBeContainedInAStateMachine = "Error_StateActivityMustBeContainedInAStateMachine"; internal static string GetError_StateActivityMustBeContainedInAStateMachine() { return GetString(Error_StateActivityMustBeContainedInAStateMachine, typeof(StateActivity).Name, typeof(StateMachineWorkflowActivity).Name, StateMachineWorkflowActivity.InitialStateNamePropertyName); } private const string Error_CannotExecuteStateMachineWithoutInitialState = "Error_CannotExecuteStateMachineWithoutInitialState"; internal static string GetError_CannotExecuteStateMachineWithoutInitialState() { return GetString(Error_CannotExecuteStateMachineWithoutInitialState, typeof(StateMachineWorkflowActivity).Name, StateMachineWorkflowActivity.InitialStateNamePropertyName); } internal static string GetError_InitialStateMustPointToAState() { return GetString(Error_SetStateMustPointToAState, StateMachineWorkflowActivity.InitialStateNamePropertyName, typeof(StateActivity).Name); } internal static string GetError_CompletedStateMustPointToAState() { return GetString(Error_SetStateMustPointToAState, StateMachineWorkflowActivity.CompletedStateNamePropertyName, typeof(StateActivity).Name); } private const string Error_SetStateMustPointToALeafNodeState = "Error_SetStateMustPointToALeafNodeState"; internal static string GetError_SetStateMustPointToALeafNodeState() { return GetString(Error_SetStateMustPointToALeafNodeState, SetStateActivity.TargetStateNameProperty, typeof(StateActivity).Name); } internal static string GetError_InitialStateMustPointToALeafNodeState() { return GetString(Error_SetStateMustPointToALeafNodeState, StateMachineWorkflowActivity.InitialStateNameProperty, typeof(StateActivity).Name); } internal static string GetError_CompletedStateMustPointToALeafNodeState() { return GetString(Error_SetStateMustPointToALeafNodeState, StateMachineWorkflowActivity.CompletedStateNamePropertyName, typeof(StateActivity).Name); } private const string Error_InitialStateMustBeDifferentThanCompletedState = "Error_InitialStateMustBeDifferentThanCompletedState"; internal static string GetError_InitialStateMustBeDifferentThanCompletedState() { return GetString(Error_InitialStateMustBeDifferentThanCompletedState, StateMachineWorkflowActivity.InitialStateNameProperty, StateMachineWorkflowActivity.CompletedStateNameProperty); } internal const string Error_CompletedStateCannotContainActivities = "Error_CompletedStateCannotContainActivities"; private const string Error_StateHandlerParentNotState = "Error_StateHandlerParentNotState"; internal static string GetError_StateInitializationParentNotState() { return GetString(Error_StateHandlerParentNotState, typeof(StateInitializationActivity).Name, typeof(StateActivity).Name); } internal static string GetError_StateFinalizationParentNotState() { return GetString(Error_StateHandlerParentNotState, typeof(StateFinalizationActivity).Name, typeof(StateActivity).Name); } private const string Error_EventActivityNotValidInStateHandler = "Error_EventActivityNotValidInStateHandler"; internal static string GetError_EventActivityNotValidInStateInitialization() { return GetString(Error_EventActivityNotValidInStateHandler, typeof(StateInitializationActivity).Name, typeof(IEventActivity).FullName); } internal static string GetError_EventActivityNotValidInStateFinalization() { return GetString(Error_EventActivityNotValidInStateHandler, typeof(StateFinalizationActivity).Name, typeof(IEventActivity).FullName); } private const string Error_MultipleStateHandlerActivities = "Error_MultipleStateHandlerActivities"; internal static string GetError_MultipleStateInitializationActivities() { return GetString(Error_MultipleStateHandlerActivities, typeof(StateInitializationActivity).Name, typeof(StateActivity).Name); } internal static string GetError_MultipleStateFinalizationActivities() { return GetString(Error_MultipleStateHandlerActivities, typeof(StateFinalizationActivity).Name, typeof(StateActivity).Name); } private const string Error_InvalidTargetStateInStateInitialization = "Error_InvalidTargetStateInStateInitialization"; internal static string GetError_InvalidTargetStateInStateInitialization() { return GetString(Error_InvalidTargetStateInStateInitialization, typeof(SetStateActivity).Name, SetStateActivity.TargetStateNamePropertyName, typeof(StateActivity).Name, typeof(StateInitializationActivity).Name); } private const string Error_CantRemoveState = "Error_CantRemoveState"; internal static string GetError_CantRemoveState(string stateName) { return GetString(Error_CantRemoveState, typeof(StateActivity).Name, stateName); } private const string Error_CantRemoveEventDrivenFromExecutingState = "Error_CantRemoveEventDrivenFromExecutingState"; internal static string GetError_CantRemoveEventDrivenFromExecutingState(string eventDrivenName, string parentStateName) { return GetString(Error_CantRemoveEventDrivenFromExecutingState, typeof(EventDrivenActivity).Name, eventDrivenName, typeof(StateActivity).Name, parentStateName); } private const string SqlTrackingServiceRequired = "SqlTrackingServiceRequired"; internal static string GetSqlTrackingServiceRequired() { return GetString(SqlTrackingServiceRequired, StateMachineWorkflowInstance.StateHistoryPropertyName, typeof(System.Workflow.Runtime.Tracking.SqlTrackingService).FullName); } private const string StateMachineWorkflowMustHaveACurrentState = "StateMachineWorkflowMustHaveACurrentState"; internal static string GetStateMachineWorkflowMustHaveACurrentState() { return GetString(StateMachineWorkflowMustHaveACurrentState, typeof(StateMachineWorkflowActivity).Name); } private const string InvalidActivityStatus = "InvalidActivityStatus"; internal static string GetInvalidActivityStatus(System.Workflow.ComponentModel.Activity activity) { return GetString(InvalidActivityStatus, activity.ExecutionStatus, activity.QualifiedName); } internal const string StateMachineWorkflowRequired = "StateMachineWorkflowRequired"; internal static string GetStateMachineWorkflowRequired() { return GetString(StateMachineWorkflowRequired, typeof(StateMachineWorkflowInstance).Name, typeof(StateMachineWorkflowActivity).Name); } private const string InvalidUserDataInStateChangeTrackingRecord = "InvalidUserDataInStateChangeTrackingRecord"; internal static string GetInvalidUserDataInStateChangeTrackingRecord() { return GetString(InvalidUserDataInStateChangeTrackingRecord, StateActivity.StateChangeTrackingDataKey, typeof(StateActivity).Name); } private const string UnableToTransitionToState = "UnableToTransitionToState"; internal static string GetUnableToTransitionToState(string stateName) { return GetString(UnableToTransitionToState, stateName); } private const string InvalidStateTransitionPath = "InvalidStateTransitionPath"; internal static string GetInvalidStateTransitionPath() { return GetString(InvalidStateTransitionPath); } private const string InvalidSetStateInStateInitialization = "InvalidSetStateInStateInitialization"; internal static string GetInvalidSetStateInStateInitialization() { return GetString(InvalidSetStateInStateInitialization, typeof(SetStateActivity).Name, typeof(StateInitializationActivity).Name); } private const string StateAlreadySubscribesToThisEvent = "StateAlreadySubscribesToThisEvent"; internal static string GetStateAlreadySubscribesToThisEvent(string stateName, IComparable queueName) { return GetString(StateAlreadySubscribesToThisEvent, typeof(StateActivity).Name, stateName, queueName); } private const string InvalidStateMachineAction = "InvalidStateMachineAction"; internal static string GetInvalidStateMachineAction(string stateName) { return GetString(InvalidStateMachineAction, typeof(StateActivity).Name, typeof(StateMachineAction).Name, stateName); } private const string Error_StateMachineWorkflowMustBeARootActivity = "Error_StateMachineWorkflowMustBeARootActivity"; internal static string GetError_StateMachineWorkflowMustBeARootActivity() { return GetString(Error_StateMachineWorkflowMustBeARootActivity, typeof(StateMachineWorkflowActivity).Name); } internal const string EventHandlingScopeActivityDescription = "EventHandlingScopeActivityDescription"; internal const string EventDrivenActivityDescription = "EventDrivenActivityDescription"; internal const string Error_EventActivityIsImmutable = "Error_EventActivityIsImmutable"; private const string Error_EventDrivenParentNotListen = "Error_EventDrivenParentNotListen"; internal static string GetError_EventDrivenParentNotListen() { return GetString(Error_EventDrivenParentNotListen, typeof(EventDrivenActivity).Name, typeof(ListenActivity).Name, typeof(EventHandlersActivity).Name, typeof(StateActivity).Name, typeof(StateMachineWorkflowActivity).Name); } internal const string Error_EventDrivenNoFirstActivity = "Error_EventDrivenNoFirstActivity"; private const string Error_EventDrivenInvalidFirstActivity = "Error_EventDrivenInvalidFirstActivity"; internal static string GetError_EventDrivenInvalidFirstActivity() { return GetString(Error_EventDrivenInvalidFirstActivity, typeof(EventDrivenActivity).Name, typeof(IEventActivity).FullName, typeof(HandleExternalEventActivity).Name, typeof(DelayActivity).Name); } private const string UndoSetAsInitialState = "UndoSetAsInitialState"; internal static string GetUndoSetAsInitialState(string stateName) { return GetString(UndoSetAsInitialState, stateName); } private const string UndoSetAsCompletedState = "UndoSetAsCompletedState"; internal static string GetUndoSetAsCompletedState(string stateName) { return GetString(UndoSetAsCompletedState, stateName); } internal const string UndoSwitchViews = "UndoSwitchViews"; private const string MoveSetState = "MoveSetState"; internal static string GetMoveSetState() { return GetString(MoveSetState, typeof(SetStateActivity).Name); } internal const string Error_EventHandlersDeclParentNotScope = "Error_EventHandlersDeclParentNotScope"; internal const string Error_EventHandlersChildNotFound = "Error_EventHandlersChildNotFound"; internal const string Error_FailedToStartTheWorkflow = "Error_FailedToStartTheWorkflow"; // workflow load errors // serializer errrors internal const string In = "In"; internal const string Out = "Out"; internal const string Ref = "Ref"; internal const string Required = "Required"; internal const string Optional = "Optional"; internal const string Parameters = "Parameters"; internal const string Properties = "Properties"; internal const string Error_UninitializedCorrelation = "Error_UninitializedCorrelation"; internal const string Error_InvalidIdentifier = "Error_InvalidIdentifier"; internal const string Error_MoreThanOneEventHandlersDecl = "Error_MoreThanOneEventHandlersDecl"; internal const string Error_MoreThanTwoActivitiesInEventHandlingScope = "Error_MoreThanTwoActivitiesInEventHandlingScope"; //Collection Editor Resources internal const string Error_ExecInAtomicScope = "Error_ExecInAtomicScope"; internal const string Error_ExecWithActivationReceive = "Error_ExecWithActivationReceive"; internal const string Error_DuplicateParameter = "Error_DuplicateParameter"; internal const string Error_GeneratorShouldContainSingleActivity = "Error_GeneratorShouldContainSingleActivity"; // Dynamic Validations internal const string Error_DynamicActivity = "Error_DynamicActivity"; internal const string Error_DynamicActivity2 = "Error_DynamicActivity2"; internal const string Error_DynamicActivity3 = "Error_DynamicActivity3"; //type filtering internal const string FilterDescription_InvokeWorkflow = "FilterDescription_InvokeWorkflow"; // Activity Category internal const string Standard = "Standard"; internal const string Base = "Base"; // Themes Category internal const string ForegroundCategory = "ForegroundCategory"; // Project options dialog //Activity Toolbox Description internal const string WebServiceResponseActivityDescription = "WebServiceResponseActivityDescription"; internal const string WebServiceFaultActivityDescription = "WebServiceFaultActivityDescription"; internal const string WebServiceReceiveActivityDescription = "WebServiceReceiveActivityDescription"; internal const string SequenceActivityDescription = "SequenceActivityDescription"; internal const string CompensatableSequenceActivityDescription = "CompensatableSequenceActivityDescription"; internal const string WhileActivityDescription = "WhileActivityDescription"; internal const string ReplicatorActivityDescription = "ReplicatorActivityDescription"; internal const string ScopeActivityDescription = "ScopeActivityDescription"; internal const string ParallelActivityDescription = "ParallelActivityDescription"; internal const string ListenActivityDescription = "ListenActivityDescription"; internal const string DelayActivityDescription = "DelayActivityDescription"; internal const string ConstrainedGroupActivityDescription = "ConstrainedGroupActivityDescription"; internal const string ConditionalActivityDescription = "ConditionalActivityDescription"; internal const string InvokeWorkflowActivityDescription = "InvokeWorkflowActivityDescription"; internal const string InvokeWebServiceActivityDescription = "InvokeWebServiceActivityDescription"; internal const string CodeActivityDescription = "CodeActivityDescription"; internal const string SetStateActivityDescription = "SetStateActivityDescription"; internal const string StateInitializationActivityDescription = "StateInitializationActivityDescription"; internal const string StateFinalizationActivityDescription = "StateFinalizationActivityDescription"; internal const string StateActivityDescription = "StateActivityDescription"; internal const string StateMachineWorkflowActivityDescription = "StateMachineWorkflowActivityDescription"; internal const string PolicyActivityDescription = "PolicyActivityDescription"; internal const string Error_WhileShouldHaveOneChild = "Error_WhileShouldHaveOneChild"; internal const string Error_ReplicatorNotExecuting = "Error_ReplicatorNotExecuting"; internal const string Error_ReplicatorChildRunning = "Error_ReplicatorChildRunning"; internal const string Error_ReplicatorNotInitialized = "Error_ReplicatorNotInitialized"; internal const string Error_ReplicatorDisconnected = "Error_ReplicatorDisconnected"; internal const string Error_InsufficientArrayPassedIn = "Error_InsufficientArrayPassedIn"; internal const string Error_MultiDimensionalArray = "Error_MultiDimensionalArray"; internal const string Error_WebServiceReceiveNotValid = "Error_WebServiceReceiveNotValid"; internal const string Error_CantInvokeSelf = "Error_CantInvokeSelf"; internal const string Error_TypeNotPublicSerializable = "Error_TypeNotPublicSerializable"; internal const string Error_CantInvokeDesignTimeTypes = "Error_CantInvokeDesignTimeTypes"; internal const string Error_TypeNotPublic = "Error_TypeNotPublic"; internal const string Error_NestedConstrainedGroupConditions = "Error_NestedConstrainedGroupConditions"; internal const string Error_ServiceMissingExternalDataExchangeInterface = "Error_ServiceMissingExternalDataExchangeInterface"; internal const string Error_CorrelationTokenInReplicator = "Error_CorrelationTokenInReplicator"; internal const string HelperExternalDataExchangeDesc = "HelperExternalDataExchangeDesc"; internal const string Error_TypePropertyInvalid = "Error_TypePropertyInvalid"; internal const string Error_ParameterTypeNotFound = "Error_ParameterTypeNotFound"; internal const string Error_ReturnTypeNotFound = "Error_ReturnTypeNotFound"; internal const string TargetStateDescription = "TargetStateDescription"; internal const string InitialStateDescription = "InitialStateDescription"; internal const string CompletedStateDescription = "CompletedStateDescription"; internal const string Error_CorrelationTokenMissing = "Error_CorrelationTokenMissing"; internal const string Error_CorrelationNotInitialized = "Error_CorrelationNotInitialized"; internal const string Error_EventDeliveryFailedException = "Error_EventDeliveryFailedException"; internal const string Error_EventArgumentSerializationException = "Error_EventArgumentSerializationException"; internal const string Error_ExternalDataExchangeException = "Error_ExternalDataExchangeException"; internal const string Error_EventNameMissing = "Error_EventNameMissing"; internal const string Error_CorrelationParameterException = "Error_CorrelationParameterException"; internal const string Error_NoInstanceInSession = "Error_NoInstanceInSession"; internal const string Error_ServiceNotFound = "Error_ServiceNotFound"; internal const string Error_MissingInterfaceType = "Error_MissingInterfaceType"; internal const string Error_CorrelationAttributeInvalid = "Error_CorrelationAttributeInvalid"; internal const string Error_DuplicateCorrelationAttribute = "Error_DuplicateCorrelationAttribute"; internal const string Error_CorrelationParameterNotFound = "Error_CorrelationParameterNotFound"; internal const string Error_CorrelationInitializerNotDefinied = "Error_CorrelationInitializerNotDefinied"; internal const string Error_InvalidMethodPropertyName = "Error_InvalidMethodPropertyName"; internal const string Error_InvalidEventPropertyName = "Error_InvalidEventPropertyName"; internal const string Error_CorrelationTokenSpecifiedForUncorrelatedInterface = "Error_CorrelationTokenSpecifiedForUncorrelatedInterface"; internal const string Error_MissingCorrelationTokenOwnerNameProperty = "Error_MissingCorrelationTokenOwnerNameProperty"; internal const string Error_OwnerActivityIsNotParent = "Error_OwnerActivityIsNotParent"; internal const string Error_InvalidEventArgsSignature = "Error_InvalidEventArgsSignature"; internal const string Error_NoMatchingActiveDirectoryEntry = "Error_NoMatchingActiveDirectoryEntry"; internal const string WorkflowAuthorizationException = "WorkflowAuthorizationException"; internal const string Error_InvalidEventMessage = "Error_InvalidEventMessage"; internal const string Error_ExternalRuntimeContainerNotFound = "Error_ExternalRuntimeContainerNotFound"; internal const string ExternalMethodNameDescr = "ExternalMethodNameDescr"; internal const string ExternalEventNameDescr = "ExternalEventNameDescr"; internal const string Error_MisMatchCorrelationTokenOwnerNameProperty = "Error_MisMatchCorrelationTokenOwnerNameProperty"; internal const string Error_WebServiceInputNotProcessed = "Error_WebServiceInputNotProcessed"; internal const string Error_CallExternalMethodArgsSerializationException = "Error_CallExternalMethodArgsSerializationException"; internal const string InvokeParameterDescription = "InvokeParameterDescription"; internal const string Error_ParameterTypeResolution = "Error_ParameterTypeResolution"; internal const string ParameterDescription = "ParameterDescription"; internal const string Error_DuplicatedActivityID = "Error_DuplicatedActivityID"; internal const string Error_InvalidLanguageIdentifier = "Error_InvalidLanguageIdentifier"; internal const string Error_ConditionalDeclNotAllConditionalBranchDecl = "Error_ConditionalDeclNotAllConditionalBranchDecl"; internal const string Error_ConditionalLessThanOneChildren = "Error_ConditionalLessThanOneChildren"; internal const string Error_ConditionalBranchUpdateAtRuntime = "Error_ConditionalBranchUpdateAtRuntime"; internal const string Error_ReplicatorInvalidExecutionType = "Error_ReplicatorInvalidExecutionType"; internal const string Error_ReplicatorCannotCancelChild = "Error_ReplicatorCannotCancelChild"; internal const string Error_InvalidCAGActivityType = "Error_InvalidCAGActivityType"; internal const string Error_CorrelationViolationException = "Error_CorrelationViolationException"; internal const string Error_CannotResolveWebServiceInput = "Error_CannotResolveWebServiceInput"; internal const string Error_InvalidLocalServiceMessage = "Error_InvalidLocalServiceMessage"; internal const string Error_InitializerInReplicator = "Error_InitializerInReplicator"; internal const string CodeConditionDisplayName = "CodeConditionDisplayName"; internal const string RuleConditionDisplayName = "RuleConditionDisplayName"; internal const string Error_InterfaceTypeNeedsExternalDataExchangeAttribute = "Error_InterfaceTypeNeedsExternalDataExchangeAttribute"; internal const string Error_WorkflowInstanceDehydratedBeforeSendingResponse = "Error_InstanceDehydratedBeforeSendingResponse"; internal const string Error_InitializerFollowerInTxnlScope = "Error_InitializerFollowerInTxnlScope"; internal const string ShowingExternalDataExchangeService = "ShowingExternalDataExchangeService"; internal const string InterfaceTypeMissing = "InterfaceTypeMissing"; internal const string MethodNameMissing = "MethodNameMissing"; internal const string MethodInfoMissing = "MethodInfoMissing"; internal const string EventNameMissing = "EventNameMissing"; internal const string EventInfoMissing = "EventInfoMissing"; internal const string HandleExternalEventActivityDescription = "HandleExternalEventActivityDescription"; internal const string CallExternalMethodActivityDescription = "CallExternalMethodActivityDescription"; internal const string Error_EventArgumentValidationException = "Error_EventArgumentValidationException"; internal const string Error_GenericMethodsNotSupported = "Error_GenericMethodsNotSupported"; internal const string Error_ReturnTypeNotVoid = "Error_ReturnTypeNotVoid"; internal const string Error_OutRefParameterNotSupported = "Error_OutRefParameterNotSupported"; internal const string InvalidTimespanFormat = "InvalidTimespanFormat"; internal const string Error_CantFindInstance = "Error_CantFindInstance"; internal static string Error_SenderMustBeActivityExecutionContext { get { return GetString("Error_SenderMustBeActivityExecutionContext", typeof(System.Workflow.ComponentModel.ActivityExecutionContext).FullName); } } }
using System; using System.Collections.Generic; using NUnit.Framework; using StructureMap.Configuration.DSL; using StructureMap.Configuration.DSL.Expressions; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using System.Linq; namespace StructureMap.Testing.Configuration.DSL { [TestFixture] public class CreatePluginFamilyTester { #region Setup/Teardown [SetUp] public void SetUp() { } #endregion public interface Something { } public class RedSomething : Something { } public class GreenSomething : Something { } public class ClassWithStringInConstructor { public ClassWithStringInConstructor(string name) { } } [Test] public void Add_an_instance_by_lambda() { var container = new Container(r => { r.For<IWidget>().Add(c => new AWidget()); }); Assert.IsInstanceOfType(typeof (AWidget), container.GetAllInstances<IWidget>()[0]); } [Test] public void add_an_instance_by_literal_object() { var aWidget = new AWidget(); var container = new Container(x => { x.For<IWidget>().Use(aWidget); }); container.GetAllInstances<IWidget>().First().ShouldBeTheSameAs(aWidget); } [Test] public void AddInstanceByNameOnlyAddsOneInstanceToStructureMap() { var container = new Container(r => { r.For<Something>().Add<RedSomething>().WithName("Red"); }); container.GetAllInstances<Something>().Count.ShouldEqual(1); } [Test] public void AddInstanceWithNameOnlyAddsOneInstanceToStructureMap() { IContainer container = new Container( registry => registry.For<Something>().Add<RedSomething>().WithName("Red")); IList<Something> instances = container.GetAllInstances<Something>(); Assert.AreEqual(1, instances.Count); } [Test] public void AsAnotherScope() { var registry = new Registry(); CreatePluginFamilyExpression<IGateway> expression = registry.BuildInstancesOf<IGateway>().CacheBy(InstanceScope.ThreadLocal); Assert.IsNotNull(expression); PluginGraph pluginGraph = registry.Build(); PluginFamily family = pluginGraph.FindFamily(typeof (IGateway)); family.Lifecycle.ShouldBeOfType<ThreadLocalStorageLifecycle>(); } [Test] public void BuildInstancesOfType() { var registry = new Registry(); registry.BuildInstancesOf<IGateway>(); PluginGraph pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.ContainsFamily(typeof (IGateway))); } [Test] public void BuildPluginFamilyAsPerRequest() { var registry = new Registry(); CreatePluginFamilyExpression<IGateway> expression = registry.BuildInstancesOf<IGateway>(); Assert.IsNotNull(expression); PluginGraph pluginGraph = registry.Build(); PluginFamily family = pluginGraph.FindFamily(typeof (IGateway)); family.Lifecycle.ShouldBeNull(); } [Test] public void BuildPluginFamilyAsSingleton() { var registry = new Registry(); CreatePluginFamilyExpression<IGateway> expression = registry.BuildInstancesOf<IGateway>().Singleton(); Assert.IsNotNull(expression); PluginGraph pluginGraph = registry.Build(); PluginFamily family = pluginGraph.FindFamily(typeof (IGateway)); family.Lifecycle.ShouldBeOfType<SingletonLifecycle>(); } [Test] public void cannot_use_a_class_with_a_primitive_constructor_in_the_TheDefaultIsConcreteType_shortcut() { try { var container = new Container(x => { x.ForRequestedType<ClassWithStringInConstructor>().TheDefaultIsConcreteType <ClassWithStringInConstructor>(); }); Assert.Fail("Should have thrown exception 231"); } catch (StructureMapException e) { e.ErrorCode.ShouldEqual(231); } } [Test] public void CanOverrideTheDefaultInstance1() { var registry = new Registry(); // Specify the default implementation for an interface registry.BuildInstancesOf<IGateway>().TheDefaultIsConcreteType<StubbedGateway>(); PluginGraph pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.ContainsFamily(typeof (IGateway))); var manager = new Container(pluginGraph); var gateway = (IGateway) manager.GetInstance(typeof (IGateway)); Assert.IsInstanceOfType(typeof (StubbedGateway), gateway); } [Test] public void CanOverrideTheDefaultInstanceAndCreateAnAllNewPluginOnTheFly() { var registry = new Registry(); registry.BuildInstancesOf<IGateway>().TheDefaultIsConcreteType<FakeGateway>(); PluginGraph pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.ContainsFamily(typeof (IGateway))); var manager = new Container(pluginGraph); var gateway = (IGateway) manager.GetInstance(typeof (IGateway)); Assert.IsInstanceOfType(typeof (FakeGateway), gateway); } [Test] public void CreatePluginFamilyWithADefault() { var container = new Container(r => { r.For<IWidget>().Use<ColorWidget>() .WithCtorArg("color").EqualTo("Red"); }); container.GetInstance<IWidget>().ShouldBeOfType<ColorWidget>().Color.ShouldEqual("Red"); } [Test] public void PutAnInterceptorIntoTheInterceptionChainOfAPluginFamilyInTheDSL() { var lifecycle = new StubbedLifecycle(); var registry = new Registry(); registry.BuildInstancesOf<IGateway>().LifecycleIs(lifecycle); PluginGraph pluginGraph = registry.Build(); pluginGraph.FindFamily(typeof (IGateway)).Lifecycle.ShouldBeTheSameAs(lifecycle); } [Test] public void Set_the_default_by_a_lambda() { var manager = new Container( registry => registry.ForRequestedType<IWidget>().TheDefault.Is.ConstructedBy(() => new AWidget())); Assert.IsInstanceOfType(typeof (AWidget), manager.GetInstance<IWidget>()); } [Test] public void Set_the_default_to_a_built_object() { var aWidget = new AWidget(); var manager = new Container( registry => registry.ForRequestedType<IWidget>().TheDefault.Is.Object(aWidget)); Assert.AreSame(aWidget, manager.GetInstance<IWidget>()); } [Test( Description = "Guid test based on problems encountered by Paul Segaro. See http://groups.google.com/group/structuremap-users/browse_thread/thread/34ddaf549ebb14f7?hl=en" )] public void TheDefaultInstanceIsALambdaForGuidNewGuid() { var manager = new Container( registry => registry.ForRequestedType<Guid>().TheDefault.Is.ConstructedBy(() => Guid.NewGuid())); Assert.IsInstanceOfType(typeof (Guid), manager.GetInstance<Guid>()); } [Test] public void TheDefaultInstanceIsConcreteType() { IContainer manager = new Container( registry => registry.BuildInstancesOf<Rule>().TheDefaultIsConcreteType<ARule>()); Assert.IsInstanceOfType(typeof (ARule), manager.GetInstance<Rule>()); } [Test] public void TheDefaultInstanceIsPickedUpFromTheAttribute() { var registry = new Registry(); registry.BuildInstancesOf<IGateway>(); registry.Scan(x => x.AssemblyContainingType<IGateway>()); PluginGraph pluginGraph = registry.Build(); Assert.IsTrue(pluginGraph.ContainsFamily(typeof (IGateway))); var manager = new Container(pluginGraph); var gateway = (IGateway) manager.GetInstance(typeof (IGateway)); Assert.IsInstanceOfType(typeof (DefaultGateway), gateway); } } public class StubbedLifecycle : ILifecycle { public void EjectAll() { throw new NotImplementedException(); } public IObjectCache FindCache() { throw new NotImplementedException(); } public string Scope { get { return "Stubbed"; } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2017 Atif Aziz. 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. #endregion namespace MoreLinq.Test { using System; using NUnit.Framework; using static FullJoinTest.Side; [TestFixture] public class FullJoinTest { public enum Side { Left, Right, Both } [Test] public void FullJoinWithHomogeneousSequencesIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<int>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, e => e, BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, int, object>())); } [Test] public void FullJoinWithHomogeneousSequencesWithComparerIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<int>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, e => e, BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<int, int, object>(), comparer: null)); } [Test] public void FullJoinIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<object>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, x => x, y => y.GetHashCode(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<object, object>(), BreakingFunc.Of<int, object, object>())); } [Test] public void FullJoinWithComparerIsLazy() { var xs = new BreakingSequence<int>(); var ys = new BreakingSequence<object>(); Assert.DoesNotThrow(() => xs.FullJoin(ys, x => x, y => y.GetHashCode(), BreakingFunc.Of<int, object>(), BreakingFunc.Of<object, object>(), BreakingFunc.Of<int, object, object>(), comparer: null)); } [Test] public void FullJoinResults() { var foo = (1, "foo"); var bar1 = (2, "bar"); var bar2 = (2, "Bar"); var bar3 = (2, "BAR"); var baz = (3, "baz"); var qux = (4, "qux"); var quux = (5, "quux"); var quuz = (6, "quuz"); var xs = new[] { foo, bar1, qux }; var ys = new[] { quux, bar2, baz, bar3, quuz }; var missing = default((int, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y)); result.AssertSequenceEqual( (Left , foo , missing), (Both , bar1 , bar2 ), (Both , bar1 , bar3 ), (Left , qux , missing), (Right, missing, quux ), (Right, missing, baz ), (Right, missing, quuz )); } [Test] public void FullJoinWithComparerResults() { var foo = ("one" , "foo"); var bar1 = ("two" , "bar"); var bar2 = ("Two" , "bar"); var bar3 = ("TWO" , "bar"); var baz = ("three", "baz"); var qux = ("four" , "qux"); var quux = ("five" , "quux"); var quuz = ("six" , "quuz"); var xs = new[] { foo, bar1, qux }; var ys = new[] { quux, bar2, baz, bar3, quuz }; var missing = default((string, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y), StringComparer.OrdinalIgnoreCase); result.AssertSequenceEqual( (Left , foo , missing), (Both , bar1 , bar2 ), (Both , bar1 , bar3 ), (Left , qux , missing), (Right, missing, quux ), (Right, missing, baz ), (Right, missing, quuz )); } [Test] public void FullJoinEmptyLeft() { var foo = (1, "foo"); var bar = (2, "bar"); var baz = (3, "baz"); var xs = new (int, string)[0]; var ys = new[] { foo, bar, baz }; var missing = default((int, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y)); result.AssertSequenceEqual( (Right, missing, foo), (Right, missing, bar), (Right, missing, baz)); } [Test] public void FullJoinEmptyRight() { var foo = (1, "foo"); var bar = (2, "bar"); var baz = (3, "baz"); var xs = new[] { foo, bar, baz }; var ys = new (int, string)[0]; var missing = default((int, string)); var result = xs.FullJoin(ys, x => x.Item1, y => y.Item1, x => (Left, x, missing), y => (Right, missing, y), (x, y) => (Both, x, y)); result.AssertSequenceEqual( (Left, foo, missing), (Left, bar, missing), (Left, baz, missing)); } } }
// $ANTLR 3.3 Nov 30, 2010 12:45:30 D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g 2011-08-16 15:05:01 // The variable 'variable' is assigned but its value is never used. #pragma warning disable 219 // Unreachable code detected. #pragma warning disable 162 using Antlr.Runtime; namespace SheepAspect.Saql.Ast { [System.CodeDom.Compiler.GeneratedCode("ANTLR", "3.3 Nov 30, 2010 12:45:30")] [System.CLSCompliant(false)] public partial class PointcutLexer : Antlr.Runtime.Lexer { public const int EOF=-1; public const int T__14=14; public const int T__15=15; public const int T__16=16; public const int T__17=17; public const int T__18=18; public const int CRITERIA=4; public const int ARRAY=5; public const int POINTCUTREF=6; public const int And=7; public const int Or=8; public const int NOT=9; public const int Identifier=10; public const int Value=11; public const int UScore=12; public const int Ws=13; const int HIDDEN = Hidden; // delegates // delegators public PointcutLexer() { OnCreated(); } public PointcutLexer(ICharStream input ) : this(input, new RecognizerSharedState()) { } public PointcutLexer(ICharStream input, RecognizerSharedState state) : base(input, state) { OnCreated(); } public override string GrammarFileName { get { return "D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g"; } } private static readonly bool[] decisionCanBacktrack = new bool[0]; partial void OnCreated(); partial void EnterRule(string ruleName, int ruleIndex); partial void LeaveRule(string ruleName, int ruleIndex); partial void Enter_T__14(); partial void Leave_T__14(); // $ANTLR start "T__14" [GrammarRule("T__14")] private void mT__14() { Enter_T__14(); EnterRule("T__14", 1); TraceIn("T__14", 1); try { int _type = T__14; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:10:7: ( ',' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:10:9: ',' { DebugLocation(10, 9); Match(','); } state.type = _type; state.channel = _channel; } finally { TraceOut("T__14", 1); LeaveRule("T__14", 1); Leave_T__14(); } } // $ANTLR end "T__14" partial void Enter_T__15(); partial void Leave_T__15(); // $ANTLR start "T__15" [GrammarRule("T__15")] private void mT__15() { Enter_T__15(); EnterRule("T__15", 2); TraceIn("T__15", 2); try { int _type = T__15; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:11:7: ( ':' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:11:9: ':' { DebugLocation(11, 9); Match(':'); } state.type = _type; state.channel = _channel; } finally { TraceOut("T__15", 2); LeaveRule("T__15", 2); Leave_T__15(); } } // $ANTLR end "T__15" partial void Enter_T__16(); partial void Leave_T__16(); // $ANTLR start "T__16" [GrammarRule("T__16")] private void mT__16() { Enter_T__16(); EnterRule("T__16", 3); TraceIn("T__16", 3); try { int _type = T__16; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:12:7: ( '@' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:12:9: '@' { DebugLocation(12, 9); Match('@'); } state.type = _type; state.channel = _channel; } finally { TraceOut("T__16", 3); LeaveRule("T__16", 3); Leave_T__16(); } } // $ANTLR end "T__16" partial void Enter_T__17(); partial void Leave_T__17(); // $ANTLR start "T__17" [GrammarRule("T__17")] private void mT__17() { Enter_T__17(); EnterRule("T__17", 4); TraceIn("T__17", 4); try { int _type = T__17; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:13:7: ( '(' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:13:9: '(' { DebugLocation(13, 9); Match('('); } state.type = _type; state.channel = _channel; } finally { TraceOut("T__17", 4); LeaveRule("T__17", 4); Leave_T__17(); } } // $ANTLR end "T__17" partial void Enter_T__18(); partial void Leave_T__18(); // $ANTLR start "T__18" [GrammarRule("T__18")] private void mT__18() { Enter_T__18(); EnterRule("T__18", 5); TraceIn("T__18", 5); try { int _type = T__18; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:14:7: ( ')' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:14:9: ')' { DebugLocation(14, 9); Match(')'); } state.type = _type; state.channel = _channel; } finally { TraceOut("T__18", 5); LeaveRule("T__18", 5); Leave_T__18(); } } // $ANTLR end "T__18" partial void Enter_NOT(); partial void Leave_NOT(); // $ANTLR start "NOT" [GrammarRule("NOT")] private void mNOT() { Enter_NOT(); EnterRule("NOT", 6); TraceIn("NOT", 6); try { int _type = NOT; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:37:5: ( '!' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:37:7: '!' { DebugLocation(37, 7); Match('!'); } state.type = _type; state.channel = _channel; } finally { TraceOut("NOT", 6); LeaveRule("NOT", 6); Leave_NOT(); } } // $ANTLR end "NOT" partial void Enter_And(); partial void Leave_And(); // $ANTLR start "And" [GrammarRule("And")] private void mAnd() { Enter_And(); EnterRule("And", 7); TraceIn("And", 7); try { int _type = And; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:38:5: ( '&&' | '&' ) int alt1=2; try { DebugEnterDecision(1, decisionCanBacktrack[1]); int LA1_0 = input.LA(1); if ((LA1_0=='&')) { int LA1_1 = input.LA(2); if ((LA1_1=='&')) { alt1=1; } else { alt1=2;} } else { NoViableAltException nvae = new NoViableAltException("", 1, 0, input); DebugRecognitionException(nvae); throw nvae; } } finally { DebugExitDecision(1); } switch (alt1) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:38:7: '&&' { DebugLocation(38, 7); Match("&&"); } break; case 2: DebugEnterAlt(2); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:38:14: '&' { DebugLocation(38, 14); Match('&'); } break; } state.type = _type; state.channel = _channel; } finally { TraceOut("And", 7); LeaveRule("And", 7); Leave_And(); } } // $ANTLR end "And" partial void Enter_Or(); partial void Leave_Or(); // $ANTLR start "Or" [GrammarRule("Or")] private void mOr() { Enter_Or(); EnterRule("Or", 8); TraceIn("Or", 8); try { int _type = Or; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:39:4: ( '||' | '|' ) int alt2=2; try { DebugEnterDecision(2, decisionCanBacktrack[2]); int LA2_0 = input.LA(1); if ((LA2_0=='|')) { int LA2_1 = input.LA(2); if ((LA2_1=='|')) { alt2=1; } else { alt2=2;} } else { NoViableAltException nvae = new NoViableAltException("", 2, 0, input); DebugRecognitionException(nvae); throw nvae; } } finally { DebugExitDecision(2); } switch (alt2) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:39:6: '||' { DebugLocation(39, 6); Match("||"); } break; case 2: DebugEnterAlt(2); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:39:13: '|' { DebugLocation(39, 13); Match('|'); } break; } state.type = _type; state.channel = _channel; } finally { TraceOut("Or", 8); LeaveRule("Or", 8); Leave_Or(); } } // $ANTLR end "Or" partial void Enter_Identifier(); partial void Leave_Identifier(); // $ANTLR start "Identifier" [GrammarRule("Identifier")] private void mIdentifier() { Enter_Identifier(); EnterRule("Identifier", 9); TraceIn("Identifier", 9); try { int _type = Identifier; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:41:11: ( ( 'A' .. 'z' | '0' .. '9' | UScore )+ ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:41:13: ( 'A' .. 'z' | '0' .. '9' | UScore )+ { DebugLocation(41, 13); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:41:13: ( 'A' .. 'z' | '0' .. '9' | UScore )+ int cnt3=0; try { DebugEnterSubRule(3); while (true) { int alt3=2; try { DebugEnterDecision(3, decisionCanBacktrack[3]); int LA3_0 = input.LA(1); if (((LA3_0>='0' && LA3_0<='9')||(LA3_0>='A' && LA3_0<='z'))) { alt3=1; } } finally { DebugExitDecision(3); } switch (alt3) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g: { DebugLocation(41, 13); if ((input.LA(1)>='0' && input.LA(1)<='9')||(input.LA(1)>='A' && input.LA(1)<='z')) { input.Consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); Recover(mse); throw mse;} } break; default: if (cnt3 >= 1) { goto loop3; } EarlyExitException eee3 = new EarlyExitException( 3, input ); DebugRecognitionException(eee3); throw eee3; } cnt3++; } loop3: ; } finally { DebugExitSubRule(3); } } state.type = _type; state.channel = _channel; } finally { TraceOut("Identifier", 9); LeaveRule("Identifier", 9); Leave_Identifier(); } } // $ANTLR end "Identifier" partial void Enter_Value(); partial void Leave_Value(); // $ANTLR start "Value" [GrammarRule("Value")] private void mValue() { Enter_Value(); EnterRule("Value", 10); TraceIn("Value", 10); try { int _type = Value; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:45:2: ( '\\'' ( 'A' .. 'z' | '0' .. '9' | '(' | ')' | '*' | '.' | ':' | ' ' | UScore )* '\\'' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:45:4: '\\'' ( 'A' .. 'z' | '0' .. '9' | '(' | ')' | '*' | '.' | ':' | ' ' | UScore )* '\\'' { DebugLocation(45, 4); Match('\''); DebugLocation(45, 9); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:45:9: ( 'A' .. 'z' | '0' .. '9' | '(' | ')' | '*' | '.' | ':' | ' ' | UScore )* try { DebugEnterSubRule(4); while (true) { int alt4=2; try { DebugEnterDecision(4, decisionCanBacktrack[4]); int LA4_0 = input.LA(1); if ((LA4_0 == ' ' || (LA4_0 >= '(' && LA4_0 <= '*') || LA4_0 == '.' || LA4_0 == ':' || (LA4_0 >= '0' && LA4_0 <= '9') || (LA4_0 >= 'A' && LA4_0 <= 'z'))) { alt4=1; } } finally { DebugExitDecision(4); } switch ( alt4 ) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g: { DebugLocation(45, 9); if (input.LA(1) == ' ' || (input.LA(1) >= '(' && input.LA(1) <= '*') || input.LA(1) == '.' || input.LA(1) == ':' || (input.LA(1) >= '0' && input.LA(1) <= '9') || (input.LA(1) >= 'A' && input.LA(1) <= 'z')) { input.Consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); Recover(mse); throw mse;} } break; default: goto loop4; } } loop4: ; } finally { DebugExitSubRule(4); } DebugLocation(45, 70); Match('\''); } state.type = _type; state.channel = _channel; } finally { TraceOut("Value", 10); LeaveRule("Value", 10); Leave_Value(); } } // $ANTLR end "Value" partial void Enter_UScore(); partial void Leave_UScore(); // $ANTLR start "UScore" [GrammarRule("UScore")] private void mUScore() { Enter_UScore(); EnterRule("UScore", 11); TraceIn("UScore", 11); try { // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:49:2: ( '_' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:49:4: '_' { DebugLocation(49, 4); Match('_'); } } finally { TraceOut("UScore", 11); LeaveRule("UScore", 11); Leave_UScore(); } } // $ANTLR end "UScore" partial void Enter_Ws(); partial void Leave_Ws(); // $ANTLR start "Ws" [GrammarRule("Ws")] private void mWs() { Enter_Ws(); EnterRule("Ws", 12); TraceIn("Ws", 12); try { int _type = Ws; int _channel = DefaultTokenChannel; // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:51:5: ( ( ' ' | '\\t' | '\\r' | '\\n' ) ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:51:9: ( ' ' | '\\t' | '\\r' | '\\n' ) { DebugLocation(51, 9); if ((input.LA(1)>='\t' && input.LA(1)<='\n')||input.LA(1)=='\r'||input.LA(1)==' ') { input.Consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); DebugRecognitionException(mse); Recover(mse); throw mse;} DebugLocation(55, 11); _channel=HIDDEN; } state.type = _type; state.channel = _channel; } finally { TraceOut("Ws", 12); LeaveRule("Ws", 12); Leave_Ws(); } } // $ANTLR end "Ws" public override void mTokens() { // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:8: ( T__14 | T__15 | T__16 | T__17 | T__18 | NOT | And | Or | Identifier | Value | Ws ) int alt5=11; try { DebugEnterDecision(5, decisionCanBacktrack[5]); switch (input.LA(1)) { case ',': { alt5=1; } break; case ':': { alt5=2; } break; case '@': { alt5=3; } break; case '(': { alt5=4; } break; case ')': { alt5=5; } break; case '!': { alt5=6; } break; case '&': { alt5=7; } break; case '|': { alt5=8; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': { alt5=9; } break; case '\'': { alt5=10; } break; case '\t': case '\n': case '\r': case ' ': { alt5=11; } break; default: { NoViableAltException nvae = new NoViableAltException("", 5, 0, input); DebugRecognitionException(nvae); throw nvae; } } } finally { DebugExitDecision(5); } switch (alt5) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:10: T__14 { DebugLocation(1, 10); mT__14(); } break; case 2: DebugEnterAlt(2); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:16: T__15 { DebugLocation(1, 16); mT__15(); } break; case 3: DebugEnterAlt(3); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:22: T__16 { DebugLocation(1, 22); mT__16(); } break; case 4: DebugEnterAlt(4); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:28: T__17 { DebugLocation(1, 28); mT__17(); } break; case 5: DebugEnterAlt(5); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:34: T__18 { DebugLocation(1, 34); mT__18(); } break; case 6: DebugEnterAlt(6); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:40: NOT { DebugLocation(1, 40); mNOT(); } break; case 7: DebugEnterAlt(7); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:44: And { DebugLocation(1, 44); mAnd(); } break; case 8: DebugEnterAlt(8); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:48: Or { DebugLocation(1, 48); mOr(); } break; case 9: DebugEnterAlt(9); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:51: Identifier { DebugLocation(1, 51); mIdentifier(); } break; case 10: DebugEnterAlt(10); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:62: Value { DebugLocation(1, 62); mValue(); } break; case 11: DebugEnterAlt(11); // D:\\Dev\\Codeplex\\SheepAop\\SheepAspect\\Saql\\Ast\\Pointcut.g:1:68: Ws { DebugLocation(1, 68); mWs(); } break; } } #region DFA protected override void InitDFAs() { base.InitDFAs(); } #endregion } } // namespace SheepAspect.Saql.Ast
// // Json.cs: MonoTouch.Dialog support for creating UIs from Json description files // // Author: // Miguel de Icaza // // See the JSON.md file for documentation // // TODO: Json to load entire view controllers // #if !TVOS using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Json; using System.Net; using System.Reflection; #if __UNIFIED__ using Foundation; using UIKit; using CoreGraphics; using NSAction = global::System.Action; #else using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreGraphics; #endif #if !__UNIFIED__ using nint = global::System.Int32; using nuint = global::System.UInt32; using nfloat = global::System.Single; using CGSize = global::System.Drawing.SizeF; using CGPoint = global::System.Drawing.PointF; using CGRect = global::System.Drawing.RectangleF; #endif namespace MonoTouch.Dialog { public class JsonElement : RootElement { JsonElement jsonParent; Dictionary<string,Element> map; const int CSIZE = 16; const int SPINNER_TAG = 1000; public string Url; bool loading; public static DateTimeKind DateKind { get; set; } //= DateTimeKind.Unspecified; UIActivityIndicatorView StartSpinner (UITableViewCell cell) { var cvb = cell.ContentView.Bounds; var spinner = new UIActivityIndicatorView (new CGRect (cvb.Width-CSIZE/2, (cvb.Height-CSIZE)/2, CSIZE, CSIZE)) { Tag = SPINNER_TAG, ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray, }; cell.ContentView.AddSubview (spinner); spinner.StartAnimating (); cell.Accessory = UITableViewCellAccessory.None; return spinner; } void RemoveSpinner (UITableViewCell cell, UIActivityIndicatorView spinner) { spinner.StopAnimating (); spinner.RemoveFromSuperview (); cell.Accessory = UITableViewCellAccessory.DisclosureIndicator; } public override UITableViewCell GetCell (UITableView tv) { var cell = base.GetCell (tv); if (Url == null) return cell; var spinner = cell.ViewWithTag (SPINNER_TAG) as UIActivityIndicatorView; if (loading){ if (spinner == null) StartSpinner (cell); else if (spinner != null) RemoveSpinner (cell, spinner); } return cell; } #if __UNIFIED__ class ConnectionDelegate : NSUrlConnectionDataDelegate { #else class ConnectionDelegate : NSUrlConnectionDelegate { #endif Action<Stream,NSError> callback; NSMutableData buffer; public ConnectionDelegate (Action<Stream,NSError> callback) { this.callback = callback; buffer = new NSMutableData (); } public override void ReceivedResponse(NSUrlConnection connection, NSUrlResponse response) { buffer.Length = 0; } public override void FailedWithError(NSUrlConnection connection, NSError error) { callback (null, error); } public override void ReceivedData(NSUrlConnection connection, NSData data) { buffer.AppendData (data); } public override void FinishedLoading(NSUrlConnection connection) { callback (buffer.AsStream (), null); } } public override void Selected (DialogViewController dvc, UITableView tableView, NSIndexPath path) { if (Url == null){ base.Selected (dvc, tableView, path); return; } tableView.DeselectRow (path, false); if (loading) return; var cell = GetActiveCell (); var spinner = StartSpinner (cell); loading = true; var request = new NSUrlRequest (new NSUrl (Url), NSUrlRequestCachePolicy.UseProtocolCachePolicy, 60); var connection = new NSUrlConnection (request, new ConnectionDelegate ((data,error) => { loading = false; spinner.StopAnimating (); spinner.RemoveFromSuperview (); if (error == null){ try { var obj = JsonValue.Load (new StreamReader (data)) as JsonObject; if (obj != null){ var root = JsonElement.FromJson (obj); var newDvc = new DialogViewController (root, true) { Autorotate = true }; PrepareDialogViewController (newDvc); dvc.ActivateController (newDvc); return; } } catch (Exception ee){ } } var alert = new UIAlertView ("Error", "Unable to download data", null, "Ok"); alert.Show (); })); } public JsonElement (string caption, string url) : base (caption) { Url = url; } public JsonElement (string caption, int section, int element, string url) : base (caption, section, element) { Url = url; } public JsonElement (string caption, Group group, string url) : base (caption, group) { Url = url; } public static JsonElement FromFile (string file, object arg) { using (var reader = File.OpenRead (file)) return FromJson (JsonObject.Load (reader) as JsonObject, arg); } public static JsonElement FromFile (string file) { return FromFile (file, null); } public static JsonElement FromJson (JsonObject json) { return FromJson (null, json, null); } public static JsonElement FromJson (JsonObject json, object data) { return FromJson (null, json, data); } public static JsonElement FromJson (JsonElement parent, JsonObject json, object data) { if (json == null) return null; var title = GetString (json, "title") ?? ""; var group = GetString (json, "group"); var url = GetString (json, "url"); var radioSelected = GetString (json, "radioselected"); JsonElement root; if (group == null){ if (radioSelected == null) root = new JsonElement (title, url); else root = new JsonElement (title, new RadioGroup (int.Parse (radioSelected)), url); } else { if (radioSelected == null) root = new JsonElement (title, new Group (group), url); else { // It does not seem that we group elements together, notice when I add // the return, and then change my mind, I have to undo *twice* instead of once. root = new JsonElement (title, new RadioGroup (group, int.Parse (radioSelected)), url); } } root.jsonParent = parent; root.LoadSections (GetArray (json, "sections"), data); return root; } void AddMapping (string id, Element element) { if (jsonParent != null){ jsonParent.AddMapping (id, element); return; } if (map == null) map = new Dictionary<string, Element> (); map.Add (id, element); } // // Retrieves the element name "key" // public Element this [string key] { get { if (jsonParent != null) return jsonParent [key]; if (map == null) return null; Element res; if (map.TryGetValue (key, out res)) return res; return null; } } static void Error (string msg) { } static void Error (string fmt, params object [] args) { Error (String.Format (fmt, args)); } static string GetString (JsonValue obj, string key) { if (obj.ContainsKey (key)) if (obj [key].JsonType == JsonType.String) return (string) obj [key]; return null; } static JsonArray GetArray (JsonObject obj, string key) { if (obj.ContainsKey (key)) if (obj [key].JsonType == JsonType.Array) return (JsonArray) obj [key]; return null; } static bool GetBoolean (JsonObject obj, string key) { try { return (bool) obj [key]; } catch { return false; } } void LoadSections (JsonArray array, object data) { if (array == null) return; int n = array.Count; for (int i = 0; i < n; i++){ var jsonSection = array [i]; var header = GetString (jsonSection, "header"); var footer = GetString (jsonSection, "footer"); var id = GetString (jsonSection, "id"); var section = new Section (header, footer); if (jsonSection.ContainsKey ("elements")) LoadSectionElements (section, jsonSection ["elements"] as JsonArray, data); Add (section); if (id != null) AddMapping (id, section); } } static string bundlePath; static string ExpandPath (string path) { if (path != null && path.Length > 1 && path [0] == '~' && path [1] == '/'){ if (bundlePath == null) bundlePath = NSBundle.MainBundle.BundlePath; return Path.Combine (bundlePath, path.Substring (2)); } return path; } static Element LoadBoolean (JsonObject json) { var caption = GetString (json, "caption"); bool bvalue = GetBoolean (json, "value"); var group = GetString (json, "group"); var onImagePath = ExpandPath (GetString (json, "on")); var offImagePath = ExpandPath (GetString (json, "off")); if (onImagePath != null && offImagePath != null){ var onImage = UIImage.FromFile (onImagePath); var offImage = UIImage.FromFile (offImagePath); return new BooleanImageElement (caption, bvalue, onImage, offImage); } else return new BooleanElement (caption, bvalue, group); } static UIKeyboardType ToKeyboardType (string kbdType) { switch (kbdType){ case "numbers": return UIKeyboardType.NumberPad; case "default": return UIKeyboardType.Default; case "ascii": return UIKeyboardType.ASCIICapable; case "numbers-and-punctuation": return UIKeyboardType.NumbersAndPunctuation; case "decimal": return UIKeyboardType.DecimalPad; case "email": return UIKeyboardType.EmailAddress; case "name": return UIKeyboardType.NamePhonePad; case "twitter": return UIKeyboardType.Twitter; case "url": return UIKeyboardType.Url; default: break; } return UIKeyboardType.Default; } static UIReturnKeyType ToReturnKeyType (string returnKeyType) { switch (returnKeyType){ case "default": return UIReturnKeyType.Default; case "done": return UIReturnKeyType.Done; case "emergencycall": return UIReturnKeyType.EmergencyCall; case "go": return UIReturnKeyType.Go; case "google": return UIReturnKeyType.Google; case "join": return UIReturnKeyType.Join; case "next": return UIReturnKeyType.Next; case "route": return UIReturnKeyType.Route; case "search": return UIReturnKeyType.Search; case "send": return UIReturnKeyType.Send; case "yahoo": return UIReturnKeyType.Yahoo; default: break; } return UIReturnKeyType.Default; } static UITextAutocapitalizationType ToAutocapitalization (string auto) { switch (auto){ case "sentences": return UITextAutocapitalizationType.Sentences; case "none": return UITextAutocapitalizationType.None; case "words": return UITextAutocapitalizationType.Words; case "all": return UITextAutocapitalizationType.AllCharacters; default: break; } return UITextAutocapitalizationType.Sentences; } static UITextAutocorrectionType ToAutocorrect (JsonValue value) { if (value.JsonType == JsonType.Boolean) return ((bool) value) ? UITextAutocorrectionType.Yes : UITextAutocorrectionType.No; if (value.JsonType == JsonType.String){ var s = ((string) value); if (s == "yes") return UITextAutocorrectionType.Yes; return UITextAutocorrectionType.No; } return UITextAutocorrectionType.Default; } static Element LoadEntry (JsonObject json, bool isPassword) { var caption = GetString (json, "caption"); var value = GetString (json, "value"); var placeholder = GetString (json, "placeholder"); var element = new EntryElement (caption, placeholder, value, isPassword); if (json.ContainsKey ("keyboard")) element.KeyboardType = ToKeyboardType (GetString (json, "keyboard")); if (json.ContainsKey ("return-key")) element.ReturnKeyType = ToReturnKeyType (GetString (json, "return-key")); if (json.ContainsKey ("capitalization")) element.AutocapitalizationType = ToAutocapitalization (GetString (json, "capitalization")); if (json.ContainsKey ("autocorrect")) element.AutocorrectionType = ToAutocorrect (json ["autocorrect"]); return element; } static UITableViewCellAccessory ToAccessory (string accesory) { switch (accesory){ case "checkmark": return UITableViewCellAccessory.Checkmark; case "detail-disclosure": return UITableViewCellAccessory.DetailDisclosureButton; case "disclosure-indicator": return UITableViewCellAccessory.DisclosureIndicator; } return UITableViewCellAccessory.None; } static int FromHex (char c) { if (c >= '0' && c <= '9') return c-'0'; if (c >= 'a' && c <= 'f') return c-'a'+10; if (c >= 'A' && c <= 'F') return c-'A'+10; Console.WriteLine ("Unexpected `{0}' in hex value for color", c); return 0; } static void ColorError (string text) { } static UIColor ParseColor (string text) { int tl = text.Length; if (tl > 1 && text [0] == '#'){ int r, g, b, a; if (tl == 4 || tl == 5){ r = FromHex (text [1]); g = FromHex (text [2]); b = FromHex (text [3]); a = tl == 5 ? FromHex (text [4]) : 15; r = r << 4 | r; g = g << 4 | g; b = b << 4 | b; a = a << 4 | a; } else if (tl == 7 || tl == 9){ r = FromHex (text [1]) << 4 | FromHex (text [2]); g = FromHex (text [3]) << 4 | FromHex (text [4]); b = FromHex (text [5]) << 4 | FromHex (text [6]); a = tl == 9 ? FromHex (text [7]) << 4 | FromHex (text [8]) : 255; } else { ColorError (text); return UIColor.Black; } return UIColor.FromRGBA (r, g, b, a); } ColorError (text); return UIColor.Black; } static UILineBreakMode ToLinebreakMode (string mode) { switch (mode){ case "character-wrap": return UILineBreakMode.CharacterWrap; case "clip": return UILineBreakMode.Clip; case "head-truncation": return UILineBreakMode.HeadTruncation; case "middle-truncation": return UILineBreakMode.MiddleTruncation; case "tail-truncation": return UILineBreakMode.TailTruncation; case "word-wrap": return UILineBreakMode.WordWrap; default: Console.WriteLine ("Unexpeted linebreak mode `{0}', valid values include: character-wrap, clip, head-truncation, middle-truncation, tail-truncation and word-wrap", mode); return UILineBreakMode.Clip; } } // Parses a font in the format: // Name[-SIZE] // if -SIZE is omitted, then the value is SystemFontSize // static UIFont ToFont (string kvalue) { int q = kvalue.LastIndexOf ("-"); string fname = kvalue; nfloat fsize = 0; if (q != -1) { nfloat.TryParse (kvalue.Substring (q+1), out fsize); fname = kvalue.Substring (0, q); } if (fsize <= 0) fsize = UIFont.SystemFontSize; var f = UIFont.FromName (fname, fsize); if (f == null) return UIFont.SystemFontOfSize (12); return f; } static UITableViewCellStyle ToCellStyle (string style) { switch (style){ case "default": return UITableViewCellStyle.Default; case "subtitle": return UITableViewCellStyle.Subtitle; case "value1": return UITableViewCellStyle.Value1; case "value2": return UITableViewCellStyle.Value2; default: Console.WriteLine ("unknown cell style `{0}', valid values are default, subtitle, value1 and value2", style); break; } return UITableViewCellStyle.Default; } static UITextAlignment ToAlignment (string align) { switch (align){ case "center": return UITextAlignment.Center; case "left": return UITextAlignment.Left; case "right": return UITextAlignment.Right; default: return UITextAlignment.Left; } } // // Creates one of the various StringElement classes, based on the // properties set. It tries to load the most memory efficient one // StringElement, if not, it fallsback to MultilineStringElement or // StyledStringElement // static Element LoadString (JsonObject json, object data) { string value = null; string caption = value; string background = null; NSAction ontap = null; NSAction onaccessorytap = null; int? lines = null; UITableViewCellAccessory? accessory = null; UILineBreakMode? linebreakmode = null; UITextAlignment? alignment = null; UIColor textcolor = null, detailcolor = null; UIFont font = null; UIFont detailfont = null; UITableViewCellStyle style = UITableViewCellStyle.Value1; foreach (var kv in json){ string kvalue = (string) kv.Value; switch (kv.Key){ case "caption": caption = kvalue; break; case "value": value = kvalue; break; case "background": background = kvalue; break; case "style": style = ToCellStyle (kvalue); break; case "ontap": case "onaccessorytap": string sontap = kvalue; int p = sontap.LastIndexOf ('.'); if (p == -1) break; NSAction d = delegate { string cname = sontap.Substring (0, p); string mname = sontap.Substring (p+1); foreach (var a in AppDomain.CurrentDomain.GetAssemblies ()){ Type type = a.GetType (cname); if (type != null){ var mi = type.GetMethod (mname, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (mi != null) mi.Invoke (null, new object [] { data }); break; } } }; if (kv.Key == "ontap") ontap = d; else onaccessorytap = d; break; case "lines": int res; if (int.TryParse (kvalue, out res)) lines = res; break; case "accessory": accessory = ToAccessory (kvalue); break; case "textcolor": textcolor = ParseColor (kvalue); break; case "linebreak": linebreakmode = ToLinebreakMode (kvalue); break; case "font": font = ToFont (kvalue); break; case "subtitle": value = kvalue; style = UITableViewCellStyle.Subtitle; break; case "detailfont": detailfont = ToFont (kvalue); break; case "alignment": alignment = ToAlignment (kvalue); break; case "detailcolor": detailcolor = ParseColor (kvalue); break; case "type": break; default: Console.WriteLine ("Unknown attribute: '{0}'", kv.Key); break; } } if (caption == null) caption = ""; if (font != null || style != UITableViewCellStyle.Value1 || detailfont != null || linebreakmode.HasValue || textcolor != null || accessory.HasValue || onaccessorytap != null || background != null || detailcolor != null){ StyledStringElement styled; if (lines.HasValue){ styled = new StyledMultilineElement (caption, value, style); styled.Lines = lines.Value; } else { styled = new StyledStringElement (caption, value, style); } if (ontap != null) styled.Tapped += ontap; if (onaccessorytap != null) styled.AccessoryTapped += onaccessorytap; if (font != null) styled.Font = font; if (detailfont != null) styled.SubtitleFont = detailfont; if (detailcolor != null) styled.DetailColor = detailcolor; if (textcolor != null) styled.TextColor = textcolor; if (accessory.HasValue) styled.Accessory = accessory.Value; if (linebreakmode.HasValue) styled.LineBreakMode = linebreakmode.Value; if (background != null){ if (background.Length > 1 && background [0] == '#') styled.BackgroundColor = ParseColor (background); else styled.BackgroundUri = new Uri (background); } if (alignment.HasValue) styled.Alignment = alignment.Value; return styled; } else { StringElement se; if (lines == 0) se = new MultilineElement (caption, value); else se = new StringElement (caption, value); if (alignment.HasValue) se.Alignment = alignment.Value; if (ontap != null) se.Tapped += ontap; return se; } } static Element LoadRadio (JsonObject json, object data) { var caption = GetString (json, "caption"); var group = GetString (json, "group"); if (group != null) return new RadioElement (caption, group); else return new RadioElement (caption); } static Element LoadCheckbox (JsonObject json, object data) { var caption = GetString (json, "caption"); var group = GetString (json, "group"); var value = GetBoolean (json, "value"); return new CheckboxElement (caption, value, group); } static DateTime GetDateWithKind (DateTime dt, DateTimeKind parsedKind) { // First we check if the given date has a specified Kind, we just return the same date if found. if (dt.Kind != DateTimeKind.Unspecified) return dt; // If not found then we check if we were able to parse a DateTimeKind from the parsedKind param else if (parsedKind != DateTimeKind.Unspecified) return DateTime.SpecifyKind (dt, parsedKind); // If no DateTimeKind from the parsedKind param was found then we check our global property from JsonElement.DateKind else if (JsonElement.DateKind != DateTimeKind.Unspecified) return DateTime.SpecifyKind (dt, JsonElement.DateKind); // If none of the above is found then we just defaut to local else return DateTime.SpecifyKind (dt, DateTimeKind.Local); } static Element LoadDateTime (JsonObject json, string type) { var caption = GetString (json, "caption"); var date = GetString (json, "value"); var kind = GetString (json, "kind"); DateTime datetime; DateTimeKind dateKind; if (!DateTime.TryParse (date, out datetime)) return null; if (kind != null) { switch (kind.ToLowerInvariant ()) { case "local": dateKind = DateTimeKind.Local; break; case "utc": dateKind = DateTimeKind.Utc; break; default: dateKind = DateTimeKind.Unspecified; break; } } else dateKind = DateTimeKind.Unspecified; datetime = GetDateWithKind (datetime, dateKind); switch (type){ case "date": return new DateElement (caption, datetime); case "time": return new TimeElement (caption, datetime); case "datetime": return new DateTimeElement (caption, datetime); default: return null; } } static Element LoadHtmlElement (JsonObject json) { var caption = GetString (json, "caption"); var url = GetString (json, "url"); return new HtmlElement (caption, url); } void LoadSectionElements (Section section, JsonArray array, object data) { if (array == null) return; for (int i = 0; i < array.Count; i++){ Element element = null; try { var json = array [i] as JsonObject; if (json == null) continue; var type = GetString (json, "type"); switch (type){ case "bool": case "boolean": element = LoadBoolean (json); break; case "entry": case "password": element = LoadEntry (json, type == "password"); break; case "string": element = LoadString (json, data); break; case "root": element = FromJson (this, json, data); break; case "radio": element = LoadRadio (json, data); break; case "checkbox": element = LoadCheckbox (json, data); break; case "datetime": case "date": case "time": element = LoadDateTime (json, type); break; case "html": element = LoadHtmlElement (json); break; default: Error ("json element at {0} contain an unknown type `{1}', json {2}", i, type, json); break; } if (element != null){ var id = GetString (json, "id"); if (id != null) AddMapping (id, element); } } catch (Exception e) { Console.WriteLine ("Error processing Json {0}, exception {1}", array, e); Console.WriteLine(e.Message + e.StackTrace); } if (element != null) section.Add (element); } } } } #endif // !TVOS
using System; using OpenTK; namespace OpenGLES20Example { struct Color { public float red; public float green; public float blue; public float alpha; } struct TextureCoord { public float S; public float T; } public static class GLCommon { public static float radiansFromDegrees (float degrees) { return (float)Math.PI * degrees / 180.0f; } public static void Matrix3DSetRotationByRadians (ref float[] matrix, float radians, ref Vector3 vector) { float mag = (float) Math.Sqrt ((vector.X * vector.X) + (vector.Y * vector.Y) + (vector.Z * vector.Z)); if (mag == 0.0f) { vector.X = 1.0f; vector.Y = 0.0f; vector.Z = 0.0f; } else if (mag != 1.0f) { vector.X /= mag; vector.Y /= mag; vector.Z /= mag; } float c = (float) Math.Cos (radians); float s = (float) Math.Sin (radians); matrix [3] = matrix [7] = matrix [11] = 0.0f; matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [15] = 1.0f; matrix [0] = (vector.X * vector.X) * (1 - c) + c; matrix [1] = (vector.Y * vector.X) * (1 - c) + (vector.Z * s); matrix [2] = (vector.X * vector.Z) * (1 - c) - (vector.Y * s); matrix [4] = (vector.X * vector.Y) * (1 - c) - (vector.Z * s); matrix [5] = (vector.Y * vector.Y) * (1 - c) + c; matrix [6] = (vector.Y * vector.Z) * (1 - c) + (vector.X * s); matrix [8] = (vector.X * vector.Z) * (1 - c) + (vector.Y * s); matrix [9] = (vector.Y * vector.Z) * (1 - c) - (vector.X * s); matrix [10] = (vector.Z * vector.Z) * (1 - c) + c; } public static void Matrix3DSetRotationByDegrees (ref float[] matrix, float degrees, Vector3 vector) { Matrix3DSetRotationByRadians (ref matrix, radiansFromDegrees (degrees), ref vector); } public static void Matrix3DSetIdentity (ref float[] matrix) { matrix [0] = matrix [5] = matrix [10] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [8] = matrix [9] = 0.0f; matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; } public static void Matrix3DSetTranslation (ref float[] matrix, float xTranslate, float yTranslate, float zTranslate) { matrix [0] = matrix [5] = matrix [10] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [8] = matrix [9] = 0.0f; matrix [11] = 0.0f; matrix [12] = xTranslate; matrix [13] = yTranslate; matrix [14] = zTranslate; } public static void Matrix3DSetScaling (ref float[] matrix, float xScale, float yScale, float zScale) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [8] = matrix [9] = 0.0f; matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [0] = xScale; matrix [5] = yScale; matrix [10] = zScale; matrix [15] = 1.0f; } public static void Matrix3DSetUniformScaling (ref float[] matrix, float scale) { Matrix3DSetScaling (ref matrix, scale, scale, scale); } public static void Matrix3DSetZRotationUsingRadians (ref float[] matrix, float radians) { matrix [0] = (float)Math.Cos (radians); matrix [1] = (float)Math.Sin (radians); matrix [4] = -matrix [1]; matrix [5] = matrix [0]; matrix [2] = matrix [3] = matrix [6] = matrix [7] = matrix [8] = 0.0f; matrix [9] = matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [10] = matrix [15] = 0; } public static void Matrix3DSetZRotationUsingDegrees (ref float[] matrix, float degrees) { Matrix3DSetZRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } public static void Matrix3DSetXRotationUsingRadians (ref float[] matrix, float radians) { matrix [0] = matrix [15] = 1.0f; matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [7] = matrix [8] = 0.0f; matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [5] = (float) Math.Cos (radians); matrix [6] = - (float)Math.Sin (radians); matrix [9] = - matrix [6]; matrix [10] = matrix [5]; } public static void Matrix3DSetXRotationUsingDegrees (ref float[] matrix, float degrees) { Matrix3DSetXRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } public static void Matrix3DSetYRotationUsingRadians (ref float[] matrix, float radians) { matrix [0] = (float)Math.Cos (radians); matrix [2] = (float)Math.Sin (radians); matrix [8] = - matrix [2]; matrix [10] = matrix [0]; matrix [1] = matrix [3] = matrix [4] = matrix [6] = matrix [7] = 0.0f; matrix [9] = matrix [11] = matrix [12] = matrix [13] = matrix [14] = 0.0f; matrix [5] = matrix [15] = 1.0f; } public static void Matrix3DSetYRotationUsingDegrees (ref float[] matrix, float degrees) { Matrix3DSetYRotationUsingRadians (ref matrix, radiansFromDegrees (degrees)); } public static float[] Matrix3DMultiply (float[] m1, float[] m2) { float[] result = new float[16]; result [0] = m1 [0] * m2 [0] + m1 [4] * m2 [1] + m1 [8] * m2 [2] + m1 [12] * m2 [3]; result [1] = m1 [1] * m2 [0] + m1 [5] * m2 [1] + m1 [9] * m2 [2] + m1 [13] * m2 [3]; result [2] = m1 [2] * m2 [0] + m1 [6] * m2 [1] + m1 [10] * m2 [2] + m1 [14] * m2 [3]; result [3] = m1 [3] * m2 [0] + m1 [7] * m2 [1] + m1 [11] * m2 [2] + m1 [15] * m2 [3]; result [4] = m1 [0] * m2 [4] + m1 [4] * m2 [5] + m1 [8] * m2 [6] + m1 [12] * m2 [7]; result [5] = m1 [1] * m2 [4] + m1 [5] * m2 [5] + m1 [9] * m2 [6] + m1 [13] * m2 [7]; result [6] = m1 [2] * m2 [4] + m1 [6] * m2 [5] + m1 [10] * m2 [6] + m1 [14] * m2 [7]; result [7] = m1 [3] * m2 [4] + m1 [7] * m2 [5] + m1 [11] * m2 [6] + m1 [15] * m2 [7]; result [8] = m1 [0] * m2 [8] + m1 [4] * m2 [9] + m1 [8] * m2 [10] + m1 [12] * m2 [11]; result [9] = m1 [1] * m2 [8] + m1 [5] * m2 [9] + m1 [9] * m2 [10] + m1 [13] * m2 [11]; result [10] = m1 [2] * m2 [8] + m1 [6] * m2 [9] + m1 [10] * m2 [10] + m1 [14] * m2 [11]; result [11] = m1 [3] * m2 [8] + m1 [7] * m2 [9] + m1 [11] * m2 [10] + m1 [15] * m2 [11]; result [12] = m1 [0] * m2 [12] + m1 [4] * m2 [13] + m1 [8] * m2 [14] + m1 [12] * m2 [15]; result [13] = m1 [1] * m2 [12] + m1 [5] * m2 [13] + m1 [9] * m2 [14] + m1 [13] * m2 [15]; result [14] = m1 [2] * m2 [12] + m1 [6] * m2 [13] + m1 [10] * m2 [14] + m1 [14] * m2 [15]; result [15] = m1 [3] * m2 [12] + m1 [7] * m2 [13] + m1 [11] * m2 [14] + m1 [15] * m2 [15]; return result; } public static void Matrix3DSetOrthoProjection (ref float[] matrix, float left, float right, float bottom, float top, float near, float far) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = matrix [6] = 0.0f; matrix [7] = matrix [8] = matrix [9] = matrix [11] = 0.0f; matrix [0] = 2.0f / (right - left); matrix [5] = 2.0f / (top - bottom); matrix [10] = -2.0f / (far - near); matrix [12] = (right + left) / (right - left); matrix [13] = (top + bottom) / (top - bottom); matrix [14] = (far + near) / (far - near); matrix [15] = 1.0f; } public static void Matrix3DSetFrustumProjection (ref float[] matrix, float left, float right, float bottom, float top, float zNear, float zFar) { matrix [1] = matrix [2] = matrix [3] = matrix [4] = 0.0f; matrix [6] = matrix [7] = matrix [12] = matrix [13] = matrix [15] = 0.0f; matrix [0] = 2 * zNear / (right - left); matrix [5] = 2 * zNear / (top - bottom); matrix [8] = (right + left) / (right - left); matrix [9] = (top + bottom) / (top - bottom); matrix [10] = - (zFar + zNear) / (zFar - zNear); matrix [11] = - 1.0f; matrix [14] = - (2 * zFar * zNear) / (zFar - zNear); } public static void Matrix3DSetPerspectiveProjectionWithFieldOfView (ref float[] matrix, float fieldOfVision, float near, float far, float aspectRatio) { float size = near * (float)Math.Tan (radiansFromDegrees (fieldOfVision) / 2.0f); Matrix3DSetFrustumProjection (ref matrix, -size, size, -size / aspectRatio, size / aspectRatio, near, far); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// The metrics associated with a virtual block device /// First published in XenServer 4.0. /// </summary> public partial class VBD_metrics : XenObject<VBD_metrics> { #region Constructors public VBD_metrics() { } public VBD_metrics(string uuid, double io_read_kbs, double io_write_kbs, DateTime last_updated, Dictionary<string, string> other_config) { this.uuid = uuid; this.io_read_kbs = io_read_kbs; this.io_write_kbs = io_write_kbs; this.last_updated = last_updated; this.other_config = other_config; } /// <summary> /// Creates a new VBD_metrics from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public VBD_metrics(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new VBD_metrics from a Proxy_VBD_metrics. /// </summary> /// <param name="proxy"></param> public VBD_metrics(Proxy_VBD_metrics proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given VBD_metrics. /// </summary> public override void UpdateFrom(VBD_metrics update) { uuid = update.uuid; io_read_kbs = update.io_read_kbs; io_write_kbs = update.io_write_kbs; last_updated = update.last_updated; other_config = update.other_config; } internal void UpdateFrom(Proxy_VBD_metrics proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; io_read_kbs = Convert.ToDouble(proxy.io_read_kbs); io_write_kbs = Convert.ToDouble(proxy.io_write_kbs); last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_VBD_metrics ToProxy() { Proxy_VBD_metrics result_ = new Proxy_VBD_metrics(); result_.uuid = uuid ?? ""; result_.io_read_kbs = io_read_kbs; result_.io_write_kbs = io_write_kbs; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this VBD_metrics /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("io_read_kbs")) io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs"); if (table.ContainsKey("io_write_kbs")) io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs"); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(VBD_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) && Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<VBD_metrics> ProxyArrayToObjectList(Proxy_VBD_metrics[] input) { var result = new List<VBD_metrics>(); foreach (var item in input) result.Add(new VBD_metrics(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, VBD_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VBD_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static VBD_metrics get_record(Session session, string _vbd_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_record(session.opaque_ref, _vbd_metrics); else return new VBD_metrics(session.XmlRpcProxy.vbd_metrics_get_record(session.opaque_ref, _vbd_metrics ?? "").parse()); } /// <summary> /// Get a reference to the VBD_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VBD_metrics> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<VBD_metrics>.Create(session.XmlRpcProxy.vbd_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static string get_uuid(Session session, string _vbd_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_uuid(session.opaque_ref, _vbd_metrics); else return session.XmlRpcProxy.vbd_metrics_get_uuid(session.opaque_ref, _vbd_metrics ?? "").parse(); } /// <summary> /// Get the io/read_kbs field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static double get_io_read_kbs(Session session, string _vbd_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_io_read_kbs(session.opaque_ref, _vbd_metrics); else return Convert.ToDouble(session.XmlRpcProxy.vbd_metrics_get_io_read_kbs(session.opaque_ref, _vbd_metrics ?? "").parse()); } /// <summary> /// Get the io/write_kbs field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static double get_io_write_kbs(Session session, string _vbd_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_io_write_kbs(session.opaque_ref, _vbd_metrics); else return Convert.ToDouble(session.XmlRpcProxy.vbd_metrics_get_io_write_kbs(session.opaque_ref, _vbd_metrics ?? "").parse()); } /// <summary> /// Get the last_updated field of the given VBD_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static DateTime get_last_updated(Session session, string _vbd_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_last_updated(session.opaque_ref, _vbd_metrics); else return session.XmlRpcProxy.vbd_metrics_get_last_updated(session.opaque_ref, _vbd_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given VBD_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _vbd_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_other_config(session.opaque_ref, _vbd_metrics); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vbd_metrics_get_other_config(session.opaque_ref, _vbd_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given VBD_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vbd_metrics, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.vbd_metrics_set_other_config(session.opaque_ref, _vbd_metrics, _other_config); else session.XmlRpcProxy.vbd_metrics_set_other_config(session.opaque_ref, _vbd_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VBD_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vbd_metrics, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.vbd_metrics_add_to_other_config(session.opaque_ref, _vbd_metrics, _key, _value); else session.XmlRpcProxy.vbd_metrics_add_to_other_config(session.opaque_ref, _vbd_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VBD_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vbd_metrics">The opaque_ref of the given vbd_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vbd_metrics, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.vbd_metrics_remove_from_other_config(session.opaque_ref, _vbd_metrics, _key); else session.XmlRpcProxy.vbd_metrics_remove_from_other_config(session.opaque_ref, _vbd_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the VBD_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VBD_metrics>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_all(session.opaque_ref); else return XenRef<VBD_metrics>.Create(session.XmlRpcProxy.vbd_metrics_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the VBD_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VBD_metrics>, VBD_metrics> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vbd_metrics_get_all_records(session.opaque_ref); else return XenRef<VBD_metrics>.Create<Proxy_VBD_metrics>(session.XmlRpcProxy.vbd_metrics_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// Read bandwidth (KiB/s) /// </summary> public virtual double io_read_kbs { get { return _io_read_kbs; } set { if (!Helper.AreEqual(value, _io_read_kbs)) { _io_read_kbs = value; NotifyPropertyChanged("io_read_kbs"); } } } private double _io_read_kbs; /// <summary> /// Write bandwidth (KiB/s) /// </summary> public virtual double io_write_kbs { get { return _io_write_kbs; } set { if (!Helper.AreEqual(value, _io_write_kbs)) { _io_write_kbs = value; NotifyPropertyChanged("io_write_kbs"); } } } private double _io_write_kbs; /// <summary> /// Time at which this information was last updated /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
// <copyright file="NumberTypeHandler.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; using System.Globalization; using System.Reflection; using BeanIO.Config; namespace BeanIO.Types { /// <summary> /// A type handler implementation for the <see cref="decimal"/> class. /// </summary> /// <remarks> /// If <see cref="Pattern"/> is set, a NumberStyle is used to parse the value and a format string to format the value. /// Otherwise, the value is parsed and formatted using the <see cref="decimal"/> class. /// </remarks> public class NumberTypeHandler : CultureSupport, IConfigurableTypeHandler { private Tuple<NumberStyles, string> _pattern; /// <summary> /// Initializes a new instance of the <see cref="NumberTypeHandler"/> class. /// </summary> /// <param name="numberType">The number type to convert from/to.</param> public NumberTypeHandler(Type numberType) { if (numberType == null) throw new ArgumentNullException(nameof(numberType)); if (!numberType.GetTypeInfo().IsValueType) throw new ArgumentOutOfRangeException(nameof(numberType)); TargetType = numberType; } /// <summary> /// Gets or sets the format pattern to use to parse and format the number value. /// </summary> public Tuple<NumberStyles, string> Pattern { get { return _pattern; } set { if (value != null && string.IsNullOrEmpty(value.Item2)) throw new ArgumentOutOfRangeException(nameof(value)); _pattern = value; } } /// <summary> /// Gets the class type supported by this handler. /// </summary> public virtual Type TargetType { get; private set; } /// <summary> /// Parses field text into an object. /// </summary> /// <param name="text">The field text to parse, which may be null if the field was not passed in the record</param> /// <returns>The parsed object</returns> public virtual object Parse(string text) { if (string.IsNullOrEmpty(text)) return null; if (Pattern == null) return CreateNumber(text); return Parse(text, Pattern.Item1); } /// <summary> /// Formats an object into field text. /// </summary> /// <param name="value">The value to format, which may be null</param> /// <returns>The formatted field text, or <code>null</code> to indicate the value is not present</returns> public virtual string Format(object value) { if (value == null) return null; var fmt = value as IFormattable; if (fmt == null) return value.ToString(); if (Pattern == null) { var dec = Convert.ToDecimal(value); return dec.ToString(Culture); } return fmt.ToString(Pattern.Item2, Culture); } /// <summary> /// Configures this type handler. /// </summary> /// <param name="properties">The properties for customizing the instance</param> public virtual void Configure(Properties properties) { string formatSetting; if (properties.TryGetValue(DefaultTypeConfigurationProperties.FORMAT_SETTING, out formatSetting)) { if (!string.IsNullOrEmpty(formatSetting)) { var parts = formatSetting.Split(new[] { ';' }, 2); var format = parts[0]; var stylesAsString = parts.Length == 2 ? parts[1] : string.Empty; NumberStyles styles; if (string.IsNullOrEmpty(stylesAsString)) { styles = NumberStyles.Number; if (format.IndexOf(',') != -1) styles |= NumberStyles.AllowThousands; if (format.IndexOf('.') != -1) styles |= NumberStyles.AllowDecimalPoint; if (format.IndexOfAny(new[] { 'e', 'E' }) != -1) styles |= NumberStyles.AllowExponent; if (format.IndexOf('-') != -1) styles |= NumberStyles.AllowLeadingSign; if (format.IndexOfAny(new[] { '(', ')' }) != -1) styles |= NumberStyles.AllowParentheses; if (format.IndexOf('$') != -1 || format.IndexOf(Culture.NumberFormat.CurrencySymbol, StringComparison.CurrentCultureIgnoreCase) != -1) styles |= NumberStyles.Currency; var hasDigitPlaceholders = format.IndexOfAny(new[] { '0', '#' }) != -1; if (!hasDigitPlaceholders && styles == NumberStyles.Number && format.IndexOfAny(new[] { 'x', 'X' }) != -1) styles |= NumberStyles.AllowHexSpecifier; } else { styles = (NumberStyles)Enum.Parse(typeof(NumberStyles), stylesAsString, true); } Pattern = Tuple.Create(styles, format); } } string numberType; if (properties.TryGetValue(DefaultTypeConfigurationProperties.NUMBER_TYPE_SETTING, out numberType)) { if (!string.IsNullOrEmpty(numberType)) { TargetType = Type.GetType(numberType, true); } } } /// <summary> /// Parses a string to a number by converting the text first to a decimal number and than /// to the target type. /// </summary> /// <param name="text">The text to convert</param> /// <param name="styles">The number styles to use</param> /// <returns>The parsed number</returns> protected virtual object Parse(string text, NumberStyles styles) { // Parse the number into a System.Decimal. decimal result; if ((styles & NumberStyles.AllowHexSpecifier) == NumberStyles.None) { if (!decimal.TryParse(text, styles, Culture, out result)) throw new TypeConversionException($"Invalid {TargetType} value '{text}'"); } else { long temp; if (!long.TryParse(text, styles, Culture, out temp)) throw new TypeConversionException($"Invalid {TargetType} value '{text}'"); result = temp; } try { // Convert the Decimal to the target type. return CreateNumber(result); } catch (Exception ex) { throw new TypeConversionException($"Invalid {TargetType} value '{text}'", ex); } } /// <summary> /// Parses a number from text. /// </summary> /// <param name="text">The text to convert to a number</param> /// <returns>The parsed number</returns> protected virtual object CreateNumber(string text) { return Parse(text, NumberStyles.Number); } /// <summary> /// Parses a number from a <see cref="decimal"/>. /// </summary> /// <param name="value">The <see cref="decimal"/> to convert to a number</param> /// <returns>The parsed number</returns> protected virtual object CreateNumber(decimal value) { return Convert.ChangeType(value, TargetType, Culture); } } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using BusinessObjects.Common; namespace BusinessObjects.MDSubjects { [Serializable] public partial class cMDSubjects_Enums_Function: CoreBusinessClass<cMDSubjects_Enums_Function> { #region Business Methods public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.String > nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Name { get { return GetProperty(nameProperty); } set { SetProperty(nameProperty, value.Trim()); } } private static readonly PropertyInfo< System.String > labelProperty = RegisterProperty<System.String>(p => p.Label, string.Empty, (System.String)null); public System.String Label { get { return GetProperty(labelProperty); } set { SetProperty(labelProperty, value.Trim()); } } private static readonly PropertyInfo< bool > isManagmentProperty = RegisterProperty<bool>(p => p.IsManagment, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public bool IsManagment { get { return GetProperty(isManagmentProperty); } set { SetProperty(isManagmentProperty, value); } } private static readonly PropertyInfo< bool? > immutableProperty = RegisterProperty<bool?>(p => p.Immutable, string.Empty,(bool?)null); public bool? Immutable { get { return GetProperty(immutableProperty); } set { SetProperty(immutableProperty, value); } } private static readonly PropertyInfo< bool? > inactiveProperty = RegisterProperty<bool?>(p => p.Inactive, string.Empty,(bool?)null); public bool? Inactive { get { return GetProperty(inactiveProperty); } set { SetProperty(inactiveProperty, value); } } private static readonly PropertyInfo< System.Int32? > enumNumberProperty = RegisterProperty<System.Int32?>(p => p.EnumNumber, string.Empty,(System.Int32?)null); public System.Int32? EnumNumber { get { return GetProperty(enumNumberProperty); } set { SetProperty(enumNumberProperty, value); } } protected static readonly PropertyInfo<System.Int32?> companyUsingServiceIdProperty = RegisterProperty<System.Int32?>(p => p.CompanyUsingServiceId, string.Empty); public System.Int32? CompanyUsingServiceId { get { return GetProperty(companyUsingServiceIdProperty); } set { SetProperty(companyUsingServiceIdProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; #endregion #region Factory Methods public static cMDSubjects_Enums_Function NewMDSubjects_Enums_Function() { return DataPortal.Create<cMDSubjects_Enums_Function>(); } public static cMDSubjects_Enums_Function GetMDSubjects_Enums_Function(int uniqueId) { return DataPortal.Fetch<cMDSubjects_Enums_Function>(new SingleCriteria<cMDSubjects_Enums_Function, int>(uniqueId)); } internal static cMDSubjects_Enums_Function GetMDSubjects_Enums_Function(MDSubjects_Enums_Function data) { return DataPortal.Fetch<cMDSubjects_Enums_Function>(data); } public static void DeleteMDSubjects_Enums_Function(int uniqueId) { DataPortal.Delete<cMDSubjects_Enums_Function>(new SingleCriteria<cMDSubjects_Enums_Function, int>(uniqueId)); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Enums_Function, int> criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = ctx.ObjectContext.MDSubjects_Enums_Function.First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<string>(labelProperty, data.Label); LoadProperty<bool>(isManagmentProperty, data.IsManagment); LoadProperty<bool?>(immutableProperty, data.Immutable); LoadProperty<int?>(enumNumberProperty, data.EnumNumber); LoadProperty<bool?>(inactiveProperty, data.Inactive); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } } private void DataPortal_Fetch(MDSubjects_Enums_Function data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<string>(labelProperty, data.Label); LoadProperty<bool>(isManagmentProperty, data.IsManagment); LoadProperty<bool?>(immutableProperty, data.Immutable); LoadProperty<int?>(enumNumberProperty, data.EnumNumber); LoadProperty<bool?>(inactiveProperty, data.Inactive); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); MarkAsChild(); } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Enums_Function(); data.Name = ReadProperty<string>(nameProperty); data.Label = ReadProperty<string>(labelProperty); data.IsManagment = ReadProperty<bool>(isManagmentProperty); data.Immutable = ReadProperty<bool?>(immutableProperty); data.EnumNumber = ReadProperty<int?>(enumNumberProperty); data.Inactive = ReadProperty<bool?>(inactiveProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.AddToMDSubjects_Enums_Function(data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); ctx.ObjectContext.SaveChanges(); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Enums_Function(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Name = ReadProperty<string>(nameProperty); data.Label = ReadProperty<string>(labelProperty); data.IsManagment = ReadProperty<bool>(isManagmentProperty); data.Immutable = ReadProperty<bool?>(immutableProperty); data.EnumNumber = ReadProperty<int?>(enumNumberProperty); data.Inactive = ReadProperty<bool?>(inactiveProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.SaveChanges(); } } [Transactional(TransactionalTypes.TransactionScope)] private void DataPortal_Delete(SingleCriteria<cMDSubjects_Enums_Function, int> criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = ctx.ObjectContext.MDSubjects_Enums_Function.First(p => p.Id == criteria.Value); ctx.ObjectContext.MDSubjects_Enums_Function.DeleteObject(data); ctx.ObjectContext.SaveChanges(); } } #endregion } public partial class cMDSubjects_Enums_Function_List : BusinessListBase<cMDSubjects_Enums_Function_List, cMDSubjects_Enums_Function> { public static cMDSubjects_Enums_Function_List GetcMDSubjects_Enums_Function_List() { return DataPortal.Fetch<cMDSubjects_Enums_Function_List>(); } public static cMDSubjects_Enums_Function_List GetcMDSubjects_Enums_Function_List(int companyId) { return DataPortal.Fetch<cMDSubjects_Enums_Function_List>(new SingleCriteria<cMDSubjects_Enums_Function_List, int>(companyId)); } public static cMDSubjects_Enums_Function_List GetcMDSubjects_Enums_Function_List(int companyId, int includeInactiveId) { return DataPortal.Fetch<cMDSubjects_Enums_Function_List>(new ActiveEnums_Criteria(companyId, includeInactiveId)); } private void DataPortal_Fetch() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_Function; foreach (var data in result) { var obj = cMDSubjects_Enums_Function.GetMDSubjects_Enums_Function(data); this.Add(obj); } } } private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Enums_Function_List, int> criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_Function.Where(p=> p.CompanyUsingServiceId == criteria.Value); foreach (var data in result) { var obj = cMDSubjects_Enums_Function.GetMDSubjects_Enums_Function(data); this.Add(obj); } } } private void DataPortal_Fetch(ActiveEnums_Criteria criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_Function.Where(p => (p.CompanyUsingServiceId == criteria.CompanyId || (p.CompanyUsingServiceId ?? 0) == 0) && ((p.Inactive ?? false) == false || p.Id == criteria.IncludeInactiveId)); foreach (var data in result) { var obj = cMDSubjects_Enums_Function.GetMDSubjects_Enums_Function(data); this.Add(obj); } } } } }
// // LinuxGraphicsContext.cs // // Author: // thefiddler <[email protected]> // // Copyright (c) 2006-2014 // // 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.Diagnostics; using System.Runtime.InteropServices; using OpenTK.Graphics; namespace OpenTK.Platform.Linux { /// \internal /// <summary> /// Defines an IGraphicsContext implementation for the Linux KMS framebuffer. /// For Linux/X11 and other Unix operating systems, use the more generic /// <see cref="OpenTK.Platform.Egl.EglUnixContext"/> instead. /// </summary> /// <remarks> /// Note: to display our results, we need to allocate a GBM framebuffer /// and point the scanout address to that via Drm.ModeSetCrtc. /// </remarks> internal class LinuxGraphicsContext : Egl.EglUnixContext { private BufferObject bo, bo_next; private int fd; private bool is_flip_queued; private int swap_interval; public LinuxGraphicsContext(GraphicsMode mode, LinuxWindowInfo window, IGraphicsContext sharedContext, int major, int minor, GraphicsContextFlags flags) : base(mode, window, sharedContext, major, minor, flags) { if (mode.Buffers < 1) { throw new ArgumentException(); } fd = window.FD; PageFlip = HandlePageFlip; PageFlipPtr = Marshal.GetFunctionPointerForDelegate(PageFlip); } public override void SwapBuffers() { base.SwapBuffers(); if (is_flip_queued) { // Todo: if we don't wait for the page flip, // we drop all rendering buffers and get a crash // in Egl.SwapBuffers(). We need to fix that // before we can disable vsync. WaitFlip(true); // WaitFlip(SwapInterval > 0) if (is_flip_queued) { Debug.Print("[KMS] Dropping frame"); return; } } bo_next = LockSurface(); int fb = GetFramebuffer(bo_next); QueueFlip(fb); } public override void Update(IWindowInfo window) { WaitFlip(true); base.SwapBuffers(); bo = LockSurface(); int fb = GetFramebuffer(bo); SetScanoutRegion(fb); } public override int SwapInterval { get { return swap_interval; } set { // We only support a SwapInterval of 0 (immediate) // or 1 (vsynced). // Todo: add support for SwapInterval of -1 (adaptive). // This requires a small change in WaitFlip(). swap_interval = MathHelper.Clamp(value, 0, 1); } } private void WaitFlip(bool block) { PollFD fds = new PollFD(); fds.fd = fd; fds.events = PollFlags.In; EventContext evctx = new EventContext(); evctx.version = EventContext.Version; evctx.page_flip_handler = PageFlipPtr; int timeout = block ? -1 : 0; while (is_flip_queued) { fds.revents = 0; if (Libc.poll(ref fds, 1, timeout) < 0) { break; } if ((fds.revents & (PollFlags.Hup | PollFlags.Error)) != 0) { break; } if ((fds.revents & PollFlags.In) != 0) { Drm.HandleEvent(fd, ref evctx); } else { break; } } // Page flip has taken place, update buffer objects if (!is_flip_queued) { IntPtr gbm_surface = WindowInfo.Handle; Gbm.ReleaseBuffer(gbm_surface, bo); bo = bo_next; } } private void QueueFlip(int buffer) { LinuxWindowInfo wnd = WindowInfo as LinuxWindowInfo; if (wnd == null) { throw new InvalidOperationException(); } unsafe { int ret = Drm.ModePageFlip(fd, wnd.DisplayDevice.Id, buffer, PageFlipFlags.FlipEvent, IntPtr.Zero); if (ret < 0) { Debug.Print("[KMS] Failed to enqueue framebuffer flip. Error: {0}", ret); } is_flip_queued = true; } } private void SetScanoutRegion(int buffer) { LinuxWindowInfo wnd = WindowInfo as LinuxWindowInfo; if (wnd == null) { throw new InvalidOperationException(); } unsafe { ModeInfo* mode = wnd.DisplayDevice.pConnector->modes; int connector_id = wnd.DisplayDevice.pConnector->connector_id; int crtc_id = wnd.DisplayDevice.Id; int x = 0; int y = 0; int connector_count = 1; int ret = Drm.ModeSetCrtc(fd, crtc_id, buffer, x, y, &connector_id, connector_count, mode); if (ret != 0) { Debug.Print("[KMS] Drm.ModeSetCrtc{0}, {1}, {2}, {3}, {4:x}, {5}, {6:x}) failed. Error: {7}", fd, crtc_id, buffer, x, y, (IntPtr)connector_id, connector_count, (IntPtr)mode, ret); } } } private BufferObject LockSurface() { IntPtr gbm_surface = WindowInfo.Handle; return Gbm.LockFrontBuffer(gbm_surface); } private int GetFramebuffer(BufferObject bo) { if (bo == BufferObject.Zero) { goto fail; } int bo_handle = bo.Handle; if (bo_handle == 0) { Debug.Print("[KMS] Gbm.BOGetHandle({0:x}) failed.", bo); goto fail; } int width = bo.Width; int height = bo.Height; int bpp = Mode.ColorFormat.BitsPerPixel; int depth = Mode.Depth; int stride = bo.Stride; if (width == 0 || height == 0 || bpp == 0) { Debug.Print("[KMS] Invalid framebuffer format: {0}x{1} {2} {3} {4}", width, height, stride, bpp, depth); goto fail; } int buffer; int ret = Drm.ModeAddFB( fd, width, height, (byte)depth, (byte)bpp, stride, bo_handle, out buffer); if (ret != 0) { Debug.Print("[KMS] Drm.ModeAddFB({0}, {1}, {2}, {3}, {4}, {5}, {6}) failed. Error: {7}", fd, width, height, depth, bpp, stride, bo_handle, ret); goto fail; } bo.SetUserData((IntPtr)buffer, DestroyFB); return buffer; fail: Debug.Print("[Error] Failed to create framebuffer."); return -1; } private readonly IntPtr PageFlipPtr; private readonly PageFlipCallback PageFlip; private void HandlePageFlip(int fd, int sequence, int tv_sec, int tv_usec, IntPtr user_data) { is_flip_queued = false; } private static readonly DestroyUserDataCallback DestroyFB = HandleDestroyFB; private static void HandleDestroyFB(BufferObject bo, IntPtr data) { IntPtr gbm = bo.Device; int fb = data.ToInt32(); Debug.Print("[KMS] Destroying framebuffer {0}", fb); if (fb != 0) { Drm.ModeRmFB(Gbm.DeviceGetFD(gbm), fb); } } protected override void Dispose(bool manual) { if (manual) { // Reset the scanout region LinuxWindowInfo wnd = WindowInfo as LinuxWindowInfo; if (wnd != null) { unsafe { int connector_id = wnd.DisplayDevice.pConnector->connector_id; ModeInfo mode = wnd.DisplayDevice.OriginalMode; Drm.ModeSetCrtc(fd, wnd.DisplayDevice.pCrtc->crtc_id, wnd.DisplayDevice.pCrtc->buffer_id, wnd.DisplayDevice.pCrtc->x, wnd.DisplayDevice.pCrtc->y, &connector_id, 1, &mode); } } } base.Dispose(manual); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // StrongNameMembershipCondition.cs // // <OWNER>[....]</OWNER> // // Implementation of membership condition for zones // namespace System.Security.Policy { using System.Text; using System.Configuration.Assemblies; using System; using SecurityManager = System.Security.SecurityManager; using StrongNamePublicKeyBlob = System.Security.Permissions.StrongNamePublicKeyBlob; using PermissionSet = System.Security.PermissionSet; using SecurityElement = System.Security.SecurityElement; using System.Collections; using System.Globalization; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] sealed public class StrongNameMembershipCondition : IMembershipCondition, IConstantMembershipCondition, IReportMatchMembershipCondition { //------------------------------------------------------ // // PRIVATE STATE DATA // //------------------------------------------------------ private StrongNamePublicKeyBlob m_publicKeyBlob; private String m_name; private Version m_version; private SecurityElement m_element; //------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ internal StrongNameMembershipCondition() { } public StrongNameMembershipCondition( StrongNamePublicKeyBlob blob, String name, Version version ) { if (blob == null) throw new ArgumentNullException( "blob" ); if (name != null && name.Equals( "" )) throw new ArgumentException( Environment.GetResourceString( "Argument_EmptyStrongName" ) ); Contract.EndContractBlock(); m_publicKeyBlob = blob; m_name = name; m_version = version; } //------------------------------------------------------ // // PUBLIC ACCESSOR METHODS // //------------------------------------------------------ public StrongNamePublicKeyBlob PublicKey { set { if (value == null) throw new ArgumentNullException( "PublicKey" ); Contract.EndContractBlock(); m_publicKeyBlob = value; } get { if (m_publicKeyBlob == null && m_element != null) ParseKeyBlob(); return m_publicKeyBlob; } } public String Name { set { if (value == null) { if (m_publicKeyBlob == null && m_element != null) ParseKeyBlob(); if ((Object) m_version == null && m_element != null) ParseVersion(); m_element = null; } else if (value.Length == 0) throw new ArgumentException( Environment.GetResourceString("Argument_EmptyName" )); m_name = value; } get { if (m_name == null && m_element != null) ParseName(); return m_name; } } public Version Version { set { if (value == null) { if (m_name == null && m_element != null) ParseName(); if (m_publicKeyBlob == null && m_element != null) ParseKeyBlob(); m_element = null; } m_version = value; } get { if ((Object) m_version == null && m_element != null) ParseVersion(); return m_version; } } //------------------------------------------------------ // // IMEMBERSHIPCONDITION IMPLEMENTATION // //------------------------------------------------------ public bool Check( Evidence evidence ) { object usedEvidence = null; return (this as IReportMatchMembershipCondition).Check(evidence, out usedEvidence); } bool IReportMatchMembershipCondition.Check(Evidence evidence, out object usedEvidence) { usedEvidence = null; if (evidence == null) return false; StrongName name = evidence.GetDelayEvaluatedHostEvidence<StrongName>(); if (name != null) { bool publicKeyMatch = PublicKey != null && PublicKey.Equals(name.PublicKey); bool nameMatch = Name == null || (name.Name != null && StrongName.CompareNames(name.Name, Name)); bool versionMatch = (object)Version == null || ((object)name.Version != null && name.Version.CompareTo(Version) == 0); if (publicKeyMatch && nameMatch && versionMatch) { // Note that we explicitly do not want to mark the strong name evidence as used at // this point, since we could be a child code group where our parent provides more // trust than we do. For instance, if we're in a setup like this: // // AllCode -> FullTrust // StrongName -> FullTrust // // the StrongName code group didn't add anything to the final grant set and therefore // does not need to be evaluated. usedEvidence = name; return true; } } return false; } private const String s_tagName = "Name"; private const String s_tagVersion = "AssemblyVersion"; private const String s_tagPublicKeyBlob = "PublicKeyBlob"; public IMembershipCondition Copy() { return new StrongNameMembershipCondition( PublicKey, Name, Version); } public SecurityElement ToXml() { return ToXml( null ); } public void FromXml( SecurityElement e ) { FromXml( e, null ); } public SecurityElement ToXml( PolicyLevel level ) { SecurityElement root = new SecurityElement( "IMembershipCondition" ); System.Security.Util.XMLUtil.AddClassAttribute( root, this.GetType(), "System.Security.Policy.StrongNameMembershipCondition" ); // If you hit this assert then most likely you are trying to change the name of this class. // This is ok as long as you change the hard coded string above and change the assert below. Contract.Assert( this.GetType().FullName.Equals( "System.Security.Policy.StrongNameMembershipCondition" ), "Class name changed!" ); root.AddAttribute( "version", "1" ); if (PublicKey != null) root.AddAttribute( s_tagPublicKeyBlob, System.Security.Util.Hex.EncodeHexString( PublicKey.PublicKey ) ); if (Name != null) root.AddAttribute( s_tagName, Name ); if ((Object) Version != null) root.AddAttribute( s_tagVersion, Version.ToString() ); return root; } public void FromXml( SecurityElement e, PolicyLevel level ) { if (e == null) throw new ArgumentNullException("e"); if (!e.Tag.Equals( "IMembershipCondition" )) { throw new ArgumentException( Environment.GetResourceString( "Argument_MembershipConditionElement" ) ); } Contract.EndContractBlock(); lock (this) { m_name = null; m_publicKeyBlob = null; m_version = null; m_element = e; } } private void ParseName() { lock (this) { if (m_element == null) return; String elSite = m_element.Attribute( s_tagName ); m_name = elSite == null ? null : elSite; if ((Object) m_version != null && m_name != null && m_publicKeyBlob != null) { m_element = null; } } } private void ParseKeyBlob() { lock (this) { if (m_element == null) return; String elBlob = m_element.Attribute( s_tagPublicKeyBlob ); StrongNamePublicKeyBlob publicKeyBlob = new StrongNamePublicKeyBlob(); if (elBlob != null) publicKeyBlob.PublicKey = System.Security.Util.Hex.DecodeHexString( elBlob ); else throw new ArgumentException( Environment.GetResourceString( "Argument_BlobCannotBeNull" ) ); m_publicKeyBlob = publicKeyBlob; if ((Object) m_version != null && m_name != null && m_publicKeyBlob != null) { m_element = null; } } } private void ParseVersion() { lock (this) { if (m_element == null) return; String elVersion = m_element.Attribute( s_tagVersion ); m_version = elVersion == null ? null : new Version( elVersion ); if ((Object) m_version != null && m_name != null && m_publicKeyBlob != null) { m_element = null; } } } public override String ToString() { String sName = ""; String sVersion = ""; if (Name != null) sName = " " + String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "StrongName_Name" ), Name ); if ((Object) Version != null) sVersion = " " + String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "StrongName_Version" ), Version ); return String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString( "StrongName_ToString" ), System.Security.Util.Hex.EncodeHexString( PublicKey.PublicKey ), sName, sVersion ); } public override bool Equals( Object o ) { StrongNameMembershipCondition that = (o as StrongNameMembershipCondition); if (that != null) { if (this.m_publicKeyBlob == null && this.m_element != null) this.ParseKeyBlob(); if (that.m_publicKeyBlob == null && that.m_element != null) that.ParseKeyBlob(); if (Equals( this.m_publicKeyBlob, that.m_publicKeyBlob )) { if (this.m_name == null && this.m_element != null) this.ParseName(); if (that.m_name == null && that.m_element != null) that.ParseName(); if (Equals( this.m_name, that.m_name )) { if (this.m_version == null && this.m_element != null) this.ParseVersion(); if (that.m_version == null && that.m_element != null) that.ParseVersion(); if ( Equals( this.m_version, that.m_version )) { return true; } } } } return false; } public override int GetHashCode() { if (m_publicKeyBlob == null && m_element != null) ParseKeyBlob(); if (m_publicKeyBlob != null) { return m_publicKeyBlob.GetHashCode(); } else { if (m_name == null && m_element != null) ParseName(); if (m_version == null && m_element != null) ParseVersion(); if (m_name != null || m_version != null) { return (m_name == null ? 0 : m_name.GetHashCode()) + (m_version == null ? 0 : m_version.GetHashCode()); } else { return typeof( StrongNameMembershipCondition ).GetHashCode(); } } } } }
//----------------------------------------------------------------------- // <copyright file="InstantPreviewManager.cs" company="Google"> // // Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using GoogleARCore; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SpatialTracking; #if UNITY_EDITOR using UnityEditor; #endif #if UNITY_IOS using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif /// <summary> /// Contains methods for managing communication to the Instant Preview /// plugin. /// </summary> public static class InstantPreviewManager { /// <summary> /// Name of the Instant Preview plugin library. /// </summary> public const string InstantPreviewNativeApi = "instant_preview_unity_plugin"; // Guid is taken from meta file and should never change. private const string k_ApkGuid = "cf7b10762fe921e40a18151a6c92a8a6"; private const string k_NoDevicesFoundAdbResult = "error: no devices/emulators found"; private const float k_MaxTolerableAspectRatioDifference = 0.1f; private const string k_MismatchedAspectRatioWarningFormatString = "The aspect ratio of your game window is different from the aspect ratio of your Instant Preview camera " + "texture. Please resize your game window's aspect ratio to match, or your preview will be distorted. The " + "camera texture resolution is {0}, {1}."; private static readonly WaitForEndOfFrame k_WaitForEndOfFrame = new WaitForEndOfFrame(); private static bool s_PauseWarned = false; private static bool s_DisabledLightEstimationWarned = false; private static bool s_DisabledPlaneFindingWarned = false; /// <summary> /// Coroutine method that communicates to the Instant Preview plugin /// every frame. /// /// If not running in the editor, this does nothing. /// </summary> /// <returns>Enumerator for a coroutine that updates Instant Preview /// every frame.</returns> public static IEnumerator InitializeIfNeeded() { // Terminates if not running in editor. if (!Application.isEditor) { yield break; } // User may have explicitly disabled Instant Preview. if (ARCoreProjectSettings.Instance != null && !ARCoreProjectSettings.Instance.IsInstantPreviewEnabled) { yield break; } #if UNITY_EDITOR // Determine if any augmented image databases need a rebuild. List<AugmentedImageDatabase> databases = new List<AugmentedImageDatabase>(); bool shouldRebuild = false; var augmentedImageDatabaseGuids = AssetDatabase.FindAssets("t:AugmentedImageDatabase"); foreach (var databaseGuid in augmentedImageDatabaseGuids) { var database = AssetDatabase.LoadAssetAtPath<AugmentedImageDatabase>( AssetDatabase.GUIDToAssetPath(databaseGuid)); databases.Add(database); shouldRebuild = shouldRebuild || database.IsBuildNeeded(); } // If the preference is to ask the user to rebuild, ask now. if (shouldRebuild && PromptToRebuildAugmentedImagesDatabase()) { foreach (var database in databases) { string error; database.BuildIfNeeded(out error); if (!string.IsNullOrEmpty(error)) { Debug.LogWarning("Failed to rebuild augmented " + "image database: " + error); } } } #endif var adbPath = InstantPreviewManager.GetAdbPath(); if (adbPath == null) { Debug.LogError("Instant Preview requires your Unity Android SDK path to be set. Please set it under " + "'Preferences > External Tools > Android'. You may need to install the Android SDK first."); yield break; } else if (!File.Exists(adbPath)) { Debug.LogErrorFormat("adb not found at \"{0}\". Please add adb to your SDK path and restart the Unity editor.", adbPath); yield break; } string localVersion; if (!StartServer(adbPath, out localVersion)) { yield break; } yield return InstallApkAndRunIfConnected(adbPath, localVersion); yield return UpdateLoop(adbPath); } /// <summary> /// Uploads the latest camera video frame received from Instant Preview /// to the specified texture. The texture might be recreated if it is /// not the right size or null. /// </summary> /// <param name="backgroundTexture">Texture variable to store the latest /// Instant Preview video frame.</param> /// <returns>True if InstantPreview updated the background texture, /// false if it did not and the texture still needs updating.</returns> public static bool UpdateBackgroundTextureIfNeeded(ref Texture2D backgroundTexture) { if (!Application.isEditor) { return false; } IntPtr pixelBytes; int width; int height; if (NativeApi.LockCameraTexture(out pixelBytes, out width, out height)) { if (backgroundTexture == null || width != backgroundTexture.width || height != backgroundTexture.height) { backgroundTexture = new Texture2D(width, height, TextureFormat.BGRA32, false); } backgroundTexture.LoadRawTextureData(pixelBytes, width * height * 4); backgroundTexture.Apply(); NativeApi.UnlockCameraTexture(); } return true; } /// <summary> /// Handles Instant Preview logic when ARCore's EarlyUpdate method is called. /// </summary> public static void OnEarlyUpdate() { var session = LifecycleManager.Instance.SessionComponent; if (Application.isEditor || session == null) { return; } if (!s_PauseWarned && !session.enabled) { Debug.LogWarning("Disabling ARCore session is not available in editor."); s_PauseWarned = true; } var config = session.SessionConfig; if (config == null) { return; } if (!s_DisabledLightEstimationWarned && !config.EnableLightEstimation) { Debug.LogWarning("ARCore light estimation cannot be disabled in editor."); s_DisabledLightEstimationWarned = true; } if (!s_DisabledPlaneFindingWarned && config.PlaneFindingMode == DetectedPlaneFindingMode.Disabled) { Debug.LogWarning("ARCore plane finding cannot be disabled in editor."); s_DisabledPlaneFindingWarned = true; } } private static IEnumerator UpdateLoop(string adbPath) { var renderEventFunc = NativeApi.GetRenderEventFunc(); var shouldConvertToBgra = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11; var loggedAspectRatioWarning = false; // Waits until the end of the first frame until capturing the screen size, // because it might be incorrect when first querying it. yield return k_WaitForEndOfFrame; var currentWidth = 0; var currentHeight = 0; var needToStartActivity = true; var prevFrameLandscape = false; RenderTexture screenTexture = null; RenderTexture targetTexture = null; RenderTexture bgrTexture = null; // Begins update loop. The coroutine will cease when the // ARCoreSession component it's called from is destroyed. for (;;) { yield return k_WaitForEndOfFrame; var curFrameLandscape = Screen.width > Screen.height; if (prevFrameLandscape != curFrameLandscape) { needToStartActivity = true; } prevFrameLandscape = curFrameLandscape; if (needToStartActivity) { string activityName = curFrameLandscape ? "InstantPreviewLandscapeActivity" : "InstantPreviewActivity"; string output; string errors; ShellHelper.RunCommand(adbPath, "shell am start -S -n com.google.ar.core.instantpreview/." + activityName, out output, out errors); needToStartActivity = false; } // Creates a target texture to capture the preview window onto. // Some video encoders prefer the dimensions to be a multiple of 16. var targetWidth = RoundUpToNearestMultipleOf16(Screen.width); var targetHeight = RoundUpToNearestMultipleOf16(Screen.height); if (targetWidth != currentWidth || targetHeight != currentHeight) { screenTexture = new RenderTexture(targetWidth, targetHeight, 0); targetTexture = screenTexture; if (shouldConvertToBgra) { bgrTexture = new RenderTexture(screenTexture.width, screenTexture.height, 0, RenderTextureFormat.BGRA32); targetTexture = bgrTexture; } currentWidth = targetWidth; currentHeight = targetHeight; } NativeApi.Update(); InstantPreviewInput.Update(); AddInstantPreviewTrackedPoseDriverWhenNeeded(); Graphics.Blit(null, screenTexture); if (shouldConvertToBgra) { Graphics.Blit(screenTexture, bgrTexture); } var cameraTexture = Frame.CameraImage.Texture; if (!loggedAspectRatioWarning && cameraTexture != null) { var sourceWidth = cameraTexture.width; var sourceHeight = cameraTexture.height; var sourceAspectRatio = (float)sourceWidth / sourceHeight; var destinationWidth = Screen.width; var destinationHeight = Screen.height; var destinationAspectRatio = (float)destinationWidth / destinationHeight; if (Mathf.Abs(sourceAspectRatio - destinationAspectRatio) > k_MaxTolerableAspectRatioDifference) { Debug.LogWarningFormat(k_MismatchedAspectRatioWarningFormatString, sourceWidth, sourceHeight); loggedAspectRatioWarning = true; } } NativeApi.SendFrame(targetTexture.GetNativeTexturePtr()); GL.IssuePluginEvent(renderEventFunc, 1); } } private static void AddInstantPreviewTrackedPoseDriverWhenNeeded() { foreach (var poseDriver in Component.FindObjectsOfType<TrackedPoseDriver>()) { poseDriver.enabled = false; var gameObject = poseDriver.gameObject; var hasInstantPreviewTrackedPoseDriver = gameObject.GetComponent<InstantPreviewTrackedPoseDriver>() != null; if (!hasInstantPreviewTrackedPoseDriver) { gameObject.AddComponent<InstantPreviewTrackedPoseDriver>(); } } } private static string GetAdbPath() { string sdkRoot = null; #if UNITY_EDITOR // Gets adb path and starts instant preview server. sdkRoot = UnityEditor.EditorPrefs.GetString("AndroidSdkRoot"); #endif // UNITY_EDITOR if (string.IsNullOrEmpty(sdkRoot)) { return null; } // Gets adb path from known directory. var adbPath = Path.Combine(Path.GetFullPath(sdkRoot), "platform-tools" + Path.DirectorySeparatorChar + "adb"); if (Application.platform == RuntimePlatform.WindowsEditor) { adbPath = Path.ChangeExtension(adbPath, "exe"); } return adbPath; } /// <summary> /// Tries to install and run the Instant Preview android app. /// </summary> /// <param name="adbPath">Path to adb to use for installing.</param> /// <param name="localVersion">Local version of Instant Preview plugin to compare installed APK against.</param> /// <returns>Enumerator for coroutine that handles installation if necessary.</returns> private static IEnumerator InstallApkAndRunIfConnected(string adbPath, string localVersion) { string apkPath = null; #if UNITY_EDITOR apkPath = UnityEditor.AssetDatabase.GUIDToAssetPath(k_ApkGuid); #endif // !UNITY_EDITOR // Early outs if set to install but the apk can't be found. if (!File.Exists(apkPath)) { Debug.LogErrorFormat("Trying to install Instant Preview APK but reference to InstantPreview.apk is " + "broken. Couldn't find an asset with .meta file guid={0}.", k_ApkGuid); yield break; } Result result = new Result(); Thread checkAdbThread = new Thread((object obj) => { Result res = (Result)obj; string output; string errors; // Gets version of installed apk. ShellHelper.RunCommand(adbPath, "shell dumpsys package com.google.ar.core.instantpreview | grep versionName", out output, out errors); string installedVersion = null; if (!string.IsNullOrEmpty(output) && string.IsNullOrEmpty(errors)) { installedVersion = output.Substring(output.IndexOf('=') + 1); } // Early outs if no device is connected. if (string.Compare(errors, k_NoDevicesFoundAdbResult) == 0) { return; } // Prints errors and exits on failure. if (!string.IsNullOrEmpty(errors)) { Debug.LogError(errors); return; } if (installedVersion == null) { Debug.LogFormat( "Instant Preview app not installed on device.", apkPath); } else if (installedVersion != localVersion) { Debug.LogFormat( "Instant Preview installed version \"{0}\" does not match local version \"{1}\".", installedVersion, localVersion); } res.ShouldPromptForInstall = installedVersion != localVersion; }); checkAdbThread.Start(result); while (!checkAdbThread.Join(0)) { yield return 0; } if (result.ShouldPromptForInstall) { if (PromptToInstall()) { Thread installThread = new Thread(() => { string output; string errors; Debug.LogFormat( "Installing Instant Preview app version {0}.", localVersion); ShellHelper.RunCommand(adbPath, string.Format("uninstall com.google.ar.core.instantpreview", apkPath), out output, out errors); ShellHelper.RunCommand(adbPath, string.Format("install \"{0}\"", apkPath), out output, out errors); // Prints any output from trying to install. if (!string.IsNullOrEmpty(output)) { Debug.LogFormat("Instant Preview installation\n{0}", output); } if (!string.IsNullOrEmpty(errors)) { Debug.LogErrorFormat("Failed to install Instant Preview app:\n{0}", errors); } }); installThread.Start(); while (!installThread.Join(0)) { yield return 0; } } else { yield break; } } } private static bool PromptToInstall() { #if UNITY_EDITOR return UnityEditor.EditorUtility.DisplayDialog("Instant Preview", "To instantly reflect your changes on device, the " + "Instant Preview app will be installed on your " + "connected device.\n\nTo disable Instant Preview, " + "uncheck 'Instant Preview Enabled' under 'Edit > Project Settings > ARCore'.", "Okay", "Don't Install This Time"); #else return false; #endif } private static bool PromptToRebuildAugmentedImagesDatabase() { #if UNITY_EDITOR return UnityEditor.EditorUtility.DisplayDialog("Augmented Images", "The Augmented Images database is out of date, " + "rebuild it now?", "Build", "Don't Build This Time"); #else return false; #endif } private static bool StartServer(string adbPath, out string version) { // Tries to start server. const int k_InstantPreviewVersionStringMaxLength = 64; var versionStringBuilder = new StringBuilder(k_InstantPreviewVersionStringMaxLength); var started = NativeApi.InitializeInstantPreview(adbPath, versionStringBuilder, versionStringBuilder.Capacity); if (!started) { Debug.LogErrorFormat("Couldn't start Instant Preview server with adb path \"{0}\".", adbPath); version = null; return false; } version = versionStringBuilder.ToString(); Debug.LogFormat("Instant Preview version {0}\n" + "To disable Instant Preview, " + "uncheck 'Instant Preview Enabled' under 'Edit > Project Settings > ARCore'.", version); return true; } private static int RoundUpToNearestMultipleOf16(int value) { return (value + 15) & ~15; } private struct NativeApi { #pragma warning disable 626 [AndroidImport(InstantPreviewNativeApi)] public static extern bool InitializeInstantPreview( string adbPath, StringBuilder version, int versionStringLength); [AndroidImport(InstantPreviewNativeApi)] public static extern void Update(); [AndroidImport(InstantPreviewNativeApi)] public static extern IntPtr GetRenderEventFunc(); [AndroidImport(InstantPreviewNativeApi)] public static extern void SendFrame(IntPtr renderTexture); [AndroidImport(InstantPreviewNativeApi)] public static extern bool LockCameraTexture(out IntPtr pixelBytes, out int width, out int height); [AndroidImport(InstantPreviewNativeApi)] public static extern void UnlockCameraTexture(); [AndroidImport(InstantPreviewNativeApi)] public static extern bool IsConnected(); #pragma warning restore 626 } private class Result { public bool ShouldPromptForInstall = false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Its.Log.Instrumentation.Extensions; namespace Its.Log.Instrumentation { internal class ExpandAllList : List<object> { static ExpandAllList() { Formatter<ExpandAllList>.ListExpansionLimit = 100; } public ExpandAllList(IEnumerable<object> collection) : base(collection) { } } /// <summary> /// A series of associated events. /// </summary> public class LogActivity : ILogActivity { private readonly LogEntry entry; private List<Delegate> paramsAccessors; private int isCompletedFlag; private bool requireConfirm = false; private bool confirmed = false; private readonly Queue<LogEntry> buffer; private HashSet<Confirmation> confirmations; /// <summary> /// Initializes a new instance of the <see cref="LogActivity"/> class. /// </summary> /// <param name="entry">The entry.</param> public LogActivity(LogEntry entry, bool requireConfirm = false) { entry.EventType = TraceEventType.Start; this.entry = entry; // TODO: (LogActivity) generalize extensions that are triggered on boundary enter if (Extension<Counter>.IsEnabledFor(entry.CallingType)) { Counter.For(entry.CallingType, entry.CallingMethod).Increment(); } this.requireConfirm = requireConfirm; if (requireConfirm) { buffer = new Queue<LogEntry>(); } Write(entry); StartTiming(); } /// <summary> /// Completes the current activity. /// </summary> public void Complete(Action magicBarbell) { if (Interlocked.CompareExchange(ref isCompletedFlag, 1, 0) != 0) { return; } if (magicBarbell != null) { entry.Message = null; entry.AnonymousMethodInfo = magicBarbell.GetAnonymousMethodInfo(); } var clone = entry.Clone(false); clone.EventType = TraceEventType.Stop; // TODO: (Complete) generalize extensions that are triggered on boundary exit if (clone.HasExtension<Stopwatch>()) { var watch = entry.GetExtension<Stopwatch>(); watch.Stop(); } if (confirmations != null) { var extension = Log.WithParams(() => new { Confirmed = new ExpandAllList(confirmations.Select(v => v.Accessor() )) }); extension.ApplyTo(clone); } Write(clone); } /// <summary> /// Writes out buffered entries in a log activity that was entered with requireConfirm set to true. /// </summary> public void Confirm(Func<object> value = null) { confirmed = true; value = value ?? (() => true); if (confirmations == null) { confirmations = new HashSet<Confirmation>(new ConfirmationEqualityComparer()); } long elapsedMilliseconds = 0; var stopwatch = entry.GetExtension<Stopwatch>(); if (stopwatch != null) { elapsedMilliseconds = stopwatch.ElapsedMilliseconds; } confirmations.Add(new Confirmation { Accessor = value, ElapsedMilliseconds = elapsedMilliseconds }); if (requireConfirm) { requireConfirm = false; while (buffer.Count > 0) { Log.Write(buffer.Dequeue()); } } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Complete(null); } /// <summary> /// Gets a value indicating whether this activity is completed. /// </summary> /// <value> /// <c>true</c> if this instance is completed; otherwise, <c>false</c>. /// </value> public bool IsCompleted { get { return isCompletedFlag == 1; } } /// <summary> /// Writes a log message associated with the current activity. /// </summary> public void Trace(string comment) { if (IsCompleted) { return; } var clone = entry.Clone(false); clone.EventType = TraceEventType.Verbose; clone.Message = comment; if (paramsAccessors != null) { foreach (var accessor in paramsAccessors) { entry.AddInfo("Traced", accessor.DynamicInvoke()); } } Write(clone); } /// <summary> /// Logs variables associated with the current activity. /// </summary> public void Trace<T>(Func<T> paramsAccessor) where T : class { TraceInner(paramsAccessor, false); } /// <summary> /// Logs variables associated with the current activity and registers them to be logged again each time additional events are logged in the activity, so that their updated values will be recorded. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="paramsAccessor"></param> public void TraceAndWatch<T>(Func<T> paramsAccessor) where T : class { if (paramsAccessors == null) { paramsAccessors = new List<Delegate>(); } paramsAccessors.Add(paramsAccessor); TraceInner(paramsAccessor, true); } private void TraceInner<T>(Func<T> paramsAccessor, bool deepClone) where T : class { if (IsCompleted) { return; } var clone = entry.Clone(deepClone); clone.AnonymousMethodInfo = paramsAccessor.GetAnonymousMethodInfo(); clone.EventType = TraceEventType.Verbose; var extension = Log.WithParams(paramsAccessor); extension.ApplyTo(clone); Write(clone); } /// <summary> /// Starts the stopwatch if one is enabled. /// </summary> private void StartTiming() { if (Extension<Stopwatch>.IsEnabledFor(entry.CallingType)) { entry.AddExtension<Stopwatch>().Start(); } } private void Write(LogEntry entry) { if (requireConfirm) { buffer.Enqueue(entry); } else { Log.Write(entry); } } private struct Confirmation { public Func<object> Accessor { get { return accessor; } set { accessor = value; } } public long ElapsedMilliseconds; private Func<object> accessor; } private class ConfirmationEqualityComparer : IEqualityComparer<Confirmation> { public bool Equals(Confirmation x, Confirmation y) { return x.Accessor.Method == y.Accessor.Method; } public int GetHashCode(Confirmation obj) { return obj.Accessor.Method.GetHashCode(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; using System.Threading.Tasks; using Infrastructure.Common; using Xunit; public static partial class ClientBaseTests { [WcfFact] [OuterLoop] public static void MessageProperty_HttpRequestMessageProperty_RoundTrip_Verify() { MyClientBase<IWcfService> client = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase<IWcfService>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); client.Endpoint.EndpointBehaviors.Add(new ClientMessagePropertyBehavior()); serviceProxy = client.ChannelFactory.CreateChannel(); // *** EXECUTE *** \\ TestHttpRequestMessageProperty property = serviceProxy.EchoHttpRequestMessageProperty(); // *** VALIDATE *** \\ Assert.NotNull(property); Assert.True(property.SuppressEntityBody == false, "Expected SuppressEntityBody to be 'false'"); Assert.Equal("POST", property.Method); Assert.Equal("My%20address", property.QueryString); Assert.True(property.Headers.Count > 0, "TestHttpRequestMessageProperty.Headers should not have empty headers"); Assert.Equal("my value", property.Headers["customer"]); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientMessageInspector_Verify_Invoke() { // This test verifies ClientMessageInspector can be added to the client endpoint behaviors // and this is it called properly when a message is sent. MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); // Add the ClientMessageInspector and give it an instance where it can record what happens when it is called. ClientMessageInspectorData data = new ClientMessageInspectorData(); client.Endpoint.EndpointBehaviors.Add(new ClientMessageInspectorBehavior(data)); serviceProxy = client.ChannelFactory.CreateChannel(); // *** EXECUTE *** \\ // This proxy call should invoke the client message inspector string result = serviceProxy.Echo("Hello"); // *** VALIDATE *** \\ Assert.Equal("Hello", result); Assert.True(data.BeforeSendRequestCalled, "BeforeSendRequest should have been called"); Assert.True(data.Request != null, "Did not call pass Request to BeforeSendRequest"); Assert.True(data.Channel != null, "Did not call pass Channel to BeforeSendRequest"); Assert.True(data.AfterReceiveReplyCalled, "AfterReceiveReplyCalled should have been called"); Assert.True(data.Reply != null, "Did not call pass Reply to AfterReceiveReplyCalled"); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Sync_RoundTrip_Check_CommunicationState() { MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase(customBinding, new EndpointAddress(Endpoints.HttpSoap12_Address)); // *** VALIDATE *** \\ Assert.Equal(CommunicationState.Created, client.State); serviceProxy = client.ChannelFactory.CreateChannel(); // *** VALIDATE *** \\ Assert.Equal(CommunicationState.Opened, client.State); // *** EXECUTE *** \\ string result = serviceProxy.Echo("Hello"); // *** VALIDATE *** \\ Assert.Equal(CommunicationState.Opened, client.State); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); // *** VALIDATE *** \\ Assert.Equal(CommunicationState.Closed, client.State); } finally { // normally we'd also check for if (client != null && client.State != CommunicationState.Closed), // but this is a test and it'd be good to have the Abort happen and the channel is still Closed if (client != null) { client.Abort(); Assert.Equal(CommunicationState.Closed, client.State); } // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Sync_Open_Close_Factory_And_Proxy_CommunicationState() { MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; ChannelFactory<IWcfServiceGenerated> factory = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); string endpoint = Endpoints.HttpSoap12_Address; client = new MyClientBase(customBinding, new EndpointAddress(endpoint)); factory = client.ChannelFactory; // *** VALIDATE *** \\ Assert.True(CommunicationState.Created == client.State, String.Format("Expected client state to be Created but actual was '{0}'", client.State)); Assert.True(CommunicationState.Created == factory.State, String.Format("Expected channel factory state to be Created but actual was '{0}'", factory.State)); // Note: both the full framework and this NET Core version open the channel factory // when asking for the internal channel. Attempting to Open the ClientBase // after obtaining the internal channel with throw InvalidOperationException attempting // to reopen the channel factory. Customers don't encounter this situation in normal use // because access to the internal channel is protected and cannot be acquired. So we // defer asking for the internal channel in this test to allow the Open() to follow the // same code path as customer code. // *** EXECUTE *** \\ // Explicitly open the ClientBase to follow general WCF guidelines ((ICommunicationObject)client).Open(); // Use the internal proxy generated by ClientBase to most resemble how svcutil-generated code works. // This test defers asking for it until the ClientBase is open to avoid the issue described above. serviceProxy = client.Proxy; Assert.True(CommunicationState.Opened == client.State, String.Format("Expected client state to be Opened but actual was '{0}'", client.State)); Assert.True(CommunicationState.Opened == factory.State, String.Format("Expected channel factory state to be Opened but actual was '{0}'", factory.State)); Assert.True(CommunicationState.Opened == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Opened but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // *** EXECUTE *** \\ // Explicitly close the ClientBase to follow general WCF guidelines ((ICommunicationObject)client).Close(); // *** VALIDATE *** \\ // Closing the ClientBase closes the internal channel and factory Assert.True(CommunicationState.Closed == client.State, String.Format("Expected client state to be Closed but actual was '{0}'", client.State)); // Closing the ClientBase also closes the internal channel Assert.True(CommunicationState.Closed == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Closed but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // Closing the ClientBase also closes the channel factory Assert.True(CommunicationState.Closed == factory.State, String.Format("Expected channel factory state to be Closed but actual was '{0}'", factory.State)); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, client, factory); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Async_Open_Close_Factory_And_Proxy_CommunicationState() { MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; ChannelFactory<IWcfServiceGenerated> factory = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); string endpoint = Endpoints.HttpSoap12_Address; client = new MyClientBase(customBinding, new EndpointAddress(endpoint)); factory = client.ChannelFactory; // *** VALIDATE *** \\ Assert.True(CommunicationState.Created == client.State, String.Format("Expected client state to be Created but actual was '{0}'", client.State)); Assert.True(CommunicationState.Created == factory.State, String.Format("Expected channel factory state to be Created but actual was '{0}'", factory.State)); // Note: both the full framework and this NET Core version open the channel factory // when asking for the internal channel. Attempting to Open the ClientBase // after obtaining the internal channel with throw InvalidOperationException attempting // to reopen the channel factory. Customers don't encounter this situation in normal use // because access to the internal channel is protected and cannot be acquired. So we // defer asking for the internal channel in this test to allow the Open() to follow the // same code path as customer code. // *** EXECUTE *** \\ // Explicitly async open the ClientBase to follow general WCF guidelines IAsyncResult ar = ((ICommunicationObject)client).BeginOpen(null, null); ((ICommunicationObject)client).EndOpen(ar); // Use the internal proxy generated by ClientBase to most resemble how svcutil-generated code works. // This test defers asking for it until the ClientBase is open to avoid the issue described above. serviceProxy = client.Proxy; Assert.True(CommunicationState.Opened == client.State, String.Format("Expected client state to be Opened but actual was '{0}'", client.State)); Assert.True(CommunicationState.Opened == factory.State, String.Format("Expected channel factory state to be Opened but actual was '{0}'", factory.State)); Assert.True(CommunicationState.Opened == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Opened but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // *** EXECUTE *** \\ // Explicitly close the ClientBase to follow general WCF guidelines ar = ((ICommunicationObject)client).BeginClose(null, null); ((ICommunicationObject)client).EndClose(ar); // *** VALIDATE *** \\ // Closing the ClientBase closes the internal channel and factory Assert.True(CommunicationState.Closed == client.State, String.Format("Expected client state to be Closed but actual was '{0}'", client.State)); // Closing the ClientBase also closes the internal channel Assert.True(CommunicationState.Closed == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Closed but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // Closing the ClientBase also closes the channel factory Assert.True(CommunicationState.Closed == factory.State, String.Format("Expected channel factory state to be Closed but actual was '{0}'", factory.State)); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, client, factory); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Async_Open_Close_TimeSpan_Factory_And_Proxy_CommunicationState() { MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; ChannelFactory<IWcfServiceGenerated> factory = null; TimeSpan timeout = ScenarioTestHelpers.TestTimeout; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); string endpoint = Endpoints.HttpSoap12_Address; client = new MyClientBase(customBinding, new EndpointAddress(endpoint)); factory = client.ChannelFactory; // *** VALIDATE *** \\ Assert.True(CommunicationState.Created == client.State, String.Format("Expected client state to be Created but actual was '{0}'", client.State)); Assert.True(CommunicationState.Created == factory.State, String.Format("Expected channel factory state to be Created but actual was '{0}'", factory.State)); // Note: both the full framework and this NET Core version open the channel factory // when asking for the internal channel. Attempting to Open the ClientBase // after obtaining the internal channel with throw InvalidOperationException attempting // to reopen the channel factory. Customers don't encounter this situation in normal use // because access to the internal channel is protected and cannot be acquired. So we // defer asking for the internal channel in this test to allow the Open() to follow the // same code path as customer code. // *** EXECUTE *** \\ // Explicitly async open the ClientBase to follow general WCF guidelines IAsyncResult ar = ((ICommunicationObject)client).BeginOpen(timeout, null, null); ((ICommunicationObject)client).EndOpen(ar); // Use the internal proxy generated by ClientBase to most resemble how svcutil-generated code works. // This test defers asking for it until the ClientBase is open to avoid the issue described above. serviceProxy = client.Proxy; Assert.True(CommunicationState.Opened == client.State, String.Format("Expected client state to be Opened but actual was '{0}'", client.State)); Assert.True(CommunicationState.Opened == factory.State, String.Format("Expected channel factory state to be Opened but actual was '{0}'", factory.State)); Assert.True(CommunicationState.Opened == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Opened but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // *** EXECUTE *** \\ // Explicitly close the ClientBase to follow general WCF guidelines ar = ((ICommunicationObject)client).BeginClose(timeout, null, null); ((ICommunicationObject)client).EndClose(ar); // *** VALIDATE *** \\ // Closing the ClientBase closes the internal channel and factory Assert.True(CommunicationState.Closed == client.State, String.Format("Expected client state to be Closed but actual was '{0}'", client.State)); // Closing the ClientBase also closes the internal channel Assert.True(CommunicationState.Closed == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Closed but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // Closing the ClientBase also closes the channel factory Assert.True(CommunicationState.Closed == factory.State, String.Format("Expected channel factory state to be Closed but actual was '{0}'", factory.State)); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, client, factory); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Abort_Aborts_Factory_And_Proxy() { MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; ChannelFactory<IWcfServiceGenerated> factory = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); string endpoint = Endpoints.HttpSoap12_Address; client = new MyClientBase(customBinding, new EndpointAddress(endpoint)); factory = client.ChannelFactory; // *** EXECUTE *** \\ // Explicitly open the ClientBase to follow general WCF guidelines ((ICommunicationObject)client).Open(); // Use the internal proxy generated by ClientBase to most resemble how svcutil-generated code works. // Customers cannot normally access this protected member explicitly, but the generated code uses it. serviceProxy = client.Proxy; // *** EXECUTE *** \\ client.Abort(); // *** VALIDATE *** \\ // Closing the ClientBase closes the internal channel and factory Assert.True(CommunicationState.Closed == client.State, String.Format("Expected client state to be Closed but actual was '{0}'", client.State)); // Closing the ClientBase also closes the internal channel Assert.True(CommunicationState.Closed == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Closed but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // Closing the ClientBase also closes the channel factory Assert.True(CommunicationState.Closed == factory.State, String.Format("Expected channel factory state to be Closed but actual was '{0}'", factory.State)); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, client, factory); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Dispose_Closes_Factory_And_Proxy() { MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; ChannelFactory<IWcfServiceGenerated> factory = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); string endpoint = Endpoints.HttpSoap12_Address; client = new MyClientBase(customBinding, new EndpointAddress(endpoint)); factory = client.ChannelFactory; // *** EXECUTE *** \\ // Explicitly open the ClientBase to follow general WCF guidelines ((ICommunicationObject)client).Open(); // Use the internal proxy generated by ClientBase to most resemble how svcutil-generated code works. // Customers cannot normally access this protected member explicitly, but the generated code uses it. serviceProxy = client.Proxy; // *** EXECUTE *** \\ // ClientBase is IDisposable, which should close the client, factory and proxy ((IDisposable)client).Dispose(); // *** VALIDATE *** \\ // Closing the ClientBase closes the internal channel and factory Assert.True(CommunicationState.Closed == client.State, String.Format("Expected client state to be Closed but actual was '{0}'", client.State)); // Closing the ClientBase also closes the internal channel Assert.True(CommunicationState.Closed == ((ICommunicationObject)serviceProxy).State, String.Format("Expected proxy state to be Closed but actual was '{0}'", ((ICommunicationObject)serviceProxy).State)); // Closing the ClientBase also closes the channel factory Assert.True(CommunicationState.Closed == factory.State, String.Format("Expected channel factory state to be Closed but actual was '{0}'", factory.State)); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, client, factory); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Sync_Open_Close_Events_Fire() { MyClientBase client = null; List<string> eventsCalled = new List<string>(4); List<string> proxyEventsCalled = new List<string>(4); IWcfServiceGenerated proxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase(customBinding, new EndpointAddress(Endpoints.HttpSoap12_Address)); // Listen to all events on the ClientBase and on the generated proxy ClientBaseTestHelpers.RegisterForEvents(client, eventsCalled); proxy = client.Proxy; ClientBaseTestHelpers.RegisterForEvents((ICommunicationObject)proxy, proxyEventsCalled); // *** EXECUTE *** \\ proxy.Echo("Hello"); ((ICommunicationObject)client).Close(); // *** VALIDATE *** \\ // We expect both the ClientBase and the generated proxy to have fired all the open/close events string expected = "Opening,Opened,Closing,Closed"; string actual = String.Join(",", eventsCalled); Assert.True(String.Equals(expected, actual), String.Format("Expected client to receive events '{0}' but actual was '{1}'", expected, actual)); actual = String.Join(",", proxyEventsCalled); Assert.True(String.Equals(expected, actual), String.Format("Expected proxy to receive events '{0}' but actual was '{1}'", expected, actual)); // *** CLEANUP *** \\ } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)proxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Async_Open_Close_Events_Fire() { MyClientBase client = null; List<string> eventsCalled = new List<string>(4); List<string> proxyEventsCalled = new List<string>(4); IWcfServiceGenerated proxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase(customBinding, new EndpointAddress(Endpoints.HttpSoap12_Address)); // Listen to all events on the ClientBase and on the generated proxy ClientBaseTestHelpers.RegisterForEvents(client, eventsCalled); proxy = client.Proxy; ClientBaseTestHelpers.RegisterForEvents((ICommunicationObject)proxy, proxyEventsCalled); // *** EXECUTE *** \\ Task<string> task = proxy.EchoAsync("Hello"); task.GetAwaiter().GetResult(); IAsyncResult ar = ((ICommunicationObject)client).BeginClose(null, null); ((ICommunicationObject)client).EndClose(ar); // *** VALIDATE *** \\ // We expect both the ClientBase and the generated proxy to have fired all the open/close events string expected = "Opening,Opened,Closing,Closed"; string actual = String.Join(",", eventsCalled); Assert.True(String.Equals(expected, actual), String.Format("Expected client to receive events '{0}' but actual was '{1}'", expected, actual)); actual = String.Join(",", proxyEventsCalled); Assert.True(String.Equals(expected, actual), String.Format("Expected proxy to receive events '{0}' but actual was '{1}'", expected, actual)); // *** CLEANUP *** \\ } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)proxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Sync_Removed_Open_Close_Events_Do_Not_Fire() { MyClientBase client = null; List<string> eventsCalled = new List<string>(4); List<string> proxyEventsCalled = new List<string>(4); IWcfServiceGenerated proxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase(customBinding, new EndpointAddress(Endpoints.HttpSoap12_Address)); // Both Add and Remove event handlers ClientBaseTestHelpers.RegisterForEvents(client, eventsCalled, deregister:true); proxy = client.Proxy; ClientBaseTestHelpers.RegisterForEvents((ICommunicationObject)proxy, proxyEventsCalled, deregister:true); // *** EXECUTE *** \\ proxy.Echo("Hello"); ((ICommunicationObject)client).Close(); // *** VALIDATE *** \\ // We expect both the ClientBase and the generated proxy to have NOT fired all the open/close events string actual = String.Join(",", eventsCalled); Assert.True(eventsCalled.Count == 0, String.Format("Expected client NOT to receive events but actual was '{0}'", actual)); actual = String.Join(",", proxyEventsCalled); Assert.True(proxyEventsCalled.Count == 0, String.Format("Expected proxy NOT to receive events but actual was '{0}'", actual)); // *** CLEANUP *** \\ } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)proxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Sync_RoundTrip_Call_Using_HttpTransport() { // This test verifies ClientBase<T> can be used to create a proxy and invoke an operation over Http MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); serviceProxy = client.ChannelFactory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo("Hello"); // *** VALIDATE *** \\ Assert.Equal("Hello", result); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void ClientBaseOfT_Sync_RoundTrip_Call_Using_NetTcpTransport() { // This test verifies ClientBase<T> can be used to create a proxy and invoke an operation over Tcp // (request reply over Tcp) MyClientBase client = null; IWcfServiceGenerated serviceProxy = null; try { // *** SETUP *** \\ CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(), new TcpTransportBindingElement()); client = new MyClientBase(binding, new EndpointAddress(Endpoints.Tcp_CustomBinding_NoSecurity_Text_Address)); serviceProxy = client.ChannelFactory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo("Hello"); // *** VALIDATE *** \\ Assert.Equal("Hello", result); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } } [WcfFact] [OuterLoop] public static void OperationContextScope_HttpRequestCustomMessageHeader_RoundTrip_Verify() { string customHeaderName = "OperationContextScopeCustomHeader"; string customHeaderNS = "http://tempuri.org/OperationContextScope_HttpRequestCustomMessageHeader_RoundTrip_Verify"; string customHeaderValue = "CustomHappyValue"; MyClientBase<IWcfService> client = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(); client = new MyClientBase<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = client.ChannelFactory.CreateChannel(); using (OperationContextScope scope = new OperationContextScope((IContextChannel)serviceProxy)) { MessageHeader header = MessageHeader.CreateHeader( customHeaderName, customHeaderNS, customHeaderValue ); OperationContext.Current.OutgoingMessageHeaders.Add(header); // *** EXECUTE *** \\ Dictionary<string, string> incomingMessageHeaders = serviceProxy.GetIncomingMessageHeaders(); string result = ClientBaseTestHelpers.GetHeader(customHeaderName, customHeaderNS, incomingMessageHeaders); // *** VALIDATE *** \\ Assert.Equal(customHeaderValue, result); } // *** EXECUTE *** \\ //Call outside of scope should not have the custom header Dictionary<string, string> outofScopeIncomingMessageHeaders = serviceProxy.GetIncomingMessageHeaders(); string outofScopeResult = ClientBaseTestHelpers.GetHeader(customHeaderName, customHeaderNS, outofScopeIncomingMessageHeaders); // *** VALIDATE *** \\ Assert.True(string.Empty == outofScopeResult, string.Format("Expect call out of the OperationContextScope does not have the custom header {0}", customHeaderName)); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } } }
// // DebugTests.cs // // Author: // Lluis Sanchez Gual <[email protected]> // // Copyright (c) 2009 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.IO; using System.Threading; using System.Reflection; using System.Collections.Generic; using Mono.Debugging.Soft; using Mono.Debugging.Client; using NUnit.Framework; namespace Mono.Debugging.Tests { [TestFixture] public abstract partial class DebugTests { protected readonly ManualResetEvent targetStoppedEvent = new ManualResetEvent (false); public readonly string EngineId; string TestName = ""; ITextFile SourceFile; SourceLocation lastStoppedPosition; public bool AllowTargetInvokes { get; protected set; } public DebuggerSession Session { get; private set; } public StackFrame Frame { get; private set; } protected DebugTests (string engineId) { EngineId = engineId; } public bool IsCorDebugger { get { return EngineId == "MonoDevelop.Debugger.Win32"; } } public void IgnoreCorDebugger (string message = "") { if (IsCorDebugger) Assert.Ignore (message); } public bool IsSoftDebugger { get { return Session is SoftDebuggerSession; } } public void IgnoreSoftDebugger (string message = "") { if (IsSoftDebugger) Assert.Ignore (message); } public bool IsVsDebugger { get { return EngineId == "NetCoreDebugger"; } } public void IgnoreVsDebugger (string message = "") { if (IsVsDebugger) Assert.Ignore (message); } // TODO: implement in another part of the class #region Partial Definitions /* /// <summary> /// Returns parent directory of target executable /// </summary> protected string TargetExeDirectory { get { throw new NotImplementedException (); } } /// <summary> /// Returns parent directory of target project sources /// </summary> protected string TargetProjectSourceDir { get { throw new NotImplementedException (); } } /// <summary> /// Creates debugger session. The type of session is dependent on <paramref name="engineId"/> /// </summary> /// <param name="test">test name, usually used as entry point method in target exe</param> /// <param name="engineId">the ID of debugger engine</param> protected DebuggerSession CreateSession (string test, string engineId); /// <summary> /// Creates start info to run the app /// </summary> /// <param name="test">test name</param> /// <param name="engineId">the ID of debugger engine</param> protected DebuggerStartInfo CreateStartInfo (string test, string engineId); /// <summary> /// Reads file from given path /// </summary> /// <param name="sourcePath"></param> /// <returns></returns> protected ITextFile ReadFile (string sourcePath) */ #endregion [OneTimeSetUp] public virtual void SetUp () { SetUpPartial (); } partial void SetUpPartial (); [OneTimeTearDown] public virtual void TearDown () { TearDownPartial (); if (Session != null) { Session.Exit (); Session.Dispose (); Session = null; } } partial void TearDownPartial (); protected virtual string TargetExePath { get { return Path.Combine (TargetExeDirectory, TestAppExeName); } } protected virtual void Start (string test) { TestName = test; Session = CreateSession (test, EngineId); // make sure we have a breakpoint store created and setup Session.Breakpoints.Clear (); var dsi = CreateStartInfo (test, EngineId); var soft = dsi as SoftDebuggerStartInfo; if (soft != null) { var assemblyName = AssemblyName.GetAssemblyName (TargetExePath); soft.UserAssemblyNames = new List<AssemblyName> {assemblyName}; } var ops = new DebuggerSessionOptions { ProjectAssembliesOnly = true, EvaluationOptions = EvaluationOptions.DefaultOptions }; ops.EvaluationOptions.AllowTargetInvoke = AllowTargetInvokes; ops.EvaluationOptions.EvaluationTimeout = 100000; var sourcePath = Path.Combine (TargetProjectSourceDir, test + ".cs"); SourceFile = ReadFile(sourcePath); AddBreakpoint ("break"); var done = new ManualResetEvent (false); Session.TargetHitBreakpoint += (sender, e) => { Frame = e.Backtrace.GetFrame (0); lastStoppedPosition = Frame.SourceLocation; targetStoppedEvent.Set (); done.Set (); }; Session.TargetExceptionThrown += (sender, e) => { Frame = e.Backtrace.GetFrame (0); for (int i = 0; i < e.Backtrace.FrameCount; i++) { if (!e.Backtrace.GetFrame (i).IsExternalCode) { Frame = e.Backtrace.GetFrame (i); break; } } lastStoppedPosition = Frame.SourceLocation; targetStoppedEvent.Set (); }; Session.TargetStopped += (sender, e) => { //This can be null in case of ForcedStop //which is called when exception is thrown //when Continue & Stepping is executed if (e.Backtrace != null) { Frame = e.Backtrace.GetFrame (0); lastStoppedPosition = Frame.SourceLocation; targetStoppedEvent.Set (); } else { Console.WriteLine ("e.Backtrace is null"); } }; var targetExited = new ManualResetEvent (false); Session.TargetExited += delegate { targetExited.Set (); }; Session.Run (dsi, ops); Session.ExceptionHandler = (ex) => { Console.WriteLine ("Session.ExceptionHandler:" + Environment.NewLine + ex.ToString ()); HandleAnyException(ex); return true; }; switch (WaitHandle.WaitAny (new WaitHandle[]{ done, targetExited }, 30000)) { case 0: //Breakpoint is hit good... run tests now break; case 1: throw new Exception ("Test application exited before hitting breakpoint"); default: throw new Exception ("Timeout while waiting for initial breakpoint"); } if (Session is SoftDebuggerSession) Console.WriteLine ("SDB protocol version:" + ((SoftDebuggerSession)Session).ProtocolVersion); } void GetLineAndColumn (string breakpointMarker, int offset, string statement, out int line, out int col, ITextFile file) { int i = file.Text.IndexOf ("/*" + breakpointMarker + "*/", StringComparison.Ordinal); if (i == -1) Assert.Fail ("Break marker not found: " + breakpointMarker + " in " + file.Name); file.GetLineColumnFromPosition (i, out line, out col); line += offset; if (statement != null) { int lineStartPosition = file.GetPositionFromLineColumn (line, 1); string lineText = file.GetText (lineStartPosition, lineStartPosition + file.GetLineLength (line)); col = lineText.IndexOf (statement, StringComparison.Ordinal) + 1; if (col == 0) Assert.Fail ("Failed to find statement:" + statement + " at " + file.Name + "(" + line + ")"); } else { col = 1; } } public Breakpoint AddBreakpoint (string breakpointMarker, int offset = 0, string statement = null, ITextFile file = null) { var bp = CreateBreakpoint (breakpointMarker, offset, statement, file); Session.Breakpoints.Add (bp); return bp; } public Breakpoint CreateBreakpoint (string breakpointMarker, int offset = 0, string statement = null, ITextFile file = null) { file = file ?? SourceFile; int col, line; GetLineAndColumn (breakpointMarker, offset, statement, out line, out col, file); var bp = new Breakpoint (file.Name, line, col); return bp; } public void RunToCursor (string breakpointMarker, int offset = 0, string statement = null, ITextFile file = null) { file = file ?? SourceFile; int col, line; GetLineAndColumn (breakpointMarker, offset, statement, out line, out col, file); targetStoppedEvent.Reset (); Session.Breakpoints.RemoveRunToCursorBreakpoints (); var bp = new RunToCursorBreakpoint (file.Name, line, col); Session.Breakpoints.Add (bp); Session.Continue (); CheckPosition (breakpointMarker, offset, statement); } public void InitializeTest () { Session.Breakpoints.Clear (); Session.Options.EvaluationOptions = EvaluationOptions.DefaultOptions; Session.Options.ProjectAssembliesOnly = true; Session.Options.StepOverPropertiesAndOperators = false; AddBreakpoint ("break"); while (!CheckPosition ("break", 0, silent: true)) { targetStoppedEvent.Reset (); Session.Continue (); } } public ObjectValue Eval (string exp) { return Frame.GetExpressionValue (exp, true).Sync (); } public void WaitStop (int miliseconds) { if (!targetStoppedEvent.WaitOne (miliseconds)) Assert.Fail ("WaitStop failure: Target stop timeout"); } public bool CheckPosition (string guid, int offset = 0, string statement = null, bool silent = false, ITextFile file = null) { file = file ?? SourceFile; if (!targetStoppedEvent.WaitOne (6000)) { if (!silent) Assert.Fail ("CheckPosition failure: Target stop timeout"); return false; } if (lastStoppedPosition.FileName == file.Name) { int i = file.Text.IndexOf ("/*" + guid + "*/", StringComparison.Ordinal); if (i == -1) { if (!silent) Assert.Fail ("CheckPosition failure: Guid marker not found:" + guid + " in file:" + file.Name); return false; } int line, col; file.GetLineColumnFromPosition (i, out line, out col); if ((line + offset) != lastStoppedPosition.Line) { if (!silent) Assert.Fail ("CheckPosition failure: Wrong line Expected:" + (line + offset) + " Actual:" + lastStoppedPosition.Line + " in file:" + file.Name); return false; } if (!string.IsNullOrEmpty (statement)) { int position = file.GetPositionFromLineColumn (lastStoppedPosition.Line, lastStoppedPosition.Column); string actualStatement = file.GetText (position, position + statement.Length); if (statement != actualStatement) { if (!silent) Assert.AreEqual (statement, actualStatement); return false; } } } else { if (!silent) Assert.Fail ("CheckPosition failure: Wrong file Excpected:" + file.Name + " Actual:" + lastStoppedPosition.FileName); return false; } return true; } public void StepIn (string guid, string statement) { StepIn (guid, 0, statement); } public void StepIn (string guid, int offset = 0, string statement = null) { targetStoppedEvent.Reset (); Session.StepInstruction (); CheckPosition (guid, offset, statement); } public void StepOver (string guid, string statement) { StepOver (guid, 0, statement); } public void StepOver (string guid, int offset = 0, string statement = null) { targetStoppedEvent.Reset (); Session.NextInstruction (); CheckPosition (guid, offset, statement); } public void StepOut (string guid, string statement) { StepOut (guid, 0, statement); } public void StepOut (string guid, int offset = 0, string statement = null) { targetStoppedEvent.Reset (); Session.Finish (); CheckPosition (guid, offset, statement); } public void Continue (string guid, string statement) { Continue (guid, 0, statement); } public void Continue (string guid, int offset = 0, string statement = null, ITextFile file = null) { targetStoppedEvent.Reset (); Session.Continue (); CheckPosition(guid, offset, statement, file: file); } public void StartTest (string methodName) { if (!targetStoppedEvent.WaitOne (3000)) Assert.Fail ("StartTest failure: Target stop timeout"); Assert.AreEqual ('"' + methodName + '"', Eval ("NextMethodToCall = \"" + methodName + "\";").Value); targetStoppedEvent.Reset (); Session.Continue (); } public void SetNextStatement (string guid, int offset = 0, string statement = null, ITextFile file = null) { file = file ?? SourceFile; int line, column; GetLineAndColumn (guid, offset, statement, out line, out column, file); Session.SetNextStatement (file.Name, line, column); } public void AddCatchpoint (string exceptionName, bool includeSubclasses) { Session.Breakpoints.Add (new Catchpoint (exceptionName, includeSubclasses)); } partial void HandleAnyException(Exception exception); } static class EvalHelper { public static bool AtLeast (this Version ver, int major, int minor) { if ((ver.Major > major) || ((ver.Major == major && ver.Minor >= minor))) return true; else return false; } public static ObjectValue Sync (this ObjectValue val) { if (!val.IsEvaluating) return val; object locker = new object (); EventHandler h = delegate { lock (locker) { Monitor.PulseAll (locker); } }; val.ValueChanged += h; lock (locker) { while (val.IsEvaluating) { if (!Monitor.Wait (locker, 8000)) throw new Exception ("Timeout while waiting for value evaluation"); } } val.ValueChanged -= h; return val; } public static ObjectValue GetChildSync (this ObjectValue val, string name, EvaluationOptions ops) { var children = val.GetAllChildrenSync (ops); foreach (var child in children) { if (child.Name == name) return child; } return null; } public static ObjectValue[] GetAllChildrenSync (this ObjectValue val, EvaluationOptions ops = null) { var children = new List<ObjectValue> (); var values = ops == null ? val.GetAllChildren () : val.GetAllChildren (ops); for (int i = 0; i < values.Length; i++) { var value = values[i].Sync (); if (value.IsEvaluatingGroup) { if (ops != null) children.AddRange (value.GetAllChildrenSync (ops)); else children.AddRange (value.GetAllChildrenSync ()); } else { children.Add (value); } } return children.ToArray (); } public static ObjectValue[] GetAllLocalsSync(this StackFrame frame) { var locals = new List<ObjectValue> (); var values = frame.GetAllLocals (); for (int i = 0; i < values.Length; i++) { var value = values[i].Sync (); if (value.IsEvaluatingGroup) locals.AddRange (value.GetAllChildrenSync ()); else locals.Add (value); } return locals.ToArray (); } public static ExceptionInfo GetExceptionSync(this StackFrame frame, EvaluationOptions options) { var exception = frame.GetException (options); if (exception != null) exception.Instance.Sync (); return exception; } } }
using UnityEngine; //using UnityEditor; using GDGeek; using System.IO; using System.Collections.Generic; using System.Security.Cryptography; using System; namespace GDGeek{ public class MagicaVoxelFormater { public static ushort[] palette_ = new ushort[] { 32767, 25599, 19455, 13311, 7167, 1023, 32543, 25375, 19231, 13087, 6943, 799, 32351, 25183, 19039, 12895, 6751, 607, 32159, 24991, 18847, 12703, 6559, 415, 31967, 24799, 18655, 12511, 6367, 223, 31775, 24607, 18463, 12319, 6175, 31, 32760, 25592, 19448, 13304, 7160, 1016, 32536, 25368, 19224, 13080, 6936, 792, 32344, 25176, 19032, 12888, 6744, 600, 32152, 24984, 18840, 12696, 6552, 408, 31960, 24792, 18648, 12504, 6360, 216, 31768, 24600, 18456, 12312, 6168, 24, 32754, 25586, 19442, 13298, 7154, 1010, 32530, 25362, 19218, 13074, 6930, 786, 32338, 25170, 19026, 12882, 6738, 594, 32146, 24978, 18834, 12690, 6546, 402, 31954, 24786, 18642, 12498, 6354, 210, 31762, 24594, 18450, 12306, 6162, 18, 32748, 25580, 19436, 13292, 7148, 1004, 32524, 25356, 19212, 13068, 6924, 780, 32332, 25164, 19020, 12876, 6732, 588, 32140, 24972, 18828, 12684, 6540, 396, 31948, 24780, 18636, 12492, 6348, 204, 31756, 24588, 18444, 12300, 6156, 12, 32742, 25574, 19430, 13286, 7142, 998, 32518, 25350, 19206, 13062, 6918, 774, 32326, 25158, 19014, 12870, 6726, 582, 32134, 24966, 18822, 12678, 6534, 390, 31942, 24774, 18630, 12486, 6342, 198, 31750, 24582, 18438, 12294, 6150, 6, 32736, 25568, 19424, 13280, 7136, 992, 32512, 25344, 19200, 13056, 6912, 768, 32320, 25152, 19008, 12864, 6720, 576, 32128, 24960, 18816, 12672, 6528, 384, 31936, 24768, 18624, 12480, 6336, 192, 31744, 24576, 18432, 12288, 6144, 28, 26, 22, 20, 16, 14, 10, 8, 4, 2, 896, 832, 704, 640, 512, 448, 320, 256, 128, 64, 28672, 26624, 22528, 20480, 16384, 14336, 10240, 8192, 4096, 2048, 29596, 27482, 23254, 21140, 16912, 14798, 10570, 8456, 4228, 2114, 1 }; private struct Point { public byte x; public byte y; public byte z; public byte i; } public static Color Short2Color(ushort s){ Color c = new Color (); c.a = 1.0f; c.r = (float)(s & 0x1f)/31.0f; c.g = (float)(s >> 5 & 0x1f)/31.0f; c.b = (float)(s >> 10 & 0x1f)/31.0f; return c; } public static ushort Color2Short(Color c){ ushort s = 0; s = (ushort)(Mathf.RoundToInt (c.r * 31.0f) | Mathf.RoundToInt (c.g * 31.0f)<<5 | Mathf.RoundToInt (c.b * 31.0f)<<10); return s; } public static Color Bytes2Color(Vector4Int v){ Color c = new Color (); c.r = ((float)(v.x))/255.0f; c.g = ((float)(v.y))/255.0f; c.b = ((float)(v.z))/255.0f; c.a = ((float)(v.w))/255.0f; return c; } public static Vector4Int Color2Bytes(Color c){ Vector4Int v; v.x = Mathf.RoundToInt (c.r * 255.0f); v.y = Mathf.RoundToInt (c.g * 255.0f); v.z = Mathf.RoundToInt (c.b * 255.0f); v.w = Mathf.RoundToInt (c.a * 255.0f); return v; } private static Point ReadPoint(BinaryReader br, bool subsample){ Point point = new Point (); point.x = (byte)(subsample ? br.ReadByte() : br.ReadByte()); point.y = (byte)(subsample ? br.ReadByte() : br.ReadByte()); point.z = (byte)(subsample ? br.ReadByte() : br.ReadByte()); point.i = (br.ReadByte()); return point; } private static Point[] WritePoints(VoxelStruct vs, Vector4Int[] palette){ Point[] points = new Point[vs.count]; for (int i = 0; i < vs.count; ++i) { var data = vs.getData(i); points[i] = new Point(); points[i].x = (byte)data.position.x; points[i].y = (byte)data.position.z; points[i].z = (byte)data.position.y; Color color = data.color; if (palette == null) { ushort s = Color2Short (color); for (int x = 0; x < palette_.Length; ++x) { if (palette_ [x] == s) { points [i].i = (byte)(x + 1); break; } } } else { Vector4Int v = Color2Bytes (color); for (int x = 0; x < palette.Length; ++x) { if (palette [x] == v) { points [i].i = (byte)(x + 1); break; } } } } return points; } private static List<VoxelData> CreateVoxelDatas(Point[] points, Vector4Int[] palette){ List<VoxelData> datas = new List<VoxelData>(); for(int i=0; i < points.Length; ++i){ VoxelData data = new VoxelData(); data.position.x = points[i].x; data.position.y = points[i].z; data.position.z = points[i].y; if(palette == null){ ushort c = palette_[points[i].i - 1]; data.color = Short2Color (c); }else{ Vector4Int v = palette[points[i].i - 1]; data.color = Bytes2Color (v);; } datas.Add (data); } return datas; } public static MagicaVoxel ReadFromFile(TextAsset file){ System.IO.BinaryReader br = GDGeek.VoxelReader.ReadFromFile (file); return MagicaVoxelFormater.ReadFromBinary (br); } public static MagicaVoxel ReadFromBinary(System.IO.BinaryReader br){ Vector4Int[] palette = null; Point[] points = null; string vox = new string(br.ReadChars(4)); if (vox != "VOX ") { return new MagicaVoxel (new VoxelStruct ());; } int version = br.ReadInt32(); MagicaVoxel.Main main = null; MagicaVoxel.Rgba rgba = null; MagicaVoxel.Size size = null; //magic.version = version; Vector3Int box = new Vector3Int (); bool subsample = false; while (br.BaseStream.Position+12 < br.BaseStream.Length) { string name = new string(br.ReadChars(4)); int length = br.ReadInt32(); int chunks = br.ReadInt32(); if (name == "MAIN") { main = new MagicaVoxel.Main (); main.size = length; main.name = name; main.chunks = chunks; } else if (name == "SIZE") { box.x = br.ReadInt32 (); box.y = br.ReadInt32 (); box.z = br.ReadInt32 (); size = new MagicaVoxel.Size (); size.size = 12; size.name = name; size.chunks = chunks; size.box = box; if (box.x > 32 || box.y > 32) { subsample = true; } br.ReadBytes (length - 4 * 3); } else if (name == "XYZI") { int count = br.ReadInt32 (); points = new Point[count]; for (int i = 0; i < points.Length; i++) { points [i] = MagicaVoxelFormater.ReadPoint (br, subsample);//new Data (stream, subsample); } } else if (name == "RGBA") { int n = length / 4; palette = new Vector4Int[n]; for (int i = 0; i < n; i++) { byte r = br.ReadByte (); byte g = br.ReadByte (); byte b = br.ReadByte (); byte a = br.ReadByte (); palette [i].x = r; palette [i].y = g; palette [i].z = b; palette [i].w = a; } rgba = new MagicaVoxel.Rgba (); rgba.size = length; rgba.name = name; rgba.chunks = chunks; rgba.palette = palette; } else{ if (br.BaseStream.Position + length >= br.BaseStream.Length) { break; } else { br.ReadBytes(length); } } } return new MagicaVoxel ( new VoxelStruct(CreateVoxelDatas(points, palette)), main, size,rgba, version); } public static string GetMd5(VoxelStruct vs){ string fileMD5 = ""; /* MemoryStream memoryStream = new MemoryStream (); BinaryWriter binaryWriter = new BinaryWriter(memoryStream); WriteToBinary (vs, binaryWriter); byte[] data = memoryStream.GetBuffer(); MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(data); foreach (byte b in result) { fileMD5 += Convert.ToString(b, 16); }*/ return fileMD5; } public static void WriteToBinary(VoxelStruct vs, System.IO.BinaryWriter bw){ bw.Write ("VOX ".ToCharArray()); MagicaVoxel magic = new MagicaVoxel (vs); bw.Write ((int)magic.version); if (magic.main != null) { bw.Write (magic.main.name.ToCharArray ()); bw.Write ((int)magic.main.size); bw.Write ((int)magic.main.chunks); } if (magic.size != null) { bw.Write (magic.size.name.ToCharArray ()); bw.Write ((int)magic.size.size); bw.Write ((int)magic.size.chunks); bw.Write ((int)magic.size.box.x); bw.Write ((int)magic.size.box.y); bw.Write ((int)magic.size.box.z); } if (magic.rgba != null && magic.rgba.palette != null) { int length = magic.rgba.palette.Length; bw.Write (magic.rgba.name.ToCharArray ()); bw.Write ((int)(length * 4)); bw.Write ((int)magic.size.chunks); for (int i = 0; i < length; i++) { Vector4Int c = magic.rgba.palette [i]; bw.Write ((byte)(c.x)); bw.Write ((byte)(c.y)); bw.Write ((byte)(c.z)); bw.Write ((byte)(c.w)); } } Point[] points = WritePoints (vs, magic.rgba.palette); bw.Write ("XYZI".ToCharArray ()); bw.Write ((int)(points.Length * 4) + 4); bw.Write ((int)0); bw.Write ((int)points.Length); for (int i = 0; i < points.Length; ++i) { Point p = points[i]; bw.Write ((byte)(p.x)); bw.Write ((byte)(p.y)); bw.Write ((byte)(p.z)); bw.Write ((byte)(p.i)); } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Monitoring.V3.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedAlertPolicyServiceClientSnippets { /// <summary>Snippet for ListAlertPolicies</summary> public void ListAlertPoliciesRequestObject() { // Snippet: ListAlertPolicies(ListAlertPoliciesRequest, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) ListAlertPoliciesRequest request = new ListAlertPoliciesRequest { ProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", OrderBy = "", }; // Make the request PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(request); // Iterate over all response items, lazily performing RPCs as required foreach (AlertPolicy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAlertPoliciesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPoliciesAsync</summary> public async Task ListAlertPoliciesRequestObjectAsync() { // Snippet: ListAlertPoliciesAsync(ListAlertPoliciesRequest, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) ListAlertPoliciesRequest request = new ListAlertPoliciesRequest { ProjectName = ProjectName.FromProject("[PROJECT]"), Filter = "", OrderBy = "", }; // Make the request PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AlertPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPolicies</summary> public void ListAlertPolicies() { // Snippet: ListAlertPolicies(string, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]"; // Make the request PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name); // Iterate over all response items, lazily performing RPCs as required foreach (AlertPolicy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAlertPoliciesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPoliciesAsync</summary> public async Task ListAlertPoliciesAsync() { // Snippet: ListAlertPoliciesAsync(string, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]"; // Make the request PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AlertPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPolicies</summary> public void ListAlertPoliciesResourceNames1() { // Snippet: ListAlertPolicies(ProjectName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) ProjectName name = ProjectName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name); // Iterate over all response items, lazily performing RPCs as required foreach (AlertPolicy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAlertPoliciesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPoliciesAsync</summary> public async Task ListAlertPoliciesResourceNames1Async() { // Snippet: ListAlertPoliciesAsync(ProjectName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = ProjectName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AlertPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPolicies</summary> public void ListAlertPoliciesResourceNames2() { // Snippet: ListAlertPolicies(OrganizationName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]"); // Make the request PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name); // Iterate over all response items, lazily performing RPCs as required foreach (AlertPolicy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAlertPoliciesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPoliciesAsync</summary> public async Task ListAlertPoliciesResourceNames2Async() { // Snippet: ListAlertPoliciesAsync(OrganizationName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]"); // Make the request PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AlertPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPolicies</summary> public void ListAlertPoliciesResourceNames3() { // Snippet: ListAlertPolicies(FolderName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) FolderName name = FolderName.FromFolder("[FOLDER]"); // Make the request PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name); // Iterate over all response items, lazily performing RPCs as required foreach (AlertPolicy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAlertPoliciesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPoliciesAsync</summary> public async Task ListAlertPoliciesResourceNames3Async() { // Snippet: ListAlertPoliciesAsync(FolderName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) FolderName name = FolderName.FromFolder("[FOLDER]"); // Make the request PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AlertPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPolicies</summary> public void ListAlertPoliciesResourceNames4() { // Snippet: ListAlertPolicies(IResourceName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); // Make the request PagedEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPolicies(name); // Iterate over all response items, lazily performing RPCs as required foreach (AlertPolicy item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAlertPoliciesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAlertPoliciesAsync</summary> public async Task ListAlertPoliciesResourceNames4Async() { // Snippet: ListAlertPoliciesAsync(IResourceName, string, int?, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); // Make the request PagedAsyncEnumerable<ListAlertPoliciesResponse, AlertPolicy> response = alertPolicyServiceClient.ListAlertPoliciesAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((AlertPolicy item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAlertPoliciesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (AlertPolicy item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<AlertPolicy> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (AlertPolicy item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetAlertPolicy</summary> public void GetAlertPolicyRequestObject() { // Snippet: GetAlertPolicy(GetAlertPolicyRequest, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) GetAlertPolicyRequest request = new GetAlertPolicyRequest { AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"), }; // Make the request AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(request); // End snippet } /// <summary>Snippet for GetAlertPolicyAsync</summary> public async Task GetAlertPolicyRequestObjectAsync() { // Snippet: GetAlertPolicyAsync(GetAlertPolicyRequest, CallSettings) // Additional: GetAlertPolicyAsync(GetAlertPolicyRequest, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) GetAlertPolicyRequest request = new GetAlertPolicyRequest { AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"), }; // Make the request AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(request); // End snippet } /// <summary>Snippet for GetAlertPolicy</summary> public void GetAlertPolicy() { // Snippet: GetAlertPolicy(string, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]"; // Make the request AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name); // End snippet } /// <summary>Snippet for GetAlertPolicyAsync</summary> public async Task GetAlertPolicyAsync() { // Snippet: GetAlertPolicyAsync(string, CallSettings) // Additional: GetAlertPolicyAsync(string, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]"; // Make the request AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(name); // End snippet } /// <summary>Snippet for GetAlertPolicy</summary> public void GetAlertPolicyResourceNames1() { // Snippet: GetAlertPolicy(AlertPolicyName, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"); // Make the request AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name); // End snippet } /// <summary>Snippet for GetAlertPolicyAsync</summary> public async Task GetAlertPolicyResourceNames1Async() { // Snippet: GetAlertPolicyAsync(AlertPolicyName, CallSettings) // Additional: GetAlertPolicyAsync(AlertPolicyName, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"); // Make the request AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(name); // End snippet } /// <summary>Snippet for GetAlertPolicy</summary> public void GetAlertPolicyResourceNames2() { // Snippet: GetAlertPolicy(IResourceName, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); // Make the request AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name); // End snippet } /// <summary>Snippet for GetAlertPolicyAsync</summary> public async Task GetAlertPolicyResourceNames2Async() { // Snippet: GetAlertPolicyAsync(IResourceName, CallSettings) // Additional: GetAlertPolicyAsync(IResourceName, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); // Make the request AlertPolicy response = await alertPolicyServiceClient.GetAlertPolicyAsync(name); // End snippet } /// <summary>Snippet for CreateAlertPolicy</summary> public void CreateAlertPolicyRequestObject() { // Snippet: CreateAlertPolicy(CreateAlertPolicyRequest, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) CreateAlertPolicyRequest request = new CreateAlertPolicyRequest { AlertPolicy = new AlertPolicy(), ProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(request); // End snippet } /// <summary>Snippet for CreateAlertPolicyAsync</summary> public async Task CreateAlertPolicyRequestObjectAsync() { // Snippet: CreateAlertPolicyAsync(CreateAlertPolicyRequest, CallSettings) // Additional: CreateAlertPolicyAsync(CreateAlertPolicyRequest, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) CreateAlertPolicyRequest request = new CreateAlertPolicyRequest { AlertPolicy = new AlertPolicy(), ProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(request); // End snippet } /// <summary>Snippet for CreateAlertPolicy</summary> public void CreateAlertPolicy() { // Snippet: CreateAlertPolicy(string, AlertPolicy, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]"; AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicyAsync</summary> public async Task CreateAlertPolicyAsync() { // Snippet: CreateAlertPolicyAsync(string, AlertPolicy, CallSettings) // Additional: CreateAlertPolicyAsync(string, AlertPolicy, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]"; AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicy</summary> public void CreateAlertPolicyResourceNames1() { // Snippet: CreateAlertPolicy(ProjectName, AlertPolicy, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) ProjectName name = ProjectName.FromProject("[PROJECT]"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicyAsync</summary> public async Task CreateAlertPolicyResourceNames1Async() { // Snippet: CreateAlertPolicyAsync(ProjectName, AlertPolicy, CallSettings) // Additional: CreateAlertPolicyAsync(ProjectName, AlertPolicy, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = ProjectName.FromProject("[PROJECT]"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicy</summary> public void CreateAlertPolicyResourceNames2() { // Snippet: CreateAlertPolicy(OrganizationName, AlertPolicy, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicyAsync</summary> public async Task CreateAlertPolicyResourceNames2Async() { // Snippet: CreateAlertPolicyAsync(OrganizationName, AlertPolicy, CallSettings) // Additional: CreateAlertPolicyAsync(OrganizationName, AlertPolicy, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) OrganizationName name = OrganizationName.FromOrganization("[ORGANIZATION]"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicy</summary> public void CreateAlertPolicyResourceNames3() { // Snippet: CreateAlertPolicy(FolderName, AlertPolicy, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) FolderName name = FolderName.FromFolder("[FOLDER]"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicyAsync</summary> public async Task CreateAlertPolicyResourceNames3Async() { // Snippet: CreateAlertPolicyAsync(FolderName, AlertPolicy, CallSettings) // Additional: CreateAlertPolicyAsync(FolderName, AlertPolicy, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) FolderName name = FolderName.FromFolder("[FOLDER]"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicy</summary> public void CreateAlertPolicyResourceNames4() { // Snippet: CreateAlertPolicy(IResourceName, AlertPolicy, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = alertPolicyServiceClient.CreateAlertPolicy(name, alertPolicy); // End snippet } /// <summary>Snippet for CreateAlertPolicyAsync</summary> public async Task CreateAlertPolicyResourceNames4Async() { // Snippet: CreateAlertPolicyAsync(IResourceName, AlertPolicy, CallSettings) // Additional: CreateAlertPolicyAsync(IResourceName, AlertPolicy, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = await alertPolicyServiceClient.CreateAlertPolicyAsync(name, alertPolicy); // End snippet } /// <summary>Snippet for DeleteAlertPolicy</summary> public void DeleteAlertPolicyRequestObject() { // Snippet: DeleteAlertPolicy(DeleteAlertPolicyRequest, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest { AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"), }; // Make the request alertPolicyServiceClient.DeleteAlertPolicy(request); // End snippet } /// <summary>Snippet for DeleteAlertPolicyAsync</summary> public async Task DeleteAlertPolicyRequestObjectAsync() { // Snippet: DeleteAlertPolicyAsync(DeleteAlertPolicyRequest, CallSettings) // Additional: DeleteAlertPolicyAsync(DeleteAlertPolicyRequest, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) DeleteAlertPolicyRequest request = new DeleteAlertPolicyRequest { AlertPolicyName = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"), }; // Make the request await alertPolicyServiceClient.DeleteAlertPolicyAsync(request); // End snippet } /// <summary>Snippet for DeleteAlertPolicy</summary> public void DeleteAlertPolicy() { // Snippet: DeleteAlertPolicy(string, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]"; // Make the request alertPolicyServiceClient.DeleteAlertPolicy(name); // End snippet } /// <summary>Snippet for DeleteAlertPolicyAsync</summary> public async Task DeleteAlertPolicyAsync() { // Snippet: DeleteAlertPolicyAsync(string, CallSettings) // Additional: DeleteAlertPolicyAsync(string, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/alertPolicies/[ALERT_POLICY]"; // Make the request await alertPolicyServiceClient.DeleteAlertPolicyAsync(name); // End snippet } /// <summary>Snippet for DeleteAlertPolicy</summary> public void DeleteAlertPolicyResourceNames1() { // Snippet: DeleteAlertPolicy(AlertPolicyName, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"); // Make the request alertPolicyServiceClient.DeleteAlertPolicy(name); // End snippet } /// <summary>Snippet for DeleteAlertPolicyAsync</summary> public async Task DeleteAlertPolicyResourceNames1Async() { // Snippet: DeleteAlertPolicyAsync(AlertPolicyName, CallSettings) // Additional: DeleteAlertPolicyAsync(AlertPolicyName, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) AlertPolicyName name = AlertPolicyName.FromProjectAlertPolicy("[PROJECT]", "[ALERT_POLICY]"); // Make the request await alertPolicyServiceClient.DeleteAlertPolicyAsync(name); // End snippet } /// <summary>Snippet for DeleteAlertPolicy</summary> public void DeleteAlertPolicyResourceNames2() { // Snippet: DeleteAlertPolicy(IResourceName, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); // Make the request alertPolicyServiceClient.DeleteAlertPolicy(name); // End snippet } /// <summary>Snippet for DeleteAlertPolicyAsync</summary> public async Task DeleteAlertPolicyResourceNames2Async() { // Snippet: DeleteAlertPolicyAsync(IResourceName, CallSettings) // Additional: DeleteAlertPolicyAsync(IResourceName, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) IResourceName name = new UnparsedResourceName("a/wildcard/resource"); // Make the request await alertPolicyServiceClient.DeleteAlertPolicyAsync(name); // End snippet } /// <summary>Snippet for UpdateAlertPolicy</summary> public void UpdateAlertPolicyRequestObject() { // Snippet: UpdateAlertPolicy(UpdateAlertPolicyRequest, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest { UpdateMask = new FieldMask(), AlertPolicy = new AlertPolicy(), }; // Make the request AlertPolicy response = alertPolicyServiceClient.UpdateAlertPolicy(request); // End snippet } /// <summary>Snippet for UpdateAlertPolicyAsync</summary> public async Task UpdateAlertPolicyRequestObjectAsync() { // Snippet: UpdateAlertPolicyAsync(UpdateAlertPolicyRequest, CallSettings) // Additional: UpdateAlertPolicyAsync(UpdateAlertPolicyRequest, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) UpdateAlertPolicyRequest request = new UpdateAlertPolicyRequest { UpdateMask = new FieldMask(), AlertPolicy = new AlertPolicy(), }; // Make the request AlertPolicy response = await alertPolicyServiceClient.UpdateAlertPolicyAsync(request); // End snippet } /// <summary>Snippet for UpdateAlertPolicy</summary> public void UpdateAlertPolicy() { // Snippet: UpdateAlertPolicy(FieldMask, AlertPolicy, CallSettings) // Create client AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create(); // Initialize request argument(s) FieldMask updateMask = new FieldMask(); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = alertPolicyServiceClient.UpdateAlertPolicy(updateMask, alertPolicy); // End snippet } /// <summary>Snippet for UpdateAlertPolicyAsync</summary> public async Task UpdateAlertPolicyAsync() { // Snippet: UpdateAlertPolicyAsync(FieldMask, AlertPolicy, CallSettings) // Additional: UpdateAlertPolicyAsync(FieldMask, AlertPolicy, CancellationToken) // Create client AlertPolicyServiceClient alertPolicyServiceClient = await AlertPolicyServiceClient.CreateAsync(); // Initialize request argument(s) FieldMask updateMask = new FieldMask(); AlertPolicy alertPolicy = new AlertPolicy(); // Make the request AlertPolicy response = await alertPolicyServiceClient.UpdateAlertPolicyAsync(updateMask, alertPolicy); // End snippet } } }
//********************************************************* // // 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 SDKTemplate; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Windows.Devices.Enumeration; using Windows.Devices.Sensors; using Windows.Globalization; using Windows.Globalization.DateTimeFormatting; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace PedometerCS { /// <summary> /// History Page that gets loaded when 'History' scenario is selected. /// </summary> public sealed partial class Scenario2_History : Page { MainPage rootPage = MainPage.Current; // Common class ID for pedometers Guid PedometerClassId = new Guid("B19F89AF-E3EB-444B-8DEA-202575A71599"); public Scenario2_History() { this.InitializeComponent(); historyRecords = new ObservableCollection<HistoryRecord>(); historyRecordsList.DataContext = historyRecords; } private void AllHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { // Collapse SpanPicker - SpanPicker will not be created yet the first time the page is loading if (SpanPicker != null) { SpanPicker.Visibility = Visibility.Collapsed; } getAllHistory = true; rootPage.NotifyUser("This will retrieve all the step count history available on the system", NotifyType.StatusMessage); } private void SpecificHistory_Checked(object sender, Windows.UI.Xaml.RoutedEventArgs e) { SpanPicker.Visibility = Visibility.Visible; getAllHistory = false; rootPage.NotifyUser("This will retrieve all the step count history for the selected time span", NotifyType.StatusMessage); } /// <summary> /// Invoked when 'Get History' button is clicked. /// Depending on the user selection, this handler uses one of the overloaded /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user /// </summary> /// <param name="sender">unused</param> /// <param name="e">unused</param> async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { GetHistory.IsEnabled = false; // Determine if we can access pedometers var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId); if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed) { // Determine if a pedometer is present // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync var sensor = await Pedometer.GetDefaultAsync(); if (sensor != null) { IReadOnlyList<PedometerReading> historyReadings = null; var timestampFormatter = new DateTimeFormatter("shortdate longtime"); // Disable subsequent history retrieval while the async operation is in progress GetHistory.IsEnabled = false; // clear previous content being displayed historyRecords.Clear(); try { if (getAllHistory) { var dt = DateTime.FromFileTimeUtc(0); var fromBeginning = new DateTimeOffset(dt); rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage); historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning); } else { String notificationString = "Retrieving history from: "; var calendar = new Calendar(); calendar.ChangeClock("24HourClock"); // DateTime picker will also include hour, minute and seconds from the the system time. // Decrement the same to be able to correctly add TimePicker values. calendar.SetDateTime(FromDate.Date); calendar.AddNanoseconds(-calendar.Nanosecond); calendar.AddSeconds(-calendar.Second); calendar.AddMinutes(-calendar.Minute); calendar.AddHours(-calendar.Hour); calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds)); DateTimeOffset fromTime = calendar.GetDateTime(); calendar.SetDateTime(ToDate.Date); calendar.AddNanoseconds(-calendar.Nanosecond); calendar.AddSeconds(-calendar.Second); calendar.AddMinutes(-calendar.Minute); calendar.AddHours(-calendar.Hour); calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds)); DateTimeOffset toTime = calendar.GetDateTime(); notificationString += timestampFormatter.Format(fromTime); notificationString += " To "; notificationString += timestampFormatter.Format(toTime); if (toTime.ToFileTime() < fromTime.ToFileTime()) { rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage); // Enable subsequent history retrieval while the async operation is in progress GetHistory.IsEnabled = true; } else { TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks); rootPage.NotifyUser(notificationString, NotifyType.StatusMessage); historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span); } } if (historyReadings != null) { foreach (PedometerReading reading in historyReadings) { HistoryRecord record = new HistoryRecord(reading); historyRecords.Add(record); // Get at most 100 records (number is arbitrary chosen for demonstration purposes) if (historyRecords.Count == 100) { break; } } rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage); } } catch (UnauthorizedAccessException) { rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage); } // Finally, re-enable history retrieval GetHistory.IsEnabled = true; } else { rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage); } } else { rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage); } } private ObservableCollection<HistoryRecord> historyRecords; private bool getAllHistory = true; } /// <summary> /// Represents a history record object that gets binded to the ListView /// controller in the XAML /// </summary> public sealed class HistoryRecord { public String TimeStamp { get { DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime"); return timestampFormatter.Format(recordTimestamp); } } public String StepKind { get { String stepString; switch (stepKind) { case PedometerStepKind.Unknown: stepString = "Unknown"; break; case PedometerStepKind.Walking: stepString = "Walking"; break; case PedometerStepKind.Running: stepString = "Running"; break; default: stepString = "Invalid Step Kind"; break; } return stepString; } } public Int32 StepsCount { get { return stepsCount; } } public double StepsDuration { get { // return Duration in ms return stepsDuration.TotalMilliseconds; } } public HistoryRecord(PedometerReading reading) { stepKind = reading.StepKind; stepsCount = reading.CumulativeSteps; recordTimestamp = reading.Timestamp; } private DateTimeOffset recordTimestamp; private PedometerStepKind stepKind; private Int32 stepsCount; private TimeSpan stepsDuration; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; namespace System.Collections.Generic { /// <summary> /// Represents a position within a <see cref="LargeArrayBuilder{T}"/>. /// </summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] internal struct CopyPosition { /// <summary> /// Constructs a new <see cref="CopyPosition"/>. /// </summary> /// <param name="row">The index of the buffer to select.</param> /// <param name="column">The index within the buffer to select.</param> internal CopyPosition(int row, int column) { Debug.Assert(row >= 0); Debug.Assert(column >= 0); Row = row; Column = column; } /// <summary> /// Represents a position at the start of a <see cref="LargeArrayBuilder{T}"/>. /// </summary> public static CopyPosition Start => default(CopyPosition); /// <summary> /// The index of the buffer to select. /// </summary> internal int Row { get; } /// <summary> /// The index within the buffer to select. /// </summary> internal int Column { get; } /// <summary> /// Gets a string suitable for display in the debugger. /// </summary> private string DebuggerDisplay => $"[{Row}, {Column}]"; } /// <summary> /// Helper type for building dynamically-sized arrays while minimizing allocations and copying. /// </summary> /// <typeparam name="T">The element type.</typeparam> internal struct LargeArrayBuilder<T> { private const int StartingCapacity = 4; private const int ResizeLimit = 8; private readonly int _maxCapacity; // The maximum capacity this builder can have. private T[] _first; // The first buffer we store items in. Resized until ResizeLimit. private ArrayBuilder<T[]> _buffers; // After ResizeLimit * 2, we store previous buffers we've filled out here. private T[] _current; // Current buffer we're reading into. If _count <= ResizeLimit, this is _first. private int _index; // Index into the current buffer. private int _count; // Count of all of the items in this builder. /// <summary> /// Constructs a new builder. /// </summary> /// <param name="initialize">Pass <c>true</c>.</param> public LargeArrayBuilder(bool initialize) : this(maxCapacity: int.MaxValue) { // This is a workaround for C# not having parameterless struct constructors yet. // Once it gets them, replace this with a parameterless constructor. Debug.Assert(initialize); } /// <summary> /// Constructs a new builder with the specified maximum capacity. /// </summary> /// <param name="maxCapacity">The maximum capacity this builder can have.</param> /// <remarks> /// Do not add more than <paramref name="maxCapacity"/> items to this builder. /// </remarks> public LargeArrayBuilder(int maxCapacity) : this() { Debug.Assert(maxCapacity >= 0); _first = _current = Array.Empty<T>(); _maxCapacity = maxCapacity; } /// <summary> /// Gets the number of items added to the builder. /// </summary> public int Count => _count; /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T item) { Debug.Assert(_maxCapacity > _count); if (_index == _current.Length) { AllocateBuffer(); } _current[_index++] = item; _count++; } /// <summary> /// Adds a range of items to this builder. /// </summary> /// <param name="items">The sequence to add.</param> /// <remarks> /// It is the caller's responsibility to ensure that adding <paramref name="items"/> /// does not cause the builder to exceed its maximum capacity. /// </remarks> public void AddRange(IEnumerable<T> items) { Debug.Assert(items != null); using (IEnumerator<T> enumerator = items.GetEnumerator()) { T[] destination = _current; int index = _index; // Continuously read in items from the enumerator, updating _count // and _index when we run out of space. while (enumerator.MoveNext()) { if (index == destination.Length) { // No more space in this buffer. Resize. _count += index - _index; _index = index; AllocateBuffer(); destination = _current; index = _index; // May have been reset to 0 } destination[index++] = enumerator.Current; } // Final update to _count and _index. _count += index - _index; _index = index; } } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> public void CopyTo(T[] array, int arrayIndex, int count) { Debug.Assert(arrayIndex >= 0); Debug.Assert(count >= 0 && count <= Count); Debug.Assert(array?.Length - arrayIndex >= count); for (int i = 0; count > 0; i++) { // Find the buffer we're copying from. T[] buffer = GetBuffer(index: i); // Copy until we satisfy count, or we reach the end of the buffer. int toCopy = Math.Min(count, buffer.Length); Array.Copy(buffer, 0, array, arrayIndex, toCopy); // Increment variables to that position. count -= toCopy; arrayIndex += toCopy; } } /// <summary> /// Copies the contents of this builder to the specified array. /// </summary> /// <param name="position">The position in this builder to start copying from.</param> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index in <see cref="array"/> to start copying to.</param> /// <param name="count">The number of items to copy.</param> /// <returns>The position in this builder that was copied up to.</returns> public CopyPosition CopyTo(CopyPosition position, T[] array, int arrayIndex, int count) { Debug.Assert(arrayIndex >= 0); Debug.Assert(count >= 0 && count <= Count); Debug.Assert(array?.Length - arrayIndex >= count); // Go through each buffer, which contains one 'row' of items. // The index in each buffer is referred to as the 'column'. /* * Visual representation: * * C0 C1 C2 .. C31 .. C63 * R0: [0] [1] [2] .. [31] * R1: [32] [33] [34] .. [63] * R2: [64] [65] [66] .. [95] .. [127] */ int row = position.Row; int column = position.Column; for (; count > 0; row++, column = 0) { T[] buffer = GetBuffer(index: row); // During this iteration, copy until we satisfy `count` or reach the // end of the current buffer. int copyCount = Math.Min(buffer.Length, count); if (copyCount > 0) { Array.Copy(buffer, column, array, arrayIndex, copyCount); arrayIndex += copyCount; count -= copyCount; column += copyCount; } } return new CopyPosition(row: row, column: column); } /// <summary> /// Retrieves the buffer at the specified index. /// </summary> /// <param name="index">The index of the buffer.</param> public T[] GetBuffer(int index) { Debug.Assert(index >= 0 && index < _buffers.Count + 2); return index == 0 ? _first : index <= _buffers.Count ? _buffers[index - 1] : _current; } /// <summary> /// Adds an item to this builder. /// </summary> /// <param name="item">The item to add.</param> /// <remarks> /// Use <see cref="Add"/> if adding to the builder is a bottleneck for your use case. /// Otherwise, use <see cref="SlowAdd"/>. /// </remarks> [MethodImpl(MethodImplOptions.NoInlining)] public void SlowAdd(T item) => Add(item); /// <summary> /// Creates an array from the contents of this builder. /// </summary> public T[] ToArray() { if (TryMove(out T[] array)) { // No resizing to do. return array; } array = new T[_count]; CopyTo(array, 0, _count); return array; } /// <summary> /// Attempts to transfer this builder into an array without copying. /// </summary> /// <param name="array">The transferred array, if the operation succeeded.</param> /// <returns><c>true</c> if the operation succeeded; otherwise, <c>false</c>.</returns> public bool TryMove(out T[] array) { array = _first; return _count == _first.Length; } private void AllocateBuffer() { // - On the first few adds, simply resize _first. // - When we pass ResizeLimit, allocate ResizeLimit elements for _current // and start reading into _current. Set _index to 0. // - When _current runs out of space, add it to _buffers and repeat the // above step, except with _current.Length * 2. // - Make sure we never pass _maxCapacity in all of the above steps. Debug.Assert((uint)_maxCapacity > (uint)_count); Debug.Assert(_index == _current.Length, $"{nameof(AllocateBuffer)} was called, but there's more space."); // If _count is int.MinValue, we want to go down the other path which will raise an exception. if ((uint)_count < (uint)ResizeLimit) { // We haven't passed ResizeLimit. Resize _first, copying over the previous items. Debug.Assert(_current == _first && _count == _first.Length); int nextCapacity = Math.Min(_count == 0 ? StartingCapacity : _count * 2, _maxCapacity); _current = new T[nextCapacity]; Array.Copy(_first, 0, _current, 0, _count); _first = _current; } else { Debug.Assert(_maxCapacity > ResizeLimit); Debug.Assert(_count == ResizeLimit ^ _current != _first); int nextCapacity; if (_count == ResizeLimit) { nextCapacity = ResizeLimit; } else { // Example scenario: Let's say _count == 64. // Then our buffers look like this: | 8 | 8 | 16 | 32 | // As you can see, our count will be just double the last buffer. // Now, say _maxCapacity is 100. We will find the right amount to allocate by // doing min(64, 100 - 64). The lhs represents double the last buffer, // the rhs the limit minus the amount we've already allocated. Debug.Assert(_count >= ResizeLimit * 2); Debug.Assert(_count == _current.Length * 2); _buffers.Add(_current); nextCapacity = Math.Min(_count, _maxCapacity - _count); } _current = new T[nextCapacity]; _index = 0; } } } }
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors using System; using System.Collections.Generic; using System.Linq; using System.Text; using Generator.Enums; using Generator.Enums.Rust; using Generator.IO; using Generator.Tables; namespace Generator.Encoder.Rust { [Generator(TargetLanguage.Rust)] sealed class RustEncoderGenerator : EncoderGenerator { readonly GeneratorContext generatorContext; readonly IdentifierConverter idConverter; readonly RustEnumsGenerator enumGenerator; public RustEncoderGenerator(GeneratorContext generatorContext) : base(generatorContext.Types) { this.generatorContext = generatorContext; idConverter = RustIdentifierConverter.Create(); enumGenerator = new RustEnumsGenerator(generatorContext); } protected override void Generate(EnumType enumType) => enumGenerator.Generate(enumType); [Flags] enum OpInfoFlags { None = 0, Legacy = 1, VEX = 2, EVEX = 4, XOP = 8, } sealed class OpInfo { public readonly OpHandlerKind OpHandlerKind; public readonly object[] Args; public readonly string Name; public OpInfoFlags Flags; public OpInfo(OpHandlerKind opHandlerKind, object[] args, string name) { OpHandlerKind = opHandlerKind; Args = args; Name = name; Flags = OpInfoFlags.None; } } sealed class OpKeyComparer : IEqualityComparer<(OpHandlerKind opHandlerKind, object[] args)> { public bool Equals((OpHandlerKind opHandlerKind, object[] args) x, (OpHandlerKind opHandlerKind, object[] args) y) { if (x.opHandlerKind != y.opHandlerKind) return false; var xa = x.args; var ya = y.args; if (xa.Length != ya.Length) return false; for (int i = 0; i < xa.Length; i++) { if (!Equals(xa[i], ya[i])) return false; } return true; } public int GetHashCode((OpHandlerKind opHandlerKind, object[] args) obj) { var args = obj.args; int hc = HashCode.Combine((int)obj.opHandlerKind, args.Length); for (int i = 0; i < args.Length; i++) hc = HashCode.Combine(args[i].GetHashCode()); return hc; } } protected override void Generate((EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] legacy, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] vex, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] xop, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] evex) { GenerateOpCodeOperandKindTables(legacy, vex, xop, evex); GenerateOpTables(legacy, vex, xop, evex); } void GenerateOpCodeOperandKindTables((EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] legacy, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] vex, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] xop, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] evex) { var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "op_kind_tables.rs"); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); writer.WriteLine("use super::super::OpCodeOperandKind;"); Generate(writer, "LEGACY_OP_KINDS", null, legacy); Generate(writer, "VEX_OP_KINDS", RustConstants.FeatureVex, vex); Generate(writer, "XOP_OP_KINDS", RustConstants.FeatureXop, xop); Generate(writer, "EVEX_OP_KINDS", RustConstants.FeatureEvex, evex); } void Generate(FileWriter writer, string name, string? feature, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] table) { var declTypeStr = genTypes[TypeIds.OpCodeOperandKind].Name(idConverter); writer.WriteLine(); writer.WriteLine(RustConstants.AttributeNoRustFmt); if (feature is not null) writer.WriteLine(feature); writer.WriteLine($"pub(super) static {name}: [{declTypeStr}; {table.Length}] = ["); using (writer.Indent()) { foreach (var info in table) writer.WriteLine($"{declTypeStr}::{info.opCodeOperandKind.Name(idConverter)},"); } writer.WriteLine("];"); } } void GenerateOpTables((EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] legacy, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] vex, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] xop, (EnumValue opCodeOperandKind, OpHandlerKind opHandlerKind, object[] args)[] evex) { var sb = new StringBuilder(); var dict = new Dictionary<(OpHandlerKind opHandlerKind, object[] args), OpInfo>(new OpKeyComparer()); Add(sb, dict, legacy.Select(a => (a.opHandlerKind, a.args)), OpInfoFlags.Legacy); Add(sb, dict, vex.Select(a => (a.opHandlerKind, a.args)), OpInfoFlags.VEX); Add(sb, dict, xop.Select(a => (a.opHandlerKind, a.args)), OpInfoFlags.XOP); Add(sb, dict, evex.Select(a => (a.opHandlerKind, a.args)), OpInfoFlags.EVEX); var usedNames = new HashSet<string>(dict.Count, StringComparer.Ordinal); foreach (var kv in dict) { if (!usedNames.Add(kv.Value.Name)) throw new InvalidOperationException(); } var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "ops_tables.rs"); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); writer.WriteLine("use super::super::*;"); writer.WriteLine("use super::ops::*;"); writer.WriteLine(); foreach (var kv in dict.OrderBy(a => a.Value.Name, StringComparer.Ordinal)) { var info = kv.Value; var structName = idConverter.Type(GetStructName(info.OpHandlerKind)); var features = GetFeatures(info); if (features is not null) writer.WriteLine(features); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.Write($"static {info.Name}: {structName} = {structName}"); switch (info.OpHandlerKind) { case OpHandlerKind.OpA: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) writer.WriteLine($"size: {(int)info.Args[0]}"); writer.WriteLine("};"); break; case OpHandlerKind.OpHx: case OpHandlerKind.OpIsX: case OpHandlerKind.OpModRM_reg: case OpHandlerKind.OpModRM_reg_mem: case OpHandlerKind.OpModRM_regF0: case OpHandlerKind.OpModRM_rm: case OpHandlerKind.OpModRM_rm_reg_only: case OpHandlerKind.OpRegEmbed8: if (info.Args.Length != 2) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) { WriteField(writer, "reg_lo", (EnumValue)info.Args[0]); WriteField(writer, "reg_hi", (EnumValue)info.Args[1]); } writer.WriteLine("};"); break; case OpHandlerKind.OpIb: case OpHandlerKind.OpId: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) WriteField(writer, "op_kind", (EnumValue)info.Args[0]); writer.WriteLine("};"); break; case OpHandlerKind.OpImm: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) writer.WriteLine($"value: {(int)info.Args[0]}"); writer.WriteLine("};"); break; case OpHandlerKind.OpJ: if (info.Args.Length != 2) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) { WriteField(writer, "op_kind", (EnumValue)info.Args[0]); writer.WriteLine($"imm_size: {(int)info.Args[1]}"); } writer.WriteLine("};"); break; case OpHandlerKind.OpJdisp: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) writer.WriteLine($"displ_size: {(int)info.Args[0]}"); writer.WriteLine("};"); break; case OpHandlerKind.OpJx: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) writer.WriteLine($"imm_size: {(int)info.Args[0]}"); writer.WriteLine("};"); break; case OpHandlerKind.OpReg: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) WriteField(writer, "register", (EnumValue)info.Args[0]); writer.WriteLine("};"); break; case OpHandlerKind.OpVsib: if (info.Args.Length != 2) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) { WriteField(writer, "vsib_index_reg_lo", (EnumValue)info.Args[0]); WriteField(writer, "vsib_index_reg_hi", (EnumValue)info.Args[1]); } writer.WriteLine("};"); break; case OpHandlerKind.None: case OpHandlerKind.OpI4: case OpHandlerKind.OpIq: case OpHandlerKind.OpIw: case OpHandlerKind.OpMRBX: case OpHandlerKind.OpO: case OpHandlerKind.OprDI: case OpHandlerKind.OpRegSTi: case OpHandlerKind.OpX: case OpHandlerKind.OpY: if (info.Args.Length != 0) throw new InvalidOperationException(); writer.WriteLine(";"); break; case OpHandlerKind.OpModRM_rm_mem_only: if (info.Args.Length != 1) throw new InvalidOperationException(); writer.WriteLine(" {"); using (writer.Indent()) WriteFieldBool(writer, "must_use_sib", (bool)info.Args[0]); writer.WriteLine("};"); break; default: throw new InvalidOperationException(); } } writer.WriteLine(); WriteTable(writer, "LEGACY_TABLE", null, dict, legacy.Select(a => (a.opCodeOperandKind, a.opHandlerKind, a.args))); WriteTable(writer, "VEX_TABLE", RustConstants.FeatureVex, dict, vex.Select(a => (a.opCodeOperandKind, a.opHandlerKind, a.args))); WriteTable(writer, "XOP_TABLE", RustConstants.FeatureXop, dict, xop.Select(a => (a.opCodeOperandKind, a.opHandlerKind, a.args))); WriteTable(writer, "EVEX_TABLE", RustConstants.FeatureEvex, dict, evex.Select(a => (a.opCodeOperandKind, a.opHandlerKind, a.args))); } static string? GetFeatures(OpInfo info) { if (info.Flags == OpInfoFlags.None) throw new InvalidOperationException("No refs"); if ((info.Flags & OpInfoFlags.Legacy) != 0) return null; var features = new List<string>(); if ((info.Flags & OpInfoFlags.VEX) != 0) features.Add(RustConstants.Vex); if ((info.Flags & OpInfoFlags.EVEX) != 0) features.Add(RustConstants.Evex); if ((info.Flags & OpInfoFlags.XOP) != 0) features.Add(RustConstants.Xop); if (features.Count == 0) return null; if (features.Count == 1) return string.Format(RustConstants.FeatureEncodingOne, features[0]); var featuresStr = string.Join(", ", features.ToArray()); return string.Format(RustConstants.FeatureEncodingMany, featuresStr); } void WriteTable(FileWriter writer, string name, string? feature, Dictionary<(OpHandlerKind opHandlerKind, object[] args), OpInfo> dict, IEnumerable<(EnumValue opKind, OpHandlerKind opHandlerKind, object[] args)> values) { var all = values.ToArray(); if (feature is not null) writer.WriteLine(feature); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"pub(super) static {name}: [&(dyn Op + Sync); {all.Length}] = ["); using (writer.Indent()) { foreach (var value in all) { var info = dict[(value.opHandlerKind, value.args)]; writer.WriteLine($"&{info.Name},// {value.opKind.Name(idConverter)}"); } } writer.WriteLine("];"); } void WriteField(FileWriter writer, string name, EnumValue value) => writer.WriteLine($"{name}: {value.DeclaringType.Name(idConverter)}::{value.Name(idConverter)},"); void WriteFieldBool(FileWriter writer, string name, bool value) => writer.WriteLine($"{name}: {(value ? "true" : "false")},"); void Add(StringBuilder sb, Dictionary<(OpHandlerKind opHandlerKind, object[] args), OpInfo> dict, IEnumerable<(OpHandlerKind opHandlerKind, object[] args)> values, OpInfoFlags flags) { foreach (var value in values) { if (!dict.TryGetValue(value, out var opInfo)) dict.Add(value, opInfo = new OpInfo(value.opHandlerKind, value.args, GetName(sb, value.opHandlerKind, value.args))); opInfo.Flags |= flags; } } string GetName(StringBuilder sb, OpHandlerKind opHandlerKind, object[] args) { sb.Clear(); sb.Append(opHandlerKind.ToString()); foreach (var obj in args) { sb.Append('_'); switch (obj) { case EnumValue value: sb.Append(value.RawName); break; case int value: sb.Append(value); break; case bool value: sb.Append(value ? "true" : "false"); break; default: throw new InvalidOperationException(); } } return idConverter.Static(sb.ToString()); } static string GetStructName(OpHandlerKind kind) { if (kind == OpHandlerKind.None) return "InvalidOpHandler"; return kind.ToString(); } } protected override void GenerateOpCodeInfo(InstructionDef[] defs) => GenerateTable(defs); void GenerateTable(InstructionDef[] defs) { var allData = GetData(defs).ToArray(); var encFlags1 = allData.Select(a => (a.def, a.encFlags1)).ToArray(); var encFlags2 = allData.Select(a => (a.def, a.encFlags2)).ToArray(); var encFlags3 = allData.Select(a => (a.def, a.encFlags3)).ToArray(); var opcFlags1 = allData.Select(a => (a.def, a.opcFlags1)).ToArray(); var opcFlags2 = allData.Select(a => (a.def, a.opcFlags2)).ToArray(); var encoderInfo = new (string name, (InstructionDef def, uint value)[] values)[] { ("ENC_FLAGS1", encFlags1), ("ENC_FLAGS2", encFlags2), ("ENC_FLAGS3", encFlags3), }; var opCodeInfo = new (string name, (InstructionDef def, uint value)[] values)[] { ("OPC_FLAGS1", opcFlags1), ("OPC_FLAGS2", opcFlags2), }; GenerateTables(defs, encoderInfo, "encoder_data.rs"); GenerateTables(defs, opCodeInfo, "op_code_data.rs"); } void GenerateTables(InstructionDef[] defs, (string name, (InstructionDef def, uint value)[] values)[] encoderInfo, string filename) { var fullFilename = generatorContext.Types.Dirs.GetRustFilename("encoder", filename); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(fullFilename))) { writer.WriteFileHeader(); foreach (var info in encoderInfo) { writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"pub(super) static {info.name}: [u32; {defs.Length}] = ["); using (writer.Indent()) { foreach (var vinfo in info.values) writer.WriteLine($"{NumberFormatter.FormatHexUInt32WithSep(vinfo.value)},// {vinfo.def.Code.Name(idConverter)}"); } writer.WriteLine("];"); } } } protected override void Generate((EnumValue value, uint size)[] immSizes) { var filename = generatorContext.Types.Dirs.GetRustFilename("encoder.rs"); new FileUpdater(TargetLanguage.Rust, "ImmSizes", filename).Generate(writer => { writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"static IMM_SIZES: [u32; {immSizes.Length}] = ["); using (writer.Indent()) { foreach (var info in immSizes) writer.WriteLine($"{info.size},// {info.value.Name(idConverter)}"); } writer.WriteLine("];"); }); } void GenerateCases(string filename, string id, EnumValue[] codeValues, string statement) { new FileUpdater(TargetLanguage.Rust, id, filename).Generate(writer => { if (codeValues.Length == 0) return; var bar = string.Empty; foreach (var value in codeValues) { writer.WriteLine($"{bar}{value.DeclaringType.Name(idConverter)}::{value.Name(idConverter)}"); bar = "| "; } writer.WriteLine($"=> {statement},"); }); } void GenerateNotInstrCases(string filename, string id, (EnumValue code, string result)[] notInstrStrings, bool useReturn) { new FileUpdater(TargetLanguage.Rust, id, filename).Generate(writer => { string @return = useReturn ? "return " : string.Empty; foreach (var info in notInstrStrings) writer.WriteLine($"{info.code.DeclaringType.Name(idConverter)}::{info.code.Name(idConverter)} => {@return}String::from(\"{info.result}\"),"); }); } protected override void GenerateInstructionFormatter((EnumValue code, string result)[] notInstrStrings) { var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "instruction_fmt.rs"); GenerateNotInstrCases(filename, "InstrFmtNotInstructionString", notInstrStrings, true); } protected override void GenerateOpCodeFormatter((EnumValue code, string result)[] notInstrStrings, EnumValue[] hasModRM, EnumValue[] hasVsib) { var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "op_code_fmt.rs"); GenerateNotInstrCases(filename, "OpCodeFmtNotInstructionString", notInstrStrings, false); GenerateCases(filename, "HasModRM", hasModRM, "return true"); GenerateCases(filename, "HasVsib", hasVsib, "return true"); } protected override void GenerateCore() => GenerateMnemonicStringTable(); void GenerateMnemonicStringTable() { var values = genTypes[TypeIds.Mnemonic].Values; var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "mnemonic_str_tbl.rs"); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"pub(super) static TO_MNEMONIC_STR: [&str; {values.Length}] = ["); using (writer.Indent()) { foreach (var value in values) writer.WriteLine($"\"{value.RawName.ToLowerInvariant()}\","); } writer.WriteLine("];"); } } protected override void GenerateInstrSwitch(EnumValue[] jccInstr, EnumValue[] simpleBranchInstr, EnumValue[] callInstr, EnumValue[] jmpInstr, EnumValue[] xbeginInstr) { var filename = generatorContext.Types.Dirs.GetRustFilename("block_enc", "instr", "mod.rs"); GenerateCases(filename, "JccInstr", jccInstr, "return Rc::new(RefCell::new(JccInstr::new(block_encoder, block, instruction)))"); GenerateCases(filename, "SimpleBranchInstr", simpleBranchInstr, "return Rc::new(RefCell::new(SimpleBranchInstr::new(block_encoder, block, instruction)))"); GenerateCases(filename, "CallInstr", callInstr, "return Rc::new(RefCell::new(CallInstr::new(block_encoder, block, instruction)))"); GenerateCases(filename, "JmpInstr", jmpInstr, "return Rc::new(RefCell::new(JmpInstr::new(block_encoder, block, instruction)))"); GenerateCases(filename, "XbeginInstr", xbeginInstr, "return Rc::new(RefCell::new(XbeginInstr::new(block_encoder, block, instruction)))"); } protected override void GenerateVsib(EnumValue[] vsib32, EnumValue[] vsib64) { var filename = generatorContext.Types.Dirs.GetRustFilename("instruction.rs"); GenerateCases(filename, "Vsib32", vsib32, "Some(false)"); GenerateCases(filename, "Vsib64", vsib64, "Some(true)"); } protected override void GenerateDecoderOptionsTable((EnumValue decOptionValue, EnumValue decoderOptions)[] values) { var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "op_code.rs"); new FileUpdater(TargetLanguage.Rust, "ToDecoderOptionsTable", filename).Generate(writer => { writer.WriteLine(RustConstants.FeatureDecoder); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"static TO_DECODER_OPTIONS: [u32; {values.Length}] = ["); using (writer.Indent()) { foreach (var (_, decoderOptions) in values) writer.WriteLine($"{decoderOptions.DeclaringType.Name(idConverter)}::{idConverter.Constant(decoderOptions.RawName)},"); } writer.WriteLine("];"); }); } protected override void GenerateImpliedOps((EncodingKind Encoding, InstrStrImpliedOp[] Ops, InstructionDef[] defs)[] impliedOpsInfo) { var filename = generatorContext.Types.Dirs.GetRustFilename("encoder", "instruction_fmt.rs"); new FileUpdater(TargetLanguage.Rust, "PrintImpliedOps", filename).Generate(writer => { foreach (var info in impliedOpsInfo) { if (RustConstants.GetFeature(info.Encoding) is string feature) writer.WriteLine(feature); var bar = string.Empty; foreach (var def in info.defs) { writer.Write($"{bar}{def.Code.DeclaringType.Name(idConverter)}::{def.Code.Name(idConverter)}"); bar = " | "; } writer.WriteLine(" => {"); using (writer.Indent()) { foreach (var op in info.Ops) { writer.WriteLine("self.write_op_separator();"); writer.WriteLine($"self.write(\"{op.Operand}\", {(op.IsUpper ? "true" : "false")});"); } } writer.WriteLine("}"); } }); } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; #if DOTNET35 // Needed for ReadOnlyDictionary, which does not exist in .NET 3.5 using Google.Protobuf.Collections; #endif namespace Google.Protobuf.Reflection { /// <summary> /// Describes a message type. /// </summary> public sealed class MessageDescriptor : DescriptorBase { private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string> { "google/protobuf/any.proto", "google/protobuf/api.proto", "google/protobuf/duration.proto", "google/protobuf/empty.proto", "google/protobuf/wrappers.proto", "google/protobuf/timestamp.proto", "google/protobuf/field_mask.proto", "google/protobuf/source_context.proto", "google/protobuf/struct.proto", "google/protobuf/type.proto", }; private readonly IList<FieldDescriptor> fieldsInDeclarationOrder; private readonly IList<FieldDescriptor> fieldsInNumberOrder; private readonly IDictionary<string, FieldDescriptor> jsonFieldMap; internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo) : base(file, file.ComputeFullName(parent, proto.Name), typeIndex) { Proto = proto; Parser = generatedCodeInfo?.Parser; ClrType = generatedCodeInfo?.ClrType; ContainingType = parent; // Note use of generatedCodeInfo. rather than generatedCodeInfo?. here... we don't expect // to see any nested oneofs, types or enums in "not actually generated" code... we do // expect fields though (for map entry messages). Oneofs = DescriptorUtil.ConvertAndMakeReadOnly( proto.OneofDecl, (oneof, index) => new OneofDescriptor(oneof, file, this, index, generatedCodeInfo.OneofNames[index])); NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly( proto.NestedType, (type, index) => new MessageDescriptor(type, file, this, index, generatedCodeInfo.NestedTypes[index])); EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly( proto.EnumType, (type, index) => new EnumDescriptor(type, file, this, index, generatedCodeInfo.NestedEnums[index])); fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly( proto.Field, (field, index) => new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index])); fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray()); // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.) jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder); file.DescriptorPool.AddSymbol(this); Fields = new FieldCollection(this); } private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields) { var map = new Dictionary<string, FieldDescriptor>(); foreach (var field in fields) { map[field.Name] = field; map[field.JsonName] = field; } return new ReadOnlyDictionary<string, FieldDescriptor>(map); } /// <summary> /// The brief name of the descriptor's target. /// </summary> public override string Name => Proto.Name; internal DescriptorProto Proto { get; } /// <summary> /// The CLR type used to represent message instances from this descriptor. /// </summary> /// <remarks> /// <para> /// The value returned by this property will be non-null for all regular fields. However, /// if a message containing a map field is introspected, the list of nested messages will include /// an auto-generated nested key/value pair message for the field. This is not represented in any /// generated type, so this property will return null in such cases. /// </para> /// <para> /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here /// will be the generated message type, not the native type used by reflection for fields of those types. Code /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents /// a wrapper type, and handle the result appropriately. /// </para> /// </remarks> public Type ClrType { get; } /// <summary> /// A parser for this message type. /// </summary> /// <remarks> /// <para> /// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically /// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>. /// </para> /// <para> /// The value returned by this property will be non-null for all regular fields. However, /// if a message containing a map field is introspected, the list of nested messages will include /// an auto-generated nested key/value pair message for the field. No message parser object is created for /// such messages, so this property will return null in such cases. /// </para> /// <para> /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here /// will be the generated message type, not the native type used by reflection for fields of those types. Code /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents /// a wrapper type, and handle the result appropriately. /// </para> /// </remarks> public MessageParser Parser { get; } /// <summary> /// Returns whether this message is one of the "well known types" which may have runtime/protoc support. /// </summary> internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name); /// <summary> /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values /// with the addition of presence. /// </summary> internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto"; /// <value> /// If this is a nested type, get the outer descriptor, otherwise null. /// </value> public MessageDescriptor ContainingType { get; } /// <value> /// A collection of fields, which can be retrieved by name or field number. /// </value> public FieldCollection Fields { get; } /// <value> /// An unmodifiable list of this message type's nested types. /// </value> public IList<MessageDescriptor> NestedTypes { get; } /// <value> /// An unmodifiable list of this message type's enum types. /// </value> public IList<EnumDescriptor> EnumTypes { get; } /// <value> /// An unmodifiable list of the "oneof" field collections in this message type. /// </value> public IList<OneofDescriptor> Oneofs { get; } /// <summary> /// Finds a field by field name. /// </summary> /// <param name="name">The unqualified name of the field (e.g. "foo").</param> /// <returns>The field's descriptor, or null if not found.</returns> public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name); /// <summary> /// Finds a field by field number. /// </summary> /// <param name="number">The field number within this message type.</param> /// <returns>The field's descriptor, or null if not found.</returns> public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number); /// <summary> /// Finds a nested descriptor by name. The is valid for fields, nested /// message types, oneofs and enums. /// </summary> /// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param> /// <returns>The descriptor, or null if not found.</returns> public T FindDescriptor<T>(string name) where T : class, IDescriptor => File.DescriptorPool.FindSymbol<T>(FullName + "." + name); /// <summary> /// Looks up and cross-links all fields and nested types. /// </summary> internal void CrossLink() { foreach (MessageDescriptor message in NestedTypes) { message.CrossLink(); } foreach (FieldDescriptor field in fieldsInDeclarationOrder) { field.CrossLink(); } foreach (OneofDescriptor oneof in Oneofs) { oneof.CrossLink(); } } /// <summary> /// A collection to simplify retrieving the field accessor for a particular field. /// </summary> public sealed class FieldCollection { private readonly MessageDescriptor messageDescriptor; internal FieldCollection(MessageDescriptor messageDescriptor) { this.messageDescriptor = messageDescriptor; } /// <value> /// Returns the fields in the message as an immutable list, in the order in which they /// are declared in the source .proto file. /// </value> public IList<FieldDescriptor> InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder; /// <value> /// Returns the fields in the message as an immutable list, in ascending field number /// order. Field numbers need not be contiguous, so there is no direct mapping from the /// index in the list to the field number; to retrieve a field by field number, it is better /// to use the <see cref="FieldCollection"/> indexer. /// </value> public IList<FieldDescriptor> InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder; // TODO: consider making this public in the future. (Being conservative for now...) /// <value> /// Returns a read-only dictionary mapping the field names in this message as they're available /// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c> /// in the message would result two entries, one with a key <c>fooBar</c> and one with a key /// <c>foo_bar</c>, both referring to the same field. /// </value> internal IDictionary<string, FieldDescriptor> ByJsonName() => messageDescriptor.jsonFieldMap; /// <summary> /// Retrieves the descriptor for the field with the given number. /// </summary> /// <param name="number">Number of the field to retrieve the descriptor for</param> /// <returns>The accessor for the given field</returns> /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field /// with the given number</exception> public FieldDescriptor this[int number] { get { var fieldDescriptor = messageDescriptor.FindFieldByNumber(number); if (fieldDescriptor == null) { throw new KeyNotFoundException("No such field number"); } return fieldDescriptor; } } /// <summary> /// Retrieves the descriptor for the field with the given name. /// </summary> /// <param name="name">Name of the field to retrieve the descriptor for</param> /// <returns>The descriptor for the given field</returns> /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field /// with the given name</exception> public FieldDescriptor this[string name] { get { var fieldDescriptor = messageDescriptor.FindFieldByName(name); if (fieldDescriptor == null) { throw new KeyNotFoundException("No such field name"); } return fieldDescriptor; } } } } }
// // ProfileConfigurationDialog.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2006-2008 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.Generic; using Mono.Unix; using Gtk; using Banshee.MediaProfiles; using Banshee.Base; namespace Banshee.MediaProfiles.Gui { internal class PipelineVariableComboBox : Gtk.ComboBox { private PipelineVariable variable; private ListStore model; public PipelineVariableComboBox(PipelineVariable variable, ListStore model) : base() { this.variable = variable; this.model = model; } protected PipelineVariableComboBox(IntPtr ptr) : base(ptr) { } public PipelineVariable Variable { get { return variable; } } public ListStore Store { get { return model; } } } public class ProfileConfigurationDialog : Gtk.Dialog { private Profile profile; private Label header_label = new Label(); private Hyena.Widgets.WrapLabel description_label = new Hyena.Widgets.WrapLabel(); private Table normal_controls_table = new Table(1, 1, false); private Table advanced_controls_table = new Table(1, 1, false); private Expander advanced_expander = new Expander(Catalog.GetString("Advanced")); private TextView sexpr_results = null; private Dictionary<string, Widget> variable_widgets = new Dictionary<string, Widget>(); public ProfileConfigurationDialog(Profile profile) : base() { this.profile = profile; HasSeparator = false; BorderWidth = 5; AccelGroup accel_group = new AccelGroup(); AddAccelGroup(accel_group); Button button = new Button(Stock.Close); button.CanDefault = true; button.Show(); if(ApplicationContext.Debugging) { Button test_button = new Button("Test S-Expr"); test_button.Show(); test_button.Clicked += delegate { if(sexpr_results != null) { sexpr_results.Buffer.Text = profile.Pipeline.GetDefaultProcess(); } }; ActionArea.PackStart(test_button, true, true, 0); sexpr_results = new TextView(); } AddActionWidget(button, ResponseType.Close); DefaultResponse = ResponseType.Close; button.AddAccelerator("activate", accel_group, (uint)Gdk.Key.Return, 0, AccelFlags.Visible); BuildContents(); LoadProfile(); } private void BuildContents() { VBox box = new VBox(); box.BorderWidth = 8; box.Spacing = 10; box.Show(); header_label.Xalign = 0.0f; header_label.Show(); description_label.Show(); normal_controls_table.Show(); advanced_controls_table.Show(); advanced_expander.Add(advanced_controls_table); advanced_expander.Show(); box.PackStart(header_label, false, false, 0); box.PackStart(description_label, false, false, 0); box.PackStart(normal_controls_table, false, false, 5); box.PackStart(advanced_expander, false, false, 0); if(sexpr_results != null) { ScrolledWindow scroll = new Gtk.ScrolledWindow(); scroll.HscrollbarPolicy = PolicyType.Automatic; scroll.VscrollbarPolicy = PolicyType.Automatic; scroll.ShadowType = ShadowType.In; sexpr_results.WrapMode = WrapMode.Word; sexpr_results.SetSizeRequest(-1, 100); scroll.Add(sexpr_results); scroll.ShowAll(); VSeparator sep = new VSeparator(); sep.Show(); Label label = new Label(); label.Markup = "<b>S-Expr Results</b>"; label.Xalign = 0.0f; label.Show(); box.PackStart(sep, false, false, 0); box.PackStart(label, false, false, 0); box.PackStart(scroll, false, false, 0); } VBox.PackStart(box, false, false, 0); SetSizeRequest(350, -1); Gdk.Geometry limits = new Gdk.Geometry(); limits.MinWidth = SizeRequest().Width; limits.MaxWidth = Gdk.Screen.Default.Width; limits.MinHeight = -1; limits.MaxHeight = -1; SetGeometryHints(this, limits, Gdk.WindowHints.MaxSize | Gdk.WindowHints.MinSize); } private void LoadProfile() { Title = String.Format (Catalog.GetString ("Configuring {0}"), profile.Name); header_label.Markup = String.Format("<big><b>{0}</b></big>", GLib.Markup.EscapeText(profile.Name)); description_label.Text = profile.Description; LoadControlTable(normal_controls_table, false); LoadControlTable(advanced_controls_table, true); advanced_expander.Visible = advanced_controls_table.Visible; } private void LoadControlTable(Table table, bool advanced) { while(table.Children.Length > 0) { table.Remove(table.Children[0]); } table.Resize(1, 1); table.RowSpacing = 5; table.ColumnSpacing = 12; uint y = 0; foreach(PipelineVariable variable in profile.Pipeline) { if(advanced != variable.Advanced) { continue; } Label label = new Label(); label.Show(); label.Markup = String.Format("<b>{0}:</b>", GLib.Markup.EscapeText(variable.Name)); label.Xalign = 0.0f; try { Widget control = BuildControl(variable); if(control == null) { throw new ApplicationException("Control could not be created"); } variable_widgets.Add(variable.Id, control); if(variable.ControlType != PipelineVariableControlType.Check) { variable_widgets.Add(".label." + variable.Id, label); } control.Show(); table.Resize(y + 1, 2); if(variable.ControlType != PipelineVariableControlType.Check) { table.Attach(label, 0, 1, y, y + 1, AttachOptions.Fill, AttachOptions.Fill, 0, 0); } table.Attach(control, 1, 2, y, y + 1, control is ComboBox ? AttachOptions.Fill : AttachOptions.Fill | AttachOptions.Expand, AttachOptions.Fill, 0, (uint)(variable.ControlType == PipelineVariableControlType.Check ? 2 : 0)); y++; } catch { } } foreach(Widget widget in variable_widgets.Values) { if(widget is PipelineVariableComboBox) { OnComboChanged(widget, EventArgs.Empty); } else if(widget is CheckButton) { (widget as CheckButton).Toggle(); } } table.Visible = y > 0; } private Widget BuildControl(PipelineVariable variable) { switch(variable.ControlType) { default: case PipelineVariableControlType.Text: return new Entry(); case PipelineVariableControlType.Slider: return BuildSlider(variable); case PipelineVariableControlType.Combo: return BuildCombo(variable); case PipelineVariableControlType.Check: return BuildCheck(variable); } } private Widget BuildCheck(PipelineVariable variable) { CheckButton check = new CheckButton(variable.Name); check.Toggled += delegate { variable.CurrentValue = Convert.ToString(check.Active ? 1 : 0); for(int i = 0; i < variable.Enables.Length; i++) { if(variable_widgets.ContainsKey(variable.Enables[i])) { variable_widgets[variable.Enables[i]].Visible = check.Active; variable_widgets[".label." + variable.Enables[i]].Visible = check.Active; } } for(int i = 0; i < variable.Disables.Length; i++) { if(variable_widgets.ContainsKey(variable.Disables[i])) { variable_widgets[variable.Disables[i]].Visible = !check.Active; variable_widgets[".label." + variable.Disables[i]].Visible = !check.Active; } } }; check.Active = ((int)variable.CurrentValueNumeric.Value) != 0; check.Show(); return check; } private Widget BuildSlider(PipelineVariable variable) { if(variable.StepValue <= 0.0) { return null; } HBox box = new HBox(); HScale slider = new HScale(variable.MinValue, variable.MaxValue, variable.StepValue); slider.DrawValue = true; slider.Digits = variable.StepPrecision; if(variable.DefaultValueNumeric != null) { slider.Value = (double)variable.DefaultValueNumeric; } if(variable.CurrentValueNumeric != null) { slider.Value = (double)variable.CurrentValueNumeric; } slider.ChangeValue += delegate { variable.CurrentValue = slider.Value.ToString(); }; if(variable.MinLabel != null) { Label min_label = new Label(); min_label.Yalign = 0.9f; min_label.Markup = String.Format("<small>{0}</small>", GLib.Markup.EscapeText(variable.MinLabel)); box.PackStart(min_label, false, false, 0); box.Spacing = 5; } box.PackStart(slider, true, true, 0); if(variable.MaxLabel != null) { Label max_label = new Label(); max_label.Yalign = 0.9f; max_label.Markup = String.Format("<small>{0}</small>", GLib.Markup.EscapeText(variable.MaxLabel)); box.PackStart(max_label, false, false, 0); box.Spacing = 5; } box.ShowAll(); return box; } private TreeIter ComboAppend(ListStore model, PipelineVariable variable, string display, string value) { if(variable.Unit != null) { return model.AppendValues(String.Format("{0} {1}", display, variable.Unit), value); } else { return model.AppendValues(display, value); } } private Widget BuildCombo(PipelineVariable variable) { ListStore model = new ListStore(typeof(string), typeof(string)); PipelineVariableComboBox box = new PipelineVariableComboBox(variable, model); TreeIter active_iter = TreeIter.Zero; box.Changed += OnComboChanged; if(variable.PossibleValuesCount > 0) { foreach(string key in variable.PossibleValuesKeys) { TreeIter iter = ComboAppend(model, variable, variable.PossibleValues[key].Display, key); if(variable.CurrentValue == key || (active_iter.Equals(TreeIter.Zero) && variable.DefaultValue == key)) { active_iter = iter; } } } else { double min = variable.MinValue; double max = variable.MaxValue; double step = variable.StepValue; double current = min; for(; current <= max; current += step) { ComboAppend(model, variable, current.ToString(), current.ToString()); } } if(active_iter.Equals(TreeIter.Zero)) { for(int i = 0, n = model.IterNChildren(); i < n; i++) { TreeIter iter; if(model.IterNthChild(out iter, i)) { string value = (string)model.GetValue(iter, 1); if(value == variable.CurrentValue) { active_iter = iter; break; } } } } CellRendererText text_renderer = new CellRendererText(); box.PackStart(text_renderer, true); box.AddAttribute(text_renderer, "text", 0); box.Model = model; if(active_iter.Equals(TreeIter.Zero)) { if(model.IterNthChild(out active_iter, 0)) { box.SetActiveIter(active_iter); } } else { box.SetActiveIter(active_iter); } return box; } private void OnComboChanged(object o, EventArgs args) { if(!(o is PipelineVariableComboBox)) { return; } PipelineVariableComboBox box = o as PipelineVariableComboBox; PipelineVariable variable = box.Variable; ListStore model = box.Store; TreeIter selected_iter = TreeIter.Zero; if(box.GetActiveIter(out selected_iter)) { variable.CurrentValue = (string)model.GetValue(selected_iter, 1); if(variable.PossibleValuesCount > 0 && variable.PossibleValues.ContainsKey(variable.CurrentValue)) { PipelineVariable.PossibleValue possible_value = variable.PossibleValues[variable.CurrentValue]; if(possible_value.Disables != null) { for(int i = 0; i < possible_value.Disables.Length; i++) { if(variable_widgets.ContainsKey(possible_value.Disables[i])) { variable_widgets[possible_value.Disables[i]].Visible = false; variable_widgets[".label." + possible_value.Disables[i]].Visible = false; } } } if(possible_value.Enables != null) { for(int i = 0; i < possible_value.Enables.Length; i++) { if(variable_widgets.ContainsKey(possible_value.Enables[i])) { variable_widgets[possible_value.Enables[i]].Visible = true; variable_widgets[".label." + possible_value.Enables[i]].Visible = true; } } } } } } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2005 // // File: XmlLanguage.cs // // Contents: A type that can be used for a property meant to hold the // a value expressed as xml:lang. // // Created: 11/22/2005 jerryd // //------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; using System.IO; using System.Windows; using MS.Internal.PresentationCore; namespace System.Windows.Markup { /// <summary> /// An RFC3066 language tag for use in Xml markup. /// </summary> /// <remarks> /// The tag may or may not have a registered CultureInfo present on the system. /// This class is useful for dealing with values represented using xml:lang in XML. /// Note that XML spec allows the empty string, although that is not permitted by RFC3066; /// therefore, this type permits "". /// </remarks> [TypeConverter(typeof(XmlLanguageConverter))] public class XmlLanguage { // There is a conscious choice here to use Hashtable rather than // Dictionary<string, XmlLanguage>. Dictionary<K, T> offers no // concurrency guarantees whatsoever. So if we used it, we would // have to take one of two implementations approaches. Either, we // would have to take a simple lock around every read and write // operation, causing needless thread-contention amongst threads // doing read operations. Or we have have to use a ReaderWriterLock, // which has measurable negative perf impact in simple real-world // scenarios that don't have heavy thread contention. // // Hashtable is implemented so that as long as writers are protected // by a lock, readers do not need to take a lock. This eliminates // the thread contention problem of the first Dictionary<K, T> // solutions. And furthermore, it has measurable performance benefits // over both of the Dictionary<K, T> solutions. private static Hashtable _cache = new Hashtable(InitialDictionarySize); private const int InitialDictionarySize = 10; // Three for "en-us", "en", and "", plus a few more private const int MaxCultureDepth = 32; private static XmlLanguage _empty = null; private readonly string _lowerCaseTag; private CultureInfo _equivalentCulture; private CultureInfo _specificCulture; private CultureInfo _compatibleCulture; private int _specificity; private bool _equivalentCultureFailed; // only consult after checking _equivalentCulture == null /// <summary> /// PRIVATE constructor. It is vital that this constructor be /// called ONLY from the implementation of GetLanguage(). /// The implementation strategy depends upon reference-equality /// being a complete test for XmlLanguage-equality, /// and GetLanguage's use of _cache is necessary to /// guarantee that reference-equality is sufficient. /// </summary> private XmlLanguage(string lowercase) { _lowerCaseTag = lowercase; _equivalentCulture = null; _specificCulture = null; _compatibleCulture = null; _specificity = -1; _equivalentCultureFailed = false; } /// <summary> /// The XmlLanguage corresponding to string.Empty, whose EquivalentCulture is /// CultureInfo.InvariantCulture. /// </summary> public static XmlLanguage Empty { get { if (_empty == null) { // We MUST NOT call the private constructor, but instead call GetLanguage()! _empty = GetLanguage(string.Empty); } return _empty; } } /// <summary> /// Retrive an XmlLanguage for a given RFC 3066 language string. /// </summary> /// <remarks> /// The language string may be empty, or else must conform to RFC 3066 rules: /// The first subtag must consist of only ASCII letters. /// Additional subtags must consist of ASCII letters or numerals. /// Subtags are separated by a single hyphen character. /// Every subtag must be 1 to 8 characters long. /// No leading or trailing hyphens are permitted. /// </remarks> /// <exception cref="ArgumentNullException"> /// ietfLanguageTag parameter is null /// </exception> /// <exception cref="ArgumentException"> /// ietfLanguageTag is non-empty, but does not conform to the syntax specified in RFC 3066. /// </exception> public static XmlLanguage GetLanguage(string ietfLanguageTag) { XmlLanguage language; if (ietfLanguageTag == null) throw new ArgumentNullException("ietfLanguageTag"); string lowercase = AsciiToLower(ietfLanguageTag); // throws on non-ascii language = (XmlLanguage) _cache[lowercase]; if (language == null) { ValidateLowerCaseTag(lowercase); // throws on RFC 3066 validation failure lock (_cache.SyncRoot) { // Double-check that it is still the case that language-tag is not // present in cache. Without this double-check, there would // be some risk that clients on two different threads might // get two different XmlLanguage instances for the same language // tag. language = (XmlLanguage) _cache[lowercase]; if (language == null) { _cache[lowercase] = language = new XmlLanguage(lowercase); } } } return language; } /// <summary> /// The RFC 3066 string. /// </summary> /// <remarks> /// MAY return a normalized version of the originally-specified string. /// MAY return the empty string. /// </remarks> public string IetfLanguageTag { get { return _lowerCaseTag; } } /// <summary> /// Returns IetfLanguageTag. /// </summary> public override string ToString() { return IetfLanguageTag; } /// <summary> /// Returns a CultureInfo if and only if one is registered matching IetfLanguageTag /// </summary> /// <exception cref="InvalidOperationException"> /// There is no registered CultureInfo with given IetfLanguageTag. /// </exception> public CultureInfo GetEquivalentCulture() { if (_equivalentCulture == null) { string lowerCaseTag = _lowerCaseTag; // xml:lang="und" // see http://www.w3.org/International/questions/qa-no-language // // Just treat it the same as xml:lang="" if(String.CompareOrdinal(lowerCaseTag, "und") == 0) { lowerCaseTag = String.Empty; } try { // Even if we previously failed to find an EquivalentCulture, we retry, if only to // capture inner exception. _equivalentCulture = SafeSecurityHelper.GetCultureInfoByIetfLanguageTag(lowerCaseTag); } catch (ArgumentException e) { _equivalentCultureFailed = true; throw new InvalidOperationException(SR.Get(SRID.XmlLangGetCultureFailure, lowerCaseTag), e); } } return _equivalentCulture; } /// <summary> /// Finds the most-closely-related non-neutral registered CultureInfo, if one is available. /// </summary> /// <returns> /// A non-Neutral CultureInfo. /// </returns> /// <exception cref="InvalidOperationException"> /// There is no related non-Neutral CultureInfo registered. /// </exception> /// <remarks> /// Will return CultureInfo.InvariantCulture if-and-only-if this.Equals(XmlLanguage.Empty). /// Finds the registered CultureInfo matching the longest-possible prefix of this XmlLanguage. /// If that registered CultureInfo is Neutral, then relies on /// CultureInfo.CreateSpecificCulture() to map from a Neutral CultureInfo to a Specific one. /// </remarks> public CultureInfo GetSpecificCulture() { if (_specificCulture == null) { if (_lowerCaseTag.Length == 0 || String.CompareOrdinal(_lowerCaseTag, "und") == 0) { _specificCulture = GetEquivalentCulture(); } else { CultureInfo culture = GetCompatibleCulture(); if (culture.IetfLanguageTag.Length == 0) { throw new InvalidOperationException(SR.Get(SRID.XmlLangGetSpecificCulture, _lowerCaseTag)); } if (!culture.IsNeutralCulture) { _specificCulture = culture; } else { try { // note that it's important that we use culture.Name, not culture.IetfLanguageTag, here culture = CultureInfo.CreateSpecificCulture(culture.Name); _specificCulture = SafeSecurityHelper.GetCultureInfoByIetfLanguageTag(culture.IetfLanguageTag); } catch (ArgumentException e) { throw new InvalidOperationException(SR.Get(SRID.XmlLangGetSpecificCulture, _lowerCaseTag), e); } } } } return _specificCulture; } /// <summary> /// Finds a registered CultureInfo corresponding to the IetfLanguageTag, or the longest /// sequence of leading subtags for which we have a registered CultureInfo. /// </summary> [FriendAccessAllowed] internal CultureInfo GetCompatibleCulture() { if (_compatibleCulture == null) { CultureInfo culture = null; if (!TryGetEquivalentCulture(out culture)) { string languageTag = IetfLanguageTag; do { languageTag = Shorten(languageTag); if (languageTag == null) { // Should never happen, because GetCultureinfoByIetfLanguageTag("") should // return InvariantCulture! culture = CultureInfo.InvariantCulture; } else { try { culture = SafeSecurityHelper.GetCultureInfoByIetfLanguageTag(languageTag); } catch (ArgumentException) { } } } while (culture == null); } _compatibleCulture = culture; } return _compatibleCulture; } /// <summary> /// Checks to see if a second XmlLanguage is included in range of languages specified /// by this XmlLanguage. /// </summary> /// <remarks> /// In addition to looking for prefix-matches in IetfLanguageTags, the implementation /// also considers the Parent relationships among registered CultureInfo's. So, in /// particular, this routine will report that "zh-hk" is in the range specified by /// "zh-hant", even though the latter is not a prefix of the former. And because it /// doesn't restrict itself to traversing CultureInfo.Parent, it will also report that /// "sr-latn-sp" is in the range covered by "sr-latn". (Note that "sr-latn" does /// does not have a registered CultureInfo.) /// </remarks> [FriendAccessAllowed] internal bool RangeIncludes(XmlLanguage language) { if (this.IsPrefixOf(language.IetfLanguageTag)) { return true; } // We still need to do CultureInfo.Parent-aware processing, to cover, for example, // the case that "zh-hant" includes "zh-hk". return RangeIncludes(language.GetCompatibleCulture()); } /// <summary> /// Checks to see if a CultureInfo is included in range of languages specified /// by this XmlLanguage. /// </summary> /// <remarks> /// In addition to looking for prefix-matches in IetfLanguageTags, the implementation /// also considers the Parent relationships among CultureInfo's. So, in /// particular, this routine will report that "zh-hk" is in the range specified by /// "zh-hant", even though the latter is not a prefix of the former. And because it /// doesn't restrict itself to traversing CultureInfo.Parent, it will also report that /// "sr-latn-sp" is in the range covered by "sr-latn". (Note that "sr-latn" does /// does not have a registered CultureInfo.) /// </remarks> internal bool RangeIncludes(CultureInfo culture) { if (culture == null) { throw new ArgumentNullException("culture"); } // no need for special cases for InvariantCulture, which has IetfLanguageTag == "" // Limit how far we'll walk up the hierarchy to avoid security threat. // We could check for cycles (e.g., culture.Parent.Parent == culture) // but in in the case of non-malicious code there should be no cycles, // whereas in malicious code, checking for cycles doesn't mitigate the // threat; one could always implement Parent such that it always returns // a new CultureInfo for which Equals always returns false. for (int i = 0; i < MaxCultureDepth; ++i) { // Note that we don't actually insist on a there being CultureInfo corresponding // to familyMapLanguage. // The use of language.StartsWith() catches, for example,the case // where this="sr-latn", and culture.IetfLanguageTag=="sr-latn-sp". // In such a case, culture.Parent.IetfLanguageTag=="sr". // (There is no registered CultureInfo with IetfLanguageTag=="sr-latn".) if (this.IsPrefixOf(culture.IetfLanguageTag)) { return true; } CultureInfo parentCulture = culture.Parent; if (parentCulture == null || parentCulture.Equals(CultureInfo.InvariantCulture) || parentCulture == culture) break; culture = parentCulture; } return false; } /// <summary> /// Compute a measure of specificity of the XmlLanguage, considering both /// subtag length and the CultureInfo.Parent hierarchy. /// </summary> internal int GetSpecificity() { if (_specificity < 0) { CultureInfo compatibleCulture = GetCompatibleCulture(); int specificity = GetSpecificity(compatibleCulture, MaxCultureDepth); if (compatibleCulture != _equivalentCulture) { specificity += GetSubtagCount(_lowerCaseTag) - GetSubtagCount(compatibleCulture.IetfLanguageTag); } _specificity = specificity; } return _specificity; } /// <summary> /// Helper function for instance-method GetSpecificity. /// </summary> /// <remarks> /// To avoid a security threat, caller provides limit on how far we'll /// walk up the CultureInfo hierarchy. /// We could check for cycles (e.g., culture.Parent.Parent == culture) /// but in in the case of non-malicious code there should be no cycles, /// whereas in malicious code, checking for cycles doesn't mitigate the /// threat; one could always implement Parent such that it always returns /// a new CultureInfo for which Equals always returns false. /// </remarks> private static int GetSpecificity(CultureInfo culture, int maxDepth) { int specificity = 0; if (maxDepth != 0 && culture != null) { string languageTag = culture.IetfLanguageTag; if (languageTag.Length > 0) { specificity = Math.Max(GetSubtagCount(languageTag), 1 + GetSpecificity(culture.Parent, maxDepth - 1)); } } return specificity; } private static int GetSubtagCount(string languageTag) { int tagLength = languageTag.Length; int subtagCount = 0; if (tagLength > 0) { subtagCount = 1; for (int i = 0; i < tagLength; i++) { if (languageTag[i] == '-') { subtagCount += 1; } } } return subtagCount; } internal MatchingLanguageCollection MatchingLanguages { get { return new MatchingLanguageCollection(this); } } // collection of matching languages, ordered from most specific to least specific, starting // with the start language and ending with invariant language ("") internal struct MatchingLanguageCollection : IEnumerable<XmlLanguage>, IEnumerable { private XmlLanguage _start; public MatchingLanguageCollection(XmlLanguage start) { _start = start; } // strongly typed, avoids boxing public MatchingLanguageEnumerator GetEnumerator() { return new MatchingLanguageEnumerator(_start); } // strongly typed, boxes IEnumerator<XmlLanguage> IEnumerable<XmlLanguage>.GetEnumerator() { return GetEnumerator(); } // weakly typed, boxed IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal struct MatchingLanguageEnumerator : IEnumerator<XmlLanguage>, IEnumerator { private readonly XmlLanguage _start; private XmlLanguage _current; private bool _atStart; private bool _pastEnd; private int _maxCultureDepth; public MatchingLanguageEnumerator(XmlLanguage start) { _start = start; _current = start; _pastEnd = false; _atStart = true; _maxCultureDepth = XmlLanguage.MaxCultureDepth; } public void Reset() { _current = _start; _pastEnd = false; _atStart = true; _maxCultureDepth = XmlLanguage.MaxCultureDepth; } public XmlLanguage Current { get { if (_atStart) { throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted)); } if (_pastEnd) { throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd)); } return _current; } } public bool MoveNext() { if (_atStart) { _atStart = false; return true; } else if (_current.IetfLanguageTag.Length == 0) { _atStart = false; _pastEnd = true; return false; } else { XmlLanguage prefixLanguage = _current.PrefixLanguage; CultureInfo culture = null; if (_maxCultureDepth > 0) { if (_current.TryGetEquivalentCulture(out culture)) { culture = culture.Parent; } else { culture = null; } } if (culture == null) { _current = prefixLanguage; _atStart = false; return true; } else { // We MUST NOT call the private constructor, but instead call GetLanguage()! XmlLanguage parentLanguage = XmlLanguage.GetLanguage(culture.IetfLanguageTag); if (parentLanguage.IsPrefixOf(prefixLanguage.IetfLanguageTag)) { _current = prefixLanguage; _atStart = false; return true; } else { // We definitely do this if // prefixLanguage.IsPrefixOf(parentLanguage.IetfLanguageTag) // But if this is not true, then we are faced with a problem with // divergent paths between prefix-tags and parent-CultureInfos. // This code makes the arbitrary decision to follow the parent // path when faced with this divergence. // // _maxCultureDepth -= 1; _current = parentLanguage; _atStart = false; return true; } } } } object IEnumerator.Current { get { return Current; } } void IDisposable.Dispose() { } } /// <remarks> /// Differs from calling string.StartsWith, because each subtag must match /// in its entirety. /// Note that this routine returns true if the tags match. /// </remarks> private bool IsPrefixOf(string longTag) { string prefix = IetfLanguageTag; // if we fail a simple string-prefix test, we know we don't have a subtag-prefix. if(!longTag.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { return false; } // string-prefix test passed -- now determine if we're at a subtag-boundary return (prefix.Length == 0 || prefix.Length == longTag.Length || longTag[prefix.Length] == '-'); } private bool TryGetEquivalentCulture(out CultureInfo culture) { culture = null; if (_equivalentCulture == null && !_equivalentCultureFailed) { try { GetEquivalentCulture(); } catch (InvalidOperationException) { } } culture = _equivalentCulture; return (culture != null); } private XmlLanguage PrefixLanguage { get { string prefix = Shorten(IetfLanguageTag); // can return null // We MUST NOT call the private constructor, but instead call GetLanguage()! return XmlLanguage.GetLanguage(prefix); // throws on null } } /// <summary> /// Shorten a well-formed RFC 3066 string by one subtag. /// </summary> /// <remarks> /// Shortens "" into null. /// </remarks> private static string Shorten(string languageTag) { if (languageTag.Length == 0) { return null; } int i = languageTag.Length - 1; while (languageTag[i] != '-' && i > 0) { i -= 1; } // i now contains of index of first character to be omitted from smaller tag return languageTag.Substring (0, i); } /// <summary> /// Throws an ArgumentException (or ArgumentNullException) is not the empty /// string, and does not conform to RFC 3066. /// </summary> /// <remarks> /// It is assumed that caller has already converted to lower-case. /// The language string may be empty, or else must conform to RFC 3066 rules: /// The first subtag must consist of only ASCII letters. /// Additional subtags must consist ASCII letters or numerals. /// Subtags are separated by a single hyphen character. /// Every subtag must be 1 to 8 characters long. /// No leading or trailing hyphens are permitted. /// </remarks> /// <param name="ietfLanguageTag"></param> /// <exception cref="ArgumentNullException">tag is NULL.</exception> /// <exception cref="ArgumentException">tag is non-empty, but does not conform to RFC 3066.</exception> private static void ValidateLowerCaseTag(string ietfLanguageTag) { if (ietfLanguageTag == null) { throw new ArgumentNullException("ietfLanguageTag"); } if (ietfLanguageTag.Length > 0) { using (StringReader reader = new StringReader(ietfLanguageTag)) { int i; i = ParseSubtag(ietfLanguageTag, reader, /* isPrimary */ true); while (i != -1) { i = ParseSubtag(ietfLanguageTag, reader, /* isPrimary */ false); } } } } // returns the character which terminated the subtag -- either '-' or -1 for // end of string. // throws exception on improper formatting // It is assumed that caller has already converted to lower-case. static private int ParseSubtag(string ietfLanguageTag, StringReader reader, bool isPrimary) { int c; bool ok; const int maxCharsPerSubtag = 8; c = reader.Read(); ok = IsLowerAlpha(c); if (!ok && !isPrimary) ok = IsDigit(c); if (!ok) { ThrowParseException(ietfLanguageTag); } int charsRead = 1; for (;;) { c = reader.Read(); charsRead++; ok = IsLowerAlpha(c); if (!ok && !isPrimary) { ok = IsDigit(c); } if (!ok) { if (c == -1 || c == '-') { return c; } else { ThrowParseException(ietfLanguageTag); } } else { if (charsRead > maxCharsPerSubtag) { ThrowParseException(ietfLanguageTag); } } } } static private bool IsLowerAlpha(int c) { return (c >= 'a' && c <= 'z'); } static private bool IsDigit(int c) { return c >= '0' && c <= '9'; } static private void ThrowParseException(string ietfLanguageTag) { throw new ArgumentException(SR.Get(SRID.XmlLangMalformed, ietfLanguageTag), "ietfLanguageTag"); } // throws if there is a non-7-bit ascii character static private string AsciiToLower(string tag) { int length = tag.Length; for (int i = 0; i < length; i++) { if (tag[i] > 127) { ThrowParseException(tag); } } return tag.ToLowerInvariant(); } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Xml.Serialization; using System.Collections.Generic; using System.Linq; using System.Text; namespace MonoDroid { public class TypeList : SerializableDictionary<string, Type> { protected override string GetKey (Type value) { return value.Name; } } public class ObjectModel { public static bool IsSystemType(string type) { if (type.StartsWith("void")) return true; if (type.StartsWith("int")) return true; if (type.StartsWith("long")) return true; if (type.StartsWith("short")) return true; if (type.StartsWith("char")) return true; if (type.StartsWith("byte")) return true; if (type.StartsWith("float")) return true; if (type.StartsWith("double")) return true; if (type.StartsWith("bool")) return true; return false; } public static ObjectModel Load(string filename) { XmlSerializer ser = new XmlSerializer(typeof(ObjectModel)); ObjectModel types = (ObjectModel)ser.Deserialize(new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)); return types; } public void AppendModel(string filename) { var other = ObjectModel.Load(filename); foreach(var type in other.Types) { Types.Add(type); } } TypeList myTypes = new TypeList(); [System.Xml.Serialization.XmlElementAttribute("Type", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)] public TypeList Types { get { return myTypes; } } public void FinalizeModel() { // clear out cached info foreach (var type in myTypes) { type.Types.Clear(); } // relink names to types foreach (var type in myTypes) { if (type.IsSystemType) continue; if (type.Parent != null) type.ParentType = FindType(type.Parent); int nestingClass = type.Name.LastIndexOf('.'); if (nestingClass != -1) { string nestingClassName = type.Name.Substring(0, nestingClass); Type nesting; if (myTypes.Dictionary.TryGetValue(nestingClassName, out nesting)) { nesting.Types.Add(type); type.NestingClass = nesting; } } type.InterfaceTypes.Clear(); type.InterfaceTypes.AddRange(from itype in type.Interfaces select FindType(itype)); foreach (var field in type.Fields) { field.FieldType = FindType(field.Type); field.ContainingType = type; } type.IsDelegate = type.Name == "java.lang.Runnable" || (type.IsInterface && type.Methods.Count == 1 && type.Interfaces.Count == 0 && type.Name.StartsWith("android.")); foreach (var method in type.Methods) { method.Type = type; if (!method.IsConstructor) method.ReturnType = FindType(method.Return); method.ParameterTypes.Clear(); method.ParameterTypes.AddRange(from p in method.Parameters select FindType(p)); /* if (method.Override != null) { Type otype = method.OverrideType = FindType(method.Override); //Console.WriteLine("{0} {1} {2} {3}", type, method, otype, method.IsSynthetic); //method.OverrideMethod = (from omethod in otype.Methods where omethod.Matches(method) select omethod).First(); //Console.WriteLine("{0}", method.OverrideMethod); } */ if (method.Type.IsInterface || method.Type.Abstract) continue; if (method.PropertyType != null) continue; if (method.IsConstructor) continue; if ((!method.Name.StartsWith("get") && !method.Name.StartsWith("set")) || method.Name == "get" || method.Name == "set") continue; var methodType = method.Name.Substring(0, 3); var propertyName = method.Name.Substring(3); if (FindType(method.Type.Name + "." + propertyName) != null) continue; if (propertyName == method.Type.SimpleName) continue; if (!char.IsLetter(propertyName[0])) continue; if ((from m in type.Methods where m.Name.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase) select m).Count() != 0) continue; if (methodType == "get") { if (method.Parameters.Count != 0) continue; // don't try to make getters where there are multiple versions. if ((from getter in type.Methods where getter.Name == method.Name && getter.Parameters.Count == 0 && getter.Return != "void" select getter).Count() != 1) continue; string setterName = "set" + propertyName; var matchedSetter = (from setter in type.Methods where setter.Name == setterName && setter.Parameters.Count == 1 && setter.Return == "void" && setter.Parameters[0] == method.Return select setter).FirstOrDefault(); if (matchedSetter != null) { matchedSetter.PropertyType = method.PropertyType = PropertyType.ReadWrite; matchedSetter.OtherPropertyAccessor = method; method.OtherPropertyAccessor = matchedSetter; } else { method.PropertyType = PropertyType.ReadOnly; } } else { if (method.Parameters.Count != 1) continue; // don't try to make setters where there are multiple versions. if ((from setter in type.Methods where setter.Name == method.Name && setter.Parameters.Count == 1 select setter).Count() != 1) continue; string getterName = "get" + propertyName; var matchedGetter = (from getter in type.Methods where getter.Name == getterName && getter.Parameters.Count == 0 && getter.Return == method.Parameters[0] select getter).FirstOrDefault(); if (matchedGetter != null) { matchedGetter.PropertyType = method.PropertyType = PropertyType.ReadWrite; matchedGetter.OtherPropertyAccessor = method; method.OtherPropertyAccessor = matchedGetter; } else { if ((from getter in type.Methods where getter.Name == "get" + propertyName && getter.Parameters.Count == 0 && getter.Return != "void" select getter).Count() != 0) continue; method.PropertyType = PropertyType.WriteOnly; } } } } } public Type FindType(string name) { Type ret = null; myTypes.Dictionary.TryGetValue(name, out ret); return ret; } } public class Accessible { public string Name { get;set; } public string Scope { get;set; } public bool Static { get;set; } public override string ToString () { return string.Format("{0}{1}", Scope, " " + Name); } } public class Overridable : Accessible { public bool IsSealed { get;set; } public bool Abstract { get;set; } public bool IsSynthetic { get;set; } public override string ToString () { return string.Format("{0}{1}{2}{3}", Scope, Abstract ? " abstract" : string.Empty, IsSealed ? " sealed" : string.Empty, " " + Name); } } public class Field : Accessible { public Type ContainingType { get;set; } public Type FieldType { get;set; } public string Type { get;set; } public bool IsReadOnly { get;set; } public string Value { get;set; } public override string ToString () { return string.Format("{0}{1}{2}{3}{4}", Scope, Static ? " static" : string.Empty, IsReadOnly ? " readonly" : string.Empty, " " + Name, Value != null ? " = " + Value : string.Empty); } } public class Type : Overridable { public bool NoAttributes { get;set; } public bool IsDelegate { get;set; } public bool HasEmptyConstructor { get;set; } public string WrappedInterface { get;set; } public Type WrappedInterfaceType { get;set; } public string NativeName { get;set; } HashSet<string> mySignatures = new HashSet<string>(); public HashSet<string> Signatures { get { return mySignatures; } } public Boolean IsNew { get;set; } public bool IsSystemType { get;set; } public string Namespace { get { var root = this; while (root.NestingClass != null) root = root.NestingClass; return root.Name.Substring(0, root.Name.Length - root.SimpleName.Length - 1); } } public string Qualifier { get { int index = Name.LastIndexOf('.'); if (index == -1) return string.Empty; return Name.Substring(0, index); } } public string SimpleName { get { int last = Name.LastIndexOf('.'); if (last == -1) return Name; return Name.Substring(last + 1); } } public Type() { } public bool IsInterface { get;set; } public bool IsEnum { get;set; } public String Parent { get;set; } public Type ParentType { get;set; } List<string> myInterfaces = new List<string>(); [System.Xml.Serialization.XmlArrayItemAttribute("Interface", typeof(string), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public List<string> Interfaces { get { return myInterfaces; } } List<Type> myTypes = new List<Type>(); public List<Type> Types { get { return myTypes; } } List<Type> myInterfaceTypes = new List<Type>(); public List<Type> InterfaceTypes { get { return myInterfaceTypes; } } public bool IsInnerClass { get;set; } public Type NestingClass { get;set; } Methods myMethods = new Methods(); [System.Xml.Serialization.XmlArrayItemAttribute("Method", typeof(Method), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public Methods Methods { get { return myMethods; } } List<Field> myFields = new List<Field>(); [System.Xml.Serialization.XmlArrayItemAttribute("Field", typeof(Field), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public List<Field> Fields { get { return myFields; } } public override string ToString () { return string.Format("{0}{1}{2}{3}", Scope, IsInterface ? " interface" : Abstract ? " abstract" : string.Empty, IsSealed ? " sealed" : string.Empty, " " + Name); } } public enum PropertyType { ReadOnly, ReadWrite, WriteOnly, } public class Methods : SerializableDictionary<string, Method> { protected override string GetKey (Method value) { return value.ToSignatureString(); } } public class Method : Overridable { public int Index { get;set; } public bool IsNew { get;set; } public bool Matches(Method other) { if (other.Return != Return) return false; if (other.Name != Name) return false; if (other.Parameters.Count != Parameters.Count) return false; for (int i = 0; i < Parameters.Count; i++) { if (other.Parameters[i] != Parameters[i]) return false; } return true; } public bool IsOverride { get;set; } public string Override { get;set; } public Type OverrideType { get;set; } public Method OverrideMethod { get;set; } public PropertyType? PropertyType { get;set; } public Method OtherPropertyAccessor { get;set; } public Type Type { get; set; } public bool IsConstructor { get;set; } public string Return { get;set; } public Type ReturnType { get;set; } List<string> myParameters = new List<string>(); [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", typeof(string), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)] public List<string> Parameters { get { return myParameters; } } List<Type> myParameterTypes = new List<Type>(); public List<Type> ParameterTypes { get { return myParameterTypes; } } public string ToSignatureString () { StringBuilder builder = new StringBuilder(); builder.Append('('); bool first = true; foreach(var param in Parameters) { if (!first) builder.Append(", "); builder.Append(param); first = false; } builder.Append(')'); return string.Format("{0}{1}", Name, builder.ToString()); } public override string ToString () { StringBuilder builder = new StringBuilder(); builder.Append('('); bool first = true; foreach(var param in Parameters) { if (!first) builder.Append(", "); builder.Append(param); first = false; } builder.Append(')'); return string.Format("{0}{1}{2}{3}{4}{5}{6}", Scope, Static ? " static" : string.Empty, Abstract ? " abstract" : string.Empty, IsSealed ? " sealed" : string.Empty, Return != null ? " " + Return : string.Empty, " " + Name, builder.ToString()); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using MMDataStructures.DictionaryBacking; namespace MMDataStructures { /// <summary> /// Disk based Dictionary to reduce the amount of RAM used for larger dictionaries. /// The maximum datasize for the dictionary is 2^32 bytes. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDisposable { private BackingUnknownSize<TKey, TValue> _persistHandler; private Mutex Mutex { get { return _persistHandler.Mutex; } } private Dictionary(BackingUnknownSize<TKey, TValue> persistHandler) { _persistHandler = persistHandler; } /// <summary> /// Initialize a new dictionary. /// </summary> /// <param name="fileName">Folder to store files in</param> /// <param name="capacity">Number of buckets for the hash</param> /// <param name="persistenceMode"></param> public Dictionary(string fileName, int capacity, PersistenceMode persistenceMode = PersistenceMode.TemporaryPersist) : this(new BackingUnknownSize<TKey, TValue>(fileName, capacity, persistenceMode)) { } #region IDictionary<TKey,TValue> Members ///<summary> ///Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"></see> contains an element with the specified key. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.Generic.IDictionary`2"></see> contains an element with the key; otherwise, false. ///</returns> /// ///<param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</param> ///<exception cref="T:System.ArgumentNullException">key is null.</exception> public bool ContainsKey(TKey key) { Mutex.WaitOne(); try { return _persistHandler.ContainsKey(key); } finally { Mutex.ReleaseMutex(); } } ///<summary> ///Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</summary> /// ///<param name="value">The object to use as the value of the element to add.</param> ///<param name="key">The object to use as the key of the element to add.</param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception> ///<exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>.</exception> ///<exception cref="T:System.ArgumentNullException">key is null.</exception> public void Add(TKey key, TValue value) { Mutex.WaitOne(); try { _persistHandler.Add(key, value); } finally { Mutex.ReleaseMutex(); } } ///<summary> ///Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</summary> /// ///<returns> ///true if the element is successfully removed; otherwise, false. This method also returns false if key was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</returns> /// ///<param name="key">The key of the element to remove.</param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception> ///<exception cref="T:System.ArgumentNullException">key is null.</exception> public bool Remove(TKey key) { Mutex.WaitOne(); try { return _persistHandler.Remove(key); } finally { Mutex.ReleaseMutex(); } } public bool TryGetValue(TKey key, out TValue value) { Mutex.WaitOne(); try { return _persistHandler.TryGetValue(key, out value); } finally { Mutex.ReleaseMutex(); } } ///<summary> ///Gets or sets the element with the specified key. ///</summary> /// ///<returns> ///The element with the specified key. ///</returns> /// ///<param name="key">The key of the element to get or set.</param> ///<exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"></see> is read-only.</exception> ///<exception cref="T:System.ArgumentNullException">key is null.</exception> ///<exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and key is not found.</exception> public TValue this[TKey key] { get { TValue val; if (TryGetValue(key, out val)) { return val; } throw new KeyNotFoundException("The given key was not present in the dictionary."); } set { Mutex.WaitOne(); try { TValue existing; if (_persistHandler.TryGetValue(key, out existing)) { if (!_persistHandler.ByteCompare(value, existing)) { _persistHandler.Remove(key); _persistHandler.Add(key, value); } } else { _persistHandler.Add(key, value); } } finally { Mutex.ReleaseMutex(); } } } ///<summary> ///Gets an <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</returns> /// public ICollection<TKey> Keys { get { return new List<TKey>(_persistHandler.AllKeys()); } } ///<summary> ///Gets an <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.Generic.ICollection`1"></see> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"></see>. ///</returns> /// public ICollection<TValue> Values { get { return new List<TValue>(_persistHandler.AllValues()); } } ///<summary> ///Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"></see>. ///</summary> /// ///<param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.</exception> public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } ///<summary> ///Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"></see>. ///</summary> /// ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only. </exception> public void Clear() { Mutex.WaitOne(); try { _persistHandler.Clear(); } finally { Mutex.ReleaseMutex(); } } ///<summary> ///Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> contains a specific value. ///</summary> /// ///<returns> ///true if item is found in the <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false. ///</returns> /// ///<param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param> public bool Contains(KeyValuePair<TKey, TValue> item) { TValue checkValue; if (TryGetValue(item.Key, out checkValue)) { return checkValue.Equals(item.Value); } return false; } ///<summary> ///Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index. ///</summary> /// ///<param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing.</param> ///<param name="index">The zero-based index in array at which copying begins.</param> ///<exception cref="T:System.ArgumentOutOfRangeException">arrayIndex is less than 0.</exception> ///<exception cref="T:System.ArgumentNullException">array is null.</exception> ///<exception cref="T:System.ArgumentException">array is multidimensional.-or-arrayIndex is equal to or greater than the length of array.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"></see> is greater than the available space from arrayIndex to the end of the destination array.-or-Type T cannot be cast automatically to the type of the destination array.</exception> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { throw new ArgumentNullException("array", "is null"); } if ((index < 0) || (index >= array.Length)) { throw new ArgumentOutOfRangeException("index", "is out of bounds"); } if ((array.Length - index) < Count) { throw new ArgumentException("array is too small"); } foreach (KeyValuePair<TKey, TValue> pair in this) { array[index++] = pair; } } ///<summary> ///Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"></see>. ///</summary> /// ///<returns> ///true if item was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"></see>; otherwise, false. This method also returns false if item is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"></see>. ///</returns> /// ///<param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"></see>.</param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only.</exception> public bool Remove(KeyValuePair<TKey, TValue> item) { TValue existing; if (TryGetValue(item.Key, out existing)) { if (_persistHandler.ByteCompare(item.Value, existing)) { Remove(item.Key); return true; } } return false; } ///<summary> ///Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>. ///</summary> /// ///<returns> ///The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"></see>. ///</returns> /// public int Count { get { return _persistHandler.Count; } } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.Generic.ICollection`1"></see> is read-only; otherwise, false. ///</returns> /// public bool IsReadOnly { get { return false; } } ///<summary> ///Returns an enumerator that iterates through the collection. ///</summary> /// ///<returns> ///A <see cref="T:System.Collections.Generic.IEnumerator`1"></see> that can be used to iterate through the collection. ///</returns> ///<filterpriority>1</filterpriority> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _persistHandler.GetEnumerator(); } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.IEnumerator"></see> object that can be used to iterate through the collection. ///</returns> ///<filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion public bool ContainsValue(TValue value) { return _persistHandler.ContainsValue(value); } ~Dictionary() { Dispose(); } public void Dispose() { if (_persistHandler != null) _persistHandler.Dispose(); _persistHandler = null; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.IO; using WebsitePanel.Setup.Web; using WebsitePanel.Setup.Windows; using Microsoft.Web.Management; using Microsoft.Web.Administration; using Ionic.Zip; using System.Xml; using System.Management; using Microsoft.Win32; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; namespace WebsitePanel.Setup.Actions { public static class MyExtensions { public static XElement Element(this XElement parent, XName name, bool createIfNotFound) { var childNode = parent.Element(name); { if (childNode != null) { return childNode; } }; // if (createIfNotFound.Equals(true)) { childNode = new XElement(name); parent.Add(childNode); } // return childNode; } } #region Actions public class CheckOperatingSystemAction : Action, IPrerequisiteAction { bool IPrerequisiteAction.Run(SetupVariables vars) { throw new NotImplementedException(); } event EventHandler<ActionProgressEventArgs<bool>> IPrerequisiteAction.Complete { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } public class CreateWindowsAccountAction : Action, IInstallAction, IUninstallAction { public const string UserAccountExists = "Account already exists"; public const string UserAccountDescription = "{0} account for anonymous access to Internet Information Services"; public const string LogStartMessage = "Creating Windows user account..."; public const string LogInfoMessage = "Creating Windows user account \"{0}\""; public const string LogEndMessage = "Created windows user account"; public const string InstallLogMessageLocal = "- Created a new Windows user account \"{0}\""; public const string InstallLogMessageDomain = "- Created a new Windows user account \"{0}\" in \"{1}\" domain"; public const string LogStartRollbackMessage = "Removing Windows user account..."; public const string LogInfoRollbackMessage = "Deleting user account \"{0}\""; public const string LogEndRollbackMessage = "User account has been removed"; public const string LogInfoRollbackMessageDomain = "Could not find user account '{0}' in domain '{1}', thus consider it removed"; public const string LogInfoRollbackMessageLocal = "Could not find user account '{0}', thus consider it removed"; public const string LogErrorRollbackMessage = "Could not remove Windows user account"; private void CreateUserAccount(SetupVariables vars) { //SetProgressText("Creating windows user account..."); var domain = vars.UserDomain; var userName = vars.UserAccount; // var description = String.Format(UserAccountDescription, vars.ComponentName); var memberOf = vars.UserMembership; var password = vars.UserPassword; Log.WriteStart(LogStartMessage); Log.WriteInfo(String.Format(LogInfoMessage, userName)); // create account SystemUserItem user = new SystemUserItem { Domain = domain, Name = userName, FullName = userName, Description = description, MemberOf = memberOf, Password = password, PasswordCantChange = true, PasswordNeverExpires = true, AccountDisabled = false, System = true }; // SecurityUtils.CreateUser(user); // add rollback action //RollBack.RegisterUserAccountAction(domain, userName); // update log Log.WriteEnd(LogEndMessage); // update install log if (String.IsNullOrEmpty(domain)) InstallLog.AppendLine(String.Format(InstallLogMessageLocal, userName)); else InstallLog.AppendLine(String.Format(InstallLogMessageDomain, userName, domain)); } public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { // Exit with an error if Windows account with the same name already exists if (vars.NewUserAccount) { if (SecurityUtils.UserExists(vars.UserDomain, vars.UserAccount)) throw new Exception(UserAccountExists); // CreateUserAccount(vars); } } void IUninstallAction.Run(SetupVariables vars) { if (!vars.NewUserAccount) return; try { Log.WriteStart(LogStartRollbackMessage); Log.WriteInfo(String.Format(LogInfoRollbackMessage, vars.UserAccount)); // if (SecurityUtils.UserExists(vars.UserDomain, vars.UserAccount)) { SecurityUtils.DeleteUser(vars.UserDomain, vars.UserAccount); } else { if (!String.IsNullOrEmpty(vars.UserDomain)) { Log.WriteInfo(String.Format(LogInfoRollbackMessageDomain, vars.UserAccount, vars.UserDomain)); } else { Log.WriteInfo(String.Format(LogInfoRollbackMessageLocal, vars.UserAccount)); } } // Log.WriteEnd(LogEndRollbackMessage); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) { return; } // Log.WriteError(LogErrorRollbackMessage, ex); throw; } } } public class ConfigureAspNetTempFolderPermissionsAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { try { string path; if (vars.IISVersion.Major == 6) { // IIS_WPG -> C:\WINDOWS\Temp path = Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.Machine); SetFolderPermission(path, "IIS_WPG", NtfsPermission.Modify); // IIS_WPG - > C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files path = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "Temporary ASP.NET Files"); if (Utils.IsWin64() && Utils.IIS32Enabled()) path = path.Replace("Framework64", "Framework"); SetFolderPermission(path, "IIS_WPG", NtfsPermission.Modify); } // NETWORK_SERVICE -> C:\WINDOWS\Temp path = Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.Machine); // SetFolderPermissionBySid(path, SystemSID.NETWORK_SERVICE, NtfsPermission.Modify); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Security error", ex); } } private void SetFolderPermission(string path, string account, NtfsPermission permission) { try { if (!FileUtils.DirectoryExists(path)) { FileUtils.CreateDirectory(path); Log.WriteInfo(string.Format("Created {0} folder", path)); } Log.WriteStart(string.Format("Setting '{0}' permission for '{1}' folder for '{2}' account", permission, path, account)); SecurityUtils.GrantNtfsPermissions(path, null, account, permission, true, true); Log.WriteEnd("Set security permissions"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Security error", ex); } } private void SetFolderPermissionBySid(string path, string account, NtfsPermission permission) { try { if (!FileUtils.DirectoryExists(path)) { FileUtils.CreateDirectory(path); Log.WriteInfo(string.Format("Created {0} folder", path)); } Log.WriteStart(string.Format("Setting '{0}' permission for '{1}' folder for '{2}' account", permission, path, account)); SecurityUtils.GrantNtfsPermissionsBySid(path, account, permission, true, true); Log.WriteEnd("Set security permissions"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Security error", ex); } } } public class SetNtfsPermissionsAction : Action, IInstallAction { public const string LogStartInstallMessage = "Configuring folder permissions..."; public const string LogEndInstallMessage = "NTFS permissions has been applied to the application folder..."; public const string LogInstallErrorMessage = "Could not set content folder NTFS permissions"; public const string FqdnIdentity = "{0}\\{1}"; public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { string contentPath = vars.InstallationFolder; //creating user account string userName = vars.UserAccount; string userDomain = vars.UserDomain; string netbiosDomain = userDomain; // try { Begin(LogStartInstallMessage); // Log.WriteStart(LogStartInstallMessage); // if (!String.IsNullOrEmpty(userDomain)) { netbiosDomain = SecurityUtils.GetNETBIOSDomainName(userDomain); } // WebUtils.SetWebFolderPermissions(contentPath, netbiosDomain, userName); // Log.WriteEnd(LogEndInstallMessage); // Finish(LogStartInstallMessage); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError(LogInstallErrorMessage, ex); throw; } } } public class CreateWebApplicationPoolAction : Action, IInstallAction, IUninstallAction { public const string AppPoolNameFormatString = "{0} Pool"; public const string LogStartInstallMessage = "Creating application pool for the web site..."; public const string LogStartUninstallMessage = "Removing application pool..."; public const string LogUninstallAppPoolNotFoundMessage = "Application pool not found"; public static string GetWebIdentity(SetupVariables vars) { var userDomain = vars.UserDomain; var netbiosDomain = userDomain; var userName = vars.UserAccount; var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); // if (!String.IsNullOrEmpty(userDomain)) { netbiosDomain = SecurityUtils.GetNETBIOSDomainName(userDomain); // if (iis7) { //for iis7 we use fqdn\user return String.Format(SetNtfsPermissionsAction.FqdnIdentity, userDomain, userName); } else { //for iis6 we use netbiosdomain\user return String.Format(SetNtfsPermissionsAction.FqdnIdentity, netbiosDomain, userName); } } // return userName; } public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { var appPoolName = String.Format(AppPoolNameFormatString, vars.ComponentFullName); var userDomain = vars.UserDomain; var netbiosDomain = userDomain; var userName = vars.UserAccount; var userPassword = vars.UserPassword; var identity = GetWebIdentity(vars); var componentId = vars.ComponentId; var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var poolExists = false; // vars.WebApplicationPoolName = appPoolName; // Maintain backward compatibility if (iis7) { poolExists = WebUtils.IIS7ApplicationPoolExists(appPoolName); } else { poolExists = WebUtils.ApplicationPoolExists(appPoolName); } // This flag is the opposite of poolExists flag vars.NewWebApplicationPool = !poolExists || vars.ComponentExists; if (poolExists) { //update app pool Log.WriteStart("Updating application pool"); Log.WriteInfo(String.Format("Updating application pool \"{0}\"", appPoolName)); // if (iis7) { WebUtils.UpdateIIS7ApplicationPool(appPoolName, userName, userPassword); } else { WebUtils.UpdateApplicationPool(appPoolName, userName, userPassword); } // //update log Log.WriteEnd("Updated application pool"); //update install log InstallLog.AppendLine(String.Format("- Updated application pool named \"{0}\"", appPoolName)); } else { // create app pool Log.WriteStart("Creating application pool"); Log.WriteInfo(String.Format("Creating application pool \"{0}\"", appPoolName)); // if (iis7) { WebUtils.CreateIIS7ApplicationPool(appPoolName, userName, userPassword); } else { WebUtils.CreateApplicationPool(appPoolName, userName, userPassword); } //update log Log.WriteEnd("Created application pool"); //update install log InstallLog.AppendLine(String.Format("- Created a new application pool named \"{0}\"", appPoolName)); } } void IUninstallAction.Run(SetupVariables vars) { try { var appPoolName = String.Format(AppPoolNameFormatString, vars.ComponentFullName); var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var poolExists = false; // Log.WriteStart(LogStartUninstallMessage); // vars.WebApplicationPoolName = appPoolName; // Maintain backward compatibility if (iis7) { poolExists = WebUtils.IIS7ApplicationPoolExists(appPoolName); } else { poolExists = WebUtils.ApplicationPoolExists(appPoolName); } if (!poolExists) { Log.WriteInfo(LogUninstallAppPoolNotFoundMessage); return; } // if (iis7) { WebUtils.DeleteIIS7ApplicationPool(appPoolName); } else { WebUtils.DeleteApplicationPool(appPoolName); } //update install log InstallLog.AppendLine(String.Format("- Removed application pool named \"{0}\"", appPoolName)); } finally { //update log //Log.WriteEnd(LogEndUninstallMessage); } } } public class CreateWebSiteAction : Action, IInstallAction, IUninstallAction { public const string LogStartMessage = "Creating web site..."; public const string LogEndMessage = ""; public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { var siteName = vars.ComponentFullName; var ip = vars.WebSiteIP; var port = vars.WebSitePort; var domain = vars.WebSiteDomain; var contentPath = vars.InstallationFolder; var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var userName = CreateWebApplicationPoolAction.GetWebIdentity(vars); var userPassword = vars.UserPassword; var appPool = vars.WebApplicationPoolName; var componentId = vars.ComponentId; var newSiteId = String.Empty; // Begin(LogStartMessage); // Log.WriteStart(LogStartMessage); // Log.WriteInfo(String.Format("Creating web site \"{0}\" ( IP: {1}, Port: {2}, Domain: {3} )", siteName, ip, port, domain)); //check for existing site var oldSiteId = iis7 ? WebUtils.GetIIS7SiteIdByBinding(ip, port, domain) : WebUtils.GetSiteIdByBinding(ip, port, domain); // if (oldSiteId != null) { // get site name string oldSiteName = iis7 ? oldSiteId : WebUtils.GetSite(oldSiteId).Name; throw new Exception( String.Format("'{0}' web site already has server binding ( IP: {1}, Port: {2}, Domain: {3} )", oldSiteName, ip, port, domain)); } // create site var site = new WebSiteItem { Name = siteName, SiteIPAddress = ip, ContentPath = contentPath, AllowExecuteAccess = false, AllowScriptAccess = true, AllowSourceAccess = false, AllowReadAccess = true, AllowWriteAccess = false, AnonymousUsername = userName, AnonymousUserPassword = userPassword, AllowDirectoryBrowsingAccess = false, AuthAnonymous = true, AuthWindows = true, DefaultDocs = null, HttpRedirect = "", InstalledDotNetFramework = AspNetVersion.AspNet20, ApplicationPool = appPool, // Bindings = new ServerBinding[] { new ServerBinding(ip, port, domain) }, }; // create site if (iis7) { newSiteId = WebUtils.CreateIIS7Site(site); } else { newSiteId = WebUtils.CreateSite(site); } try { Utils.OpenFirewallPort(vars.ComponentFullName, vars.WebSitePort, vars.IISVersion); } catch (Exception ex) { Log.WriteError("Open windows firewall port error", ex); } vars.VirtualDirectory = String.Empty; vars.NewWebSite = true; vars.NewVirtualDirectory = false; // update setup variables vars.WebSiteId = newSiteId; //update log Log.WriteEnd("Created web site"); // Finish(LogStartMessage); //update install log InstallLog.AppendLine(string.Format("- Created a new web site named \"{0}\" ({1})", siteName, newSiteId)); InstallLog.AppendLine(" You can access the application by the following URLs:"); string[] urls = Utils.GetApplicationUrls(ip, domain, port, null); foreach (string url in urls) { InstallLog.AppendLine(" http://" + url); } } void IUninstallAction.Run(SetupVariables vars) { var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var siteId = vars.WebSiteId; // try { Log.WriteStart("Deleting web site"); Log.WriteInfo(String.Format("Deleting web site \"{0}\"", siteId)); if (iis7) { if (WebUtils.IIS7SiteExists(siteId)) { WebUtils.DeleteIIS7Site(siteId); Log.WriteEnd("Deleted web site"); } } else { if (WebUtils.SiteIdExists(siteId)) { WebUtils.DeleteSite(siteId); Log.WriteEnd("Deleted web site"); } } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Web site delete error", ex); throw; } } } public class CopyFilesAction : Action, IInstallAction, IUninstallAction { public const string LogStartInstallMessage = "Copying files..."; public const string LogStartUninstallMessage = "Deleting files copied..."; internal void DoFilesCopyProcess(string source, string destination) { var sourceFolder = new DirectoryInfo(source); var destFolder = new DirectoryInfo(destination); // unzip long totalSize = FileUtils.CalculateFolderSize(sourceFolder.FullName); long copied = 0; int i = 0; List<DirectoryInfo> folders = new List<DirectoryInfo>(); List<FileInfo> files = new List<FileInfo>(); DirectoryInfo di = null; //FileInfo fi = null; string path = null; // Part 1: Indexing folders.Add(sourceFolder); while (i < folders.Count) { foreach (DirectoryInfo info in folders[i].GetDirectories()) { if (!folders.Contains(info)) folders.Add(info); } foreach (FileInfo info in folders[i].GetFiles()) { files.Add(info); } i++; } // Part 2: Destination Folders Creation /////////////////////////////////////////////////////// for (i = 0; i < folders.Count; i++) { if (folders[i].Exists) { path = destFolder.FullName + Path.DirectorySeparatorChar + folders[i].FullName.Remove(0, sourceFolder.FullName.Length); di = new DirectoryInfo(path); // Prevent IOException if (!di.Exists) di.Create(); } } // Part 3: Source to Destination File Copy /////////////////////////////////////////////////////// for (i = 0; i < files.Count; i++) { if (files[i].Exists) { path = destFolder.FullName + Path.DirectorySeparatorChar + files[i].FullName.Remove(0, sourceFolder.FullName.Length + 1); FileUtils.CopyFile(files[i], path); copied += files[i].Length; if (totalSize != 0) { // Update progress OnInstallProgressChanged(files[i].Name, Convert.ToInt32(copied * 100 / totalSize)); } } } } public override bool Indeterminate { get { return false; } } void IInstallAction.Run(SetupVariables vars) { try { Begin(LogStartInstallMessage); // var source = vars.InstallerFolder; var destination = vars.InstallationFolder; // string component = vars.ComponentFullName; // Log.WriteStart(LogStartInstallMessage); Log.WriteInfo(String.Format("Copying files from \"{0}\" to \"{1}\"", source, destination)); //showing copy process DoFilesCopyProcess(source, destination); // InstallLog.AppendLine(String.Format("- Copied {0} files", component)); // rollback //RollBack.RegisterDirectoryAction(destination); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Copy error", ex); throw; } } void IUninstallAction.Run(SetupVariables vars) { try { var path = vars.InstallationFolder; // Log.WriteStart(LogStartUninstallMessage); Log.WriteInfo(String.Format("Deleting directory \"{0}\"", path)); if (FileUtils.DirectoryExists(path)) { FileUtils.DeleteDirectory(path); } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Directory delete error", ex); throw; } } } public class SetServerPasswordAction : Action, IInstallAction { public const string LogStartInstallMessage = "Setting server password..."; public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { try { Begin(LogStartInstallMessage); Log.WriteStart("Updating configuration file (server password)"); Log.WriteInfo(String.Format("Server password is: '{0}'", vars.ServerPassword)); Log.WriteInfo("Single quotes are added for clarity purposes"); string file = Path.Combine(vars.InstallationFolder, vars.ConfigurationFile); string hash = Utils.ComputeSHA1(vars.ServerPassword); var XmlDoc = new XmlDocument(); XmlDoc.Load(file); var Node = XmlDoc.SelectSingleNode("configuration/websitepanel.server/security/password") as XmlElement; if (Node == null) throw new Exception("Unable to set a server access password. Check structure of configuration file."); else Node.SetAttribute("value", hash); XmlDoc.Save(file); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Configuration file update error", ex); throw; } } } public class SetCommonDistributiveParamsAction : Action, IPrepareDefaultsAction { public override bool Indeterminate { get { return true; } } void IPrepareDefaultsAction.Run(SetupVariables vars) { // if (String.IsNullOrEmpty(vars.InstallationFolder)) vars.InstallationFolder = String.Format(@"C:\WebsitePanel\{0}", vars.ComponentName); // if (String.IsNullOrEmpty(vars.WebSiteDomain)) vars.WebSiteDomain = String.Empty; // Force create new web site vars.NewWebSite = true; vars.NewVirtualDirectory = false; // if (String.IsNullOrEmpty(vars.ConfigurationFile)) vars.ConfigurationFile = "web.config"; } } public class EnsureServiceAccntSecured : Action, IPrepareDefaultsAction { public const string LogStartMessage = "Verifying setup parameters..."; public override bool Indeterminate { get { return true; } } void IPrepareDefaultsAction.Run(SetupVariables vars) { //Begin(LogStartMessage); // if (!String.IsNullOrEmpty(vars.UserPassword)) return; // vars.UserPassword = Guid.NewGuid().ToString(); // //Finish(LogEndMessage); } } public class SetServerDefaultInstallationSettingsAction : Action, IPrepareDefaultsAction { public override bool Indeterminate { get { return true; } } void IPrepareDefaultsAction.Run(SetupVariables vars) { // if (String.IsNullOrEmpty(vars.WebSiteIP)) vars.WebSiteIP = Global.Server.DefaultIP; // if (String.IsNullOrEmpty(vars.WebSitePort)) vars.WebSitePort = Global.Server.DefaultPort; // if (string.IsNullOrEmpty(vars.UserAccount)) vars.UserAccount = Global.Server.ServiceAccount; } } public class SaveComponentConfigSettingsAction : Action, IInstallAction, IUninstallAction { #region Uninstall public const string LogStartUninstallMessage = "Removing \"{0}\" component's configuration details"; public const string LogUninstallInfoMessage = "Deleting \"{0}\" component settings"; public const string LogErrorUninstallMessage = "Failed to remove the component configuration details"; public const string LogEndUninstallMessage = "Component's configuration has been removed"; #endregion public const string LogStartInstallMessage = "Updating system configuration..."; void IInstallAction.Run(SetupVariables vars) { Begin(LogStartInstallMessage); // Log.WriteStart(LogStartInstallMessage); // AppConfig.EnsureComponentConfig(vars.ComponentId); // AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ApplicationName", vars.ApplicationName); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ComponentCode", vars.ComponentCode); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ComponentName", vars.ComponentName); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ComponentDescription", vars.ComponentDescription); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Release", vars.Version); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Instance", vars.Instance); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "InstallFolder", vars.InstallationFolder); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Installer", vars.Installer); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "InstallerType", vars.InstallerType); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "InstallerPath", vars.InstallerPath); // update config setings AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewApplicationPool", vars.NewWebApplicationPool); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ApplicationPool", vars.WebApplicationPoolName); // update config setings AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSiteId", vars.WebSiteId); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSiteIP", vars.WebSiteIP); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSitePort", vars.WebSitePort); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSiteDomain", vars.WebSiteDomain); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "VirtualDirectory", vars.VirtualDirectory); AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewWebSite", vars.NewWebSite); AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewVirtualDirectory", vars.NewVirtualDirectory); // AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewUserAccount", vars.NewUserAccount); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "UserAccount", vars.UserAccount); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Domain", vars.UserDomain); // AppConfig.SaveConfiguration(); } void IUninstallAction.Run(SetupVariables vars) { try { Log.WriteStart(LogStartUninstallMessage); Log.WriteInfo(String.Format(LogUninstallInfoMessage, vars.ComponentFullName)); XmlUtils.RemoveXmlNode(AppConfig.GetComponentConfig(vars.ComponentId)); AppConfig.SaveConfiguration(); Log.WriteEnd(LogEndUninstallMessage); InstallLog.AppendLine("- Updated system configuration"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) { return; } // Log.WriteError(LogErrorUninstallMessage, ex); throw; } } } public class SwitchAppPoolAspNetVersion : Action, IInstallAction { public const string Iis6_AspNet_v4 = "v4.0.30319"; public const string Iis7_AspNet_v4 = "v4.0"; void IInstallAction.Run(SetupVariables vars) { if (vars.IISVersion.Major >= 7) { ChangeAspNetVersionOnIis7(vars); } else { ChangeAspNetVersionOnIis6(vars); } } private void ChangeAspNetVersionOnIis7(SetupVariables vars) { using (var srvman = new ServerManager()) { var appPool = srvman.ApplicationPools[vars.WebApplicationPoolName]; // if (appPool == null) throw new ArgumentNullException("appPool"); // appPool.ManagedRuntimeVersion = Iis7_AspNet_v4; // srvman.CommitChanges(); } } private void ChangeAspNetVersionOnIis6(SetupVariables vars) { // Utils.ExecAspNetRegistrationToolCommand(vars, String.Format("-norestart -s {0}", vars.WebSiteId)); } } public class RegisterAspNet40Action : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { if (CheckAspNet40Registered(vars) == false) { RegisterAspNet40(vars); } } private void RegisterAspNet40(Setup.SetupVariables setupVariables) { // Run ASP.NET Registration Tool command Utils.ExecAspNetRegistrationToolCommand(setupVariables, arguments: (setupVariables.IISVersion.Major == 6) ? "-ir -enable" : "-ir"); } private bool CheckAspNet40Registered(SetupVariables setupVariables) { // var aspNet40Registered = false; // Run ASP.NET Registration Tool command var psOutput = Utils.ExecAspNetRegistrationToolCommand(setupVariables, "-lv"); // Split process output per lines var strLines = psOutput.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); // Lookup for an evidence of ASP.NET 4.0 aspNet40Registered = strLines.Any((string s) => { return s.Contains("4.0.30319.0"); }); // return aspNet40Registered; } } public class EnableAspNetWebExtensionAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { if (vars.IISVersion.Major > 6) return; // Enable ASP.NET 4.0 Web Server Extension if it is prohibited if (Utils.GetAspNetWebExtensionStatus_Iis6(vars) == WebExtensionStatus.Prohibited) { Utils.EnableAspNetWebExtension_Iis6(); } } } public class MigrateServerWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // DoMigration(vars); } private void DoMigration(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Find/add WCF endpoints configuration section (DDTK) var serviceModelNode = xdoc.Root.Element("system.serviceModel", true); { // Find/add bindings node if does not exist var bindingsNode = serviceModelNode.Element("bindings", true); { // Find/add wsHttpBinding node if does not exist var wsHttpBindingNode = bindingsNode.Element("wsHttpBinding", true); { // Find SCVMM-DDTK endpoint binding configuration var vmmBindingNode = wsHttpBindingNode.XPathSelectElement("binding[@name='WSHttpBinding_IVirtualMachineManagementService']"); // Add SCVMM-DDTK endpoint binding configuration if (vmmBindingNode == null) wsHttpBindingNode.Add(XElement.Parse("<binding name=\"WSHttpBinding_IVirtualMachineManagementService\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:01:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"10485760\" messageEncoding=\"Text\" textEncoding=\"utf-8\" useDefaultWebProxy=\"true\" allowCookies=\"false\"><readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" /><reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\" /><security mode=\"Message\"><transport clientCredentialType=\"Windows\" proxyCredentialType=\"None\" realm=\"\" /><message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" algorithmSuite=\"Default\" /></security></binding>")); // Find SCOM-DDTK endpoint binding configuration var omBindingNode = wsHttpBindingNode.XPathSelectElement("binding[@name='WSHttpBinding_IMonitoringService']"); // Add SCOM-DDTK endpoint binding configuration if (omBindingNode == null) wsHttpBindingNode.Add(XElement.Parse("<binding name=\"WSHttpBinding_IMonitoringService\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:01:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"10485760\" messageEncoding=\"Text\" textEncoding=\"utf-8\" useDefaultWebProxy=\"true\" allowCookies=\"false\"><readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" /><reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\" /><security mode=\"Message\"><transport clientCredentialType=\"Windows\" proxyCredentialType=\"None\" realm=\"\" /><message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" algorithmSuite=\"Default\" /></security></binding>")); }; }; }; // Save all changes xdoc.Save(fileName); } } public class MigrateEntServerWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // DoMigration(vars); } private void DoMigration(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Save all changes xdoc.Save(fileName); } } public class AdjustHttpRuntimeRequestLengthAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // DoMigration(vars); } private void DoMigration(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // Adjust httpRuntime maximum request length if (swnode.Element("httpRuntime") != null) { var htnode = swnode.Element("httpRuntime"); // htnode.SetAttributeValue("maxRequestLength", "16384"); } }; // Save all changes xdoc.Save(fileName); } } public class MigrateWebPortalWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // if (vars.IISVersion.Major == 6) { DoMigrationOnIis6(vars); } else { DoMigrationOnIis7(vars); } } private void DoMigrationOnIis7(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Remove <configSections /> node if (xdoc.Root.Element("configSections") != null) xdoc.Root.Element("configSections").Remove(); // Remove <system.web.extensions /> node if (xdoc.Root.Element("system.web.extensions") != null) xdoc.Root.Element("system.web.extensions").Remove(); // Modify <appSettings /> node var apsnode = xdoc.Root.Element("appSettings"); { if (apsnode.XPathSelectElement("add[@key='ChartImageHandler']") == null) apsnode.Add(XElement.Parse("<add key=\"ChartImageHandler\" value=\"storage=file;timeout=20;\" />")); } // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // Modify <pages /> node var pnode = swnode.Element("pages"); { // Set rendering compatibility pnode.SetAttributeValue("controlRenderingCompatibilityVersion", "3.5"); // Select all legacy controls definitions var nodes = from node in pnode.Element("controls").Elements() where (String)node.Attribute("tagPrefix") == "asp" select node; // Remove all nodes found nodes.Remove(); }; // Set compatible request validation mode swnode.Element("httpRuntime").SetAttributeValue("requestValidationMode", "2.0"); // Modify <httpHandlers /> node var hhnode = swnode.Element("httpHandlers"); { // Remove <remove /> node if (hhnode.XPathSelectElement("remove[@path='*.asmx']") != null) hhnode.XPathSelectElement("remove[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*_AppService.axd']") != null) hhnode.XPathSelectElement("add[@path='*_AppService.axd']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*.asmx']") != null) hhnode.XPathSelectElement("add[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='ScriptResource.axd']") != null) hhnode.XPathSelectElement("add[@path='ScriptResource.axd']").Remove(); }; // Remove <httpModules /> node if (swnode.Element("httpModules") != null) swnode.Element("httpModules").Remove(); // if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Remove <system.codedom /> node if (xdoc.Root.Element("system.codedom") != null) xdoc.Root.Element("system.codedom").Remove(); // var swrnode = xdoc.Root.Element("system.webServer"); { // Remove <modules /> node if (swrnode.Element("modules") != null) swrnode.Element("modules").Remove(); // Remove <handlers /> node if (swrnode.Element("handlers") != null) swrnode.Element("handlers").Remove(); // Add <handlers /> node if (swrnode.Element("handlers") == null) swrnode.Add(new XElement("handlers")); // Modify <handlers /> node var hsnode = swrnode.Element("handlers"); { // if (hsnode.XPathSelectElement("add[@path='Reserved.ReportViewerWebControl.axd']") == null) hsnode.Add(XElement.Parse("<add name=\"ReportViewerWebControl\" verb=\"*\" path=\"Reserved.ReportViewerWebControl.axd\" type=\"Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />")); // if (hsnode.XPathSelectElement("add[@path='ChartImg.axd']") == null) hsnode.Add(XElement.Parse("<add name=\"ChartImg\" path=\"ChartImg.axd\" verb=\"GET,HEAD,POST\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />")); } }; // Remove <runtime /> node if (xdoc.Root.Element("runtime") != null) xdoc.Root.Element("runtime").Remove(); // Save all changes xdoc.Save(fileName); } private void DoMigrationOnIis6(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Remove <configSections /> node if (xdoc.Root.Element("configSections") != null) xdoc.Root.Element("configSections").Remove(); // Remove <system.web.extensions /> node if (xdoc.Root.Element("system.web.extensions") != null) xdoc.Root.Element("system.web.extensions").Remove(); // Modify <appSettings /> node var apsnode = xdoc.Root.Element("appSettings"); { if (apsnode.XPathSelectElement("add[@key='ChartImageHandler']") == null) apsnode.Add(XElement.Parse("<add key=\"ChartImageHandler\" value=\"storage=file;timeout=20;\" />")); } // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // Modify <pages /> node var pnode = swnode.Element("pages"); { // Set rendering compatibility pnode.SetAttributeValue("controlRenderingCompatibilityVersion", "3.5"); // Select all legacy controls definitions var nodes = from node in pnode.Element("controls").Elements() where (String)node.Attribute("tagPrefix") == "asp" select node; // Remove all nodes found nodes.Remove(); }; // Set compatible request validation mode swnode.Element("httpRuntime").SetAttributeValue("requestValidationMode", "2.0"); // Modify <httpHandlers /> node var hhnode = swnode.Element("httpHandlers"); { // Remove <remove /> node if (hhnode.XPathSelectElement("remove[@path='*.asmx']") != null) hhnode.XPathSelectElement("remove[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*_AppService.axd']") != null) hhnode.XPathSelectElement("add[@path='*_AppService.axd']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*.asmx']") != null) hhnode.XPathSelectElement("add[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='ScriptResource.axd']") != null) hhnode.XPathSelectElement("add[@path='ScriptResource.axd']").Remove(); // if (hhnode.XPathSelectElement("add[@path='ChartImg.axd']") == null) hhnode.Add(XElement.Parse("<add path=\"ChartImg.axd\" verb=\"GET,HEAD,POST\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\" />")); }; // Remove <httpModules /> node if (swnode.Element("httpModules") != null) swnode.Element("httpModules").Remove(); // Remove <compilation /> node if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Remove <system.codedom /> node if (xdoc.Root.Element("system.codedom") != null) xdoc.Root.Element("system.codedom").Remove(); // Remove <runtime /> node if (xdoc.Root.Element("runtime") != null) xdoc.Root.Element("runtime").Remove(); // Save all changes xdoc.Save(fileName); } } public class CleanupWebsitePanelModulesListAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { var filePath = Path.Combine(vars.InstallationFolder, @"App_Data\WebsitePanel_Modules.config"); // var xdoc = XDocument.Load(filePath); // if (xdoc.XPathSelectElement("//Control[@key='view_addon']") == null) { return; } // xdoc.XPathSelectElement("//Control[@key='view_addon']").Remove(); // xdoc.Save(filePath); } } #endregion public class RaiseExceptionAction : Action, IInstallAction { public override bool Indeterminate { get { return false; } } void IInstallAction.Run(SetupVariables vars) { throw new NotImplementedException(); } } public class ServerActionManager : BaseActionManager { public static readonly List<Action> InstallScenario = new List<Action> { new SetCommonDistributiveParamsAction(), new SetServerDefaultInstallationSettingsAction(), new EnsureServiceAccntSecured(), new CopyFilesAction(), new SetServerPasswordAction(), new CreateWindowsAccountAction(), new ConfigureAspNetTempFolderPermissionsAction(), new SetNtfsPermissionsAction(), new CreateWebApplicationPoolAction(), new CreateWebSiteAction(), new SwitchAppPoolAspNetVersion(), new SaveComponentConfigSettingsAction() }; public ServerActionManager(SetupVariables sessionVars) : base(sessionVars) { Initialize += new EventHandler(ServerActionManager_Initialize); } void ServerActionManager_Initialize(object sender, EventArgs e) { // switch (SessionVariables.SetupAction) { case SetupActions.Install: // Install LoadInstallationScenario(); break; default: break; } } protected virtual void LoadInstallationScenario() { CurrentScenario.AddRange(InstallScenario); } } }
#region Header // -------------------------------------------------------------------------- // Tethys.Silverlight // ========================================================================== // // This library contains common for .Net Windows applications. // // =========================================================================== // // <copyright file="CRC32.cs" company="Tethys"> // Copyright 1998-2015 by Thomas Graf // All rights reserved. // Licensed under the Apache License, Version 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. // </copyright> // // System ... Microsoft .Net Framework 4 // Tools .... Microsoft Visual Studio 2013 // // --------------------------------------------------------------------------- #endregion namespace Tethys.Cryptography { using System; using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; /// <summary> /// The class CRC32 implements a fast CRC-32 checksum algorithm, /// that uses the following polynomial:<br/> /// <code> /// x**32 + x**26 + x**23 + x**22 + x**16 + x**12 + x**11 + /// x**10 + x**8 + x**7 + x**5 + x**4 + x**2 + x + 1 /// ( = 0x04C11DB7) /// </code> /// This algorithm is also used in <c>Winzip</c>.<br/> /// Default initial value = 0xffffffff,<br/> /// default final XOR value = 0xffffffff. /// </summary> [CLSCompliant(false)] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CRC", Justification = "Ok here.")] public sealed class CRC32 : HashAlgorithm { // =================================================================== // CHECKSUM RESULTS // =================================================================== // TEST1 is the three character sequence "ABC". // TEST2 is the three character sequence "CBA". // TEST3 is the eight character sequence of "12345678" // TEST4 is the 1024 character sequence of "12345678" // repeated 128 times. // // Value byte[0] byte[1] byte[2] byte[3] // --------- ------- ------- ------- ------- // CRC-32(TEST1) = A383:0348 0x48 0x03 0x83 0xA3 // CRC-32(TEST2) = 4E09:B60A 0x0A 0xB6 0x09 0x4E // CRC-32(TEST3) = 9AE0:DAAF 0xAF 0xDA 0xE0 0x9A // CRC-32(TEST4) = DCC5:6324 0x24 0x63 0xC5 0xDC // =================================================================== /********************************************************************** Note This algorithm is specified by W. D. Schwaderer in his book ---- "C Programmer's Guide to NetBIOS" Howard W. Sams & Company First Edition 1988. The implementation of the minimized-table-4-bit variant was designed by Marcellus Buchheit after the guidelines of the CRC-CCITT algorithm in the book above. **********************************************************************/ /// <summary> /// Constants used to compute the CRC-32 checksum. /// </summary> private static readonly uint[] PreCalcTab = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D }; // PreCalcTab[] /// <summary> /// Hash size in bits. /// </summary> private const int HashSizeBitsCrc32 = 32; /// <summary> /// Hash size in bytes. /// </summary> private const int HashSizeBytesCrc32 = 4; /// <summary> /// Default initial value. /// </summary> public const uint DefaultInit = 0xffffffff; /// <summary> /// Default final XOR value. /// </summary> public const uint DefaultXor = 0xffffffff; /// <summary> /// Initial value. /// </summary> private uint initValue; /// <summary> /// Final XOR value. /// </summary> private uint xorValue; /// <summary> /// 32 bit CRC value. /// </summary> private uint crc; #region PUBLIC HASH ALGORITHM METHODS /// <summary> /// Gets or sets the initial value. /// </summary> public uint InitValue { get { return this.initValue; } set { this.initValue = value; Initialize(); } } // InitValue /// <summary> /// Gets or sets the final XOR value. /// </summary> public uint XorValue { get { return this.xorValue; } set { this.xorValue = value; } } // XorValue /// <summary> /// Initializes a new instance of the <see cref="CRC32"/> class. /// </summary> public CRC32() { HashSizeValue = HashSizeBitsCrc32; HashValue = new byte[HashSizeBytesCrc32]; this.initValue = DefaultInit; this.xorValue = DefaultXor; Initialize(); HashValue[0] = (byte)(this.crc >> 24); HashValue[1] = (byte)((this.crc & 0x00ff0000) >> 16); HashValue[2] = (byte)((this.crc & 0x0000ff00) >> 8); HashValue[3] = (byte)(this.crc & 0x000000ff); } // CRC32() /// <summary> /// Initializes this implementation of HashAlgorithm. /// </summary> public override void Initialize() { this.crc = this.initValue; } // Initialize() #endregion // PUBLIC HASH ALGORITHM METHODS #region PROTECTED HASH ALGORITHM METHODS /// <summary> /// Routes data written to the object into the hash /// algorithm for computing the hash. /// </summary> /// <param name="buffer">The input for which to compute the hash code. </param> /// <param name="offset">The offset into the byte array from which to begin using data. </param> /// <param name="count">The number of bytes in the byte array to use as data.</param> protected override void HashCore(byte[] buffer, int offset, int count) { for (; count != 0; count--, offset++) { // calculate CRC for next byte // using table with 256 entries uint i = (byte)(this.crc ^ buffer[offset]); this.crc = ((this.crc >> 8) & 0x00FFFFFF) ^ PreCalcTab[i]; } // for } // HashCore() /// <summary> /// Finalizes the hash computation after the last data is processed /// by the cryptographic stream object. /// </summary> /// <returns>The computed hash code.</returns> protected override byte[] HashFinal() { uint crcRet = this.crc ^ this.xorValue; // save new calculated value var myHash = new byte[4]; myHash[0] = (byte)(crcRet >> 24); myHash[1] = (byte)((crcRet & 0x00ff0000) >> 16); myHash[2] = (byte)((crcRet & 0x0000ff00) >> 8); myHash[3] = (byte)(crcRet & 0x000000ff); return myHash; } // HashFinal() #endregion // PROTECTED HASH ALGORITHM METHODS } // CRC32 } // Tethys.Cryptography // ======================= // Tethys: end of crc32.cs // =======================
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; using System.Drawing; using System.Drawing.Imaging; using System.Timers; using System.Threading; using System.Runtime.CompilerServices; using NavigationSimulator; using NeuralNetworkLib; namespace OnlabNeuralis { public enum inputType { wheelAngle, wheelSpeed }; public class NeuralController { public const double MAX_NEURON_VALUE = 10; public const double MIN_NEURON_VALUE = -10; public const double POSITION_SCALE = 1; private const int EPOCH_COUNT = 40; public const inputType INPUT_TYPE = inputType.wheelAngle; public MLPDll controller; private IModelSimulator model; public List<CarModelState> trainInnerStates; private IObstaclePositionProvider obstacleProvider; private ICarPositionProvider carStateProvider; private IFinishPositionProvider finishStateProvider; bool trainingStopped; Thread trainThread; NewTrainEpochDelegate callback; public double mu; public NeuralController(IModelSimulator model, IObstaclePositionProvider obstacle, ICarPositionProvider start, IFinishPositionProvider finish) { this.model = model; if (INPUT_TYPE == inputType.wheelAngle) { controller = new MLPDll(new int[] { 20, 1 }, 4);//4 bemenet a state, 1 kimenet az input } else if (INPUT_TYPE == inputType.wheelSpeed) { controller = new MLPDll(new int[] { 75, 2 }, 4);//4 bemenet a state, 2 kimenet az input } obstacleProvider = obstacle; carStateProvider = start; finishStateProvider = finish; trainingStopped = true; mu = 0.005; } //public NeuralController(IModelSimulator model, IObstaclePositionProvider obstacle, ICarPositionProvider start, IFinishPositionProvider finish, string filename) //{ // this.model = model; // controller = new MLPDll(filename); // obstacleProvider = obstacle; // carStateProvider = start; // finishStateProvider = finish; // trainingStopped = true; // mu = 0.005; //} public Bitmap VisualizeObstacleField(int width, int height) { lock (this) { uint[] buf = new uint[width * height]; for (int x = 0; x < width; ++x) for (int y = 0; y < height; ++y) { CarModelState state = new CarModelState(); state.Angle = 0; state.Position = new PointD(ComMath.Normal(x, 0, width - 1, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(y, 0, height - 1, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)); double err = obstacleFieldError(state); if (err > 255) err = 255; buf[y * width + x] = 0x80000000 + ((uint)(err)); } Bitmap bm = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bmData = bm.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int len = bmData.Width * bmData.Height; unsafe { uint* cim = (uint*)bmData.Scan0.ToPointer();//direkt bitmap memoriaba rajzolunk, gyors for (int i = 0; i < len; ++i) { cim[i] = buf[i]; } } bm.UnlockBits(bmData); return bm; } } private double[] obstacleFieldErrorGradient(CarModelState state, int time) { //C = sum((1/d(X) - 1/d(0))^2) //dC/dy_x =... //dC/dy_y =... double ksi = 0.0001; double errX = 0; double errY = 0; List<ObstacleState> obstacles = obstacleProvider.GetObstacleStates(time); foreach (ObstacleState obst in obstacles) { double x = ComMath.Normal(state.Position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double y = ComMath.Normal(state.Position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double x0 = ComMath.Normal(obst.pp.position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double y0 = ComMath.Normal(obst.pp.position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double r = ComMath.Normal(obst.radius + CarModel.SHAFT_LENGTH/2, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double dist = Math.Sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0)) - r; if (dist <= 0.0001) dist = 0.0001; double err = (1 / (dist * dist * dist)); errX += err * (x - x0); errY += err * (y - y0); } if (obstacles.Count > 0) { errX /= obstacles.Count; errY /= obstacles.Count; } return new double[] { ksi * errX, ksi * errY, 0, 0 }; } private double obstacleFieldError(CarModelState state) { double err = 0; List<ObstacleState> obstacles = obstacleProvider.GetObstacleStates(1); foreach (ObstacleState obst in obstacles) { double x = ComMath.Normal(state.Position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double y = ComMath.Normal(state.Position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double x0 = ComMath.Normal(obst.pp.position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double y0 = ComMath.Normal(obst.pp.position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double dist = Math.Sqrt((x - x0) * (x - x0) + (y - y0) * (y - y0)); err += Math.Pow(1 / dist - 1 / obst.radius, 2); } return err; } public delegate void NewTrainEpochDelegate(); public void StartTrain(NewTrainEpochDelegate aCallback) { if (trainingStopped) { callback = aCallback; trainThread = new Thread(new ThreadStart(this.Train)); trainThread.Start(); trainThread.IsBackground = true; trainingStopped = false; } } public void StopTrain() { trainingStopped = true;//magatol ki fog lepni } private void Train() { while (!trainingStopped) { double error = 0, error2 = 0; double sumSimCount = 0; for (int epoch = 0; epoch < EPOCH_COUNT; ++epoch) { double ii; error += TrainOneEpoch(mu, out ii, out trainInnerStates); sumSimCount += ii; } error /= EPOCH_COUNT; sumSimCount /= EPOCH_COUNT; //if (error2 <= error ) mu *= 0.75; error2 = error; //System.Console.WriteLine(error.ToString() + " " + sumSimCount.ToString()); callback();//ertesitsuk a callbacken keresztul a fromot hogy veget ert egy epoch Thread.Sleep(0); } trainInnerStates.Clear(); callback(); //controller.SaveNN("neuralcontroller.mlp"); } private double TrainOneEpoch(double mu, out double SumSimCount, out List<CarModelState> innerStates) { int maxSimCount = 100; double sumSimCount = 0; double error = 0; innerStates = new List<CarModelState>(); List<double> deltaws = new List<double>(); MLPDll[] controllers = new MLPDll[maxSimCount]; IModelSimulator[] models = new IModelSimulator[maxSimCount]; CarModelState state = carStateProvider.GetCarState(); CarModelInput input = new CarModelInput(); //kimenet kiszamitasa int simCount = 0; List<double[]> singleErrors = new List<double[]>(); List<double[]> regularizationErrors = new List<double[]>(); CarModelState laststate; bool earlyStop; do { controllers[simCount] = new MLPDll(controller);//lemasoljuk models[simCount] = model.Clone();//a modellt is laststate = state; NeuralController.SimulateOneStep(controllers[simCount], models[simCount], state, out input, out state);//vegigszimulaljuk a simCount darab controlleren es modellen innerStates.Add(state); //kozbulso hibak kiszamitasa, itt csak az akadalyoktol valo tavolsag "hibajat" vesszuk figyelembe, irany nem szamit -> hibaja 0 regularizationErrors.Add(obstacleFieldErrorGradient(state, simCount)); //minden pont celtol vett tavolsaga double[] desiredOutput = (double[])finishStateProvider.GetFinishState(simCount); singleErrors.Add(new double[] { 1*ComMath.Normal(desiredOutput[0] - state.Position.X,CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE), 1*ComMath.Normal(desiredOutput[1] - state.Position.Y,CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE), 0.1*ComMath.Normal(desiredOutput[2] - state.Orientation.X,CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE), 0.1*ComMath.Normal(desiredOutput[3] - state.Orientation.Y,CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE) } ); ++simCount; earlyStop = false; if (simCount > 3) { double[] err1 = singleErrors[simCount-1]; double[] err2 = singleErrors[simCount-2]; double[] err3 = singleErrors[simCount-3]; double error1, error2, error3; error1 = error2 = error3 = 0; for (int i = 0; i < err1.Length; i++) { error1 += err1[i] * err1[i]; error2 += err2[i] * err2[i]; error3 += err3[i] * err3[i]; } earlyStop = ((error1 > error2) && (error3 > error2)); if (earlyStop) { //utolso elemet toroljuk singleErrors.RemoveAt(singleErrors.Count - 1); regularizationErrors.RemoveAt(regularizationErrors.Count - 1); innerStates.RemoveAt(innerStates.Count - 1); --simCount; } } } while ((simCount < maxSimCount) && !earlyStop); double[] errors = singleErrors[singleErrors.Count-1]; sumSimCount += simCount; //hibavisszaterjesztes for (int i = simCount - 1; i >= 0; --i) { double[] sensitibility; models[i].CalcErrorSensibility(errors, out sensitibility); double[] inputSensitibility; if (INPUT_TYPE == inputType.wheelAngle) { inputSensitibility = new double[1]; inputSensitibility[0] = sensitibility[6]; } else if (INPUT_TYPE == inputType.wheelSpeed) { inputSensitibility = new double[2]; inputSensitibility[0] = sensitibility[4]; inputSensitibility[1] = sensitibility[5]; } double[] sensitibility2; controllers[i].SetOutputError(inputSensitibility); controllers[i].Backpropagate(); controllers[i].CalculateDeltaWeights(); sensitibility2 = controllers[i].SensitibilityD(); errors[0] = (sensitibility[0] + sensitibility2[0]); errors[1] = (sensitibility[1] + sensitibility2[1]); errors[2] = (sensitibility[2] + sensitibility2[2]); errors[3] = (sensitibility[3] + sensitibility2[3]); //regularizaciobol szarmazo hiba hozzaadasa errors[0] += regularizationErrors[i][0]; errors[1] += regularizationErrors[i][1]; } controller.ClearDeltaWeights(); //sulymodositasok osszegzese for (int i2 = 0; i2 < simCount; ++i2) { controller.AddDeltaWeights(controllers[i2]); } float maxdw = controller.MaxDeltaWeight(); //if (maxdw < 50) maxdw = 50; controller.ChangeWeights(mu / maxdw); ////sulymodositasok osszegzese //for (int i2 = 0; i2 < simCount; ++i2) //simCount //{ // int count = 0; // for (int i = 1; i < controllers[i2]; ++i) // { // foreach (INeuron n in controllers[i2].mlp[i]) // { // foreach (NeuronInput ni in ((Neuron)n).inputs) // { // if (deltaws.Count <= count) deltaws.Add(ni.deltaw); // else deltaws[count] += ni.deltaw; // ++count; // } // } // } //} ////legnagyobb sulymodositas ertekenek meghatarozasa, majd ezzel normalas //double maxdw = 1; //foreach (double dw in deltaws) //{ // if (Math.Abs(dw) > maxdw) maxdw = Math.Abs(dw); //} //if (maxdw < 50) maxdw = 50; ////sulymodositasok ervenyre juttatasa a controllerben //int count2 = 0; //for (int i = 1; i < controller.mlp.Count; ++i) //{ // foreach (INeuron n in controller.mlp[i]) // { // foreach (NeuronInput ni in ((Neuron)n).inputs) // { // ni.w += mu * deltaws[count2] / maxdw; // ++count2; // } // } //} SumSimCount = sumSimCount; return error; } public void Simulate(CarModelState initialState, int simCount, out CarModelInput[] inputs, out CarModelState[] states) { inputs = new CarModelInput[simCount]; states = new CarModelState[simCount]; CarModelState state = initialState; for (int i = 0; i < simCount; ++i) { SimulateOneStep(state, out inputs[i], out states[i]); state = states[i]; } } public void SimulateOneStep(CarModelState state, out CarModelInput outInput, out CarModelState outState) { NeuralController.SimulateOneStep(this.controller, this.model, state, out outInput, out outState); } public static void SimulateOneStep(MLPDll controller, IModelSimulator model, CarModelState state, out CarModelInput outInput, out CarModelState outState) { double[] inputs = new double[4]; inputs[0] = ComMath.Normal(state.Position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, POSITION_SCALE * MIN_NEURON_VALUE, POSITION_SCALE * MAX_NEURON_VALUE); inputs[1] = ComMath.Normal(state.Position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, POSITION_SCALE * MIN_NEURON_VALUE, POSITION_SCALE * MAX_NEURON_VALUE); inputs[2] = ComMath.Normal(state.Orientation.X, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); inputs[3] = ComMath.Normal(state.Orientation.Y, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); double[] controllerOutputs = controller.Output(inputs); if (INPUT_TYPE == inputType.wheelAngle) { outInput = new CarModelInput(); outInput.Angle = ComMath.Normal(controllerOutputs[0], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelInput.MIN_ANGLE, CarModelInput.MAX_ANGLE); } else if (INPUT_TYPE == inputType.wheelSpeed) { outInput = new CarModelInput(ComMath.Normal(controllerOutputs[0], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED), ComMath.Normal(controllerOutputs[1], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED)); //******** //hatrafele tilos mennie if (outInput.LeftSpeed < 0) outInput.LeftSpeed = 0; if (outInput.RightSpeed < 0) outInput.RightSpeed = 0; //******** } model.SimulateModel(state, outInput, out outState); } /*private bool IsOutOfBounds(CarModelState state) { bool oob = false; double distance = CarModel.SIMULATION_TIME_STEP * CarModelInput.MAX_SPEED; if ((state.Position.X < CarModelState.MIN_POS_X + 2 * distance) || (state.Position.X > CarModelState.MAX_POS_X - 2 * distance) || (state.Position.Y < CarModelState.MIN_POS_Y + 2 * distance) || (state.Position.Y > CarModelState.MAX_POS_Y - 2 * distance)) oob = true; if ((Math.Abs(state.Position.X - (CarModelState.MIN_POS_X + CarModelState.MAX_POS_X) / 2) < 3 * distance) && (state.Position.Y - (CarModelState.MIN_POS_Y + CarModelState.MAX_POS_Y) / 2 < 2 * distance) && (state.Position.Y - (CarModelState.MIN_POS_Y + CarModelState.MAX_POS_Y) / 2 > -distance) && (state.Orientation.Y > 0.5)) oob = true; foreach (ObstacleModel obst in obstacles) { double x = (state.Position.X - obst.state.position.X); double y = (state.Position.Y - obst.state.position.Y); if (x * x + y * y <= obst.state.radius * obst.state.radius) oob = true; } return oob; } public Bitmap VisualizeBounds(int width, int height, double angle) { uint[] buf = new uint[width * height]; for (int x = 0; x < width; ++x) for (int y = 0; y < height; ++y) { CarModelState state = new CarModelState(); state.Angle = angle; state.Position = new PointD(ComMath.Normal(x, 0, width - 1, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(y, 0, height - 1, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)); bool outp = IsOutOfBounds(state); if (outp) buf[y * width + x] = 0x80FF0000; else buf[y * width + x] = 0x00000000; } Bitmap bm = new Bitmap(width, height,PixelFormat.Format32bppArgb); BitmapData bmData = bm.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); int len = bmData.Width * bmData.Height; unsafe { uint* cim = (uint*)bmData.Scan0.ToPointer();//direkt bitmap memoriaba rajzolunk, gyors for (int i = 0; i < len; ++i) { cim[i] = buf[i]; } } bm.UnlockBits(bmData); return bm; }*/ } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace Codisa.InterwayDocs.Business { /// <summary> /// IncomingInfo (read only object).<br/> /// This is a generated <see cref="IncomingInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="IncomingBook"/> collection. /// </remarks> [Serializable] public partial class IncomingInfo : ReadOnlyBase<IncomingInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="RegisterId"/> property. /// </summary> public static readonly PropertyInfo<int> RegisterIdProperty = RegisterProperty<int>(p => p.RegisterId, "Register Id"); /// <summary> /// Gets the Register Id. /// </summary> /// <value>The Register Id.</value> public int RegisterId { get { return GetProperty(RegisterIdProperty); } } /// <summary> /// Maintains metadata about <see cref="RegisterDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> RegisterDateProperty = RegisterProperty<SmartDate>(p => p.RegisterDate, "Register Date"); /// <summary> /// Gets the Register Date. /// </summary> /// <value>The Register Date.</value> public string RegisterDate { get { return GetPropertyConvert<SmartDate, string>(RegisterDateProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentType"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentTypeProperty = RegisterProperty<string>(p => p.DocumentType, "Document Type"); /// <summary> /// Gets the Document Type. /// </summary> /// <value>The Document Type.</value> public string DocumentType { get { return GetProperty(DocumentTypeProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentReference"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentReferenceProperty = RegisterProperty<string>(p => p.DocumentReference, "Document Reference"); /// <summary> /// Gets the Document Reference. /// </summary> /// <value>The Document Reference.</value> public string DocumentReference { get { return GetProperty(DocumentReferenceProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentEntity"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentEntityProperty = RegisterProperty<string>(p => p.DocumentEntity, "Document Entity"); /// <summary> /// Gets the Document Entity. /// </summary> /// <value>The Document Entity.</value> public string DocumentEntity { get { return GetProperty(DocumentEntityProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDept"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentDeptProperty = RegisterProperty<string>(p => p.DocumentDept, "Document Dept"); /// <summary> /// Gets the Document Dept. /// </summary> /// <value>The Document Dept.</value> public string DocumentDept { get { return GetProperty(DocumentDeptProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentClass"/> property. /// </summary> public static readonly PropertyInfo<string> DocumentClassProperty = RegisterProperty<string>(p => p.DocumentClass, "Document Class"); /// <summary> /// Gets the Document Class. /// </summary> /// <value>The Document Class.</value> public string DocumentClass { get { return GetProperty(DocumentClassProperty); } } /// <summary> /// Maintains metadata about <see cref="DocumentDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> DocumentDateProperty = RegisterProperty<SmartDate>(p => p.DocumentDate, "Document Date"); /// <summary> /// Gets the Document Date. /// </summary> /// <value>The Document Date.</value> public string DocumentDate { get { return GetPropertyConvert<SmartDate, string>(DocumentDateProperty); } } /// <summary> /// Maintains metadata about <see cref="Subject"/> property. /// </summary> public static readonly PropertyInfo<string> SubjectProperty = RegisterProperty<string>(p => p.Subject, "Subject"); /// <summary> /// Gets the Subject. /// </summary> /// <value>The Subject.</value> public string Subject { get { return GetProperty(SubjectProperty); } } /// <summary> /// Maintains metadata about <see cref="SenderName"/> property. /// </summary> public static readonly PropertyInfo<string> SenderNameProperty = RegisterProperty<string>(p => p.SenderName, "Sender Name"); /// <summary> /// Gets the Sender Name. /// </summary> /// <value>The Sender Name.</value> public string SenderName { get { return GetProperty(SenderNameProperty); } } /// <summary> /// Maintains metadata about <see cref="ReceptionDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ReceptionDateProperty = RegisterProperty<SmartDate>(p => p.ReceptionDate, "Reception Date"); /// <summary> /// Gets the Reception Date. /// </summary> /// <value>The Reception Date.</value> public string ReceptionDate { get { return GetPropertyConvert<SmartDate, string>(ReceptionDateProperty); } } /// <summary> /// Maintains metadata about <see cref="RoutedTo"/> property. /// </summary> public static readonly PropertyInfo<string> RoutedToProperty = RegisterProperty<string>(p => p.RoutedTo, "Routed To"); /// <summary> /// Gets the Routed To. /// </summary> /// <value>The Routed To.</value> public string RoutedTo { get { return GetProperty(RoutedToProperty); } } /// <summary> /// Maintains metadata about <see cref="Notes"/> property. /// </summary> public static readonly PropertyInfo<string> NotesProperty = RegisterProperty<string>(p => p.Notes, "Notes"); /// <summary> /// Gets the Notes. /// </summary> /// <value>The Notes.</value> public string Notes { get { return GetProperty(NotesProperty); } } /// <summary> /// Maintains metadata about <see cref="ArchiveLocation"/> property. /// </summary> public static readonly PropertyInfo<string> ArchiveLocationProperty = RegisterProperty<string>(p => p.ArchiveLocation, "Archive Location"); /// <summary> /// Gets the Archive Location. /// </summary> /// <value>The Archive Location.</value> public string ArchiveLocation { get { return GetProperty(ArchiveLocationProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="IncomingInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="IncomingInfo"/> object.</returns> internal static IncomingInfo GetIncomingInfo(SafeDataReader dr) { IncomingInfo obj = new IncomingInfo(); obj.Fetch(dr); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="IncomingInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public IncomingInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="IncomingInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(RegisterIdProperty, dr.GetInt32("RegisterId")); LoadProperty(RegisterDateProperty, dr.GetSmartDate("RegisterDate", true)); LoadProperty(DocumentTypeProperty, dr.GetString("DocumentType")); LoadProperty(DocumentReferenceProperty, dr.GetString("DocumentReference")); LoadProperty(DocumentEntityProperty, dr.GetString("DocumentEntity")); LoadProperty(DocumentDeptProperty, dr.GetString("DocumentDept")); LoadProperty(DocumentClassProperty, dr.GetString("DocumentClass")); LoadProperty(DocumentDateProperty, dr.GetSmartDate("DocumentDate", true)); LoadProperty(SubjectProperty, dr.GetString("Subject")); LoadProperty(SenderNameProperty, dr.GetString("SenderName")); LoadProperty(ReceptionDateProperty, dr.GetSmartDate("ReceptionDate", true)); LoadProperty(RoutedToProperty, dr.GetString("RoutedTo")); LoadProperty(NotesProperty, dr.GetString("Notes")); LoadProperty(ArchiveLocationProperty, dr.GetString("ArchiveLocation")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using NUnit.Framework; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Indicators; using QuantConnect.Orders; using QuantConnect.Orders.Fills; using QuantConnect.Securities; using QuantConnect.Securities.Forex; using QuantConnect.Tests.Common.Data; using QuantConnect.Tests.Common.Securities; using QuantConnect.Securities.Equity; namespace QuantConnect.Tests.Common.Orders.Fills { [TestFixture] public class EquityFillModelTests { private static readonly DateTime Noon = new DateTime(2014, 6, 24, 12, 0, 0); private static readonly TimeKeeper TimeKeeper = new TimeKeeper(Noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork }); [TestCase(11, 11, 11, "")] [TestCase(12, 11, 11,"")] [TestCase(12, 10, 11, "Warning: No quote information")] [TestCase(12, 10, 10, "Warning: fill at stale price")] public void PerformsMarketFillBuy(int orderHour, int quoteBarHour, int tradeBarHour, string message) { var configTradeBar = CreateTradeBarConfig(Symbols.SPY); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var equity = CreateEquity(configTradeBar); var orderTime = new DateTime(2014, 6, 24, orderHour, 0, 0).ConvertToUtc(equity.Exchange.TimeZone); var quoteBarTime = new DateTime(2014, 6, 24, quoteBarHour, 0, 0).AddMinutes(-1); var tradeBarTime = new DateTime(2014, 6, 24, tradeBarHour, 0, 0).AddMinutes(-1); var model = (EquityFillModel)equity.FillModel; var order = new MarketOrder(Symbols.SPY, 100, orderTime); var parameters = new FillModelParameters(equity, order, configProvider, Time.OneHour); // Sets price at time zero equity.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); equity.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.123m)); // IndicatorDataPoint is not market data Assert.Throws<InvalidOperationException>(() => model.Fill(parameters), $"Cannot get ask price to perform fill for {equity.Symbol} because no market data subscription were found."); const decimal close = 101.234m; var bidBar = new Bar(101.123m, 101.123m, 101.123m, 101.123m); var askBar = new Bar(101.234m, 101.234m, 101.234m, close); var tradeBar = new TradeBar(tradeBarTime, Symbols.SPY, 101.123m, 101.123m, 101.123m, close, 100); equity.SetMarketPrice(new QuoteBar(quoteBarTime, Symbols.SPY, bidBar, 0, askBar, 0)); equity.SetMarketPrice(tradeBar); var fill = model.Fill(parameters).OrderEvent; Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(close, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); Assert.IsTrue(fill.Message.StartsWith(message, StringComparison.InvariantCultureIgnoreCase)); } [TestCase(11, 11, 11, "")] [TestCase(12, 11, 11, "")] [TestCase(12, 10, 11, "Warning: No quote information")] [TestCase(12, 10, 10, "Warning: fill at stale price")] public void PerformsMarketFillSell(int orderHour, int quoteBarHour, int tradeBarHour, string message) { var configTradeBar = CreateTradeBarConfig(Symbols.SPY); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var equity = CreateEquity(configTradeBar); var orderTime = new DateTime(2014, 6, 24, orderHour, 0, 0).ConvertToUtc(equity.Exchange.TimeZone); var quoteBarTime = new DateTime(2014, 6, 24, quoteBarHour, 0, 0).AddMinutes(-1); var tradeBarTime = new DateTime(2014, 6, 24, tradeBarHour, 0, 0).AddMinutes(-1); var model = (EquityFillModel)equity.FillModel; var order = new MarketOrder(Symbols.SPY, -100, orderTime); var parameters = new FillModelParameters(equity, order, configProvider, Time.OneHour); // Sets price at time zero equity.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); equity.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.123m)); // IndicatorDataPoint is not market data Assert.Throws<InvalidOperationException>(() => model.Fill(parameters), $"Cannot get bid price to perform fill for {equity.Symbol} because no market data subscription were found."); const decimal close = 101.123m; var bidBar = new Bar(101.123m, 101.123m, 101.123m, close); var askBar = new Bar(101.234m, 101.234m, 101.234m, 101.234m); var tradeBar = new TradeBar(tradeBarTime, Symbols.SPY, 101.234m, 101.234m, 101.234m, close, 100); equity.SetMarketPrice(new QuoteBar(quoteBarTime, Symbols.SPY, bidBar, 0, askBar, 0)); equity.SetMarketPrice(tradeBar); var fill = model.Fill(parameters).OrderEvent; Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(close, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); Assert.IsTrue(fill.Message.StartsWith(message, StringComparison.InvariantCultureIgnoreCase)); } [Test] public void PerformsLimitFillBuy() { var model = new EquityFillModel(); var order = new LimitOrder(Symbols.SPY, 100, 101.5m, Noon); var config = CreateTradeBarConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 102m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 102m, 103m, 101m, 102.3m, 100)); fill = model.LimitFill(security, order); // this fills worst case scenario, so it's at the limit price Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(Math.Min(order.LimitPrice, security.High), fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsLimitFillSell() { var model = new EquityFillModel(); var order = new LimitOrder(Symbols.SPY, -100, 101.5m, Noon); var config = CreateTradeBarConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 102m, 103m, 101m, 102.3m, 100)); fill = model.LimitFill(security, order); // this fills worst case scenario, so it's at the limit price Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(Math.Max(order.LimitPrice, security.Low), fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsStopLimitFillBuy() { var model = new EquityFillModel(); var order = new StopLimitOrder(Symbols.SPY, 100, 101.5m, 101.75m, Noon); var config = CreateTradeBarConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 100m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 102m)); fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.66m)); fill = model.StopLimitFill(security, order); // this fills worst case scenario, so it's at the limit price Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(security.High, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsStopLimitFillSell() { var model = new EquityFillModel(); var order = new StopLimitOrder(Symbols.SPY, -100, 101.75m, 101.50m, Noon); var config = CreateTradeBarConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 102m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101m)); fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101.66m)); fill = model.StopLimitFill(security, order); // this fills worst case scenario, so it's at the limit price Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(security.Low, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsStopMarketFillBuy() { var model = new EquityFillModel(); var order = new StopMarketOrder(Symbols.SPY, 100, 101.5m, Noon); var config = CreateTradeBarConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 102.5m)); fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; // this fills worst case scenario, so it's min of asset/stop price Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(Math.Max(security.Price, order.StopPrice), fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsLimitIfTouchedSell() { var model = new EquityFillModel(); var order = new LimitIfTouchedOrder(Symbols.SPY, -100, 101.5m, 105m, Noon); var configTradeBar = CreateTradeBarConfig(Symbols.SPY); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), configTradeBar, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); // Sets price at time zero security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 100m, 100m, 90m, 90m, 100)); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var fill = model.Fill(new FillModelParameters( security, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); // Time jump => trigger touched but not limit security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 102m, 103m, 102m, 102m, 100)); security.SetMarketPrice(new QuoteBar(Noon, Symbols.SPY, new Bar(101m, 102m, 100m, 100m), 100, // Bid bar new Bar(103m, 104m, 102m, 102m), 100) // Ask bar ); Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); fill = model.Fill(new FillModelParameters( security, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); // Time jump => limit reached, security bought // |---> First, ensure that price data are not used to fill security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 100m, 100m, 99m, 99m, 100)); fill = model.LimitIfTouchedFill(security, order); Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); // |---> Lastly, ensure that quote data used to fill security.SetMarketPrice(new QuoteBar(Noon, Symbols.SPY, new Bar(105m, 105m, 105m, 105m), 100, // Bid bar new Bar(105m, 105m, 105m, 105m), 100) // Ask bar ); fill = model.LimitIfTouchedFill(security, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(order.LimitPrice, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsLimitIfTouchedBuy() { var model = new EquityFillModel(); var order = new LimitIfTouchedOrder(Symbols.SPY, 100, 101.5m, 100m, Noon); var configTradeBar = CreateTradeBarConfig(Symbols.SPY); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), configTradeBar, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); // Sets price at time zero security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 102m, 102m, 102m, 102m, 100)); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var fill = model.Fill(new FillModelParameters( security, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); // Time jump => trigger touched but not limit security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 101m, 101m, 100.5m, 101m, 100)); security.SetMarketPrice(new QuoteBar(Noon, Symbols.SPY, new Bar(101m, 101m, 100.5m, 101m), 100, // Bid bar new Bar(101m, 101m, 100.5m, 101m), 100) // Ask bar ); Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); fill = model.Fill(new FillModelParameters( security, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); // Time jump => limit reached, security bought // |---> First, ensure that price data are not used to fill security.SetMarketPrice(new TradeBar(Noon, Symbols.SPY, 100m, 100m, 99m, 99m, 100)); fill = model.LimitIfTouchedFill(security, order); Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); // |---> Lastly, ensure that quote data used to fill security.SetMarketPrice(new QuoteBar(Noon, Symbols.SPY, new Bar(100m, 100m, 100m, 100m), 100, // Bid bar new Bar(100m, 100m, 100m, 100m), 100) // Ask bar ); fill = model.LimitIfTouchedFill(security, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(order.LimitPrice, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [Test] public void PerformsStopMarketFillSell() { var model = new EquityFillModel(); var order = new StopMarketOrder(Symbols.SPY, -100, 101.5m, Noon); var config = CreateTradeBarConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 102m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, Noon, 101m)); fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; // this fills worst case scenario, so it's min of asset/stop price Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(Math.Min(security.Price, order.StopPrice), fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnOpenUsingOpenPriceWithMinuteSubscription(int quantity) { var reference = new DateTime(2015, 06, 05, 9, 0, 0); // before market open var configTradeBar = CreateTradeBarConfig(Symbols.SPY); var equity = CreateEquity(configTradeBar); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnOpenOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time, Symbols.SPY, 1m, 2m, 0.5m, 1.33m, 100)); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var fill = model.Fill(new FillModelParameters( equity, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // market opens after 30min, so this is just before market open time = reference.AddMinutes(29); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time, Symbols.SPY, 1.33m, 2.75m, 1.15m, 1.45m, 100)); fill = model.Fill(new FillModelParameters( equity, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); const decimal expected = 1.45m; // market opens after 30min time = reference.AddMinutes(30); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); // Does not fill with quote data equity.SetMarketPrice(new QuoteBar(time, Symbols.SPY, new Bar(1.45m, 1.99m, 1.09m, 1.39m), 100, new Bar(1.46m, 2.01m, 1.11m, 1.41m), 100)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); // Fill with trade bar equity.SetMarketPrice(new TradeBar(time, Symbols.SPY, expected, 2.0m, 1.1m, 1.40m, 100)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnOpenUsingOpenPriceWithDailySubscription(int quantity) { Func<DateTime, decimal, TradeBar> getTradeBar = (t, o) => new TradeBar(t.RoundDown(Time.OneDay), Symbols.SPY, o, 2m, 0.5m, 1.33m, 100, Time.OneDay); var reference = new DateTime(2015, 06, 05, 12, 0, 0); // market is open var config = CreateTradeBarConfig(Symbols.SPY, Resolution.Daily); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnOpenOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(getTradeBar(time, 2m)); // Will not fill because the order was placed before the bar is closed var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // It will not fill in the next morning because needs to wait for day to close const decimal expected = 1m; time = equity.Exchange.Hours.GetNextMarketOpen(time, false); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); // Fill once the equity is updated with the day bar equity.SetMarketPrice(getTradeBar(time, expected)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnOpenUsingOpenPriceWithTickSubscription(int quantity) { var reference = new DateTime(2015, 06, 05, 9, 0, 0); // before market open var config = CreateTickConfig(Symbols.SPY); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnOpenOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); var saleCondition = "04000001"; equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, saleCondition, "P", 100, 1m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // market opens after 30min, so this is just before market open time = reference.AddMinutes(29); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, saleCondition, "P", 100, 1m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); const decimal expected = 1m; // market opens after 30min time = reference.AddMinutes(30); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); // The quote is received after the market is open, but the trade is not equity.Update(new List<Tick> { new Tick(time.AddMinutes(-1), Symbols.SPY, saleCondition, "P", 100, expected), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); // The trade is received after the market is open, but it is not have a official open flag equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "", "P", 100, expected), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual("No trade with the OfficialOpen or OpeningPrints flag within the 1-minute timeout.", fill.Message); // One quote and some trades with different conditions are received after the market is open, // but there is trade prior to that with different price equity.Update(new List<Tick> { new Tick(time.AddMinutes(-1), Symbols.SPY, "80000001", "P", 100, 0.9m), // Not Open new Tick(time, Symbols.SPY, saleCondition, "Q", 100, 0.95m), // Open but not primary exchange new Tick(time, Symbols.SPY, saleCondition, "P", 100, expected), // Fill with this tick new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.95m), // Open but not primary exchange }, typeof(Tick)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); } [TestCase(-100, 0.9)] [TestCase(100, 1.1)] public void PerformsMarketOnOpenUsingOpenPriceWithTickSubscriptionButNoSalesCondition(int quantity, decimal expected) { var reference = new DateTime(2015, 06, 05, 9, 0, 0); // before market open var config = CreateTickConfig(Symbols.SPY); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnOpenOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); // No Sales Condition var saleCondition = ""; equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 1m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); const decimal price = 1m; // market opens after 30min. 1 minute after open to accept the last trade time = reference.AddMinutes(32); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.9m), // Not Close new Tick(time, Symbols.SPY, saleCondition, "P", 100, 0.95m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.95m), // Open but not primary exchange new Tick(time, Symbols.SPY, saleCondition, "Q", 100, price), // Fill with this tick }, typeof(Tick)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(price, fill.FillPrice); // Test whether it fills on the bid/ask if there is no trade equity.Cache.Reset(); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), }, typeof(Tick)); fill = model.MarketOnOpenFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); Assert.IsTrue(fill.Message.Contains("Fill with last Quote data.", StringComparison.InvariantCulture)); } [TestCase(Resolution.Minute, 3, 17, 0, 9, 29)] [TestCase(Resolution.Minute, 4, 0, 0, 9, 29)] [TestCase(Resolution.Minute, 4, 8, 0, 9, 29)] [TestCase(Resolution.Minute, 4, 9, 30, 9, 29, true)] [TestCase(Resolution.Minute, 4, 9, 30, 9, 31, true)] [TestCase(Resolution.Hour, 3, 17, 0, 8, 29)] [TestCase(Resolution.Hour, 4, 0, 0, 8, 0)] [TestCase(Resolution.Hour, 4, 8, 0, 8, 0)] [TestCase(Resolution.Hour, 4, 9, 30, 8, 0, true)] [TestCase(Resolution.Hour, 4, 9, 30, 11, 0, true)] [TestCase(Resolution.Daily, 3, 17, 0, 8, 0)] [TestCase(Resolution.Daily, 4, 0, 0, 8, 0)] [TestCase(Resolution.Daily, 4, 8, 0, 8, 0)] [TestCase(Resolution.Daily, 4, 9, 30, 8, 0)] public void PerformsMarketOnOpenUsingOpenPriceWithDifferentOrderSubmissionDateTime(Resolution resolution, int day, int hour, int minute, int ref_hour, int ref_minute, bool nextDay = false) { var period = resolution.ToTimeSpan(); var configTradeBar = CreateTradeBarConfig(Symbols.SPY, resolution); var equity = CreateEquity(configTradeBar); var model = (EquityFillModel)equity.FillModel; var orderTime = new DateTime(2015, 6, day, hour, minute, 0).ConvertToUtc(TimeZones.NewYork); var order = new MarketOnOpenOrder(Symbols.SPY, 100, orderTime); var reference = new DateTime(2015, 6, 4, ref_hour, ref_minute, 0).RoundDown(period); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time, Symbols.SPY, 1m, 2m, 0.5m, 1.33m, 100, period)); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var fill = model.Fill(new FillModelParameters( equity, order, configProvider, Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); const decimal expected = 1.45m; var tradeBar = new TradeBar(reference.Add(period), Symbols.SPY, expected, 2.75m, 1.15m, 1.45m, 100, period); equity.SetMarketPrice(tradeBar); TimeKeeper.SetUtcDateTime(tradeBar.EndTime.ConvertToUtc(TimeZones.NewYork)); fill = model.MarketOnOpenFill(equity, order); // Special case when the order exactly when the market opens. // Should only fill on the next day if (nextDay) { Assert.AreEqual(0, fill.FillQuantity); return; } Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnCloseUsingClosingPriceWithDailySubscription(int quantity) { Func<DateTime, decimal, TradeBar> getTradeBar = (t, c) => new TradeBar(t.RoundDown(Time.OneDay * 2), Symbols.SPY, 1.33m, 2m, 0.5m, c, 100, Time.OneDay); var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close var config = CreateTradeBarConfig(Symbols.SPY, Resolution.Daily); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnCloseOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(getTradeBar(time, 2m)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // market closes after 60min, so this is just before market Close time = reference.AddMinutes(59); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(getTradeBar(time, 1.45m)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); // market closes const decimal expected = 1.40m; time = reference.AddMinutes(60); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(getTradeBar(time, expected)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnCloseUsingClosingPriceWithMinuteTradeBarSubscription(int quantity) { var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close var config = CreateTradeBarConfig(Symbols.SPY); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnCloseOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time - config.Increment, Symbols.SPY, 1m, 2m, 0.5m, 1.33m, 100, config.Increment)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // market closes after 60min, so this is just before market Close time = reference.AddMinutes(59); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time - config.Increment, Symbols.SPY, 1.33m, 2.75m, 1.15m, 1.45m, 100, config.Increment)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); // market closes time = reference.AddMinutes(60); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time - config.Increment, Symbols.SPY, 1.45m, 2.0m, 1.1m, 1.40m, 100, config.Increment)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(equity.Close, fill.FillPrice); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnCloseUsingClosingPriceWithMinuteQuoteBarSubscription(int quantity) { var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close var config = CreateQuoteBarConfig(Symbols.SPY); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnCloseOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new QuoteBar(time, Symbols.SPY, new Bar(1.45m, 1.99m, 1.09m, 1.39m), 100, new Bar(1.46m, 2.01m, 1.11m, 1.41m), 100, config.Increment)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // market closes after 60min, so this is just before market Close time = reference.AddMinutes(59); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new QuoteBar(time - config.Increment, Symbols.SPY, new Bar(1.45m, 1.99m, 1.09m, 1.39m), 100, new Bar(1.46m, 2.01m, 1.11m, 1.41m), 100, config.Increment)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); const decimal expected = 1.4m; // market closes time = reference.AddMinutes(60); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.SetMarketPrice(new TradeBar(time - config.Increment, Symbols.SPY, 1.45m, 2.0m, 1.1m, 1.40m, 100, config.Increment)); equity.SetMarketPrice(new QuoteBar(time, Symbols.SPY, new Bar(1.45m, 1.99m, 1.09m, expected), 100, new Bar(1.46m, 2.01m, 1.11m, expected), 100, config.Increment)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); Assert.IsTrue(fill.Message.StartsWith("Warning: No trade information available", StringComparison.InvariantCulture)); } [TestCase(-100, true)] [TestCase(100, true)] [TestCase(-100, false)] [TestCase(100, false)] public void PerformsMarketOnCloseUsingClosingPriceWithTickSubscription(int quantity, bool extendedHours) { var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close var config = CreateTickConfig(Symbols.SPY, extendedHours: extendedHours); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnCloseOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); // Official Close var saleCondition = "1000001"; equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 1m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); // market closes after 60min, so this is just before market Close time = reference.AddMinutes(59); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { // It should fill with this tick based on sales condition but the market is still open new Tick(time, Symbols.SPY, saleCondition, "P", 100, 1) }, typeof(Tick)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); const decimal expected = 1m; // market closes time = reference.AddMinutes(60); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.9m), // Not Close new Tick(time, Symbols.SPY, "80000001", "Q", 100, 0.95m), // Close but not primary exchange new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.98m), // Fill with this tick new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), new Tick(time, Symbols.SPY, "80000001", "P", 100, expected), // Fill with this tick is no extended hours }, typeof(Tick)); // If the subscriptions doesn't include extended hours, fills with the last tick if (!extendedHours) { fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); Assert.AreEqual("No trade with the OfficialClose or ClosingPrints flag for data that does not include extended market hours. Fill with last Trade data.", fill.Message); return; } Assert.AreEqual(0, fill.FillQuantity); // market closes time = reference.AddMinutes(60).AddMilliseconds(100); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.9m), // Not Close new Tick(time, Symbols.SPY, saleCondition, "Q", 100, 0.95m), // Close but not primary exchange new Tick(time, Symbols.SPY, saleCondition, "P", 100, expected), // Fill with this tick new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.95m), // Open but not primary exchange }, typeof(Tick)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); } [TestCase(-100)] [TestCase(100)] public void PerformsMarketOnCloseUsingClosingPriceWithTickSubscriptionButNoSalesCondition(int quantity) { var reference = new DateTime(2015, 06, 05, 15, 0, 0); // before market close var config = CreateTickConfig(Symbols.SPY); var equity = CreateEquity(config); var model = (EquityFillModel)equity.FillModel; var order = new MarketOnCloseOrder(Symbols.SPY, quantity, reference); var time = reference; TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); // No Sales Condition var saleCondition = ""; equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 1m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m) }, typeof(Tick)); var fill = model.Fill(new FillModelParameters( equity, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); const decimal expected = 1m; // market closes time = reference.AddMinutes(60).AddMilliseconds(100); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.9m), // Not Close new Tick(time, Symbols.SPY, saleCondition, "Q", 100, 0.95m), // Close but not primary exchange new Tick(time, Symbols.SPY, saleCondition, "P", 100, expected), // Fill with this tick new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.95m), // Open but not primary exchange }, typeof(Tick)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual("No trade with the OfficialClose or ClosingPrints flag within the 1-minute timeout.", fill.Message); // 2 minutes after the close time = reference.AddMinutes(62); TimeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); equity.Update(new List<Tick> { new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.9m), // Not Close new Tick(time, Symbols.SPY, saleCondition, "P", 100, 0.95m), new Tick(time, Symbols.SPY, 1m, 0.9m, 1.1m), new Tick(time, Symbols.SPY, "80000001", "P", 100, 0.95m), // Open but not primary exchange new Tick(time, Symbols.SPY, saleCondition, "Q", 100, expected), // Fill with this tick }, typeof(Tick)); fill = model.MarketOnCloseFill(equity, order); Assert.AreEqual(order.Quantity, fill.FillQuantity); Assert.AreEqual(expected, fill.FillPrice); Assert.IsTrue(fill.Message.Contains("Fill with last Trade data.", StringComparison.InvariantCulture)); } [TestCase(OrderDirection.Buy)] [TestCase(OrderDirection.Sell)] public void MarketOrderFillsAtBidAsk(OrderDirection direction) { var symbol = Symbol.Create("EURUSD", SecurityType.Forex, "fxcm"); var exchangeHours = SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork); var quoteCash = new Cash(Currencies.USD, 1000, 1); var symbolProperties = SymbolProperties.GetDefault(Currencies.USD); var config = new SubscriptionDataConfig(typeof(Tick), symbol, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var security = new Forex(exchangeHours, quoteCash, config, symbolProperties, ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null); var reference = DateTime.Now; var referenceUtc = reference.ConvertToUtc(TimeZones.NewYork); var timeKeeper = new TimeKeeper(referenceUtc); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var brokerageModel = new FxcmBrokerageModel(); var fillModel = brokerageModel.GetFillModel(security); const decimal bidPrice = 1.13739m; const decimal askPrice = 1.13746m; security.SetMarketPrice(new Tick(DateTime.Now, symbol, bidPrice, askPrice)); var quantity = direction == OrderDirection.Buy ? 1 : -1; var order = new MarketOrder(symbol, quantity, DateTime.Now); var fill = fillModel.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; var expected = direction == OrderDirection.Buy ? askPrice : bidPrice; Assert.AreEqual(expected, fill.FillPrice); Assert.AreEqual(0, fill.OrderFee.Value.Amount); } [Test] public void EquityFillModelUsesPriceForTicksWhenBidAskSpreadsAreNotAvailable() { var noon = new DateTime(2014, 6, 24, 12, 0, 0); var timeKeeper = new TimeKeeper(noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork }); var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); var config = new SubscriptionDataConfig(typeof(Tick), Symbols.SPY, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, noon, 101.123m)); // Add both a tradebar and a tick to the security cache // This is the case when a tick is seeded with minute data in an algorithm security.Cache.AddData(new TradeBar(DateTime.MinValue, symbol, 1.0m, 1.0m, 1.0m, 1.0m, 1.0m)); security.Cache.AddData(new Tick(config, "42525000,1000000,100,A,@,0", DateTime.MinValue)); var fillModel = new EquityFillModel(); var order = new MarketOrder(symbol, 1000, DateTime.Now); var fill = fillModel.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; // The fill model should use the tick.Price Assert.AreEqual(fill.FillPrice, 100m); Assert.AreEqual(0, fill.OrderFee.Value.Amount); } [Test] public void EquityFillModelDoesNotUseTicksWhenThereIsNoTickSubscription() { var noon = new DateTime(2014, 6, 24, 12, 0, 0); var timeKeeper = new TimeKeeper(noon.ConvertToUtc(TimeZones.NewYork), new[] { TimeZones.NewYork }); var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); // Minute subscription var config = new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new IndicatorDataPoint(Symbols.SPY, noon, 101.123m)); // This is the case when a tick is seeded with minute data in an algorithm security.Cache.AddData(new TradeBar(DateTime.MinValue, symbol, 1.0m, 1.0m, 1.0m, 1.0m, 1.0m)); security.Cache.AddData(new Tick(config, "42525000,1000000,100,A,@,0", DateTime.MinValue)); var fillModel = new EquityFillModel(); var order = new MarketOrder(symbol, 1000, DateTime.Now); var fill = fillModel.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; // The fill model should use the tick.Price Assert.AreEqual(fill.FillPrice, 1.0m); Assert.AreEqual(0, fill.OrderFee.Value.Amount); } [TestCase(100, 290.50)] [TestCase(-100, 291.50)] public void LimitOrderDoesNotFillUsingDataBeforeSubmitTime(decimal orderQuantity, decimal limitPrice) { var time = new DateTime(2018, 9, 24, 9, 30, 0); var timeKeeper = new TimeKeeper(time.ConvertToUtc(TimeZones.NewYork), TimeZones.NewYork); var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); var config = new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); time += TimeSpan.FromMinutes(1); timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); var fillForwardBar = (TradeBar)tradeBar.Clone(true); security.SetMarketPrice(fillForwardBar); var fillModel = new EquityFillModel(); var order = new LimitOrder(symbol, orderQuantity, limitPrice, time.ConvertToUtc(TimeZones.NewYork)); var fill = fillModel.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); time += TimeSpan.FromMinutes(1); timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); fill = fillModel.LimitFill(security, order); Assert.AreEqual(orderQuantity, fill.FillQuantity); Assert.AreEqual(limitPrice, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); Assert.AreEqual(0, fill.OrderFee.Value.Amount); } [TestCase(100, 291.50)] [TestCase(-100, 290.50)] public void StopMarketOrderDoesNotFillUsingDataBeforeSubmitTime(decimal orderQuantity, decimal stopPrice) { var time = new DateTime(2018, 9, 24, 9, 30, 0); var timeKeeper = new TimeKeeper(time.ConvertToUtc(TimeZones.NewYork), TimeZones.NewYork); var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); var config = new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); time += TimeSpan.FromMinutes(1); timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); var fillForwardBar = (TradeBar)tradeBar.Clone(true); security.SetMarketPrice(fillForwardBar); var fillModel = new EquityFillModel(); var order = new StopMarketOrder(symbol, orderQuantity, stopPrice, time.ConvertToUtc(TimeZones.NewYork)); var fill = fillModel.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); time += TimeSpan.FromMinutes(1); timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); fill = fillModel.StopMarketFill(security, order); Assert.AreEqual(orderQuantity, fill.FillQuantity); Assert.AreEqual(stopPrice, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); Assert.AreEqual(0, fill.OrderFee.Value.Amount); } [TestCase(100, 291.50, 291.75)] [TestCase(-100, 290.50, 290.25)] public void StopLimitOrderDoesNotFillUsingDataBeforeSubmitTime(decimal orderQuantity, decimal stopPrice, decimal limitPrice) { var time = new DateTime(2018, 9, 24, 9, 30, 0); var timeKeeper = new TimeKeeper(time.ConvertToUtc(TimeZones.NewYork), TimeZones.NewYork); var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); var config = new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); time += TimeSpan.FromMinutes(1); timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); var fillForwardBar = (TradeBar)tradeBar.Clone(true); security.SetMarketPrice(fillForwardBar); var fillModel = new EquityFillModel(); var order = new StopLimitOrder(symbol, orderQuantity, stopPrice, limitPrice, time.ConvertToUtc(TimeZones.NewYork)); var fill = fillModel.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.AreEqual(0, fill.FillQuantity); Assert.AreEqual(0, fill.FillPrice); Assert.AreEqual(OrderStatus.None, fill.Status); time += TimeSpan.FromMinutes(1); timeKeeper.SetUtcDateTime(time.ConvertToUtc(TimeZones.NewYork)); tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); fill = fillModel.StopLimitFill(security, order); Assert.AreEqual(orderQuantity, fill.FillQuantity); Assert.AreEqual(limitPrice, fill.FillPrice); Assert.AreEqual(OrderStatus.Filled, fill.Status); Assert.AreEqual(0, fill.OrderFee.Value.Amount); } [Test] public void MarketOrderFillWithStalePriceHasWarningMessage() { var model = new EquityFillModel(); var order = new MarketOrder(Symbols.SPY, -100, Noon.ConvertToUtc(TimeZones.NewYork).AddMinutes(61)); var config = CreateTickConfig(Symbols.SPY); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); security.SetMarketPrice(new Tick(Noon, Symbols.SPY, 101.123m, 101.456m)); var fill = model.Fill(new FillModelParameters( security, order, new MockSubscriptionDataConfigProvider(config), Time.OneHour)).OrderEvent; Assert.IsTrue(fill.Message.Contains("Warning: fill at stale price")); } [TestCase(OrderDirection.Sell, 11)] [TestCase(OrderDirection.Buy, 21)] // uses the trade bar last close [TestCase(OrderDirection.Hold, 291)] public void PriceReturnsQuoteBarsIfPresent(OrderDirection orderDirection, decimal expected) { var time = new DateTime(2018, 9, 24, 9, 30, 0); var timeKeeper = new TimeKeeper(time.ConvertToUtc(TimeZones.NewYork), TimeZones.NewYork); var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA); var configTradeBar = new SubscriptionDataConfig(typeof(TradeBar), symbol, Resolution.Minute, TimeZones.NewYork, TimeZones.NewYork, true, true, false); var configQuoteBar = new SubscriptionDataConfig(configTradeBar, typeof(QuoteBar)); var security = new Security( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), configQuoteBar, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, new SecurityCache() ); security.SetLocalTimeKeeper(timeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); var tradeBar = new TradeBar(time, symbol, 290m, 292m, 289m, 291m, 12345); security.SetMarketPrice(tradeBar); var quoteBar = new QuoteBar(time, symbol, new Bar(10, 15, 5, 11), 100, new Bar(20, 25, 15, 21), 100); security.SetMarketPrice(quoteBar); var configProvider = new MockSubscriptionDataConfigProvider(configQuoteBar); configProvider.SubscriptionDataConfigs.Add(configTradeBar); var testFillModel = new TestFillModel(); testFillModel.SetParameters(new FillModelParameters(security, null, configProvider, TimeSpan.FromDays(1))); var result = testFillModel.GetPricesPublic(security, orderDirection); Assert.AreEqual(expected, result.Close); } private Equity CreateEquity(SubscriptionDataConfig config) { var equity = new Equity( SecurityExchangeHoursTests.CreateUsEquitySecurityExchangeHours(), config, new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null, Exchange.ARCA ); equity.SetLocalTimeKeeper(TimeKeeper.GetLocalTimeKeeper(TimeZones.NewYork)); return equity; } private SubscriptionDataConfig CreateTickConfig(Symbol symbol, bool extendedHours = true) { return new SubscriptionDataConfig(typeof(Tick), symbol, Resolution.Tick, TimeZones.NewYork, TimeZones.NewYork, true, extendedHours, false); } private SubscriptionDataConfig CreateQuoteBarConfig(Symbol symbol, Resolution resolution = Resolution.Minute, bool extendedHours = true) { return new SubscriptionDataConfig(typeof(QuoteBar), symbol, resolution, TimeZones.NewYork, TimeZones.NewYork, true, extendedHours, false); } private SubscriptionDataConfig CreateTradeBarConfig(Symbol symbol, Resolution resolution = Resolution.Minute, bool extendedHours = true) { return new SubscriptionDataConfig(typeof(TradeBar), symbol, resolution, TimeZones.NewYork, TimeZones.NewYork, true, extendedHours, false); } private class TestFillModel : EquityFillModel { public void SetParameters(FillModelParameters parameters) { Parameters = parameters; } public Prices GetPricesPublic(Security asset, OrderDirection direction) { return base.GetPrices(asset, direction); } } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. */ using System; using fyiReporting.RDL; using System.IO; using System.Collections; using System.Text; namespace fyiReporting.RDL { ///<summary> ///The primary class to "run" a report to XML ///</summary> internal class RenderCsv : IPresent { Report report; // report DelimitedTextWriter tw; // where the output is going public RenderCsv(Report report, IStreamGen sg) { this.report = report; tw = new DelimitedTextWriter(sg.GetTextWriter(), ","); } public void Dispose() { } public Report Report() { return report; } public bool IsPagingNeeded() { return false; } public void Start() { } public void End() { } public void RunPages(Pages pgs) { } public void BodyStart(Body b) { } public void BodyEnd(Body b) { } public void PageHeaderStart(PageHeader ph) { } public void PageHeaderEnd(PageHeader ph) { if (ph.PrintOnFirstPage||ph.PrintOnLastPage) {tw.WriteLine();} } public void PageFooterStart(PageFooter pf) { } public void PageFooterEnd(PageFooter pf) { if (pf.PrintOnLastPage || pf.PrintOnFirstPage) {tw.WriteLine();} } public void Textbox(Textbox tb, string t, Row r) { object value = tb.Evaluate(report, r); tw.Write(value); } public void DataRegionNoRows(DataRegion d, string noRowsMsg) { } public bool ListStart(List l, Row r) { return true; } public void ListEnd(List l, Row r) { tw.WriteLine(); } public void ListEntryBegin(List l, Row r) { } public void ListEntryEnd(List l, Row r) { tw.WriteLine(); } public bool TableStart(Table t, Row r) { return true; } public void TableEnd(Table t, Row r) { } public void TableBodyStart(Table t, Row r) { } public void TableBodyEnd(Table t, Row r) { } public void TableFooterStart(Footer f, Row r) { } public void TableFooterEnd(Footer f, Row r) { } public void TableHeaderStart(Header h, Row r) { } public void TableHeaderEnd(Header h, Row r) { } public void TableRowStart(TableRow tr, Row r) { } public void TableRowEnd(TableRow tr, Row r) { tw.WriteLine(); } public void TableCellStart(TableCell t, Row r) { } public void TableCellEnd(TableCell t, Row r) { } public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) { return true; } public void MatrixColumns(Matrix m, MatrixColumns mc) { } public void MatrixRowStart(Matrix m, int row, Row r) { } public void MatrixRowEnd(Matrix m, int row, Row r) { tw.WriteLine(); } public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan) { } public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r) { } public void MatrixEnd(Matrix m, Row r) { } public void Chart(Chart c, Row r, ChartBase cb) { } public void Image(Image i, Row r, string mimeType, Stream io) { } public void Line(Line l, Row r) { } public bool RectangleStart(Rectangle rect, Row r) { return true; } public void RectangleEnd(Rectangle rect, Row r) { } public void Subreport(Subreport s, Row r) { } public void GroupingStart(Grouping g) { } public void GroupingInstanceStart(Grouping g) { } public void GroupingInstanceEnd(Grouping g) { } public void GroupingEnd(Grouping g) { } } }
// 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. /*============================================================ ** ** ** ** Purpose: This class will encapsulate a long and provide an ** Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct Int64 : IComparable, IFormattable, IComparable<Int64>, IEquatable<Int64>, IConvertible { internal long m_value; public const long MaxValue = 0x7fffffffffffffffL; public const long MinValue = unchecked((long)0x8000000000000000L); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int64, this method throws an ArgumentException. // int IComparable.CompareTo(Object value) { if (value == null) { return 1; } if (value is Int64) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. long i = (long)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeInt64); } public int CompareTo(Int64 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is Int64)) { return false; } return m_value == ((Int64)obj).m_value; } [NonVersionable] public bool Equals(Int64 obj) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32)); } [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatInt64(m_value, null, null); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatInt64(m_value, null, provider); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatInt64(m_value, format, null); } [System.Security.SecuritySafeCritical] // auto-generated public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatInt64(m_value, format, provider); } public static long Parse(String s) { return FormatProvider.ParseInt64(s, NumberStyles.Integer, null); } public static long Parse(String s, NumberStyles style) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.ParseInt64(s, style, null); } public static long Parse(String s, IFormatProvider provider) { return FormatProvider.ParseInt64(s, NumberStyles.Integer, provider); } // Parses a long from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // public static long Parse(String s, NumberStyles style, IFormatProvider provider) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.ParseInt64(s, style, provider); } public static Boolean TryParse(String s, out Int64 result) { return FormatProvider.TryParseInt64(s, NumberStyles.Integer, null, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.TryParseInt64(s, style, provider, out result); } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.Int64; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return m_value; } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Int64", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// 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.AcceptanceTestsAzureSpecials { using Fixtures.Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApiVersionDefaultOperations operations. /// </summary> internal partial class ApiVersionDefaultOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IApiVersionDefaultOperations { /// <summary> /// Initializes a new instance of the ApiVersionDefaultOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApiVersionDefaultOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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, "GetMethodGlobalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetMethodGlobalNotProvidedValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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, "GetMethodGlobalNotProvidedValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetPathGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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, "GetPathGlobalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// GET method with api-version modeled in global settings. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetSwaggerGlobalValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // 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, "GetSwaggerGlobalValid", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using Runtime = Alachisoft.NCache.Runtime; namespace Alachisoft.NCache.Common { //This class is to serve as the basis for live upgrades and cross version communication in future /// <summary> /// Returns the version of the NCache running on a particular Node. /// This returns a single instance per installation /// </summary> public class ProductVersion: IComparable, Runtime.Serialization.ICompactSerializable { #region members private byte _majorVersion1=0; private byte _majorVersion2=0; private byte _minorVersion1=0; private byte _minorVersion2=0; private string _productName= string.Empty;//JvCache,NCache private int _editionID=-1; private static volatile ProductVersion _productInfo; private static object _syncRoot = new object(); // this object is to serve as locking instance to avoid deadlocks private byte[] _additionalData; #endregion #region Properties /// <summary> /// Gets the productInfo /// </summary> public static ProductVersion ProductInfo { //Double check locking approach is used because of the multi-threaded nature of NCache get { if (_productInfo == null) { lock (_syncRoot) { if (_productInfo == null) { _productInfo = new ProductVersion(); _productInfo._editionID = 34; _productInfo._majorVersion1 = 4; _productInfo._majorVersion2 = 3; _productInfo._minorVersion1 = 0; _productInfo._minorVersion2 = 0; _productInfo._productName = "NCACHE"; _productInfo._additionalData = new byte[0]; } } } return _productInfo; } } /// <summary> /// Gets/Sets the Product Name(JvCache/NCache) /// </summary> public string ProductName { get { return _productName; } private set { _productName = value; } } /// <summary> /// Get/Sets the editionID of the product /// </summary> public int EditionID { get { return _editionID; } private set { _editionID = value; } } /// <summary> /// Get/Set the edditional data that needs /// to be send. /// </summary> public byte[] AdditionalData { get { return _additionalData; } private set { _additionalData = value; } } /// <summary> /// Get/Set the second minor version of the API /// </summary> public byte MinorVersion2 { get { return _minorVersion2; } private set { _minorVersion2 = value; } } /// <summary> /// Get/Set the first minor version of the API /// </summary> public byte MinorVersion1 { get { return _minorVersion1; } private set { _minorVersion1 = value; } } /// <summary> /// Get/Set the second major version of the API /// </summary> public byte MajorVersion2 { get { return _majorVersion2; } private set { _majorVersion2 = value; } } /// <summary> /// Get/Set the first major version of the API /// </summary> public byte MajorVersion1 { get { return _majorVersion1; } private set { _majorVersion1 = value; } } #endregion #region methods /// <summary> /// /// </summary> public ProductVersion() { } /// <summary> /// compares editionIDs to ensure whether the version is correct or not /// </summary> /// <param name="id"></param> /// <returns> /// true: Incase of same edition /// False: Incase of incorrect edition /// </returns> public bool IsValidVersion(int editionID) { if (this.EditionID == editionID) return true; else return false; } #endregion #region ICompact Serializable Members public void Deserialize(Runtime.Serialization.IO.CompactReader reader) { _majorVersion1 = reader.ReadByte(); _majorVersion2 = reader.ReadByte(); _minorVersion1 = reader.ReadByte(); _minorVersion2 = reader.ReadByte(); _productName =(string) reader.ReadObject(); _editionID = reader.ReadInt32(); int temp = reader.ReadInt32(); _additionalData = reader.ReadBytes(temp); } public void Serialize(Runtime.Serialization.IO.CompactWriter writer) { writer.Write(_majorVersion1); writer.Write(_majorVersion2); writer.Write(_minorVersion1); writer.Write(_minorVersion2); writer.WriteObject(_productName); writer.Write(_editionID); writer.Write(_additionalData.Length);// to know the lengt5h of the additional data to be followed; used when deserializing writer.Write(_additionalData); } #endregion #region IComparable Members public int CompareTo(object obj) { int result = -1; if (obj != null && obj is ProductVersion) { ProductVersion other = (ProductVersion)obj; if (_editionID == other.EditionID) { if (_majorVersion1 == other.MajorVersion1) { if (_majorVersion2 == other.MajorVersion2) { if (_minorVersion1 == other.MinorVersion1) { if (_minorVersion2 == other._minorVersion2) { result = 0; } else if (_minorVersion2 < other.MinorVersion2) result = -1; else result = 1; } else if (_minorVersion1 < other.MinorVersion1) result = -1; else result = 1; } else if (_majorVersion2 < other.MajorVersion2) result = -1; else result = 1; } else if (_majorVersion1 < other.MajorVersion1) result = -1; else result = 1; } else result = -1; // Suggestion- Incase of invalid type an exception should be thrown!! } return result; } #endregion } }
// 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; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private abstract partial class CSharpCodeGenerator : CodeGenerator<StatementSyntax, ExpressionSyntax, SyntaxNode> { private SyntaxToken _methodName; public static Task<GeneratedCode> GenerateAsync( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult, CancellationToken cancellationToken) { var codeGenerator = Create(insertionPoint, selectionResult, analyzerResult); return codeGenerator.GenerateAsync(cancellationToken); } private static CSharpCodeGenerator Create( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) { if (ExpressionCodeGenerator.IsExtractMethodOnExpression(selectionResult)) { return new ExpressionCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (SingleStatementCodeGenerator.IsExtractMethodOnSingleStatement(selectionResult)) { return new SingleStatementCodeGenerator(insertionPoint, selectionResult, analyzerResult); } if (MultipleStatementsCodeGenerator.IsExtractMethodOnMultipleStatements(selectionResult)) { return new MultipleStatementsCodeGenerator(insertionPoint, selectionResult, analyzerResult); } return Contract.FailWithReturn<CSharpCodeGenerator>("Unknown selection"); } protected CSharpCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { Contract.ThrowIfFalse(this.SemanticDocument == selectionResult.SemanticDocument); var nameToken = CreateMethodName(); _methodName = nameToken.WithAdditionalAnnotations(this.MethodNameAnnotation); } private CSharpSelectionResult CSharpSelectionResult { get { return (CSharpSelectionResult)this.SelectionResult; } } protected override SyntaxNode GetPreviousMember(SemanticDocument document) { var node = this.InsertionPoint.With(document).GetContext(); return (node.Parent is GlobalStatementSyntax) ? node.Parent : node; } protected override async Task<OperationStatus<IMethodSymbol>> GenerateMethodDefinitionAsync(CancellationToken cancellationToken) { var result = await CreateMethodBodyAsync(cancellationToken).ConfigureAwait(false); var methodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: Accessibility.Private, modifiers: CreateMethodModifiers(), returnType: this.AnalyzerResult.ReturnType, returnsByRef: false, explicitInterfaceSymbol: null, name: _methodName.ToString(), typeParameters: CreateMethodTypeParameters(cancellationToken), parameters: CreateMethodParameters(), statements: result.Data); return result.With( this.MethodDefinitionAnnotation.AddAnnotationToSymbol( Formatter.Annotation.AddAnnotationToSymbol(methodSymbol))); } protected override async Task<SyntaxNode> GenerateBodyForCallSiteContainerAsync(CancellationToken cancellationToken) { var container = this.GetOutermostCallSiteContainerToProcess(cancellationToken); var variableMapToRemove = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveIntoMethodDefinition(cancellationToken), cancellationToken); var firstStatementToRemove = GetFirstStatementOrInitializerSelectedAtCallSite(); var lastStatementToRemove = GetLastStatementOrInitializerSelectedAtCallSite(); Contract.ThrowIfFalse(firstStatementToRemove.Parent == lastStatementToRemove.Parent); var statementsToInsert = await CreateStatementsOrInitializerToInsertAtCallSiteAsync(cancellationToken).ConfigureAwait(false); var callSiteGenerator = new CallSiteContainerRewriter( container, variableMapToRemove, firstStatementToRemove, lastStatementToRemove, statementsToInsert); return container.CopyAnnotationsTo(callSiteGenerator.Generate()).WithAdditionalAnnotations(Formatter.Annotation); } private async Task<IEnumerable<SyntaxNode>> CreateStatementsOrInitializerToInsertAtCallSiteAsync(CancellationToken cancellationToken) { var selectedNode = this.GetFirstStatementOrInitializerSelectedAtCallSite(); // field initializer, constructor initializer, expression bodied member case if (selectedNode is ConstructorInitializerSyntax || selectedNode is FieldDeclarationSyntax || IsExpressionBodiedMember(selectedNode) || IsExpressionBodiedAccessor(selectedNode)) { var statement = await GetStatementOrInitializerContainingInvocationToExtractedMethodAsync(this.CallSiteAnnotation, cancellationToken).ConfigureAwait(false); return SpecializedCollections.SingletonEnumerable(statement); } // regular case var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var statements = SpecializedCollections.EmptyEnumerable<StatementSyntax>(); statements = await AddSplitOrMoveDeclarationOutStatementsToCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = postProcessor.MergeDeclarationStatements(statements); statements = await AddAssignmentStatementToCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = await AddInvocationAtCallSiteAsync(statements, cancellationToken).ConfigureAwait(false); statements = AddReturnIfUnreachable(statements, cancellationToken); return statements; } private bool IsExpressionBodiedMember(SyntaxNode node) => node is MemberDeclarationSyntax member && member.GetExpressionBody() != null; private bool IsExpressionBodiedAccessor(SyntaxNode node) => node is AccessorDeclarationSyntax accessor && accessor.ExpressionBody != null; private SimpleNameSyntax CreateMethodNameForInvocation() { return this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0 ? (SimpleNameSyntax)SyntaxFactory.IdentifierName(_methodName) : SyntaxFactory.GenericName(_methodName, SyntaxFactory.TypeArgumentList(CreateMethodCallTypeVariables())); } private SeparatedSyntaxList<TypeSyntax> CreateMethodCallTypeVariables() { Contract.ThrowIfTrue(this.AnalyzerResult.MethodTypeParametersInDeclaration.Count == 0); // propagate any type variable used in extracted code var typeVariables = new List<TypeSyntax>(); foreach (var methodTypeParameter in this.AnalyzerResult.MethodTypeParametersInDeclaration) { typeVariables.Add(SyntaxFactory.ParseTypeName(methodTypeParameter.Name)); } return SyntaxFactory.SeparatedList(typeVariables); } protected SyntaxNode GetCallSiteContainerFromOutermostMoveInVariable(CancellationToken cancellationToken) { var outmostVariable = GetOutermostVariableToMoveIntoMethodDefinition(cancellationToken); if (outmostVariable == null) { return null; } var idToken = outmostVariable.GetIdentifierTokenAtDeclaration(this.SemanticDocument); var declStatement = idToken.GetAncestor<LocalDeclarationStatementSyntax>(); Contract.ThrowIfNull(declStatement); Contract.ThrowIfFalse(declStatement.Parent.IsStatementContainerNode()); return declStatement.Parent; } private DeclarationModifiers CreateMethodModifiers() { var isUnsafe = this.CSharpSelectionResult.ShouldPutUnsafeModifier(); var isAsync = this.CSharpSelectionResult.ShouldPutAsyncModifier(); return new DeclarationModifiers( isUnsafe: isUnsafe, isAsync: isAsync, isStatic: !this.AnalyzerResult.UseInstanceMember); } private static SyntaxKind GetParameterRefSyntaxKind(ParameterBehavior parameterBehavior) { return parameterBehavior == ParameterBehavior.Ref ? SyntaxKind.RefKeyword : parameterBehavior == ParameterBehavior.Out ? SyntaxKind.OutKeyword : SyntaxKind.None; } private async Task<OperationStatus<ImmutableArray<SyntaxNode>>> CreateMethodBodyAsync(CancellationToken cancellationToken) { var statements = GetInitialStatementsForMethodDefinitions(); statements = await SplitOrMoveDeclarationIntoMethodDefinitionAsync(statements, cancellationToken).ConfigureAwait(false); statements = MoveDeclarationOutFromMethodDefinition(statements, cancellationToken); statements = AppendReturnStatementIfNeeded(statements); statements = CleanupCode(statements); // set output so that we can use it in negative preview var wrapped = WrapInCheckStatementIfNeeded(statements); return CheckActiveStatements(statements).With(wrapped.ToImmutableArray<SyntaxNode>()); } private IEnumerable<StatementSyntax> WrapInCheckStatementIfNeeded(IEnumerable<StatementSyntax> statements) { var kind = this.CSharpSelectionResult.UnderCheckedStatementContext(); if (kind == SyntaxKind.None) { return statements; } if (statements.Skip(1).Any()) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } var block = statements.Single() as BlockSyntax; if (block != null) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, block)); } return SpecializedCollections.SingletonEnumerable<StatementSyntax>(SyntaxFactory.CheckedStatement(kind, SyntaxFactory.Block(statements))); } private IEnumerable<StatementSyntax> CleanupCode(IEnumerable<StatementSyntax> statements) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); statements = postProcessor.RemoveRedundantBlock(statements); statements = postProcessor.RemoveDeclarationAssignmentPattern(statements); statements = postProcessor.RemoveInitializedDeclarationAndReturnPattern(statements); return statements; } private OperationStatus CheckActiveStatements(IEnumerable<StatementSyntax> statements) { var count = statements.Count(); if (count == 0) { return OperationStatus.NoActiveStatement; } if (count == 1) { var returnStatement = statements.Single() as ReturnStatementSyntax; if (returnStatement != null && returnStatement.Expression == null) { return OperationStatus.NoActiveStatement; } } foreach (var statement in statements) { var declStatement = statement as LocalDeclarationStatementSyntax; if (declStatement == null) { // found one return OperationStatus.Succeeded; } foreach (var variable in declStatement.Declaration.Variables) { if (variable.Initializer != null) { // found one return OperationStatus.Succeeded; } } } return OperationStatus.NoActiveStatement; } private IEnumerable<StatementSyntax> MoveDeclarationOutFromMethodDefinition( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var variableToRemoveMap = CreateVariableDeclarationToRemoveMap( this.AnalyzerResult.GetVariablesToMoveOutToCallSiteOrDelete(cancellationToken), cancellationToken); statements = statements.Select(s => FixDeclarationExpressionsAndDeclarationPatterns(s, variableToRemoveMap)); foreach (var statement in statements) { var declarationStatement = statement as LocalDeclarationStatementSyntax; if (declarationStatement == null) { // if given statement is not decl statement. yield return statement; continue; } var expressionStatements = new List<StatementSyntax>(); var list = new List<VariableDeclaratorSyntax>(); var triviaList = new List<SyntaxTrivia>(); // When we modify the declaration to an initialization we have to preserve the leading trivia var firstVariableToAttachTrivia = true; // go through each var decls in decl statement, and create new assignment if // variable is initialized at decl. foreach (var variableDeclaration in declarationStatement.Declaration.Variables) { if (variableToRemoveMap.HasSyntaxAnnotation(variableDeclaration)) { if (variableDeclaration.Initializer != null) { SyntaxToken identifier = ApplyTriviaFromDeclarationToAssignmentIdentifier(declarationStatement, firstVariableToAttachTrivia, variableDeclaration); // move comments with the variable here expressionStatements.Add(CreateAssignmentExpressionStatement(identifier, variableDeclaration.Initializer.Value)); } else { // we don't remove trivia around tokens we remove triviaList.AddRange(variableDeclaration.GetLeadingTrivia()); triviaList.AddRange(variableDeclaration.GetTrailingTrivia()); } firstVariableToAttachTrivia = false; continue; } // Prepend the trivia from the declarations without initialization to the next persisting variable declaration if (triviaList.Count > 0) { list.Add(variableDeclaration.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); firstVariableToAttachTrivia = false; continue; } firstVariableToAttachTrivia = false; list.Add(variableDeclaration); } if (list.Count == 0 && triviaList.Count > 0) { // well, there are trivia associated with the node. // we can't just delete the node since then, we will lose // the trivia. unfortunately, it is not easy to attach the trivia // to next token. for now, create an empty statement and associate the // trivia to the statement // TODO : think about a way to trivia attached to next token yield return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))); triviaList.Clear(); } // return survived var decls if (list.Count > 0) { yield return SyntaxFactory.LocalDeclarationStatement( declarationStatement.Modifiers, SyntaxFactory.VariableDeclaration( declarationStatement.Declaration.Type, SyntaxFactory.SeparatedList(list)), declarationStatement.SemicolonToken.WithPrependedLeadingTrivia(triviaList)); triviaList.Clear(); } // return any expression statement if there was any foreach (var expressionStatement in expressionStatements) { yield return expressionStatement; } } } /// <summary> /// If the statement has an `out var` declaration expression for a variable which /// needs to be removed, we need to turn it into a plain `out` parameter, so that /// it doesn't declare a duplicate variable. /// If the statement has a pattern declaration (such as `3 is int i`) for a variable /// which needs to be removed, we will annotate it as a conflict, since we don't have /// a better refactoring. /// </summary> private StatementSyntax FixDeclarationExpressionsAndDeclarationPatterns(StatementSyntax statement, HashSet<SyntaxAnnotation> variablesToRemove) { var replacements = new Dictionary<SyntaxNode, SyntaxNode>(); var declarations = statement.DescendantNodes() .Where(n => n.IsKind(SyntaxKind.DeclarationExpression, SyntaxKind.DeclarationPattern)); foreach (var node in declarations) { switch (node.Kind()) { case SyntaxKind.DeclarationExpression: { var declaration = (DeclarationExpressionSyntax)node; if (declaration.Designation.Kind() != SyntaxKind.SingleVariableDesignation) { break; } var designation = (SingleVariableDesignationSyntax)declaration.Designation; var name = designation.Identifier.ValueText; if (variablesToRemove.HasSyntaxAnnotation(designation)) { var newLeadingTrivia = new SyntaxTriviaList(); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetLeadingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(declaration.Type.GetTrailingTrivia()); newLeadingTrivia = newLeadingTrivia.AddRange(designation.GetLeadingTrivia()); replacements.Add(declaration, SyntaxFactory.IdentifierName(designation.Identifier) .WithLeadingTrivia(newLeadingTrivia)); } break; } case SyntaxKind.DeclarationPattern: { var pattern = (DeclarationPatternSyntax)node; if (!variablesToRemove.HasSyntaxAnnotation(pattern)) { break; } // We don't have a good refactoring for this, so we just annotate the conflict // For instance, when a local declared by a pattern declaration (`3 is int i`) is // used outside the block we're trying to extract. var designation = pattern.Designation as SingleVariableDesignationSyntax; if (designation == null) { break; } var identifier = designation.Identifier; var annotation = ConflictAnnotation.Create(CSharpFeaturesResources.Conflict_s_detected); var newIdentifier = identifier.WithAdditionalAnnotations(annotation); var newDesignation = designation.WithIdentifier(newIdentifier); replacements.Add(pattern, pattern.WithDesignation(newDesignation)); break; } } } return statement.ReplaceNodes(replacements.Keys, (orig, partiallyReplaced) => replacements[orig]); } private static SyntaxToken ApplyTriviaFromDeclarationToAssignmentIdentifier(LocalDeclarationStatementSyntax declarationStatement, bool firstVariableToAttachTrivia, VariableDeclaratorSyntax variable) { var identifier = variable.Identifier; var typeSyntax = declarationStatement.Declaration.Type; if (firstVariableToAttachTrivia && typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia); } return identifier; } private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax) { if (typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); var identifierTrailingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } if (typeSyntax.HasTrailingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia) .WithTrailingTrivia(identifierTrailingTrivia); } return identifier; } private async Task<IEnumerable<StatementSyntax>> SplitOrMoveDeclarationIntoMethodDefinitionAsync( IEnumerable<StatementSyntax> statements, CancellationToken cancellationToken) { var semanticModel = this.SemanticDocument.SemanticModel; var context = this.InsertionPoint.GetContext(); var postProcessor = new PostProcessor(semanticModel, context.SpanStart); var declStatements = await CreateDeclarationStatementsAsync(AnalyzerResult.GetVariablesToSplitOrMoveIntoMethodDefinition(cancellationToken), cancellationToken).ConfigureAwait(false); declStatements = postProcessor.MergeDeclarationStatements(declStatements); return declStatements.Concat(statements); } private ExpressionSyntax CreateAssignmentExpression(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.AssignmentExpression( SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(identifier), rvalue); } protected override bool LastStatementOrHasReturnStatementInReturnableConstruct() { var lastStatement = this.GetLastStatementOrInitializerSelectedAtCallSite(); var container = lastStatement.GetAncestorsOrThis<SyntaxNode>().FirstOrDefault(n => n.IsReturnableConstruct()); if (container == null) { // case such as field initializer return false; } var blockBody = container.GetBlockBody(); if (blockBody == null) { // such as expression lambda. there is no statement return false; } // check whether it is last statement except return statement var statements = blockBody.Statements; if (statements.Last() == lastStatement) { return true; } var index = statements.IndexOf((StatementSyntax)lastStatement); return statements[index + 1].Kind() == SyntaxKind.ReturnStatement; } protected override SyntaxToken CreateIdentifier(string name) { return SyntaxFactory.Identifier(name); } protected override StatementSyntax CreateReturnStatement(string identifierName = null) { return string.IsNullOrEmpty(identifierName) ? SyntaxFactory.ReturnStatement() : SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(identifierName)); } protected override ExpressionSyntax CreateCallSignature() { var methodName = CreateMethodNameForInvocation().WithAdditionalAnnotations(Simplifier.Annotation); var arguments = new List<ArgumentSyntax>(); foreach (var argument in this.AnalyzerResult.MethodParameters) { var modifier = GetParameterRefSyntaxKind(argument.ParameterModifier); var refOrOut = modifier == SyntaxKind.None ? default(SyntaxToken) : SyntaxFactory.Token(modifier); arguments.Add(SyntaxFactory.Argument(SyntaxFactory.IdentifierName(argument.Name)).WithRefOrOutKeyword(refOrOut)); } var invocation = SyntaxFactory.InvocationExpression(methodName, SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments))); var shouldPutAsyncModifier = this.CSharpSelectionResult.ShouldPutAsyncModifier(); if (!shouldPutAsyncModifier) { return invocation; } return SyntaxFactory.AwaitExpression(invocation); } protected override StatementSyntax CreateAssignmentExpressionStatement(SyntaxToken identifier, ExpressionSyntax rvalue) { return SyntaxFactory.ExpressionStatement(CreateAssignmentExpression(identifier, rvalue)); } protected override async Task<StatementSyntax> CreateDeclarationStatementAsync( VariableInfo variable, ExpressionSyntax initialValue, CancellationToken cancellationToken) { // Convert to 'var' if appropriate. Note: because we're extracting out // to a method, the initialValue will be a method-call. Types are not // apperant with method calls (i.e. as opposed to a 'new XXX()' expression, // where the type is apperant). var options = await SemanticDocument.Document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var type = variable.GetVariableType(this.SemanticDocument); var typeNode = initialValue == null ? type.GenerateTypeSyntax() : type.GenerateTypeSyntaxOrVar(options, typeIsApparent: false); var equalsValueClause = initialValue == null ? null : SyntaxFactory.EqualsValueClause(value: initialValue); return SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration(typeNode) .AddVariables(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(variable.Name)).WithInitializer(equalsValueClause))); } protected override async Task<GeneratedCode> CreateGeneratedCodeAsync(OperationStatus status, SemanticDocument newDocument, CancellationToken cancellationToken) { if (status.Succeeded()) { // in hybrid code cases such as extract method, formatter will have some difficulties on where it breaks lines in two. // here, we explicitly insert newline at the end of "{" of auto generated method decl so that anchor knows how to find out // indentation of inserted statements (from users code) with user code style preserved var root = newDocument.Root; var methodDefinition = root.GetAnnotatedNodes<MethodDeclarationSyntax>(this.MethodDefinitionAnnotation).First(); var newMethodDefinition = TweakNewLinesInMethod(methodDefinition); newDocument = await newDocument.WithSyntaxRootAsync( root.ReplaceNode(methodDefinition, newMethodDefinition), cancellationToken).ConfigureAwait(false); } return await base.CreateGeneratedCodeAsync(status, newDocument, cancellationToken).ConfigureAwait(false); } private static MethodDeclarationSyntax TweakNewLinesInMethod(MethodDeclarationSyntax methodDefinition) { if (methodDefinition.Body != null) { return methodDefinition.ReplaceToken( methodDefinition.Body.OpenBraceToken, methodDefinition.Body.OpenBraceToken.WithAppendedTrailingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed))); } else if (methodDefinition.ExpressionBody != null) { return methodDefinition.ReplaceToken( methodDefinition.ExpressionBody.ArrowToken, methodDefinition.ExpressionBody.ArrowToken.WithPrependedLeadingTrivia( SpecializedCollections.SingletonEnumerable(SyntaxFactory.CarriageReturnLineFeed))); } else { return methodDefinition; } } protected StatementSyntax GetStatementContainingInvocationToExtractedMethodWorker() { var callSignature = CreateCallSignature(); if (this.AnalyzerResult.HasReturnType) { Contract.ThrowIfTrue(this.AnalyzerResult.HasVariableToUseAsReturnValue); return SyntaxFactory.ReturnStatement(callSignature); } return SyntaxFactory.ExpressionStatement(callSignature); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Collections; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; namespace System.Data.SqlClient { internal sealed class SqlConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class DEFAULT { internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const string AttachDBFilename = ""; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const string Current_Language = ""; internal const string Data_Source = ""; internal const bool Encrypt = false; internal const string FailoverPartner = ""; internal const string Initial_Catalog = ""; internal const bool Integrated_Security = false; internal const int Load_Balance_Timeout = 0; // default of 0 means don't use internal const bool MARS = false; internal const int Max_Pool_Size = 100; internal const int Min_Pool_Size = 0; internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; internal const int Packet_Size = 8000; internal const string Password = ""; internal const bool Persist_Security_Info = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string Type_System_Version = ""; internal const string User_ID = ""; internal const bool User_Instance = false; internal const bool Replication = false; internal const int Connect_Retry_Count = 1; internal const int Connect_Retry_Interval = 10; } // SqlConnection ConnectionString Options // keys must be lowercase! internal static class KEY { internal const string ApplicationIntent = "applicationintent"; internal const string Application_Name = "application name"; internal const string AsynchronousProcessing = "asynchronous processing"; internal const string AttachDBFilename = "attachdbfilename"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; internal const string Data_Source = "data source"; internal const string Encrypt = "encrypt"; internal const string Enlist = "enlist"; internal const string FailoverPartner = "failover partner"; internal const string Initial_Catalog = "initial catalog"; internal const string Integrated_Security = "integrated security"; internal const string Load_Balance_Timeout = "load balance timeout"; internal const string MARS = "multipleactiveresultsets"; internal const string Max_Pool_Size = "max pool size"; internal const string Min_Pool_Size = "min pool size"; internal const string MultiSubnetFailover = "multisubnetfailover"; internal const string Network_Library = "network library"; internal const string Packet_Size = "packet size"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Pooling = "pooling"; internal const string TransactionBinding = "transaction binding"; internal const string TrustServerCertificate = "trustservercertificate"; internal const string Type_System_Version = "type system version"; internal const string User_ID = "user id"; internal const string User_Instance = "user instance"; internal const string Workstation_Id = "workstation id"; internal const string Replication = "replication"; internal const string Connect_Retry_Count = "connectretrycount"; internal const string Connect_Retry_Interval = "connectretryinterval"; } // Constant for the number of duplicate options in the connection string private static class SYNONYM { // application name internal const string APP = "app"; internal const string Async = "async"; // attachDBFilename internal const string EXTENDED_PROPERTIES = "extended properties"; internal const string INITIAL_FILE_NAME = "initial file name"; // connect timeout internal const string CONNECTION_TIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; // current language internal const string LANGUAGE = "language"; // data source internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORK_ADDRESS = "network address"; // initial catalog internal const string DATABASE = "database"; // integrated security internal const string TRUSTED_CONNECTION = "trusted_connection"; // load balance timeout internal const string Connection_Lifetime = "connection lifetime"; // network library internal const string NET = "net"; internal const string NETWORK = "network"; // password internal const string Pwd = "pwd"; // persist security info internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; // user id internal const string UID = "uid"; internal const string User = "user"; // workstation id internal const string WSID = "wsid"; // make sure to update SynonymCount value below when adding or removing synonyms } internal const int SynonymCount = 18; internal const int DeprecatedSynonymCount = 3; internal enum TypeSystem { Latest = 2008, SQLServer2000 = 2000, SQLServer2005 = 2005, SQLServer2008 = 2008, SQLServer2012 = 2012, } internal static class TYPESYSTEMVERSION { internal const string Latest = "Latest"; internal const string SQL_Server_2000 = "SQL Server 2000"; internal const string SQL_Server_2005 = "SQL Server 2005"; internal const string SQL_Server_2008 = "SQL Server 2008"; internal const string SQL_Server_2012 = "SQL Server 2012"; } private static Dictionary<string, string> s_sqlClientSynonyms; private readonly bool _integratedSecurity; private readonly bool _encrypt; private readonly bool _trustServerCertificate; private readonly bool _mars; private readonly bool _persistSecurityInfo; private readonly bool _pooling; private readonly bool _replication; private readonly bool _userInstance; private readonly bool _multiSubnetFailover; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; private readonly int _minPoolSize; private readonly int _packetSize; private readonly int _connectRetryCount; private readonly int _connectRetryInterval; private readonly ApplicationIntent _applicationIntent; private readonly string _applicationName; private readonly string _attachDBFileName; private readonly string _currentLanguage; private readonly string _dataSource; private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB private readonly string _failoverPartner; private readonly string _initialCatalog; private readonly string _password; private readonly string _userID; private readonly string _workstationId; private readonly TypeSystem _typeSystemVersion; internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms()) { ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing); ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset); ThrowUnsupportedIfKeywordSet(KEY.Context_Connection); ThrowUnsupportedIfKeywordSet(KEY.Enlist); ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding); // Network Library has its own special error message if (ContainsKey(KEY.Network_Library)) { throw SQL.NetworkLibraryKeywordNotSupported(); } _integratedSecurity = ConvertValueToIntegratedSecurity(); _encrypt = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (string.IsNullOrEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount < 0) || (_connectRetryCount > 255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } } // This c-tor is used to create SSE and user instance connection strings when user instance is set to true // BUG (VSTFDevDiv) 479687: Using TransactionScope with Linq2SQL against user instances fails with "connection has been broken" message internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _encrypt = connectionOptions._encrypt; _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _workstationId = connectionOptions._workstationId; _typeSystemVersion = connectionOptions._typeSystemVersion; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); } internal bool IntegratedSecurity { get { return _integratedSecurity; } } // We always initialize in Async mode so that both synchronous and asynchronous methods // will work. In the future we can deprecate the keyword entirely. internal bool Asynchronous { get { return true; } } // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security internal bool ConnectionReset { get { return true; } } // internal bool EnableUdtDownload { get { return _enableUdtDownload;} } internal bool Encrypt { get { return _encrypt; } } internal bool TrustServerCertificate { get { return _trustServerCertificate; } } internal bool MARS { get { return _mars; } } internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } } internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } } internal bool Pooling { get { return _pooling; } } internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } internal int MinPoolSize { get { return _minPoolSize; } } internal int PacketSize { get { return _packetSize; } } internal int ConnectRetryCount { get { return _connectRetryCount; } } internal int ConnectRetryInterval { get { return _connectRetryInterval; } } internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } } internal string ApplicationName { get { return _applicationName; } } internal string AttachDBFilename { get { return _attachDBFileName; } } internal string CurrentLanguage { get { return _currentLanguage; } } internal string DataSource { get { return _dataSource; } } internal string LocalDBInstance { get { return _localDBInstance; } } internal string FailoverPartner { get { return _failoverPartner; } } internal string InitialCatalog { get { return _initialCatalog; } } internal string Password { get { return _password; } } internal string UserID { get { return _userID; } } internal string WorkstationId { get { return _workstationId; } } internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } } // This dictionary is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string. internal static Dictionary<string, string> GetParseSynonyms() { Dictionary<string, string> synonyms = s_sqlClientSynonyms; if (null == synonyms) { int count = SqlConnectionStringBuilder.KeywordsCount + SqlConnectionStringBuilder.DeprecatedKeywordsCount + SynonymCount + DeprecatedSynonymCount; synonyms = new Dictionary<string, string>(count) { { KEY.ApplicationIntent, KEY.ApplicationIntent }, { KEY.Application_Name, KEY.Application_Name }, { KEY.AsynchronousProcessing, KEY.AsynchronousProcessing }, { KEY.AttachDBFilename, KEY.AttachDBFilename }, { KEY.Connect_Timeout, KEY.Connect_Timeout }, { KEY.Connection_Reset, KEY.Connection_Reset }, { KEY.Context_Connection, KEY.Context_Connection }, { KEY.Current_Language, KEY.Current_Language }, { KEY.Data_Source, KEY.Data_Source }, { KEY.Encrypt, KEY.Encrypt }, { KEY.Enlist, KEY.Enlist }, { KEY.FailoverPartner, KEY.FailoverPartner }, { KEY.Initial_Catalog, KEY.Initial_Catalog }, { KEY.Integrated_Security, KEY.Integrated_Security }, { KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout }, { KEY.MARS, KEY.MARS }, { KEY.Max_Pool_Size, KEY.Max_Pool_Size }, { KEY.Min_Pool_Size, KEY.Min_Pool_Size }, { KEY.MultiSubnetFailover, KEY.MultiSubnetFailover }, { KEY.Network_Library, KEY.Network_Library }, { KEY.Packet_Size, KEY.Packet_Size }, { KEY.Password, KEY.Password }, { KEY.Persist_Security_Info, KEY.Persist_Security_Info }, { KEY.Pooling, KEY.Pooling }, { KEY.Replication, KEY.Replication }, { KEY.TrustServerCertificate, KEY.TrustServerCertificate }, { KEY.TransactionBinding, KEY.TransactionBinding }, { KEY.Type_System_Version, KEY.Type_System_Version }, { KEY.User_ID, KEY.User_ID }, { KEY.User_Instance, KEY.User_Instance }, { KEY.Workstation_Id, KEY.Workstation_Id }, { KEY.Connect_Retry_Count, KEY.Connect_Retry_Count }, { KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval }, { SYNONYM.APP, KEY.Application_Name }, { SYNONYM.Async, KEY.AsynchronousProcessing }, { SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename }, { SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename }, { SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout }, { SYNONYM.TIMEOUT, KEY.Connect_Timeout }, { SYNONYM.LANGUAGE, KEY.Current_Language }, { SYNONYM.ADDR, KEY.Data_Source }, { SYNONYM.ADDRESS, KEY.Data_Source }, { SYNONYM.NETWORK_ADDRESS, KEY.Data_Source }, { SYNONYM.SERVER, KEY.Data_Source }, { SYNONYM.DATABASE, KEY.Initial_Catalog }, { SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security }, { SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout }, { SYNONYM.NET, KEY.Network_Library }, { SYNONYM.NETWORK, KEY.Network_Library }, { SYNONYM.Pwd, KEY.Password }, { SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info }, { SYNONYM.UID, KEY.User_ID }, { SYNONYM.User, KEY.User_ID }, { SYNONYM.WSID, KEY.Workstation_Id } }; Debug.Assert(synonyms.Count == count, "incorrect initial ParseSynonyms size"); s_sqlClientSynonyms = synonyms; } return synonyms; } internal string ObtainWorkstationId() { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; if (null == result) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted // the information is shared with the server, but not directly with the user result = ADP.MachineName(); ValidateValueLength(result, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } return result; } private void ValidateValueLength(string value, int limit, string key) { if (limit < value.Length) { throw ADP.InvalidConnectionOptionValueLength(key, limit); } } internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent() { string value; if (!TryGetParsetableValue(KEY.ApplicationIntent, out value)) { return DEFAULT.ApplicationIntent; } // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor, // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool) try { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } // ArgumentException and other types are raised as is (no wrapping) } internal void ThrowUnsupportedIfKeywordSet(string keyword) { if (ContainsKey(keyword)) { throw SQL.UnsupportedKeyword(keyword); } } } }