context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Text; namespace NServiceKit.Common { /// <summary> /// Creates a Unified Resource Name (URN) with the following formats: /// /// - urn:{TypeName}:{IdFieldValue} e.g. urn:UserSession:1 /// - urn:{TypeName}:{IdFieldName}:{IdFieldValue} e.g. urn:UserSession:UserId:1 /// /// </summary> public class UrnId { private const char FieldSeperator = ':'; private const char FieldPartsSeperator = '/'; /// <summary>Gets the name of the type.</summary> /// /// <value>The name of the type.</value> public string TypeName { get; private set; } /// <summary>Gets the identifier field value.</summary> /// /// <value>The identifier field value.</value> public string IdFieldValue { get; private set; } /// <summary>Gets the name of the identifier field.</summary> /// /// <value>The name of the identifier field.</value> public string IdFieldName { get; private set; } const int HasNoIdFieldName = 3; const int HasIdFieldName = 4; private UrnId() { } /// <summary>Parses.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="urnId">Identifier for the URN.</param> /// /// <returns>An UrnId.</returns> public static UrnId Parse(string urnId) { var urnParts = urnId.Split(FieldSeperator); if (urnParts.Length == HasNoIdFieldName) { return new UrnId { TypeName = urnParts[1], IdFieldValue = urnParts[2] }; } if (urnParts.Length == HasIdFieldName) { return new UrnId { TypeName = urnParts[1], IdFieldName = urnParts[2], IdFieldValue = urnParts[3] }; } throw new ArgumentException("Cannot parse invalid urn: '{0}'", urnId); } /// <summary>Creates a new string.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="objectTypeName">Name of the object type.</param> /// <param name="idFieldValue"> The identifier field value.</param> /// /// <returns>A string.</returns> public static string Create(string objectTypeName, string idFieldValue) { if (objectTypeName.Contains(FieldSeperator.ToString())) { throw new ArgumentException("objectTypeName cannot have the illegal characters: ':'", "objectTypeName"); } if (idFieldValue.Contains(FieldSeperator.ToString())) { throw new ArgumentException("idFieldValue cannot have the illegal characters: ':'", "idFieldValue"); } return string.Format("urn:{0}:{1}", objectTypeName, idFieldValue); } /// <summary>Creates with parts.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="objectTypeName">Name of the object type.</param> /// <param name="keyParts"> A variable-length parameters list containing key parts.</param> /// /// <returns>The new with parts.</returns> public static string CreateWithParts(string objectTypeName, params string[] keyParts) { if (objectTypeName.Contains(FieldSeperator.ToString())) { throw new ArgumentException("objectTypeName cannot have the illegal characters: ':'", "objectTypeName"); } var sb = new StringBuilder(); foreach (var keyPart in keyParts) { if (sb.Length > 0) sb.Append(FieldPartsSeperator); sb.Append(keyPart); } return string.Format("urn:{0}:{1}", objectTypeName, sb); } /// <summary>Creates with parts.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="keyParts">A variable-length parameters list containing key parts.</param> /// /// <returns>The new with parts.</returns> public static string CreateWithParts<T>(params string[] keyParts) { return CreateWithParts(typeof(T).Name, keyParts); } /// <summary>Creates a new string.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="idFieldValue">The identifier field value.</param> /// /// <returns>A string.</returns> public static string Create<T>(string idFieldValue) { return Create(typeof(T), idFieldValue); } /// <summary>Creates a new string.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="idFieldValue">The identifier field value.</param> /// /// <returns>A string.</returns> public static string Create<T>(object idFieldValue) { return Create(typeof(T), idFieldValue.ToString()); } /// <summary>Creates a new string.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="objectType"> Type of the object.</param> /// <param name="idFieldValue">The identifier field value.</param> /// /// <returns>A string.</returns> public static string Create(Type objectType, string idFieldValue) { if (idFieldValue.Contains(FieldSeperator.ToString())) { throw new ArgumentException("idFieldValue cannot have the illegal characters: ':'", "idFieldValue"); } return string.Format("urn:{0}:{1}", objectType.Name, idFieldValue); } /// <summary>Creates a new string.</summary> /// /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="idFieldName"> Name of the identifier field.</param> /// <param name="idFieldValue">The identifier field value.</param> /// /// <returns>A string.</returns> public static string Create<T>(string idFieldName, string idFieldValue) { return Create(typeof (T), idFieldName, idFieldValue); } /// <summary>Creates a new string.</summary> /// /// <exception cref="ArgumentException">Thrown when one or more arguments have unsupported or illegal values.</exception> /// /// <param name="objectType"> Type of the object.</param> /// <param name="idFieldName"> Name of the identifier field.</param> /// <param name="idFieldValue">The identifier field value.</param> /// /// <returns>A string.</returns> public static string Create(Type objectType, string idFieldName, string idFieldValue) { if (idFieldValue.Contains(FieldSeperator.ToString())) { throw new ArgumentException("idFieldValue cannot have the illegal characters: ':'", "idFieldValue"); } if (idFieldName.Contains(FieldSeperator.ToString())) { throw new ArgumentException("idFieldName cannot have the illegal characters: ':'", "idFieldName"); } return string.Format("urn:{0}:{1}:{2}", objectType.Name, idFieldName, idFieldValue); } /// <summary>Gets string identifier.</summary> /// /// <param name="urn">The URN.</param> /// /// <returns>The string identifier.</returns> public static string GetStringId(string urn) { return Parse(urn).IdFieldValue; } /// <summary>Gets unique identifier.</summary> /// /// <param name="urn">The URN.</param> /// /// <returns>The unique identifier.</returns> public static Guid GetGuidId(string urn) { return new Guid(Parse(urn).IdFieldValue); } /// <summary>Gets long identifier.</summary> /// /// <param name="urn">The URN.</param> /// /// <returns>The long identifier.</returns> public static long GetLongId(string urn) { return long.Parse(Parse(urn).IdFieldValue); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnTipoDocumento class. /// </summary> [Serializable] public partial class PnTipoDocumentoCollection : ActiveList<PnTipoDocumento, PnTipoDocumentoCollection> { public PnTipoDocumentoCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnTipoDocumentoCollection</returns> public PnTipoDocumentoCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnTipoDocumento o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_tipo_documento table. /// </summary> [Serializable] public partial class PnTipoDocumento : ActiveRecord<PnTipoDocumento>, IActiveRecord { #region .ctors and Default Settings public PnTipoDocumento() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnTipoDocumento(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnTipoDocumento(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnTipoDocumento(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_tipo_documento", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdTipoDocumento = new TableSchema.TableColumn(schema); colvarIdTipoDocumento.ColumnName = "id_tipo_documento"; colvarIdTipoDocumento.DataType = DbType.Int32; colvarIdTipoDocumento.MaxLength = 0; colvarIdTipoDocumento.AutoIncrement = true; colvarIdTipoDocumento.IsNullable = false; colvarIdTipoDocumento.IsPrimaryKey = true; colvarIdTipoDocumento.IsForeignKey = false; colvarIdTipoDocumento.IsReadOnly = false; colvarIdTipoDocumento.DefaultSetting = @""; colvarIdTipoDocumento.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdTipoDocumento); TableSchema.TableColumn colvarTipo = new TableSchema.TableColumn(schema); colvarTipo.ColumnName = "tipo"; colvarTipo.DataType = DbType.AnsiString; colvarTipo.MaxLength = 5; colvarTipo.AutoIncrement = false; colvarTipo.IsNullable = true; colvarTipo.IsPrimaryKey = false; colvarTipo.IsForeignKey = false; colvarTipo.IsReadOnly = false; colvarTipo.DefaultSetting = @""; colvarTipo.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipo); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.AnsiString; colvarDescripcion.MaxLength = 50; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = true; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarIdBeneficiario = new TableSchema.TableColumn(schema); colvarIdBeneficiario.ColumnName = "id_beneficiario"; colvarIdBeneficiario.DataType = DbType.Int32; colvarIdBeneficiario.MaxLength = 0; colvarIdBeneficiario.AutoIncrement = false; colvarIdBeneficiario.IsNullable = false; colvarIdBeneficiario.IsPrimaryKey = false; colvarIdBeneficiario.IsForeignKey = false; colvarIdBeneficiario.IsReadOnly = false; colvarIdBeneficiario.DefaultSetting = @""; colvarIdBeneficiario.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdBeneficiario); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_tipo_documento",schema); } } #endregion #region Props [XmlAttribute("IdTipoDocumento")] [Bindable(true)] public int IdTipoDocumento { get { return GetColumnValue<int>(Columns.IdTipoDocumento); } set { SetColumnValue(Columns.IdTipoDocumento, value); } } [XmlAttribute("Tipo")] [Bindable(true)] public string Tipo { get { return GetColumnValue<string>(Columns.Tipo); } set { SetColumnValue(Columns.Tipo, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("IdBeneficiario")] [Bindable(true)] public int IdBeneficiario { get { return GetColumnValue<int>(Columns.IdBeneficiario); } set { SetColumnValue(Columns.IdBeneficiario, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varTipo,string varDescripcion,int varIdBeneficiario) { PnTipoDocumento item = new PnTipoDocumento(); item.Tipo = varTipo; item.Descripcion = varDescripcion; item.IdBeneficiario = varIdBeneficiario; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdTipoDocumento,string varTipo,string varDescripcion,int varIdBeneficiario) { PnTipoDocumento item = new PnTipoDocumento(); item.IdTipoDocumento = varIdTipoDocumento; item.Tipo = varTipo; item.Descripcion = varDescripcion; item.IdBeneficiario = varIdBeneficiario; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdTipoDocumentoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn TipoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdBeneficiarioColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string IdTipoDocumento = @"id_tipo_documento"; public static string Tipo = @"tipo"; public static string Descripcion = @"descripcion"; public static string IdBeneficiario = @"id_beneficiario"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.CompilerServices; using System.Text; using System.Threading; namespace ICSharpCode.TextEditor.Document { public class FoldingManager { private class StartComparer : IComparer<FoldMarker> { public static readonly FoldingManager.StartComparer Instance = new FoldingManager.StartComparer(); public int Compare(FoldMarker x, FoldMarker y) { if (x.StartLine < y.StartLine) { return -1; } if (x.StartLine == y.StartLine) { return x.StartColumn.CompareTo(y.StartColumn); } return 1; } } private class EndComparer : IComparer<FoldMarker> { public static readonly FoldingManager.EndComparer Instance = new FoldingManager.EndComparer(); public int Compare(FoldMarker x, FoldMarker y) { if (x.EndLine < y.EndLine) { return -1; } if (x.EndLine == y.EndLine) { return x.EndColumn.CompareTo(y.EndColumn); } return 1; } } private List<FoldMarker> foldMarker = new List<FoldMarker>(); private List<FoldMarker> foldMarkerByEnd = new List<FoldMarker>(); private IFoldingStrategy foldingStrategy; private IDocument document; public event EventHandler FoldingsChanged; public IList<FoldMarker> FoldMarker { get { return this.foldMarker.AsReadOnly(); } } public IFoldingStrategy FoldingStrategy { get { return this.foldingStrategy; } set { this.foldingStrategy = value; } } internal FoldingManager(IDocument document, LineManager lineTracker) { this.document = document; document.DocumentChanged += new DocumentEventHandler(this.DocumentChanged); } private void DocumentChanged(object sender, DocumentEventArgs e) { int count = this.foldMarker.Count; this.document.UpdateSegmentListOnDocumentChange<FoldMarker>(this.foldMarker, e); if (count != this.foldMarker.Count) { this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea)); } } public List<FoldMarker> GetFoldingsFromPosition(int line, int column) { List<FoldMarker> list = new List<FoldMarker>(); if (this.foldMarker != null) { for (int i = 0; i < this.foldMarker.Count; i++) { FoldMarker foldMarker = this.foldMarker[i]; if ((foldMarker.StartLine == line && column > foldMarker.StartColumn && (foldMarker.EndLine != line || column < foldMarker.EndColumn)) || (foldMarker.EndLine == line && column < foldMarker.EndColumn && (foldMarker.StartLine != line || column > foldMarker.StartColumn)) || (line > foldMarker.StartLine && line < foldMarker.EndLine)) { list.Add(foldMarker); } } } return list; } private List<FoldMarker> GetFoldingsByStartAfterColumn(int lineNumber, int column, bool forceFolded) { List<FoldMarker> list = new List<FoldMarker>(); if (this.foldMarker != null) { int i = this.foldMarker.BinarySearch(new FoldMarker(this.document, lineNumber, column, lineNumber, column), FoldingManager.StartComparer.Instance); if (i < 0) { i = ~i; } while (i < this.foldMarker.Count) { FoldMarker foldMarker = this.foldMarker[i]; if (foldMarker.StartLine > lineNumber) { break; } if (foldMarker.StartColumn > column && (!forceFolded || foldMarker.IsFolded)) { list.Add(foldMarker); } i++; } } return list; } public List<FoldMarker> GetFoldingsWithStart(int lineNumber) { return this.GetFoldingsByStartAfterColumn(lineNumber, -1, false); } public List<FoldMarker> GetFoldedFoldingsWithStart(int lineNumber) { return this.GetFoldingsByStartAfterColumn(lineNumber, -1, true); } public List<FoldMarker> GetFoldedFoldingsWithStartAfterColumn(int lineNumber, int column) { return this.GetFoldingsByStartAfterColumn(lineNumber, column, true); } private List<FoldMarker> GetFoldingsByEndAfterColumn(int lineNumber, int column, bool forceFolded) { List<FoldMarker> list = new List<FoldMarker>(); if (this.foldMarker != null) { int i = this.foldMarkerByEnd.BinarySearch(new FoldMarker(this.document, lineNumber, column, lineNumber, column), FoldingManager.EndComparer.Instance); if (i < 0) { i = ~i; } while (i < this.foldMarkerByEnd.Count) { FoldMarker foldMarker = this.foldMarkerByEnd[i]; if (foldMarker.EndLine > lineNumber) { break; } if (foldMarker.EndColumn > column && (!forceFolded || foldMarker.IsFolded)) { list.Add(foldMarker); } i++; } } return list; } public List<FoldMarker> GetFoldingsWithEnd(int lineNumber) { return this.GetFoldingsByEndAfterColumn(lineNumber, -1, false); } public List<FoldMarker> GetFoldedFoldingsWithEnd(int lineNumber) { return this.GetFoldingsByEndAfterColumn(lineNumber, -1, true); } public bool IsFoldStart(int lineNumber) { return this.GetFoldingsWithStart(lineNumber).Count > 0; } public bool IsFoldEnd(int lineNumber) { return this.GetFoldingsWithEnd(lineNumber).Count > 0; } public List<FoldMarker> GetFoldingsContainsLineNumber(int lineNumber) { List<FoldMarker> list = new List<FoldMarker>(); if (this.foldMarker != null) { foreach (FoldMarker current in this.foldMarker) { if (current.StartLine < lineNumber && lineNumber < current.EndLine) { list.Add(current); } } } return list; } public bool IsBetweenFolding(int lineNumber) { return this.GetFoldingsContainsLineNumber(lineNumber).Count > 0; } public bool IsLineVisible(int lineNumber) { foreach (FoldMarker current in this.GetFoldingsContainsLineNumber(lineNumber)) { if (current.IsFolded) { return false; } } return true; } public List<FoldMarker> GetTopLevelFoldedFoldings() { List<FoldMarker> list = new List<FoldMarker>(); if (this.foldMarker != null) { Point point = new Point(0, 0); foreach (FoldMarker current in this.foldMarker) { if (current.IsFolded && (current.StartLine > point.Y || (current.StartLine == point.Y && current.StartColumn >= point.X))) { list.Add(current); point = new Point(current.EndColumn, current.EndLine); } } } return list; } public void UpdateFoldings(string fileName, object parseInfo) { this.UpdateFoldings(this.foldingStrategy.GenerateFoldMarkers(this.document, fileName, parseInfo)); } public void UpdateFoldings(List<FoldMarker> newFoldings) { int count = this.foldMarker.Count; Monitor.Enter(this); try { if (newFoldings != null && newFoldings.Count != 0) { newFoldings.Sort(); if (this.foldMarker.Count == newFoldings.Count) { for (int i = 0; i < this.foldMarker.Count; i++) { newFoldings[i].IsFolded = this.foldMarker[i].IsFolded; } this.foldMarker = newFoldings; } else { int num = 0; int num2 = 0; while (num < this.foldMarker.Count && num2 < newFoldings.Count) { int num3 = newFoldings[num2].CompareTo(this.foldMarker[num]); if (num3 > 0) { num++; } else { if (num3 == 0) { newFoldings[num2].IsFolded = this.foldMarker[num].IsFolded; } num2++; } } } } if (newFoldings != null) { this.foldMarker = newFoldings; this.foldMarkerByEnd = new List<FoldMarker>(newFoldings); this.foldMarkerByEnd.Sort(FoldingManager.EndComparer.Instance); } else { this.foldMarker.Clear(); this.foldMarkerByEnd.Clear(); } } finally { Monitor.Exit(this); } if (count != this.foldMarker.Count) { this.document.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea)); this.document.CommitUpdate(); } } public string SerializeToString() { StringBuilder stringBuilder = new StringBuilder(); foreach (FoldMarker current in this.foldMarker) { stringBuilder.Append(current.Offset); stringBuilder.Append("\n"); stringBuilder.Append(current.Length); stringBuilder.Append("\n"); stringBuilder.Append(current.FoldText); stringBuilder.Append("\n"); stringBuilder.Append(current.IsFolded); stringBuilder.Append("\n"); } return stringBuilder.ToString(); } public void DeserializeFromString(string str) { try { string[] array = str.Split(new char[] { '\n' }); int num = 0; while (num < array.Length && array[num].Length > 0) { int num2 = int.Parse(array[num]); int num3 = int.Parse(array[num + 1]); string foldText = array[num + 2]; bool isFolded = bool.Parse(array[num + 3]); bool flag = false; foreach (FoldMarker current in this.foldMarker) { if (current.Offset == num2 && current.Length == num3) { current.IsFolded = isFolded; flag = true; break; } } if (!flag) { this.foldMarker.Add(new FoldMarker(this.document, num2, num3, foldText, isFolded)); } num += 4; } if (array.Length > 0) { this.NotifyFoldingsChanged(EventArgs.Empty); } } catch (Exception) { } } public void NotifyFoldingsChanged(EventArgs e) { if (this.FoldingsChanged != null) { this.FoldingsChanged(this, e); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API includes operations for managing the virtual /// machine extensions in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for /// more information) /// </summary> internal partial class VirtualMachineExtensionOperations : IServiceOperations<ComputeManagementClient>, IVirtualMachineExtensionOperations { /// <summary> /// Initializes a new instance of the VirtualMachineExtensionOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualMachineExtensionOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The List Resource Extensions operation lists the resource /// extensions that are available to add to a Virtual Machine. In /// Azure, a process can run as a resource extension of a Virtual /// Machine. For example, Remote Desktop Access or the Azure /// Diagnostics Agent can run as resource extensions to the Virtual /// Machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Resource Extensions operation response. /// </returns> public async Task<VirtualMachineExtensionListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/resourceextensions"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineExtensionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineExtensionListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement resourceExtensionsSequenceElement = responseDoc.Element(XName.Get("ResourceExtensions", "http://schemas.microsoft.com/windowsazure")); if (resourceExtensionsSequenceElement != null) { foreach (XElement resourceExtensionsElement in resourceExtensionsSequenceElement.Elements(XName.Get("ResourceExtension", "http://schemas.microsoft.com/windowsazure"))) { VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension(); result.ResourceExtensions.Add(resourceExtensionInstance); XElement publisherElement = resourceExtensionsElement.Element(XName.Get("Publisher", "http://schemas.microsoft.com/windowsazure")); if (publisherElement != null) { string publisherInstance = publisherElement.Value; resourceExtensionInstance.Publisher = publisherInstance; } XElement nameElement = resourceExtensionsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; resourceExtensionInstance.Name = nameInstance; } XElement versionElement = resourceExtensionsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null) { string versionInstance = versionElement.Value; resourceExtensionInstance.Version = versionInstance; } XElement labelElement = resourceExtensionsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; resourceExtensionInstance.Label = labelInstance; } XElement descriptionElement = resourceExtensionsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; resourceExtensionInstance.Description = descriptionInstance; } XElement publicConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (publicConfigurationSchemaElement != null) { string publicConfigurationSchemaInstance = TypeConversion.FromBase64String(publicConfigurationSchemaElement.Value); resourceExtensionInstance.PublicConfigurationSchema = publicConfigurationSchemaInstance; } XElement privateConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (privateConfigurationSchemaElement != null) { string privateConfigurationSchemaInstance = TypeConversion.FromBase64String(privateConfigurationSchemaElement.Value); resourceExtensionInstance.PrivateConfigurationSchema = privateConfigurationSchemaInstance; } XElement sampleConfigElement = resourceExtensionsElement.Element(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure")); if (sampleConfigElement != null) { string sampleConfigInstance = TypeConversion.FromBase64String(sampleConfigElement.Value); resourceExtensionInstance.SampleConfig = sampleConfigInstance; } XElement replicationCompletedElement = resourceExtensionsElement.Element(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure")); if (replicationCompletedElement != null && !string.IsNullOrEmpty(replicationCompletedElement.Value)) { bool replicationCompletedInstance = bool.Parse(replicationCompletedElement.Value); resourceExtensionInstance.ReplicationCompleted = replicationCompletedInstance; } XElement eulaElement = resourceExtensionsElement.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement != null) { Uri eulaInstance = TypeConversion.TryParseUri(eulaElement.Value); resourceExtensionInstance.Eula = eulaInstance; } XElement privacyUriElement = resourceExtensionsElement.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement.Value); resourceExtensionInstance.PrivacyUri = privacyUriInstance; } XElement homepageUriElement = resourceExtensionsElement.Element(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure")); if (homepageUriElement != null) { Uri homepageUriInstance = TypeConversion.TryParseUri(homepageUriElement.Value); resourceExtensionInstance.HomepageUri = homepageUriInstance; } XElement isJsonExtensionElement = resourceExtensionsElement.Element(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure")); if (isJsonExtensionElement != null && !string.IsNullOrEmpty(isJsonExtensionElement.Value)) { bool isJsonExtensionInstance = bool.Parse(isJsonExtensionElement.Value); resourceExtensionInstance.IsJsonExtension = isJsonExtensionInstance; } XElement isInternalExtensionElement = resourceExtensionsElement.Element(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure")); if (isInternalExtensionElement != null && !string.IsNullOrEmpty(isInternalExtensionElement.Value)) { bool isInternalExtensionInstance = bool.Parse(isInternalExtensionElement.Value); resourceExtensionInstance.IsInternalExtension = isInternalExtensionInstance; } XElement disallowMajorVersionUpgradeElement = resourceExtensionsElement.Element(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure")); if (disallowMajorVersionUpgradeElement != null && !string.IsNullOrEmpty(disallowMajorVersionUpgradeElement.Value)) { bool disallowMajorVersionUpgradeInstance = bool.Parse(disallowMajorVersionUpgradeElement.Value); resourceExtensionInstance.DisallowMajorVersionUpgrade = disallowMajorVersionUpgradeInstance; } XElement supportedOSElement = resourceExtensionsElement.Element(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure")); if (supportedOSElement != null) { string supportedOSInstance = supportedOSElement.Value; resourceExtensionInstance.SupportedOS = supportedOSInstance; } XElement companyNameElement = resourceExtensionsElement.Element(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure")); if (companyNameElement != null) { string companyNameInstance = companyNameElement.Value; resourceExtensionInstance.CompanyName = companyNameInstance; } XElement publishedDateElement = resourceExtensionsElement.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement != null && !string.IsNullOrEmpty(publishedDateElement.Value)) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); resourceExtensionInstance.PublishedDate = publishedDateInstance; } XElement regionsElement = resourceExtensionsElement.Element(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure")); if (regionsElement != null) { string regionsInstance = regionsElement.Value; resourceExtensionInstance.Regions = regionsInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Resource Extension Versions operation lists the versions /// of a resource extension that are available to add to a Virtual /// Machine. In Azure, a process can run as a resource extension of a /// Virtual Machine. For example, Remote Desktop Access or the Azure /// Diagnostics Agent can run as resource extensions to the Virtual /// Machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx /// for more information) /// </summary> /// <param name='publisherName'> /// Required. The name of the publisher. /// </param> /// <param name='extensionName'> /// Required. The name of the extension. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Resource Extensions operation response. /// </returns> public async Task<VirtualMachineExtensionListResponse> ListVersionsAsync(string publisherName, string extensionName, CancellationToken cancellationToken) { // Validate if (publisherName == null) { throw new ArgumentNullException("publisherName"); } if (extensionName == null) { throw new ArgumentNullException("extensionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("publisherName", publisherName); tracingParameters.Add("extensionName", extensionName); TracingAdapter.Enter(invocationId, this, "ListVersionsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/resourceextensions/"; url = url + Uri.EscapeDataString(publisherName); url = url + "/"; url = url + Uri.EscapeDataString(extensionName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineExtensionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineExtensionListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement resourceExtensionsSequenceElement = responseDoc.Element(XName.Get("ResourceExtensions", "http://schemas.microsoft.com/windowsazure")); if (resourceExtensionsSequenceElement != null) { foreach (XElement resourceExtensionsElement in resourceExtensionsSequenceElement.Elements(XName.Get("ResourceExtension", "http://schemas.microsoft.com/windowsazure"))) { VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension(); result.ResourceExtensions.Add(resourceExtensionInstance); XElement publisherElement = resourceExtensionsElement.Element(XName.Get("Publisher", "http://schemas.microsoft.com/windowsazure")); if (publisherElement != null) { string publisherInstance = publisherElement.Value; resourceExtensionInstance.Publisher = publisherInstance; } XElement nameElement = resourceExtensionsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; resourceExtensionInstance.Name = nameInstance; } XElement versionElement = resourceExtensionsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null) { string versionInstance = versionElement.Value; resourceExtensionInstance.Version = versionInstance; } XElement labelElement = resourceExtensionsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; resourceExtensionInstance.Label = labelInstance; } XElement descriptionElement = resourceExtensionsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; resourceExtensionInstance.Description = descriptionInstance; } XElement publicConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (publicConfigurationSchemaElement != null) { string publicConfigurationSchemaInstance = TypeConversion.FromBase64String(publicConfigurationSchemaElement.Value); resourceExtensionInstance.PublicConfigurationSchema = publicConfigurationSchemaInstance; } XElement privateConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (privateConfigurationSchemaElement != null) { string privateConfigurationSchemaInstance = TypeConversion.FromBase64String(privateConfigurationSchemaElement.Value); resourceExtensionInstance.PrivateConfigurationSchema = privateConfigurationSchemaInstance; } XElement sampleConfigElement = resourceExtensionsElement.Element(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure")); if (sampleConfigElement != null) { string sampleConfigInstance = TypeConversion.FromBase64String(sampleConfigElement.Value); resourceExtensionInstance.SampleConfig = sampleConfigInstance; } XElement replicationCompletedElement = resourceExtensionsElement.Element(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure")); if (replicationCompletedElement != null && !string.IsNullOrEmpty(replicationCompletedElement.Value)) { bool replicationCompletedInstance = bool.Parse(replicationCompletedElement.Value); resourceExtensionInstance.ReplicationCompleted = replicationCompletedInstance; } XElement eulaElement = resourceExtensionsElement.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement != null) { Uri eulaInstance = TypeConversion.TryParseUri(eulaElement.Value); resourceExtensionInstance.Eula = eulaInstance; } XElement privacyUriElement = resourceExtensionsElement.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement.Value); resourceExtensionInstance.PrivacyUri = privacyUriInstance; } XElement homepageUriElement = resourceExtensionsElement.Element(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure")); if (homepageUriElement != null) { Uri homepageUriInstance = TypeConversion.TryParseUri(homepageUriElement.Value); resourceExtensionInstance.HomepageUri = homepageUriInstance; } XElement isJsonExtensionElement = resourceExtensionsElement.Element(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure")); if (isJsonExtensionElement != null && !string.IsNullOrEmpty(isJsonExtensionElement.Value)) { bool isJsonExtensionInstance = bool.Parse(isJsonExtensionElement.Value); resourceExtensionInstance.IsJsonExtension = isJsonExtensionInstance; } XElement isInternalExtensionElement = resourceExtensionsElement.Element(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure")); if (isInternalExtensionElement != null && !string.IsNullOrEmpty(isInternalExtensionElement.Value)) { bool isInternalExtensionInstance = bool.Parse(isInternalExtensionElement.Value); resourceExtensionInstance.IsInternalExtension = isInternalExtensionInstance; } XElement disallowMajorVersionUpgradeElement = resourceExtensionsElement.Element(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure")); if (disallowMajorVersionUpgradeElement != null && !string.IsNullOrEmpty(disallowMajorVersionUpgradeElement.Value)) { bool disallowMajorVersionUpgradeInstance = bool.Parse(disallowMajorVersionUpgradeElement.Value); resourceExtensionInstance.DisallowMajorVersionUpgrade = disallowMajorVersionUpgradeInstance; } XElement supportedOSElement = resourceExtensionsElement.Element(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure")); if (supportedOSElement != null) { string supportedOSInstance = supportedOSElement.Value; resourceExtensionInstance.SupportedOS = supportedOSInstance; } XElement companyNameElement = resourceExtensionsElement.Element(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure")); if (companyNameElement != null) { string companyNameInstance = companyNameElement.Value; resourceExtensionInstance.CompanyName = companyNameInstance; } XElement publishedDateElement = resourceExtensionsElement.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement != null && !string.IsNullOrEmpty(publishedDateElement.Value)) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); resourceExtensionInstance.PublishedDate = publishedDateInstance; } XElement regionsElement = resourceExtensionsElement.Element(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure")); if (regionsElement != null) { string regionsInstance = regionsElement.Value; resourceExtensionInstance.Regions = regionsInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.CompositeKeys { public sealed class CompositeKeyTests : IClassFixture<IntegrationTestContext<TestableStartup<CompositeDbContext>, CompositeDbContext>> { private readonly IntegrationTestContext<TestableStartup<CompositeDbContext>, CompositeDbContext> _testContext; public CompositeKeyTests(IntegrationTestContext<TestableStartup<CompositeDbContext>, CompositeDbContext> testContext) { _testContext = testContext; testContext.UseController<DealershipsController>(); testContext.UseController<EnginesController>(); testContext.UseController<CarsController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceRepository<CarCompositeKeyAwareRepository<Car, string>>(); services.AddResourceRepository<CarCompositeKeyAwareRepository<Dealership>>(); }); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.AllowClientGeneratedIds = true; } [Fact] public async Task Can_filter_on_ID_in_primary_resources() { // Arrange var car = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Cars.Add(car); await dbContext.SaveChangesAsync(); }); const string route = "/cars?filter=any(id,'123:AA-BB-11','999:XX-YY-22')"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(car.StringId); } [Fact] public async Task Can_get_primary_resource_by_ID() { // Arrange var car = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Cars.Add(car); await dbContext.SaveChangesAsync(); }); string route = $"/cars/{car.StringId}"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Id.Should().Be(car.StringId); } [Fact] public async Task Can_sort_on_ID() { // Arrange var car = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Cars.Add(car); await dbContext.SaveChangesAsync(); }); const string route = "/cars?sort=id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(car.StringId); } [Fact] public async Task Can_select_ID() { // Arrange var car = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Cars.Add(car); await dbContext.SaveChangesAsync(); }); const string route = "/cars?fields[cars]=id"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); responseDocument.Data.ManyValue.Should().HaveCount(1); responseDocument.Data.ManyValue[0].Id.Should().Be(car.StringId); } [Fact] public async Task Can_create_resource() { // Arrange await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); }); var requestBody = new { data = new { type = "cars", attributes = new { regionId = 123, licensePlate = "AA-BB-11" } } }; const string route = "/cars"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Car carInDatabase = await dbContext.Cars.FirstOrDefaultAsync(car => car.RegionId == 123 && car.LicensePlate == "AA-BB-11"); carInDatabase.Should().NotBeNull(); carInDatabase.Id.Should().Be("123:AA-BB-11"); }); } [Fact] public async Task Can_create_OneToOne_relationship() { // Arrange var existingCar = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; var existingEngine = new Engine { SerialCode = "1234567890" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.AddInRange(existingCar, existingEngine); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "engines", id = existingEngine.StringId, relationships = new { car = new { data = new { type = "cars", id = existingCar.StringId } } } } }; string route = $"/engines/{existingEngine.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Engine engineInDatabase = await dbContext.Engines.Include(engine => engine.Car).FirstWithIdAsync(existingEngine.Id); engineInDatabase.Car.Should().NotBeNull(); engineInDatabase.Car.Id.Should().Be(existingCar.StringId); }); } [Fact] public async Task Can_clear_OneToOne_relationship() { // Arrange var existingEngine = new Engine { SerialCode = "1234567890", Car = new Car { RegionId = 123, LicensePlate = "AA-BB-11" } }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Engines.Add(existingEngine); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "engines", id = existingEngine.StringId, relationships = new { car = new { data = (object)null } } } }; string route = $"/engines/{existingEngine.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Engine engineInDatabase = await dbContext.Engines.Include(engine => engine.Car).FirstWithIdAsync(existingEngine.Id); engineInDatabase.Car.Should().BeNull(); }); } [Fact] public async Task Can_remove_from_OneToMany_relationship() { // Arrange var existingDealership = new Dealership { Address = "Dam 1, 1012JS Amsterdam, the Netherlands", Inventory = new HashSet<Car> { new() { RegionId = 123, LicensePlate = "AA-BB-11" }, new() { RegionId = 456, LicensePlate = "CC-DD-22" } } }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Dealerships.Add(existingDealership); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "cars", id = "123:AA-BB-11" } } }; string route = $"/dealerships/{existingDealership.StringId}/relationships/inventory"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Dealership dealershipInDatabase = await dbContext.Dealerships .Include(dealership => dealership.Inventory).FirstWithIdOrDefaultAsync(existingDealership.Id); dealershipInDatabase.Inventory.Should().HaveCount(1); dealershipInDatabase.Inventory.Should().ContainSingle(car => car.Id == existingDealership.Inventory.ElementAt(1).Id); }); } [Fact] public async Task Can_add_to_OneToMany_relationship() { // Arrange var existingDealership = new Dealership { Address = "Dam 1, 1012JS Amsterdam, the Netherlands" }; var existingCar = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.AddInRange(existingDealership, existingCar); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "cars", id = "123:AA-BB-11" } } }; string route = $"/dealerships/{existingDealership.StringId}/relationships/inventory"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Dealership dealershipInDatabase = await dbContext.Dealerships .Include(dealership => dealership.Inventory).FirstWithIdOrDefaultAsync(existingDealership.Id); dealershipInDatabase.Inventory.Should().HaveCount(1); dealershipInDatabase.Inventory.Should().ContainSingle(car => car.Id == existingCar.Id); }); } [Fact] public async Task Can_replace_OneToMany_relationship() { // Arrange var existingDealership = new Dealership { Address = "Dam 1, 1012JS Amsterdam, the Netherlands", Inventory = new HashSet<Car> { new() { RegionId = 123, LicensePlate = "AA-BB-11" }, new() { RegionId = 456, LicensePlate = "CC-DD-22" } } }; var existingCar = new Car { RegionId = 789, LicensePlate = "EE-FF-33" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.AddInRange(existingDealership, existingCar); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "cars", id = "123:AA-BB-11" }, new { type = "cars", id = "789:EE-FF-33" } } }; string route = $"/dealerships/{existingDealership.StringId}/relationships/inventory"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Dealership dealershipInDatabase = await dbContext.Dealerships .Include(dealership => dealership.Inventory).FirstWithIdOrDefaultAsync(existingDealership.Id); dealershipInDatabase.Inventory.Should().HaveCount(2); dealershipInDatabase.Inventory.Should().ContainSingle(car => car.Id == existingCar.Id); dealershipInDatabase.Inventory.Should().ContainSingle(car => car.Id == existingDealership.Inventory.ElementAt(0).Id); }); } [Fact] public async Task Cannot_remove_from_ManyToOne_relationship_for_unknown_relationship_ID() { // Arrange var existingDealership = new Dealership { Address = "Dam 1, 1012JS Amsterdam, the Netherlands" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Dealerships.Add(existingDealership); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "cars", id = "999:XX-YY-22" } } }; string route = $"/dealerships/{existingDealership.StringId}/relationships/inventory"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteDeleteAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NotFound); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.NotFound); error.Title.Should().Be("A related resource does not exist."); error.Detail.Should().Be("Related resource of type 'cars' with ID '999:XX-YY-22' in relationship 'inventory' does not exist."); } [Fact] public async Task Can_delete_resource() { // Arrange var existingCar = new Car { RegionId = 123, LicensePlate = "AA-BB-11" }; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<Car>(); dbContext.Cars.Add(existingCar); await dbContext.SaveChangesAsync(); }); string route = $"/cars/{existingCar.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Car carInDatabase = await dbContext.Cars.FirstOrDefaultAsync(car => car.RegionId == existingCar.RegionId && car.LicensePlate == existingCar.LicensePlate); carInDatabase.Should().BeNull(); }); } } }
using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Text; namespace MapFileDecryptor { class MapElem { public Byte Unk; public SByte Z; public UInt16 NewGraphic; public MapElem() { Unk = 0; Z = 0; NewGraphic = 0; } } class MapCell : MapElem { public UInt16 Unk2; public UInt16 OldGraphic; public MapCell() { OldGraphic = 0; Unk2 = 0; } } class MapDelimiter : MapElem { public Byte Direction; public MapDelimiter Next; public MapDelimiter() { Direction = 0; Next = null; } public Byte Count() { Byte c = 1; MapDelimiter mp=this; while (mp.Next != null) { c++; mp = mp.Next; } return c; } public MapDelimiter AppendNew() { MapDelimiter mp = this; while (mp.Next != null) mp = mp.Next; mp.Next = new MapDelimiter(); return mp.Next; } } class MapStaticBlock : MapElem { public UInt16 SGraphic; public UInt16 UnkS; public UInt16 Color; public MapStaticBlock Next; public MapStaticBlock() { SGraphic = 0; UnkS = 0; Next = null; } public Byte Count() { Byte c = 1; MapStaticBlock mp = this; while (mp.Next != null) { c++; mp = mp.Next; } return c; } public MapStaticBlock AppendNew() { MapStaticBlock mp = this; while (mp.Next != null) mp = mp.Next; mp.Next = new MapStaticBlock(); return mp.Next; } } class TransTable { public ArrayList trans_table; private Random r; public int this[int i] { get { try { int[] arr = (int[])trans_table[i]; if (arr.Length == 1) return arr[0]; else return arr[r.Next(arr.Length)]; } catch { throw new Exception("Error on " + i + "graphic"); } } } public TransTable() { r = new Random(); trans_table = new ArrayList(); for (int i = 0; i < 764; i++) trans_table.Add(null); trans_table[0] = new int[] { 2, 3, 151 }; trans_table[1] = new int[] { 0, 2, 3, 24 }; trans_table[2] = new int[] { 0, 2, 3, 24, 151 }; trans_table[3] = new int[] { 1, 2, 3, 24, 58, 151 }; trans_table[4] = new int[] { 1, 2, 6, 24, 60 }; trans_table[5] = new int[] { 1, 2, 6, 59 }; trans_table[6] = new int[] { 1, 6, 11 }; trans_table[7] = new int[] { 6, 11 }; trans_table[8] = new int[] { 3, 11 }; trans_table[9] = new int[] { 3, 4, 11, 20, 64, 151 }; trans_table[10] = new int[] { 3, 4, 12, 20, 151 }; trans_table[11] = new int[] { 4, 12, 20, 151 }; trans_table[12] = new int[] { 3, 4, 8, 12, 20, 151 }; trans_table[13] = new int[] { 3, 8, 12, 20, 151, 160 }; trans_table[14] = new int[] { 8, 20, 22, 49, 151, 161 }; trans_table[15] = new int[] { 6, 8, 20, 22, 49, 162 }; trans_table[16] = new int[] { 6, 20, 22, 163 }; trans_table[17] = new int[] { 4, 6, 20, 22 }; trans_table[18] = new int[] { 6, 20, 23 }; trans_table[19] = new int[] { 6, 20, 23 }; trans_table[20] = new int[] { 6, 8, 20, 23 }; trans_table[21] = new int[] { 3, 4, 8, 20, 23 }; trans_table[22] = new int[] { 3, 4, 7, 8, 94 }; trans_table[23] = new int[] { 4, 7, 8, 95 }; trans_table[24] = new int[] { 3, 4, 7, 96 }; trans_table[25] = new int[] { 4, 7, 97 }; trans_table[26] = new int[] { 4, 54, 93 }; trans_table[27] = new int[] { 4, 56, 90 }; trans_table[28] = new int[] { 4, 55, 91 }; trans_table[29] = new int[] { 6, 49, 55, 92 }; trans_table[30] = new int[] { 6, 7, 49, 57, 89 }; trans_table[31] = new int[] { 6, 7, 57, 73, 146 }; trans_table[32] = new int[] { 6, 7, 55, 78, 146 }; trans_table[33] = new int[] { 7, 56, 79, 146 }; trans_table[34] = new int[] { 6, 54, 80, 146 }; trans_table[35] = new int[] { 2, 6, 54, 81, 146 }; trans_table[36] = new int[] { 2, 6, 56, 75, 146 }; trans_table[37] = new int[] { 2, 6, 56, 76, 146 }; trans_table[38] = new int[] { 2, 54, 77, 146 }; trans_table[39] = new int[] { 2, 54, 74, 146 }; trans_table[40] = new int[] { 56, 88, 146 }; trans_table[41] = new int[] { 2, 56, 98, 146 }; trans_table[42] = new int[] { 2, 7, 49, 54, 99, 146 }; trans_table[43] = new int[] { 2, 7, 49, 54, 100, 146 }; trans_table[44] = new int[] { 2, 7, 49, 101, 146 }; trans_table[45] = new int[] { 2, 7, 49, 57, 102, 146 }; trans_table[46] = new int[] { 49, 55, 103, 146 }; trans_table[47] = new int[] { 2, 49, 55, 72, 146 }; trans_table[48] = new int[] { 2, 49, 55, 82, 146 }; trans_table[49] = new int[] { 2, 49, 56, 83 }; trans_table[50] = new int[] { 49, 54, 84 }; trans_table[51] = new int[] { 2, 7, 49, 85 }; trans_table[52] = new int[] { 2, 7, 45, 49, 86 }; trans_table[53] = new int[] { 2, 6, 7, 45, 49, 87 }; trans_table[54] = new int[] { 5, 6, 7, 25, 45, 49 }; trans_table[55] = new int[] { 2, 5, 6, 7, 25, 45, 49 }; trans_table[56] = new int[] { 2, 6, 7, 25, 45, 49 }; trans_table[57] = new int[] { 2, 7, 25, 45, 49 }; trans_table[58] = new int[] { 2, 7, 26 }; trans_table[59] = new int[] { 6, 7, 13, 26, 169 }; trans_table[60] = new int[] { 7, 13, 26 }; trans_table[61] = new int[] { 2, 6, 7, 13, 26 }; trans_table[62] = new int[] { 2, 6, 7, 13, 27 }; trans_table[63] = new int[] { 2, 27 }; trans_table[64] = new int[] { 2, 27 }; trans_table[65] = new int[] { 2, 27 }; trans_table[66] = new int[] { 1, 2, 7, 28 }; trans_table[67] = new int[] { 1, 2, 7, 28 }; trans_table[68] = new int[] { 2, 7, 29, 56 }; trans_table[69] = new int[] { 2, 13, 29, 54 }; trans_table[70] = new int[] { 2, 13, 30, 54 }; trans_table[71] = new int[] { 2, 13, 30 }; trans_table[72] = new int[] { 0, 2, 13, 30, 55 }; trans_table[73] = new int[] { 0, 2, 13, 30, 57 }; trans_table[74] = new int[] { 2, 6, 31, 57, 171 }; trans_table[75] = new int[] { 0, 2, 7, 31, 55, 172 }; trans_table[76] = new int[] { 2, 7, 31, 52, 173 }; trans_table[77] = new int[] { 2, 7, 31, 52, 174 }; trans_table[78] = new int[] { 2, 32, 52, 175 }; trans_table[79] = new int[] { 2, 4, 7, 32, 52, 176 }; trans_table[80] = new int[] { 4, 7, 21, 32, 52, 177 }; trans_table[81] = new int[] { 4, 7, 21, 32, 52, 178 }; trans_table[82] = new int[] { 4, 7, 21, 33, 52, 179 }; trans_table[83] = new int[] { 2, 4, 7, 21, 33, 52, 180 }; trans_table[84] = new int[] { 2, 7, 21, 33, 52, 181 }; trans_table[85] = new int[] { 2, 4, 8, 21, 33, 52, 182 }; trans_table[86] = new int[] { 2, 21, 30, 52, 183 }; trans_table[87] = new int[] { 2, 8, 21, 30, 52, 188 }; trans_table[88] = new int[] { 2, 8, 21, 30, 52 }; trans_table[89] = new int[] { 7, 21, 30, 52, 189 }; trans_table[90] = new int[] { 7, 16, 30, 52 }; trans_table[91] = new int[] { 6, 7, 16, 30, 52 }; trans_table[92] = new int[] { 6, 7, 15, 30, 52 }; trans_table[93] = new int[] { 4, 16, 30, 52 }; trans_table[94] = new int[] { 4, 16, 30, 52 }; trans_table[95] = new int[] { 4, 16, 30, 52 }; trans_table[96] = new int[] { 4, 16, 30, 52 }; trans_table[97] = new int[] { 4, 16, 30, 52 }; trans_table[98] = new int[] { 4, 17, 30, 52, 184 }; trans_table[99] = new int[] { 4, 30, 52, 185 }; trans_table[100] = new int[] { 4, 30, 52, 186 }; trans_table[101] = new int[] { 4, 30, 52, 187 }; trans_table[102] = new int[] { 4, 14, 30, 52 }; trans_table[103] = new int[] { 2, 4, 14, 30 }; trans_table[104] = new int[] { 2, 4, 15, 30, 52 }; trans_table[105] = new int[] { 2, 14, 30, 52, 147 }; trans_table[106] = new int[] { 2, 14, 30, 52, 147 }; trans_table[107] = new int[] { 2, 16, 52, 147 }; trans_table[108] = new int[] { 2, 16, 30, 52 }; trans_table[109] = new int[] { 2, 16, 30, 52 }; trans_table[110] = new int[] { 2, 3, 30, 52, 64, 149 }; trans_table[111] = new int[] { 1, 2, 3, 30, 52, 147 }; trans_table[112] = new int[] { 1, 2, 3, 30, 147 }; trans_table[113] = new int[] { 1, 2, 3, 30, 155 }; trans_table[114] = new int[] { 1, 2, 30, 155 }; trans_table[115] = new int[] { 1, 2, 30, 148, 155 }; trans_table[116] = new int[] { 1, 2, 30, 149, 155 }; trans_table[117] = new int[] { 1, 2, 30, 147 }; trans_table[118] = new int[] { 1, 2, 3, 30, 147 }; trans_table[119] = new int[] { 2, 3, 30, 58 }; trans_table[120] = new int[] { 2, 3, 30, 58 }; trans_table[121] = new int[] { 2, 3, 30, 58, 62, 148 }; trans_table[122] = new int[] { 1, 2, 3, 34, 58, 61 }; trans_table[123] = new int[] { 1, 2, 3, 34, 60, 63, 149 }; trans_table[124] = new int[] { 1, 2, 3, 34, 60, 147 }; trans_table[125] = new int[] { 1, 3, 34, 60, 64 }; trans_table[126] = new int[] { 1, 2, 35, 60, 64, 147 }; trans_table[127] = new int[] { 0, 1, 2, 35, 59, 148 }; trans_table[128] = new int[] { 1, 2, 36, 58 }; trans_table[129] = new int[] { 0, 2, 3, 36, 59, 147 }; trans_table[130] = new int[] { 1, 3, 7, 36, 59, 149 }; trans_table[131] = new int[] { 1, 3, 36, 60, 149 }; trans_table[132] = new int[] { 0, 3, 7, 35, 58, 149 }; trans_table[133] = new int[] { 2, 3, 7, 35, 60, 148 }; trans_table[134] = new int[] { 2, 3, 9, 37, 58 }; trans_table[135] = new int[] { 2, 3, 37, 60 }; trans_table[136] = new int[] { 2, 3, 37, 58 }; trans_table[137] = new int[] { 1, 2, 37, 58, 149 }; trans_table[138] = new int[] { 1, 2, 7, 58, 104, 149 }; trans_table[139] = new int[] { 1, 2, 7, 58, 105 }; trans_table[140] = new int[] { 2, 46, 58, 60, 106 }; trans_table[141] = new int[] { 2, 3, 7, 58, 60, 107 }; trans_table[142] = new int[] { 2, 3, 47, 58, 60, 108 }; trans_table[143] = new int[] { 2, 3, 38, 58, 60, 149 }; trans_table[144] = new int[] { 2, 3, 38, 58, 60, 150 }; trans_table[145] = new int[] { 38, 58, 60 }; trans_table[146] = new int[] { 38, 60, 147 }; trans_table[147] = new int[] { 39, 60 }; trans_table[148] = new int[] { 39, 58, 60, 149 }; trans_table[149] = new int[] { 39, 46, 59, 150 }; trans_table[150] = new int[] { 2, 19, 39, 58 }; trans_table[151] = new int[] { 2, 58, 59, 68, 147 }; trans_table[152] = new int[] { 2, 19, 58, 59, 147 }; trans_table[153] = new int[] { 2, 19, 58, 60 }; trans_table[154] = new int[] { 2, 19, 60, 149 }; trans_table[155] = new int[] { 2, 19, 58, 60, 149 }; trans_table[156] = new int[] { 2, 19, 60, 149 }; trans_table[157] = new int[] { 2, 19, 60, 147 }; trans_table[158] = new int[] { 2, 19, 58, 147 }; trans_table[159] = new int[] { 2, 3, 19, 58, 147 }; trans_table[160] = new int[] { 2, 19, 58, 147 }; trans_table[161] = new int[] { 3, 19, 58 }; trans_table[162] = new int[] { 2, 3, 19, 60, 148 }; trans_table[163] = new int[] { 2, 19, 60, 147 }; trans_table[164] = new int[] { 1, 2, 19, 58, 147 }; trans_table[165] = new int[] { 1, 2, 19, 60, 147 }; trans_table[166] = new int[] { 2, 3, 19, 60, 147 }; trans_table[167] = new int[] { 1, 2, 19, 58, 147 }; trans_table[168] = new int[] { 2, 5, 7, 68 }; trans_table[169] = new int[] { 2, 5, 7, 68 }; trans_table[170] = new int[] { 5, 7, 9, 68, 148 }; trans_table[171] = new int[] { 5, 7, 9, 68, 147 }; trans_table[172] = new int[] { 3, 9, 58, 68, 147 }; trans_table[173] = new int[] { 3, 9, 58, 68 }; trans_table[174] = new int[] { 3, 60, 68, 170 }; trans_table[175] = new int[] { 0, 2, 3, 4, 60, 68, 147 }; trans_table[176] = new int[] { 0, 2, 3, 4, 60, 68 }; trans_table[177] = new int[] { 2, 4, 60, 68 }; trans_table[178] = new int[] { 4, 60, 68 }; trans_table[179] = new int[] { 3, 4, 60, 68, 109 }; trans_table[180] = new int[] { 3, 4, 58, 68, 110 }; trans_table[181] = new int[] { 1, 58, 68, 111, 147 }; trans_table[182] = new int[] { 1, 3, 58, 68, 112, 147 }; trans_table[183] = new int[] { 1, 3, 58, 68, 113, 147 }; trans_table[184] = new int[] { 1, 58, 68, 114, 147 }; trans_table[185] = new int[] { 1, 3, 7, 54, 58, 68, 115, 151 }; trans_table[186] = new int[] { 1, 56, 60, 68, 116, 151 }; trans_table[187] = new int[] { 4, 7, 19, 55, 60, 117, 151 }; trans_table[188] = new int[] { 3, 4, 7, 55, 60, 119, 151 }; trans_table[189] = new int[] { 3, 4, 7, 57, 60, 120, 151 }; trans_table[190] = new int[] { 3, 4, 7, 57, 58, 121 }; trans_table[191] = new int[] { 1, 3, 7, 55, 58, 122, 151 }; trans_table[192] = new int[] { 1, 7, 56, 69, 123, 151 }; trans_table[193] = new int[] { 1, 6, 124, 129, 151 }; trans_table[194] = new int[] { 1, 6, 54, 125, 130 }; trans_table[195] = new int[] { 1, 6, 56, 126, 148 }; trans_table[196] = new int[] { 1, 4, 6, 48, 56, 127, 151 }; trans_table[197] = new int[] { 1, 4, 54, 118, 151 }; trans_table[198] = new int[] { 1, 4, 54, 128, 151 }; trans_table[199] = new int[] { 4, 6, 7, 152 }; trans_table[200] = new int[] { 4, 6, 7, 56 }; trans_table[201] = new int[] { 4, 7, 54, 152 }; trans_table[202] = new int[] { 4, 7, 54, 147 }; trans_table[203] = new int[] { 1, 4, 151 }; trans_table[204] = new int[] { 1, 4, 50, 57, 151 }; trans_table[205] = new int[] { 0, 1, 4, 6, 50, 55 }; trans_table[206] = new int[] { 1, 4, 50, 55, 151 }; trans_table[207] = new int[] { 4, 6, 50, 55, 153 }; trans_table[208] = new int[] { 4, 6, 56, 153 }; trans_table[209] = new int[] { 4, 6, 54, 71, 153 }; trans_table[210] = new int[] { 4, 6, 54, 151 }; trans_table[211] = new int[] { 4, 6, 148, 154 }; trans_table[212] = new int[] { 4, 56, 151, 154 }; trans_table[213] = new int[] { 4, 147, 154 }; trans_table[214] = new int[] { 4, 54, 147, 154 }; trans_table[215] = new int[] { 4, 151, 154 }; trans_table[216] = new int[] { 1, 151, 154 }; trans_table[217] = new int[] { 1, 131, 151, 154 }; trans_table[218] = new int[] { 1, 6, 148, 154 }; trans_table[219] = new int[] { 1, 6, 132, 151 }; trans_table[220] = new int[] { 2, 6, 133 }; trans_table[221] = new int[] { 2, 6 }; trans_table[222] = new int[] { 1, 2, 134 }; trans_table[223] = new int[] { 1, 2, 135 }; trans_table[224] = new int[] { 1, 2, 136 }; trans_table[225] = new int[] { 1, 2, 137 }; trans_table[226] = new int[] { 2, 138 }; trans_table[227] = new int[] { 2, 139, 149 }; trans_table[228] = new int[] { 2, 6, 140, 148 }; trans_table[229] = new int[] { 2, 6, 58, 141, 149 }; trans_table[230] = new int[] { 2, 6, 58, 142 }; trans_table[231] = new int[] { 0, 2, 6, 58, 143 }; trans_table[232] = new int[] { 2, 58, 144 }; trans_table[233] = new int[] { 2, 9, 41, 60, 70 }; trans_table[234] = new int[] { 2, 9, 41, 60, 70 }; trans_table[235] = new int[] { 2, 6, 9, 42, 60, 70, 149 }; trans_table[236] = new int[] { 2, 9, 42, 44, 60, 70, 149 }; trans_table[237] = new int[] { 2, 6, 42, 44, 59, 149 }; trans_table[238] = new int[] { 0, 2, 6, 42, 44, 58, 149 }; trans_table[239] = new int[] { 0, 2, 4, 6, 43, 44, 59, 147 }; trans_table[240] = new int[] { 0, 3, 4, 43, 44, 59, 145 }; trans_table[241] = new int[] { 3, 4, 6, 43, 44, 60, 145 }; trans_table[242] = new int[] { 0, 4, 6, 43, 60, 145, 148 }; trans_table[243] = new int[] { 0, 2, 4, 58, 145, 148 }; trans_table[244] = new int[] { 0, 4, 6, 10, 60, 145, 148 }; trans_table[245] = new int[] { 2, 3, 6, 10, 60, 145 }; trans_table[246] = new int[] { 2, 3, 6, 10, 58, 145 }; trans_table[247] = new int[] { 2, 6, 10, 58, 145, 147 }; trans_table[248] = new int[] { 2, 3, 4, 58, 145, 147, 190 }; trans_table[249] = new int[] { 2, 4, 58, 147, 190 }; trans_table[250] = new int[] { 2, 4, 53, 60, 147, 190 }; trans_table[251] = new int[] { 2, 4, 6, 53, 60, 147, 190 }; trans_table[252] = new int[] { 2, 6, 53, 58 }; trans_table[253] = new int[] { 2, 6, 53, 60, 151 }; trans_table[254] = new int[] { 2, 6, 53, 60 }; trans_table[255] = new int[] { 2, 53, 58 }; trans_table[262] = new int[] { 149 }; trans_table[264] = new int[] { 149 }; trans_table[266] = new int[] { 63 }; trans_table[267] = new int[] { 63 }; trans_table[274] = new int[] { 63 }; trans_table[282] = new int[] { 8 }; trans_table[283] = new int[] { 8 }; trans_table[284] = new int[] { 8 }; trans_table[285] = new int[] { 8 }; trans_table[294] = new int[] { 7 }; trans_table[295] = new int[] { 7 }; trans_table[296] = new int[] { 7 }; trans_table[297] = new int[] { 7 }; trans_table[305] = new int[] { 1 }; trans_table[306] = new int[] { 1 }; trans_table[307] = new int[] { 1 }; trans_table[308] = new int[] { 1 }; trans_table[313] = new int[] { 1 }; trans_table[314] = new int[] { 1 }; trans_table[315] = new int[] { 1 }; trans_table[316] = new int[] { 1 }; trans_table[317] = new int[] { 1 }; trans_table[318] = new int[] { 1 }; trans_table[319] = new int[] { 1 }; trans_table[320] = new int[] { 1 }; trans_table[321] = new int[] { 1 }; trans_table[324] = new int[] { 170 }; trans_table[325] = new int[] { 8 }; trans_table[327] = new int[] { 8 }; trans_table[337] = new int[] { 8 }; trans_table[344] = new int[] { 13 }; trans_table[349] = new int[] { 8 }; trans_table[351] = new int[] { 8 }; trans_table[352] = new int[] { 8 }; trans_table[365] = new int[] { 63 }; trans_table[367] = new int[] { 62 }; trans_table[368] = new int[] { 62 }; trans_table[369] = new int[] { 63, 147 }; trans_table[370] = new int[] { 63, 149 }; trans_table[371] = new int[] { 61 }; trans_table[375] = new int[] { 149 }; trans_table[376] = new int[] { 149 }; trans_table[380] = new int[] { 62 }; trans_table[381] = new int[] { 147 }; trans_table[383] = new int[] { 62 }; trans_table[384] = new int[] { 63 }; trans_table[385] = new int[] { 61 }; trans_table[386] = new int[] { 61 }; trans_table[387] = new int[] { 63 }; trans_table[388] = new int[] { 63 }; trans_table[389] = new int[] { 8, 61 }; trans_table[390] = new int[] { 8, 61 }; trans_table[391] = new int[] { 8, 63 }; trans_table[392] = new int[] { 8, 63 }; trans_table[393] = new int[] { 8, 61 }; trans_table[394] = new int[] { 8, 61 }; trans_table[395] = new int[] { 8 }; trans_table[396] = new int[] { 8 }; trans_table[401] = new int[] { 8 }; trans_table[402] = new int[] { 8 }; trans_table[404] = new int[] { 8 }; trans_table[417] = new int[] { 8, 147 }; trans_table[418] = new int[] { 8 }; trans_table[419] = new int[] { 8 }; trans_table[424] = new int[] { 147 }; trans_table[425] = new int[] { 8, 147 }; trans_table[426] = new int[] { 8 }; trans_table[427] = new int[] { 8 }; trans_table[428] = new int[] { 8 }; trans_table[433] = new int[] { 147 }; trans_table[444] = new int[] { 14 }; trans_table[445] = new int[] { 14 }; trans_table[446] = new int[] { 15 }; trans_table[448] = new int[] { 16 }; trans_table[449] = new int[] { 16 }; trans_table[451] = new int[] { 69 }; trans_table[452] = new int[] { 14, 69 }; trans_table[453] = new int[] { 14, 69 }; trans_table[454] = new int[] { 69 }; trans_table[455] = new int[] { 14, 69 }; trans_table[456] = new int[] { 16, 69, 152 }; trans_table[457] = new int[] { 7, 69 }; trans_table[458] = new int[] { 7, 16, 69 }; trans_table[459] = new int[] { 7, 16, 69 }; trans_table[460] = new int[] { 7 }; trans_table[461] = new int[] { 7, 69 }; trans_table[462] = new int[] { 7, 69 }; trans_table[463] = new int[] { 69 }; trans_table[464] = new int[] { 7, 69 }; trans_table[465] = new int[] { 69 }; trans_table[466] = new int[] { 1, 69 }; trans_table[467] = new int[] { 1, 69 }; trans_table[468] = new int[] { 1, 6, 69 }; trans_table[469] = new int[] { 1, 69 }; trans_table[470] = new int[] { 1, 69 }; trans_table[471] = new int[] { 69 }; trans_table[472] = new int[] { 1, 69 }; trans_table[473] = new int[] { 1 }; trans_table[474] = new int[] { 69 }; trans_table[475] = new int[] { 154 }; trans_table[476] = new int[] { 2 }; trans_table[477] = new int[] { 2, 69 }; trans_table[478] = new int[] { 2 }; trans_table[479] = new int[] { 2 }; trans_table[480] = new int[] { 2 }; trans_table[481] = new int[] { 2 }; trans_table[482] = new int[] { 2 }; trans_table[483] = new int[] { 2 }; trans_table[486] = new int[] { 151 }; trans_table[487] = new int[] { 151 }; trans_table[488] = new int[] { 151 }; trans_table[492] = new int[] { 4 }; trans_table[493] = new int[] { 4, 69 }; trans_table[494] = new int[] { 4, 69 }; trans_table[495] = new int[] { 69 }; trans_table[496] = new int[] { 5, 69, 151 }; trans_table[497] = new int[] { 69, 151 }; trans_table[500] = new int[] { 2 }; trans_table[504] = new int[] { 190 }; trans_table[508] = new int[] { 3 }; trans_table[509] = new int[] { 3 }; trans_table[510] = new int[] { 3, 151 }; trans_table[511] = new int[] { 3 }; trans_table[512] = new int[] { 2 }; trans_table[584] = new int[] { 2 }; trans_table[586] = new int[] { 2 }; trans_table[587] = new int[] { 2 }; trans_table[588] = new int[] { 2 }; trans_table[589] = new int[] { 2 }; trans_table[590] = new int[] { 2 }; trans_table[591] = new int[] { 2 }; trans_table[596] = new int[] { 2 }; trans_table[598] = new int[] { 2 }; trans_table[615] = new int[] { 2 }; trans_table[616] = new int[] { 2 }; trans_table[617] = new int[] { 2 }; trans_table[618] = new int[] { 2 }; trans_table[619] = new int[] { 2 }; trans_table[620] = new int[] { 2 }; trans_table[621] = new int[] { 2 }; trans_table[622] = new int[] { 2 }; trans_table[623] = new int[] { 2 }; trans_table[624] = new int[] { 2 }; trans_table[625] = new int[] { 2 }; trans_table[626] = new int[] { 2 }; trans_table[627] = new int[] { 2 }; trans_table[628] = new int[] { 2 }; trans_table[631] = new int[] { 2 }; trans_table[632] = new int[] { 2 }; trans_table[633] = new int[] { 2 }; trans_table[634] = new int[] { 2 }; trans_table[635] = new int[] { 2 }; trans_table[636] = new int[] { 2 }; trans_table[645] = new int[] { 2 }; trans_table[646] = new int[] { 2 }; trans_table[647] = new int[] { 2 }; trans_table[648] = new int[] { 2 }; trans_table[649] = new int[] { 2 }; trans_table[650] = new int[] { 2 }; trans_table[651] = new int[] { 2 }; trans_table[652] = new int[] { 2 }; trans_table[666] = new int[] { 2 }; trans_table[761] = new int[] { 2 }; trans_table[763] = new int[] { 2 }; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using Autofac.Features.Metadata; using Orchard.Environment.Extensions.Models; namespace Orchard.UI.Resources { public class ResourceManager : IResourceManager, IUnitOfWorkDependency { private readonly Dictionary<Tuple<String, String>, RequireSettings> _required = new Dictionary<Tuple<String, String>, RequireSettings>(); private readonly List<LinkEntry> _links = new List<LinkEntry>(); private readonly Dictionary<string, MetaEntry> _metas = new Dictionary<string, MetaEntry> { { "generator", new MetaEntry { Content = "Orchard", Name = "generator" } } }; private readonly Dictionary<string, IList<ResourceRequiredContext>> _builtResources = new Dictionary<string, IList<ResourceRequiredContext>>(StringComparer.OrdinalIgnoreCase); private readonly IEnumerable<Meta<IResourceManifestProvider>> _providers; private ResourceManifest _dynamicManifest; private List<String> _headScripts; private List<String> _footScripts; private IEnumerable<IResourceManifest> _manifests; private const string NotIE = "!IE"; private static string ToAppRelativePath(string resourcePath) { if (!String.IsNullOrEmpty(resourcePath) && !Uri.IsWellFormedUriString(resourcePath, UriKind.Absolute)) { resourcePath = VirtualPathUtility.ToAppRelative(resourcePath); } return resourcePath; } private static string FixPath(string resourcePath, string relativeFromPath) { if (!String.IsNullOrEmpty(resourcePath) && !VirtualPathUtility.IsAbsolute(resourcePath) && !Uri.IsWellFormedUriString(resourcePath, UriKind.Absolute)) { // appears to be a relative path (e.g. 'foo.js' or '../foo.js', not "/foo.js" or "http://..") if (String.IsNullOrEmpty(relativeFromPath)) { throw new InvalidOperationException("ResourcePath cannot be relative unless a base relative path is also provided."); } resourcePath = VirtualPathUtility.ToAbsolute(VirtualPathUtility.Combine(relativeFromPath, resourcePath)); } return resourcePath; } private static TagBuilder GetTagBuilder(ResourceDefinition resource, string url) { var tagBuilder = new TagBuilder(resource.TagName); tagBuilder.MergeAttributes(resource.TagBuilder.Attributes); if (!String.IsNullOrEmpty(resource.FilePathAttributeName)) { if (!String.IsNullOrEmpty(url)) { if (VirtualPathUtility.IsAppRelative(url)) { url = VirtualPathUtility.ToAbsolute(url); } tagBuilder.MergeAttribute(resource.FilePathAttributeName, url, true); } } return tagBuilder; } public static void WriteResource(TextWriter writer, ResourceDefinition resource, string url, string condition, Dictionary<string, string> attributes) { if (!string.IsNullOrEmpty(condition)) { if (condition == NotIE) { writer.WriteLine("<!--[if " + condition + "]>-->"); } else { writer.WriteLine("<!--[if " + condition + "]>"); } } var tagBuilder = GetTagBuilder(resource, url); if (attributes != null) { // todo: try null value tagBuilder.MergeAttributes(attributes, true); } writer.WriteLine(tagBuilder.ToString(resource.TagRenderMode)); if (!string.IsNullOrEmpty(condition)) { if (condition == NotIE) { writer.WriteLine("<!--<![endif]-->"); } else { writer.WriteLine("<![endif]-->"); } } } public ResourceManager(IEnumerable<Meta<IResourceManifestProvider>> resourceProviders) { _providers = resourceProviders; } public IEnumerable<IResourceManifest> ResourceProviders { get { if (_manifests == null) { var builder = new ResourceManifestBuilder(); foreach (var provider in _providers) { builder.Feature = provider.Metadata.ContainsKey("Feature") ? (Feature)provider.Metadata["Feature"] : null; provider.Value.BuildManifests(builder); } _manifests = builder.ResourceManifests; } return _manifests; } } public virtual ResourceManifest DynamicResources { get { return _dynamicManifest ?? (_dynamicManifest = new ResourceManifest()); } } public virtual RequireSettings Require(string resourceType, string resourceName) { if (resourceType == null) { throw new ArgumentNullException("resourceType"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } RequireSettings settings; var key = new Tuple<string, string>(resourceType, resourceName); if (!_required.TryGetValue(key, out settings)) { settings = new RequireSettings { Type = resourceType, Name = resourceName }; _required[key] = settings; } _builtResources[resourceType] = null; return settings; } public virtual RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath) { return Include(resourceType, resourcePath, null, null); } public virtual RequireSettings Include(string resourceType, string resourcePath, string resourceDebugPath, string relativeFromPath) { if (resourceType == null) { throw new ArgumentNullException("resourceType"); } if (resourcePath == null) { throw new ArgumentNullException("resourcePath"); } if (VirtualPathUtility.IsAppRelative(resourcePath)) { // ~/ ==> convert to absolute path (e.g. /orchard/..) resourcePath = VirtualPathUtility.ToAbsolute(resourcePath); } resourcePath = FixPath(resourcePath, relativeFromPath); resourceDebugPath = FixPath(resourceDebugPath, relativeFromPath); return Require(resourceType, ToAppRelativePath(resourcePath)).Define(d => d.SetUrl(resourcePath, resourceDebugPath)); } public virtual void RegisterHeadScript(string script) { if (_headScripts == null) { _headScripts = new List<string>(); } _headScripts.Add(script); } public virtual void RegisterFootScript(string script) { if (_footScripts == null) { _footScripts = new List<string>(); } _footScripts.Add(script); } public virtual void NotRequired(string resourceType, string resourceName) { if (resourceType == null) { throw new ArgumentNullException("resourceType"); } if (resourceName == null) { throw new ArgumentNullException("resourceName"); } var key = new Tuple<string, string>(resourceType, resourceName); _builtResources[resourceType] = null; _required.Remove(key); } public virtual ResourceDefinition FindResource(RequireSettings settings) { return FindResource(settings, true); } private ResourceDefinition FindResource(RequireSettings settings, bool resolveInlineDefinitions) { // find the resource with the given type and name // that has at least the given version number. If multiple, // return the resource with the greatest version number. // If not found and an inlineDefinition is given, define the resource on the fly // using the action. var name = settings.Name ?? ""; var type = settings.Type; var resource = (from p in ResourceProviders from r in p.GetResources(type) where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase) orderby r.Value.Version descending select r.Value).FirstOrDefault(); if (resource == null && _dynamicManifest != null) { resource = (from r in _dynamicManifest.GetResources(type) where name.Equals(r.Key, StringComparison.OrdinalIgnoreCase) orderby r.Value.Version descending select r.Value).FirstOrDefault(); } if (resolveInlineDefinitions && resource == null) { // Does not seem to exist, but it's possible it is being // defined by a Define() from a RequireSettings somewhere. if (ResolveInlineDefinitions(settings.Type)) { // if any were defined, now try to find it resource = FindResource(settings, false); } } return resource; } private bool ResolveInlineDefinitions(string resourceType) { bool anyWereDefined = false; foreach (var settings in GetRequiredResources(resourceType).Where(settings => settings.InlineDefinition != null)) { // defining it on the fly var resource = FindResource(settings, false); if (resource == null) { // does not already exist, so define it resource = DynamicResources.DefineResource(resourceType, settings.Name).SetBasePath(settings.BasePath); anyWereDefined = true; } settings.InlineDefinition(resource); settings.InlineDefinition = null; } return anyWereDefined; } public virtual IEnumerable<RequireSettings> GetRequiredResources(string type) { return _required.Where(r => r.Key.Item1 == type).Select(r => r.Value); } public virtual IList<LinkEntry> GetRegisteredLinks() { return _links.AsReadOnly(); } public virtual IList<MetaEntry> GetRegisteredMetas() { return _metas.Values.ToList().AsReadOnly(); } public virtual IList<String> GetRegisteredHeadScripts() { return _headScripts == null ? null : _headScripts.AsReadOnly(); } public virtual IList<String> GetRegisteredFootScripts() { return _footScripts == null ? null : _footScripts.AsReadOnly(); } public virtual IList<ResourceRequiredContext> BuildRequiredResources(string resourceType) { IList<ResourceRequiredContext> requiredResources; if (_builtResources.TryGetValue(resourceType, out requiredResources) && requiredResources != null) { return requiredResources; } var allResources = new OrderedDictionary(); foreach (var settings in GetRequiredResources(resourceType)) { var resource = FindResource(settings); if (resource == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "A '{1}' named '{0}' could not be found.", settings.Name, settings.Type)); } ExpandDependencies(resource, settings, allResources); } requiredResources = (from DictionaryEntry entry in allResources select new ResourceRequiredContext { Resource = (ResourceDefinition)entry.Key, Settings = (RequireSettings)entry.Value }).ToList(); _builtResources[resourceType] = requiredResources; return requiredResources; } protected virtual void ExpandDependencies(ResourceDefinition resource, RequireSettings settings, OrderedDictionary allResources) { if (resource == null) { return; } // Settings is given so they can cascade down into dependencies. For example, if Foo depends on Bar, and Foo's required // location is Head, so too should Bar's location. // forge the effective require settings for this resource // (1) If a require exists for the resource, combine with it. Last settings in gets preference for its specified values. // (2) If no require already exists, form a new settings object based on the given one but with its own type/name. settings = allResources.Contains(resource) ? ((RequireSettings)allResources[resource]).Combine(settings) : new RequireSettings { Type = resource.Type, Name = resource.Name }.Combine(settings); if (resource.Dependencies != null) { var dependencies = from d in resource.Dependencies select FindResource(new RequireSettings { Type = resource.Type, Name = d }); foreach (var dependency in dependencies) { if (dependency == null) { continue; } ExpandDependencies(dependency, settings, allResources); } } allResources[resource] = settings; } public void RegisterLink(LinkEntry link) { _links.Add(link); } public void SetMeta(MetaEntry meta) { if (meta == null || String.IsNullOrEmpty(meta.Name)) { return; } _metas[meta.Name] = meta; } public void AppendMeta(MetaEntry meta, string contentSeparator) { if (meta == null || String.IsNullOrEmpty(meta.Name)) { return; } MetaEntry existingMeta; if (_metas.TryGetValue(meta.Name, out existingMeta)) { meta = MetaEntry.Combine(existingMeta, meta, contentSeparator); } _metas[meta.Name] = meta; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Orleans; using Orleans.Providers.Streams.AzureQueue; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.StreamingTests; using Xunit; namespace Tester.StreamingTests { public abstract class StreamFilteringTestsBase : OrleansTestingBase { protected Guid StreamId; protected string StreamNamespace; protected string streamProviderName; private static readonly TimeSpan timeout = TimeSpan.FromSeconds(30); protected StreamFilteringTestsBase() { StreamId = Guid.NewGuid(); StreamNamespace = Guid.NewGuid().ToString(); } // Test support functions protected async Task Test_Filter_EvenOdd(bool allCheckEven = false) { streamProviderName.Should().NotBeNull("Stream provider name not set."); // Consumers const int numConsumers = 10; var consumers = new IFilteredStreamConsumerGrain[numConsumers]; var promises = new List<Task>(); for (int loopCount = 0; loopCount < numConsumers; loopCount++) { IFilteredStreamConsumerGrain grain = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(Guid.NewGuid()); consumers[loopCount] = grain; bool isEven = allCheckEven || loopCount % 2 == 0; Task promise = grain.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, isEven); promises.Add(promise); } await Task.WhenAll(promises); // Producer IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(Guid.NewGuid()); await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 1, timeout); } // Check initial counts var sb = new StringBuilder(); int[] counts = new int[numConsumers]; for (int i = 0; i < numConsumers; i++) { counts[i] = await consumers[i].GetReceivedCount(); sb.AppendFormat("Baseline count = {0} for consumer {1}", counts[i], i); sb.AppendLine(); } logger.Info(sb.ToString()); // Get producer to send some messages for (int round = 1; round <= 10; round++) { bool roundIsEven = round % 2 == 0; await producer.SendItem(round); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout); } for (int i = 0; i < numConsumers; i++) { bool indexIsEven = i % 2 == 0; int expected = counts[i]; if (roundIsEven) { if (indexIsEven || allCheckEven) expected += 1; } else if (allCheckEven) { // No change to expected counts for odd rounds } else { if (!indexIsEven) expected += 1; } int count = await consumers[i].GetReceivedCount(); logger.Info("Received count = {0} in round {1} for consumer {2}", count, round, i); count.Should().Be(expected, "Expected count in round {0} for consumer {1}", round, i); counts[i] = expected; // Set new baseline } } } protected async Task Test_Filter_BadFunc() { streamProviderName.Should().NotBeNull("Stream provider name not set."); Guid id = Guid.NewGuid(); IFilteredStreamConsumerGrain grain = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id); try { await grain.Ping(); await grain.SubscribeWithBadFunc(id, StreamNamespace, streamProviderName); } catch (AggregateException ae) { Exception exc = ae.GetBaseException(); logger.Info("Got exception " + exc); throw exc; } } protected async Task Test_Filter_TwoObsv_Different() { streamProviderName.Should().NotBeNull("Stream provider name not set."); Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); // Same consumer grain subscribes twice, with two different filters IFilteredStreamConsumerGrain consumer = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id1); await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, false); // Odd IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(id2); await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName); int expectedCount = 1; // Producer always sends first message when it becomes active await producer.SendItem(1); expectedCount++; // One observer receives, the other does not. if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout); } int count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after first send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after first send"); await producer.SendItem(2); expectedCount++; if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 3, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after second send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); await producer.SendItem(3); expectedCount++; if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 4, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after third send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); } protected async Task Test_Filter_TwoObsv_Same() { streamProviderName.Should().NotBeNull("Stream provider name not set."); Guid id1 = Guid.NewGuid(); Guid id2 = Guid.NewGuid(); // Same consumer grain subscribes twice, with two identical filters IFilteredStreamConsumerGrain consumer = GrainClient.GrainFactory.GetGrain<IFilteredStreamConsumerGrain>(id1); await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even await consumer.BecomeConsumer(StreamId, StreamNamespace, streamProviderName, true); // Even IStreamLifecycleProducerGrain producer = GrainClient.GrainFactory.GetGrain<IStreamLifecycleProducerGrain>(id2); await producer.BecomeProducer(StreamId, StreamNamespace, streamProviderName); int expectedCount = 2; // When Producer becomes active, it always sends first message to each subscriber await producer.SendItem(1); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 2, timeout); } int count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after first send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after first send"); await producer.SendItem(2); expectedCount += 2; if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 3, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after second send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); await producer.SendItem(3); if (StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME.Equals(streamProviderName)) { // Allow some time for messages to propagate through the system await TestingUtils.WaitUntilAsync(async tryLast => await producer.GetSendCount() >= 4, timeout); } count = await consumer.GetReceivedCount(); logger.Info("Received count = {0} after third send for consumer {1}", count, consumer); count.Should().Be(expectedCount, "Expected count after second send"); } } public class StreamFilteringTests_SMS : StreamFilteringTestsBase, IClassFixture<StreamFilteringTests_SMS.Fixture> { public class Fixture : BaseTestClusterFixture { public const string StreamProvider = StreamTestsConstants.SMS_STREAM_PROVIDER_NAME; protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); options.ClusterConfiguration.AddMemoryStorageProvider("MemoryStore"); options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false); options.ClientConfiguration.AddSimpleMessageStreamProvider(StreamProvider, false); return new TestCluster(options); } } public StreamFilteringTests_SMS() { streamProviderName = Fixture.StreamProvider; } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_Basic() { await Test_Filter_EvenOdd(true); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_EvenOdd() { await Test_Filter_EvenOdd(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_BadFunc() { await Assert.ThrowsAsync(typeof(ArgumentException), () => Test_Filter_BadFunc()); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_TwoObsv_Different() { await Test_Filter_TwoObsv_Different(); } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters")] public async Task SMS_Filter_TwoObsv_Same() { await Test_Filter_TwoObsv_Same(); } } public class StreamFilteringTests_AQ : StreamFilteringTestsBase, IClassFixture<StreamFilteringTests_AQ.Fixture>, IDisposable { private readonly string deploymentId; public class Fixture : BaseTestClusterFixture { public const string StreamProvider = StreamTestsConstants.AZURE_QUEUE_STREAM_PROVIDER_NAME; protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); options.ClusterConfiguration.AddMemoryStorageProvider("MemoryStore"); options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.AddAzureQueueStreamProvider(StreamProvider); return new TestCluster(options); } public override void Dispose() { var deploymentId = this.HostedCluster.DeploymentId; base.Dispose(); AzureQueueStreamProviderUtils.DeleteAllUsedAzureQueues(StreamProvider, deploymentId, TestDefaultConfiguration.DataConnectionString) .Wait(); } } public StreamFilteringTests_AQ(Fixture fixture) { this.deploymentId = fixture.HostedCluster.DeploymentId; streamProviderName = Fixture.StreamProvider; } public virtual void Dispose() { AzureQueueStreamProviderUtils.ClearAllUsedAzureQueues( streamProviderName, this.deploymentId, TestDefaultConfiguration.DataConnectionString).Wait(); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_Basic() { await Test_Filter_EvenOdd(true); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_EvenOdd() { await Test_Filter_EvenOdd(); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_BadFunc() { await Assert.ThrowsAsync(typeof(ArgumentException), () => Test_Filter_BadFunc()); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_TwoObsv_Different() { await Test_Filter_TwoObsv_Different(); } [Fact, TestCategory("Functional"), TestCategory("Streaming"), TestCategory("Filters"), TestCategory("Azure")] public async Task AQ_Filter_TwoObsv_Same() { await Test_Filter_TwoObsv_Same(); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections; using System.Reflection; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Numerics; using System.Text; using Scriban.Functions; using Scriban.Helpers; using Scriban.Parsing; using Scriban.Runtime; namespace Scriban.Syntax { [ScriptSyntax("binary expression", "<expression> operator <expression>")] public partial class ScriptBinaryExpression : ScriptExpression { private ScriptExpression _left; private ScriptToken _operatorToken; private ScriptExpression _right; public ScriptExpression Left { get => _left; set => ParentToThis(ref _left, value); } public ScriptBinaryOperator Operator { get; set; } public ScriptToken OperatorToken { get => _operatorToken; set => ParentToThis(ref _operatorToken, value); } public string OperatorAsText => OperatorToken?.Value ?? Operator.ToText(); public ScriptExpression Right { get => _right; set => ParentToThis(ref _right, value); } public override object Evaluate(TemplateContext context) { var leftValue = context.Evaluate(Left); switch (Operator) { case ScriptBinaryOperator.And: { var leftBoolValue = context.ToBool(Left.Span, leftValue); if (!leftBoolValue) return false; var rightValue = context.Evaluate(Right); var rightBoolValue = context.ToBool(Right.Span, rightValue); return leftBoolValue && rightBoolValue; } case ScriptBinaryOperator.Or: { var leftBoolValue = context.ToBool(Left.Span, leftValue); if (leftBoolValue) return true; var rightValue = context.Evaluate(Right); return context.ToBool(Right.Span, rightValue); } default: { var rightValue = context.Evaluate(Right); return Evaluate(context, OperatorToken?.Span ?? Span , Operator, Left.Span, leftValue, Right.Span, rightValue); } } } public override void PrintTo(ScriptPrinter printer) { printer.Write(Left); // Because a-b is a variable name, we need to transform binary op a-b to a - b if (Operator == ScriptBinaryOperator.Substract && !printer.PreviousHasSpace) { printer.ExpectSpace(); } if (OperatorToken != null) { printer.Write(OperatorToken); } else { printer.Write(Operator.ToText()); } if (Operator == ScriptBinaryOperator.Substract) { printer.ExpectSpace(); } printer.Write(Right); } public override bool CanHaveLeadingTrivia() { return false; } public static object Evaluate(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, object leftValue, object rightValue) { return Evaluate(context, span, op, span, leftValue, span, rightValue); } public static object Evaluate(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue) { if (op == ScriptBinaryOperator.EmptyCoalescing) { return leftValue ?? rightValue; } switch (op) { case ScriptBinaryOperator.LiquidHasKey: { var leftDict = leftValue as IDictionary<string, object>; if (leftDict != null) { return ObjectFunctions.HasKey(leftDict, context.ObjectToString(rightValue)); } } break; case ScriptBinaryOperator.LiquidHasValue: { var leftDict = leftValue as IDictionary<string, object>; if (leftDict != null) { return ObjectFunctions.HasValue(leftDict, context.ObjectToString(rightValue)); } } break; case ScriptBinaryOperator.CompareEqual: case ScriptBinaryOperator.CompareNotEqual: case ScriptBinaryOperator.CompareGreater: case ScriptBinaryOperator.CompareLess: case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLessOrEqual: case ScriptBinaryOperator.Add: case ScriptBinaryOperator.Substract: case ScriptBinaryOperator.Multiply: case ScriptBinaryOperator.Divide: case ScriptBinaryOperator.DivideRound: case ScriptBinaryOperator.Modulus: case ScriptBinaryOperator.Power: case ScriptBinaryOperator.BinaryAnd: case ScriptBinaryOperator.BinaryOr: case ScriptBinaryOperator.ShiftLeft: case ScriptBinaryOperator.ShiftRight: case ScriptBinaryOperator.RangeInclude: case ScriptBinaryOperator.RangeExclude: case ScriptBinaryOperator.LiquidContains: case ScriptBinaryOperator.LiquidStartsWith: case ScriptBinaryOperator.LiquidEndsWith: try { if (leftValue is string || rightValue is string || leftValue is char || rightValue is char) { if (leftValue is char leftChar) leftValue = leftChar.ToString(context.CurrentCulture); if (rightValue is char rightChar) rightValue = rightChar.ToString(CultureInfo.InvariantCulture); return CalculateToString(context, span, op, leftSpan, leftValue, rightSpan, rightValue); } else if (leftValue == EmptyScriptObject.Default || rightValue == EmptyScriptObject.Default) { return CalculateEmpty(context, span, op, leftSpan, leftValue, rightSpan, rightValue); } // Allow custom binary operation else if (leftValue is IScriptCustomBinaryOperation leftBinaryOp) { if (leftBinaryOp.TryEvaluate(context, span, op, leftSpan, leftValue, rightSpan, rightValue, out var result)) { return result; } break; } else if (rightValue is IScriptCustomBinaryOperation rightBinaryOp) { if (rightBinaryOp.TryEvaluate(context, span, op, leftSpan, leftValue, rightSpan, rightValue, out var result)) { return result; } break; } else { return CalculateOthers(context, span, op, leftSpan, leftValue, rightSpan, rightValue); } } catch (Exception ex) when(!(ex is ScriptRuntimeException)) { throw new ScriptRuntimeException(span, ex.Message); } } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not supported between `{leftValue}` and `{rightValue}`"); } private static object CalculateEmpty(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue) { var leftIsEmptyObject = leftValue == EmptyScriptObject.Default; var rightIsEmptyObject = rightValue == EmptyScriptObject.Default; // If both are empty, we return false or empty if (leftIsEmptyObject && rightIsEmptyObject) { switch (op) { case ScriptBinaryOperator.CompareEqual: case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLessOrEqual: return true; case ScriptBinaryOperator.CompareNotEqual: case ScriptBinaryOperator.CompareGreater: case ScriptBinaryOperator.CompareLess: case ScriptBinaryOperator.LiquidContains: case ScriptBinaryOperator.LiquidStartsWith: case ScriptBinaryOperator.LiquidEndsWith: return false; } return EmptyScriptObject.Default; } var against = leftIsEmptyObject ? rightValue : leftValue; var againstEmpty = context.IsEmpty(span, against); switch (op) { case ScriptBinaryOperator.CompareEqual: return againstEmpty; case ScriptBinaryOperator.CompareNotEqual: return againstEmpty is bool ? !(bool)againstEmpty : againstEmpty; case ScriptBinaryOperator.CompareGreater: case ScriptBinaryOperator.CompareLess: return false; case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLessOrEqual: return againstEmpty; case ScriptBinaryOperator.Add: case ScriptBinaryOperator.Substract: case ScriptBinaryOperator.Multiply: case ScriptBinaryOperator.Power: case ScriptBinaryOperator.BinaryOr: case ScriptBinaryOperator.BinaryAnd: case ScriptBinaryOperator.Divide: case ScriptBinaryOperator.DivideRound: case ScriptBinaryOperator.Modulus: case ScriptBinaryOperator.RangeInclude: case ScriptBinaryOperator.RangeExclude: return EmptyScriptObject.Default; case ScriptBinaryOperator.LiquidContains: case ScriptBinaryOperator.LiquidStartsWith: case ScriptBinaryOperator.LiquidEndsWith: return false; } throw new ScriptRuntimeException(span, $"Operator `{op.ToText()}` is not implemented for `{(leftIsEmptyObject ? "empty" : leftValue)}` / `{(rightIsEmptyObject ? "empty" : rightValue)}`"); } private static object CalculateToString(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object left, SourceSpan rightSpan, object right) { switch (op) { case ScriptBinaryOperator.Add: return context.ObjectToString(left) + context.ObjectToString(right); case ScriptBinaryOperator.Multiply: var spanMultiplier = rightSpan; if (right is string) { var temp = left; left = right; right = temp; spanMultiplier = leftSpan; } // Don't fail when converting int value; try { value = context.ToInt(span, right); } catch { throw new ScriptRuntimeException(spanMultiplier, $"Expecting an integer. The operator `{op.ToText()}` is not supported for the expression. Only working on string x int or int x string"); // unit test: 112-binary-string-error1 } var leftText = context.ObjectToString(left); var builder = new StringBuilder(); for (int i = 0; i < value; i++) { builder.Append(leftText); } return builder.ToString(); case ScriptBinaryOperator.CompareEqual: return context.ObjectToString(left) == context.ObjectToString(right); case ScriptBinaryOperator.CompareNotEqual: return context.ObjectToString(left) != context.ObjectToString(right); case ScriptBinaryOperator.CompareGreater: return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) > 0; case ScriptBinaryOperator.CompareLess: return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) < 0; case ScriptBinaryOperator.CompareGreaterOrEqual: return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) >= 0; case ScriptBinaryOperator.CompareLessOrEqual: return context.ObjectToString(left).CompareTo(context.ObjectToString(right)) <= 0; case ScriptBinaryOperator.LiquidContains: return context.ObjectToString(left).Contains(context.ObjectToString(right)); case ScriptBinaryOperator.LiquidStartsWith: return context.ObjectToString(left).StartsWith(context.ObjectToString(right)); case ScriptBinaryOperator.LiquidEndsWith: return context.ObjectToString(left).EndsWith(context.ObjectToString(right)); default: break; } // unit test: 150-range-expression-error1.out.txt throw new ScriptRuntimeException(span, $"Operator `{op.ToText()}` is not supported on string objects"); // unit test: 112-binary-string-error2.txt } private static IEnumerable<object> RangeInclude(long left, long right) { // unit test: 150-range-expression.txt if (left < right) { for (var i = left; i <= right; i++) { yield return FitToBestInteger(i); } } else { for (var i = left; i >= right; i--) { yield return FitToBestInteger(i); } } } private static IEnumerable<object> RangeExclude(long left, long right) { // unit test: 150-range-expression.txt if (left < right) { for (var i = left; i < right; i++) { yield return FitToBestInteger(i); } } else { for (var i = left; i > right; i--) { yield return FitToBestInteger(i); } } } private static IEnumerable<object> RangeInclude(BigInteger left, BigInteger right) { // unit test: 150-range-expression.txt if (left < right) { for (var i = left; i <= right; i++) { yield return FitToBestInteger(i); } } else { for (var i = left; i >= right; i--) { yield return FitToBestInteger(i); } } } private static IEnumerable<object> RangeExclude(BigInteger left, BigInteger right) { // unit test: 150-range-expression.txt if (left < right) { for (var i = left; i < right; i++) { yield return FitToBestInteger(i); } } else { for (var i = left; i > right; i--) { yield return FitToBestInteger(i); } } } private static object CalculateOthers(TemplateContext context, SourceSpan span, ScriptBinaryOperator op, SourceSpan leftSpan, object leftValue, SourceSpan rightSpan, object rightValue) { // Both values are null, applies the relevant binary ops if (leftValue == null && rightValue == null) { switch (op) { case ScriptBinaryOperator.CompareEqual: return true; case ScriptBinaryOperator.CompareNotEqual: return false; case ScriptBinaryOperator.CompareGreater: case ScriptBinaryOperator.CompareLess: case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLessOrEqual: if (context.UseScientific) throw new ScriptRuntimeException(span, $"Both left and right expressions are null. Cannot perform this operation on null values."); return false; case ScriptBinaryOperator.Add: case ScriptBinaryOperator.Substract: case ScriptBinaryOperator.Multiply: case ScriptBinaryOperator.Divide: case ScriptBinaryOperator.Power: case ScriptBinaryOperator.BinaryOr: case ScriptBinaryOperator.BinaryAnd: case ScriptBinaryOperator.ShiftLeft: case ScriptBinaryOperator.ShiftRight: case ScriptBinaryOperator.DivideRound: case ScriptBinaryOperator.Modulus: case ScriptBinaryOperator.RangeInclude: case ScriptBinaryOperator.RangeExclude: if (context.UseScientific) throw new ScriptRuntimeException(span, $"Both left and right expressions are null. Cannot perform this operation on null values."); return null; case ScriptBinaryOperator.LiquidContains: case ScriptBinaryOperator.LiquidStartsWith: case ScriptBinaryOperator.LiquidEndsWith: return false; } return null; } // One value is null if (leftValue == null || rightValue == null) { switch (op) { case ScriptBinaryOperator.CompareEqual: return false; case ScriptBinaryOperator.CompareNotEqual: return true; case ScriptBinaryOperator.CompareGreater: case ScriptBinaryOperator.CompareLess: case ScriptBinaryOperator.CompareGreaterOrEqual: case ScriptBinaryOperator.CompareLessOrEqual: case ScriptBinaryOperator.LiquidContains: case ScriptBinaryOperator.LiquidStartsWith: case ScriptBinaryOperator.LiquidEndsWith: if (context.UseScientific) throw new ScriptRuntimeException(span, $"The {(leftValue == null ? "left" : "right")} expression is null. Cannot perform this operation on a null value."); return false; case ScriptBinaryOperator.Add: case ScriptBinaryOperator.Substract: case ScriptBinaryOperator.Multiply: case ScriptBinaryOperator.Divide: case ScriptBinaryOperator.DivideRound: case ScriptBinaryOperator.Power: case ScriptBinaryOperator.BinaryOr: case ScriptBinaryOperator.BinaryAnd: case ScriptBinaryOperator.ShiftLeft: case ScriptBinaryOperator.ShiftRight: case ScriptBinaryOperator.Modulus: case ScriptBinaryOperator.RangeInclude: case ScriptBinaryOperator.RangeExclude: if (context.UseScientific) throw new ScriptRuntimeException(span, $"The {(leftValue == null ? "left" : "right")} expression is null. Cannot perform this operation on a null value."); return null; } return null; } var leftType = leftValue.GetType(); var rightType = rightValue.GetType(); // The order matters: decimal, double, float, long, int if (leftType == typeof(decimal)) { var rightDecimal = (decimal)context.ToObject(span, rightValue, typeof(decimal)); return CalculateDecimal(op, span, (decimal)leftValue, rightDecimal); } if (rightType == typeof(decimal)) { var leftDecimal = (decimal)context.ToObject(span, leftValue, typeof(decimal)); return CalculateDecimal(op, span, leftDecimal, (decimal)rightValue); } if (leftType == typeof(double)) { var rightDouble = (double)context.ToObject(span, rightValue, typeof(double)); return CalculateDouble(op, span, (double)leftValue, rightDouble); } if (rightType == typeof(double)) { var leftDouble = (double)context.ToObject(span, leftValue, typeof(double)); return CalculateDouble(op, span, leftDouble, (double)rightValue); } if (leftType == typeof(float)) { var rightFloat = (float)context.ToObject(span, rightValue, typeof(float)); return CalculateFloat(op, span, (float)leftValue, rightFloat); } if (rightType == typeof(float)) { var leftFloat = (float)context.ToObject(span, leftValue, typeof(float)); return CalculateFloat(op, span, leftFloat, (float)rightValue); } if (leftType == typeof(BigInteger)) { var rightBig = (BigInteger)context.ToObject(span, rightValue, typeof(BigInteger)); return CalculateBigInteger(op, span, (BigInteger)leftValue, rightBig); } if (rightType == typeof(BigInteger)) { var leftBig = (BigInteger)context.ToObject(span, leftValue, typeof(BigInteger)); return CalculateBigInteger(op, span, leftBig, (BigInteger)rightValue); } if (leftType == typeof(long)) { var rightLong = (long)context.ToObject(span, rightValue, typeof(long)); return CalculateLong(op, span, (long)leftValue, rightLong); } if (rightType == typeof(long)) { var leftLong = (long)context.ToObject(span, leftValue, typeof(long)); return CalculateLong(op, span, leftLong, (long)rightValue); } if (leftType == typeof(long)) { var rightLong = (long)context.ToObject(span, rightValue, typeof(long)); return CalculateLong(op, span, (long)leftValue, rightLong); } if (rightType == typeof(long)) { var leftLong = (long)context.ToObject(span, leftValue, typeof(long)); return CalculateLong(op, span, leftLong, (long)rightValue); } if (leftType == typeof(int) || (leftType != null && leftType.IsEnum)) { var rightInt = (int)context.ToObject(span, rightValue, typeof(int)); return CalculateInt(op, span, (int)leftValue, rightInt); } if (rightType == typeof(int) || (rightType != null && rightType.IsEnum)) { var leftInt = (int)context.ToObject(span, leftValue, typeof(int)); return CalculateInt(op, span, leftInt, (int)rightValue); } if (leftType == typeof(bool)) { var rightBool = (bool)context.ToObject(span, rightValue, typeof(bool)); return CalculateBool(op, span, (bool)leftValue, rightBool); } if (rightType == typeof(bool)) { var leftBool = (bool)context.ToObject(span, leftValue, typeof(bool)); return CalculateBool(op, span, leftBool, (bool)rightValue); } if (leftType == typeof(DateTime) && rightType == typeof(DateTime)) { return CalculateDateTime(op, span, (DateTime)leftValue, (DateTime)rightValue); } if (leftType == typeof(DateTime) && rightType == typeof(TimeSpan)) { return CalculateDateTime(op, span, (DateTime)leftValue, (TimeSpan)rightValue); } //allows to check equality for objects with not only primitive types if (op == ScriptBinaryOperator.CompareEqual) { return leftValue.Equals(rightValue); } throw new ScriptRuntimeException(span, $"Unsupported types `{leftValue}/{context.GetTypeName(leftValue)}` {op.ToText()} `{rightValue}/{context.GetTypeName(rightValue)}` for binary operation"); } private static object CalculateInt(ScriptBinaryOperator op, SourceSpan span, int left, int right) { return FitToBestInteger(CalculateLongWithInt(op, span, left, right)); } private static object FitToBestInteger(object value) { if (value is int) return value; if (value is long longValue) { return FitToBestInteger(longValue); } if (value is BigInteger bigInt) { return FitToBestInteger(bigInt); } return value; } private static object FitToBestInteger(long longValue) { if (longValue >= int.MinValue && longValue <= int.MaxValue) return (int)longValue; return longValue; } private static object FitToBestInteger(BigInteger bigInt) { if (bigInt >= int.MinValue && bigInt <= int.MaxValue) return (int)bigInt; if (bigInt >= long.MinValue && bigInt <= long.MaxValue) return (long)bigInt; return bigInt; } /// <summary> /// Use this value as a maximum integer /// </summary> private static readonly BigInteger MaxBigInteger = BigInteger.One << 1024 * 1024; private static object CalculateLongWithInt(ScriptBinaryOperator op, SourceSpan span, int leftInt, int rightInt) { long left = leftInt; long right = rightInt; switch (op) { case ScriptBinaryOperator.Add: return left + right; case ScriptBinaryOperator.Substract: return left - right; case ScriptBinaryOperator.Multiply: return left * right; case ScriptBinaryOperator.Divide: return (double)left / (double)right; case ScriptBinaryOperator.DivideRound: return left / right; case ScriptBinaryOperator.ShiftLeft: return (BigInteger)left << (int)right; case ScriptBinaryOperator.ShiftRight: return (BigInteger)left >> (int)right; case ScriptBinaryOperator.Power: if (right < 0) { return Math.Pow(left, right); } else { return BigInteger.ModPow(left, right, MaxBigInteger); } case ScriptBinaryOperator.BinaryOr: return left | right; case ScriptBinaryOperator.BinaryAnd: return left & right; case ScriptBinaryOperator.Modulus: return left % right; case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; case ScriptBinaryOperator.CompareGreater: return left > right; case ScriptBinaryOperator.CompareLess: return left < right; case ScriptBinaryOperator.CompareGreaterOrEqual: return left >= right; case ScriptBinaryOperator.CompareLessOrEqual: return left <= right; case ScriptBinaryOperator.RangeInclude: return new ScriptRange(RangeInclude(left, right)); case ScriptBinaryOperator.RangeExclude: return new ScriptRange(RangeExclude(left, right)); } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for long<->long"); } private static object CalculateLong(ScriptBinaryOperator op, SourceSpan span, long left, long right) { return CalculateBigInteger(op, span, new BigInteger(left), new BigInteger(right)); } private static object CalculateBigInteger(ScriptBinaryOperator op, SourceSpan span, BigInteger left, BigInteger right) { return FitToBestInteger(CalculateBigIntegerNoFit(op, span, left, right)); } private static object CalculateBigIntegerNoFit(ScriptBinaryOperator op, SourceSpan span, BigInteger left, BigInteger right) { switch (op) { case ScriptBinaryOperator.Add: return left + right; case ScriptBinaryOperator.Substract: return left - right; case ScriptBinaryOperator.Multiply: return left * right; case ScriptBinaryOperator.Divide: return (double)left / (double)right; case ScriptBinaryOperator.DivideRound: return left / right; case ScriptBinaryOperator.ShiftLeft: return left << (int)right; case ScriptBinaryOperator.ShiftRight: return left >> (int)right; case ScriptBinaryOperator.Power: if (right < 0) { return Math.Pow((double)left, (double)right); } else { return BigInteger.ModPow(left, right, MaxBigInteger); } case ScriptBinaryOperator.BinaryOr: return left | right; case ScriptBinaryOperator.BinaryAnd: return left & right; case ScriptBinaryOperator.Modulus: return left % right; case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; case ScriptBinaryOperator.CompareGreater: return left > right; case ScriptBinaryOperator.CompareLess: return left < right; case ScriptBinaryOperator.CompareGreaterOrEqual: return left >= right; case ScriptBinaryOperator.CompareLessOrEqual: return left <= right; case ScriptBinaryOperator.RangeInclude: return new ScriptRange(RangeInclude(left, right)); case ScriptBinaryOperator.RangeExclude: return new ScriptRange(RangeExclude(left, right)); } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for long<->long"); } private static object CalculateDouble(ScriptBinaryOperator op, SourceSpan span, double left, double right) { switch (op) { case ScriptBinaryOperator.Add: return left + right; case ScriptBinaryOperator.Substract: return left - right; case ScriptBinaryOperator.Multiply: return left * right; case ScriptBinaryOperator.Divide: return left / right; case ScriptBinaryOperator.DivideRound: return Math.Round(left / right); case ScriptBinaryOperator.ShiftLeft: return left * Math.Pow(2, right); case ScriptBinaryOperator.ShiftRight: return left / Math.Pow(2, right); case ScriptBinaryOperator.Power: return Math.Pow(left, right); case ScriptBinaryOperator.Modulus: return left % right; case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; case ScriptBinaryOperator.CompareGreater: return left > right; case ScriptBinaryOperator.CompareLess: return left < right; case ScriptBinaryOperator.CompareGreaterOrEqual: return left >= right; case ScriptBinaryOperator.CompareLessOrEqual: return left <= right; } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for double<->double"); } private static object CalculateDecimal(ScriptBinaryOperator op, SourceSpan span, decimal left, decimal right) { switch (op) { case ScriptBinaryOperator.Add: return left + right; case ScriptBinaryOperator.Substract: return left - right; case ScriptBinaryOperator.Multiply: return left * right; case ScriptBinaryOperator.Divide: return left / right; case ScriptBinaryOperator.DivideRound: return Math.Round(left / right); case ScriptBinaryOperator.ShiftLeft: return left * (decimal) Math.Pow(2, (double) right); case ScriptBinaryOperator.ShiftRight: return left / (decimal) Math.Pow(2, (double) right); case ScriptBinaryOperator.Power: return (decimal)Math.Pow((double)left, (double)right); case ScriptBinaryOperator.Modulus: return left % right; case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; case ScriptBinaryOperator.CompareGreater: return left > right; case ScriptBinaryOperator.CompareLess: return left < right; case ScriptBinaryOperator.CompareGreaterOrEqual: return left >= right; case ScriptBinaryOperator.CompareLessOrEqual: return left <= right; } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for decimal<->decimal"); } private static object CalculateFloat(ScriptBinaryOperator op, SourceSpan span, float left, float right) { switch (op) { case ScriptBinaryOperator.Add: return left + right; case ScriptBinaryOperator.Substract: return left - right; case ScriptBinaryOperator.Multiply: return left * right; case ScriptBinaryOperator.Divide: return (float)left / right; case ScriptBinaryOperator.DivideRound: return (float)(int)(left / right); #if NETSTANDARD2_1 case ScriptBinaryOperator.Power: return MathF.Pow(left, right); #else case ScriptBinaryOperator.Power: return (float)Math.Pow(left, right); #endif #if NETSTANDARD2_1 case ScriptBinaryOperator.ShiftLeft: return left * (float)MathF.Pow(2.0f, right); case ScriptBinaryOperator.ShiftRight: return left / (float)MathF.Pow(2.0f, right); #else case ScriptBinaryOperator.ShiftLeft: return left * (float)Math.Pow(2, right); case ScriptBinaryOperator.ShiftRight: return left / (float)Math.Pow(2, right); #endif case ScriptBinaryOperator.Modulus: return left % right; case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; case ScriptBinaryOperator.CompareGreater: return left > right; case ScriptBinaryOperator.CompareLess: return left < right; case ScriptBinaryOperator.CompareGreaterOrEqual: return left >= right; case ScriptBinaryOperator.CompareLessOrEqual: return left <= right; } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not implemented for float<->float"); } private static object CalculateDateTime(ScriptBinaryOperator op, SourceSpan span, DateTime left, DateTime right) { switch (op) { case ScriptBinaryOperator.Substract: return left - right; case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; case ScriptBinaryOperator.CompareLess: return left < right; case ScriptBinaryOperator.CompareLessOrEqual: return left <= right; case ScriptBinaryOperator.CompareGreater: return left > right; case ScriptBinaryOperator.CompareGreaterOrEqual: return left >= right; } throw new ScriptRuntimeException(span, $"The operator `{op}` is not supported for DateTime"); } private static object CalculateDateTime(ScriptBinaryOperator op, SourceSpan span, DateTime left, TimeSpan right) { switch (op) { case ScriptBinaryOperator.Add: return left + right; } throw new ScriptRuntimeException(span, $"The operator `{op}` is not supported for between <DateTime> and <TimeSpan>"); } private static object CalculateBool(ScriptBinaryOperator op, SourceSpan span, bool left, bool right) { switch (op) { case ScriptBinaryOperator.CompareEqual: return left == right; case ScriptBinaryOperator.CompareNotEqual: return left != right; } throw new ScriptRuntimeException(span, $"The operator `{op.ToText()}` is not valid for bool<->bool"); } } }
// 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 Microsoft.Win32.SafeHandles; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class ChainTests { [Fact] public static void BuildChain() { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) using (var unrelated = new X509Certificate2(TestData.DssCer)) { X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.Add(unrelated); chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; // Halfway between microsoftDotCom's NotBefore and NotAfter // This isn't a boundary condition test. chain.ChainPolicy.VerificationTime = new DateTime(2015, 10, 15, 12, 01, 01, DateTimeKind.Local); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(microsoftDotCom); Assert.True(valid, "Chain built validly"); // The chain should have 3 members Assert.Equal(3, chain.ChainElements.Count); // These are the three specific members. Assert.Equal(microsoftDotCom, chain.ChainElements[0].Certificate); Assert.Equal(microsoftDotComIssuer, chain.ChainElements[1].Certificate); Assert.Equal(microsoftDotComRoot, chain.ChainElements[2].Certificate); } } /// <summary> /// Tests that when a certificate chain has a root certification which is not trusted by the trust provider, /// Build returns false and a ChainStatus returns UntrustedRoot /// </summary> [Fact] [OuterLoop] public static void BuildChainExtraStoreUntrustedRoot() { using (var testCert = new X509Certificate2(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword)) { X509Certificate2Collection collection = new X509Certificate2Collection(); collection.Import(Path.Combine("TestData", "test.pfx"), TestData.ChainPfxPassword, X509KeyStorageFlags.DefaultKeySet); X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.AddRange(collection); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = new DateTime(2015, 9, 22, 12, 25, 0); bool valid = chain.Build(testCert); Assert.False(valid); Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.UntrustedRoot); } } public static IEnumerable<object[]> VerifyExpressionData() { // The test will be using the chain for TestData.MicrosoftDotComSslCertBytes // The leaf cert (microsoft.com) is valid from 2014-10-15 00:00:00Z to 2016-10-15 23:59:59Z DateTime[] validTimes = { // The NotBefore value new DateTime(2014, 10, 15, 0, 0, 0, DateTimeKind.Utc), // One second before the NotAfter value new DateTime(2016, 10, 15, 23, 59, 58, DateTimeKind.Utc), }; // The NotAfter value as a boundary condition differs on Windows and OpenSSL. // Windows considers it valid (<= NotAfter). // OpenSSL considers it invalid (< NotAfter), with a comment along the lines of // "it'll be invalid in a millisecond, why bother with the <=" // So that boundary condition is not being tested. DateTime[] invalidTimes = { // One second before the NotBefore time new DateTime(2014, 10, 14, 23, 59, 59, DateTimeKind.Utc), // One second after the NotAfter time new DateTime(2016, 10, 16, 0, 0, 0, DateTimeKind.Utc), }; List<object[]> testCases = new List<object[]>((validTimes.Length + invalidTimes.Length) * 3); // Build (date, result, kind) tuples. The kind is used to help describe the test case. // The DateTime format that xunit uses does show a difference in the DateTime itself, but // having the Kind be a separate parameter just helps. foreach (DateTime utcTime in validTimes) { DateTime local = utcTime.ToLocalTime(); DateTime unspecified = new DateTime(local.Ticks); testCases.Add(new object[] { utcTime, true, utcTime.Kind }); testCases.Add(new object[] { local, true, local.Kind }); testCases.Add(new object[] { unspecified, true, unspecified.Kind }); } foreach (DateTime utcTime in invalidTimes) { DateTime local = utcTime.ToLocalTime(); DateTime unspecified = new DateTime(local.Ticks); testCases.Add(new object[] { utcTime, false, utcTime.Kind }); testCases.Add(new object[] { local, false, local.Kind }); testCases.Add(new object[] { unspecified, false, unspecified.Kind }); } return testCases; } [Theory] [MemberData(nameof(VerifyExpressionData))] public static void VerifyExpiration_LocalTime(DateTime verificationTime, bool shouldBeValid, DateTimeKind kind) { using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) { X509Chain chain = new X509Chain(); chain.ChainPolicy.ExtraStore.Add(microsoftDotComIssuer); chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot); // Ignore anything except NotTimeValid chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags & ~X509VerificationFlags.IgnoreNotTimeValid; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = verificationTime; bool builtSuccessfully = chain.Build(microsoftDotCom); Assert.Equal(shouldBeValid, builtSuccessfully); // If we failed to build the chain, ensure that NotTimeValid is one of the reasons. if (!shouldBeValid) { Assert.Contains(chain.ChainStatus, s => s.Status == X509ChainStatusFlags.NotTimeValid); } } } [Fact] public static void BuildChain_WithApplicationPolicy_Match() { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (X509Chain chain = new X509Chain()) { // Code Signing chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3")); chain.ChainPolicy.VerificationTime = msCer.NotBefore.AddHours(2); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(msCer); Assert.True(valid, "Chain built validly"); } } [Fact] public static void BuildChain_WithApplicationPolicy_NoMatch() { using (var cert = new X509Certificate2(TestData.MsCertificate)) using (X509Chain chain = new X509Chain()) { // Gibberish. (Code Signing + ".1") chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3.1")); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2); bool valid = chain.Build(cert); Assert.False(valid, "Chain built validly"); Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue); Assert.NotSame(cert, chain.ChainElements[0].Certificate); Assert.Equal(cert, chain.ChainElements[0].Certificate); X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus; Assert.InRange(chainElementStatus.Length, 1, int.MaxValue); Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage); } } [Fact] public static void BuildChain_WithCertificatePolicy_Match() { using (var cert = new X509Certificate2(TestData.CertWithPolicies)) using (X509Chain chain = new X509Chain()) { // Code Signing chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.18.19")); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; bool valid = chain.Build(cert); Assert.True(valid, "Chain built validly"); } } [Fact] public static void BuildChain_WithCertificatePolicy_NoMatch() { using (var cert = new X509Certificate2(TestData.CertWithPolicies)) using (X509Chain chain = new X509Chain()) { chain.ChainPolicy.CertificatePolicy.Add(new Oid("2.999")); chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationTime = cert.NotBefore.AddHours(2); bool valid = chain.Build(cert); Assert.False(valid, "Chain built validly"); Assert.InRange(chain.ChainElements.Count, 1, int.MaxValue); Assert.NotSame(cert, chain.ChainElements[0].Certificate); Assert.Equal(cert, chain.ChainElements[0].Certificate); X509ChainStatus[] chainElementStatus = chain.ChainElements[0].ChainElementStatus; Assert.InRange(chainElementStatus.Length, 1, int.MaxValue); Assert.Contains(chainElementStatus, x => x.Status == X509ChainStatusFlags.NotValidForUsage); } } [Fact] public static void SafeX509ChainHandle_InvalidHandle_IsInvalid() { Assert.True(SafeX509ChainHandle.InvalidHandle.IsInvalid); } [Fact] public static void SafeX509ChainHandle_InvalidHandle_StaticObject() { SafeX509ChainHandle firstCall = SafeX509ChainHandle.InvalidHandle; SafeX509ChainHandle secondCall = SafeX509ChainHandle.InvalidHandle; Assert.Same(firstCall, secondCall); } } }
/* * @(#)Node.java 1.11 2000/08/16 * */ using System; using Comzept.Genesis.Tidy.Xml.Dom; namespace Comzept.Genesis.Tidy { /// <summary> /// Node /// /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.java for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// /// </summary> /// <author> Dave Raggett dsr@w3.org /// </author> /// <author> Andy Quick ac.quick@sympatico.ca (translation to Java) /// </author> /// <version> 1.0, 1999/05/22 /// </version> /// <version> 1.0.1, 1999/05/29 /// </version> /// <version> 1.1, 1999/06/18 Java Bean /// </version> /// <version> 1.2, 1999/07/10 Tidy Release 7 Jul 1999 /// </version> /// <version> 1.3, 1999/07/30 Tidy Release 26 Jul 1999 /// </version> /// <version> 1.4, 1999/09/04 DOM support /// </version> /// <version> 1.5, 1999/10/23 Tidy Release 27 Sep 1999 /// </version> /// <version> 1.6, 1999/11/01 Tidy Release 22 Oct 1999 /// </version> /// <version> 1.7, 1999/12/06 Tidy Release 30 Nov 1999 /// </version> /// <version> 1.8, 2000/01/22 Tidy Release 13 Jan 2000 /// </version> /// <version> 1.9, 2000/06/03 Tidy Release 30 Apr 2000 /// </version> /// <version> 1.10, 2000/07/22 Tidy Release 8 Jul 2000 /// </version> /// <version> 1.11, 2000/08/16 Tidy Release 4 Aug 2000 /// </version> /* Used for elements and text nodes element name is null for text nodes start and end are offsets into lexbuf which contains the textual content of all elements in the parse tree. parent and content allow traversal of the parse tree in any direction. attributes are represented as a linked list of AttVal nodes which hold the strings for attribute/value pairs.*/ public class Node : System.ICloneable { virtual public bool Element { get { return (this.type == StartTag || this.type == StartEndTag?true:false); } } virtual protected internal Comzept.Genesis.Tidy.Dom.Node Adapter { get { if (adapter == null) { switch (this.type) { case RootNode: adapter = new DOMDocumentImpl(this); break; case StartTag: case StartEndTag: adapter = new DOMElementImpl(this); break; case DocTypeTag: adapter = new DOMDocumentTypeImpl(this); break; case CommentTag: adapter = new DOMCommentImpl(this); break; case TextNode: adapter = new DOMTextImpl(this); break; case CDATATag: adapter = new DOMCDATASectionImpl(this); break; case ProcInsTag: adapter = new DOMProcessingInstructionImpl(this); break; default: adapter = new DOMNodeImpl(this); break; } } return adapter; } } virtual protected internal short Type { set { this.type = value; } /* --------------------- END DOM ------------------------ */ } /// <summary> /// Node type /// </summary> public const short RootNode = 0; /// <summary> /// Node type /// </summary> public const short DocTypeTag = 1; /// <summary> /// Node type /// </summary> public const short CommentTag = 2; /// <summary> /// Node type /// </summary> public const short ProcInsTag = 3; /// <summary> /// Node type /// </summary> public const short TextNode = 4; /// <summary> /// Node type /// </summary> public const short StartTag = 5; /// <summary> /// Node type /// </summary> public const short EndTag = 6; /// <summary> /// Node type /// </summary> public const short StartEndTag = 7; /// <summary> /// Node type /// </summary> public const short CDATATag = 8; /// <summary> /// Node type /// </summary> public const short SectionTag = 9; /// <summary> /// Node type /// </summary> public const short AspTag = 10; /// <summary> /// Node type /// </summary> public const short JsteTag = 11; /// <summary> /// Node type /// </summary> public const short PhpTag = 12; /// <summary> /// Node in list /// </summary> protected internal Node parent; /// <summary> /// Node in list /// </summary> protected internal Node prev; /// <summary> /// Node in list /// </summary> protected internal Node next; /// <summary> /// Node in list /// </summary> protected internal Node last; /// <summary> /// start of span onto text array /// </summary> protected internal int start; /* start of span onto text array */ /// <summary> /// end of span onto text array /// </summary> protected internal int end; /* end of span onto text array */ /// <summary> /// the text array /// </summary> protected internal sbyte[] textarray; /* the text array */ /// <summary> /// TextNode, StartTag, EndTag etc. /// </summary> protected internal short type; /* TextNode, StartTag, EndTag etc. */ /// <summary> /// true if closed by explicit end tag /// </summary> protected internal bool closed; /* true if closed by explicit end tag */ /// <summary> /// true if inferred /// </summary> protected internal bool implicit_Renamed; /* true if inferred */ /// <summary> /// true if followed by a line break /// </summary> protected internal bool linebreak; /* true if followed by a line break */ /// <summary> /// old tag when it was changed /// </summary> protected internal Dict was; /* old tag when it was changed */ /// <summary> /// tag's dictionary definition /// </summary> protected internal Dict tag; /* tag's dictionary definition */ /// <summary> /// name (null for text nodes) /// </summary> protected internal System.String element; /* name (null for text nodes) */ protected internal AttVal attributes; protected internal Node content; /// <summary> /// Ctor /// </summary> public Node():this(TextNode, null, 0, 0) { } /// <summary> /// Ctor /// </summary> /// <param name="type"></param> /// <param name="textarray"></param> /// <param name="start"></param> /// <param name="end"></param> public Node(short type, sbyte[] textarray, int start, int end) { this.parent = null; this.prev = null; this.next = null; this.last = null; this.start = start; this.end = end; this.textarray = textarray; this.type = type; this.closed = false; this.implicit_Renamed = false; this.linebreak = false; this.was = null; this.tag = null; this.element = null; this.attributes = null; this.content = null; } public Node(short type, sbyte[] textarray, int start, int end, System.String element, TagTable tt) { this.parent = null; this.prev = null; this.next = null; this.last = null; this.start = start; this.end = end; this.textarray = textarray; this.type = type; this.closed = false; this.implicit_Renamed = false; this.linebreak = false; this.was = null; this.tag = null; this.element = element; this.attributes = null; this.content = null; if (type == StartTag || type == StartEndTag || type == EndTag) tt.findTag(this); } /* used to clone heading nodes when split by an <HR> */ public virtual System.Object Clone() { Node node = new Node(); node.parent = this.parent; if (this.textarray != null) { node.textarray = new sbyte[this.end - this.start]; node.start = 0; node.end = this.end - this.start; if (node.end > 0) Array.Copy(this.textarray, this.start, node.textarray, node.start, node.end); } node.type = this.type; node.closed = this.closed; node.implicit_Renamed = this.implicit_Renamed; node.linebreak = this.linebreak; node.was = this.was; node.tag = this.tag; if (this.element != null) node.element = this.element; if (this.attributes != null) node.attributes = (AttVal) this.attributes.Clone(); return node; } public virtual AttVal getAttrByName(System.String name) { AttVal attr; for (attr = this.attributes; attr != null; attr = attr.next) { if (name != null && attr.attribute != null && attr.attribute.Equals(name)) break; } return attr; } /* default method for checking an element's attributes */ public virtual void checkAttributes(Lexer lexer) { AttVal attval; for (attval = this.attributes; attval != null; attval = attval.next) attval.checkAttribute(lexer, this); } public virtual void checkUniqueAttributes(Lexer lexer) { AttVal attval; for (attval = this.attributes; attval != null; attval = attval.next) { if (attval.asp == null && attval.php == null) attval.checkUniqueAttribute(lexer, this); } } public virtual void addAttribute(System.String name, System.String value_Renamed) { AttVal av = new AttVal(null, null, null, null, '"', name, value_Renamed); av.dict = AttributeTable.DefaultAttributeTable.findAttribute(av); if (this.attributes == null) this.attributes = av; /* append to end of attributes */ else { AttVal here = this.attributes; while (here.next != null) here = here.next; here.next = av; } } /* remove attribute from node then free it */ public virtual void removeAttribute(AttVal attr) { AttVal av; AttVal prev = null; AttVal next; for (av = this.attributes; av != null; av = next) { next = av.next; if (av == attr) { if (prev != null) prev.next = next; else this.attributes = next; } else prev = av; } } /* find doctype element */ public virtual Node findDocType() { Node node; for (node = this.content; node != null && node.type != DocTypeTag; node = node.next) ; return node; } public virtual void discardDocType() { Node node; node = findDocType(); if (node != null) { if (node.prev != null) node.prev.next = node.next; else node.parent.content = node.next; if (node.next != null) node.next.prev = node.prev; node.next = null; } } /* remove node from markup tree and discard it */ public static Node discardElement(Node element) { Node next = null; if (element != null) { next = element.next; removeNode(element); } return next; } /* insert node into markup tree */ public static void insertNodeAtStart(Node element, Node node) { node.parent = element; if (element.content == null) element.last = node; else element.content.prev = node; // AQ added 13 Apr 2000 node.next = element.content; node.prev = null; element.content = node; } /* insert node into markup tree */ public static void insertNodeAtEnd(Node element, Node node) { node.parent = element; node.prev = element.last; if (element.last != null) element.last.next = node; else element.content = node; element.last = node; } /* insert node into markup tree in pace of element which is moved to become the child of the node */ public static void insertNodeAsParent(Node element, Node node) { node.content = element; node.last = element; node.parent = element.parent; element.parent = node; if (node.parent.content == element) node.parent.content = node; if (node.parent.last == element) node.parent.last = node; node.prev = element.prev; element.prev = null; if (node.prev != null) node.prev.next = node; node.next = element.next; element.next = null; if (node.next != null) node.next.prev = node; } /* insert node into markup tree before element */ public static void insertNodeBeforeElement(Node element, Node node) { Node parent; parent = element.parent; node.parent = parent; node.next = element; node.prev = element.prev; element.prev = node; if (node.prev != null) node.prev.next = node; if (parent.content == element) parent.content = node; } /* insert node into markup tree after element */ public static void insertNodeAfterElement(Node element, Node node) { Node parent; parent = element.parent; node.parent = parent; // AQ - 13Jan2000 fix for parent == null if (parent != null && parent.last == element) parent.last = node; else { node.next = element.next; // AQ - 13Jan2000 fix for node.next == null if (node.next != null) node.next.prev = node; } element.next = node; node.prev = element; } public static void trimEmptyElement(Lexer lexer, Node element) { TagTable tt = lexer.configuration.tt; if (lexer.canPrune(element)) { if (element.type != TextNode) Report.Warning(lexer, element, null, Report.TRIM_EMPTY_ELEMENT); discardElement(element); } else if (element.tag == tt.tagP && element.content == null) { /* replace <p></p> by <br/><br/> to preserve formatting */ Node node = lexer.inferredTag("br"); Node.coerceNode(lexer, element, tt.tagBr); Node.insertNodeAfterElement(element, node); } } /* This maps <em>hello </em><strong>world</strong> to <em>hello</em> <strong>world</strong> If last child of element is a text node then trim trailing white space character moving it to after element's end tag. */ public static void trimTrailingSpace(Lexer lexer, Node element, Node last) { sbyte c; TagTable tt = lexer.configuration.tt; if (last != null && last.type == Node.TextNode && last.end > last.start) { c = lexer.lexbuf[last.end - 1]; if (c == 160 || c == (sbyte) ' ') { /* take care with <td>&nbsp;</td> */ if (element.tag == tt.tagTd || element.tag == tt.tagTh) { if (last.end > last.start + 1) last.end -= 1; } else { last.end -= 1; if (((element.tag.model & Dict.CM_INLINE) != 0) && !((element.tag.model & Dict.CM_FIELD) != 0)) lexer.insertspace = true; /* if empty string then delete from parse tree */ if (last.start == last.end) trimEmptyElement(lexer, last); } } } } /* This maps <p>hello<em> world</em> to <p>hello <em>world</em> Trims initial space, by moving it before the start tag, or if this element is the first in parent's content, then by discarding the space */ public static void trimInitialSpace(Lexer lexer, Node element, Node text) { Node prev, node; // GLP: Local fix to Bug 119789. Remove this comment when parser.c is updated. // 31-Oct-00. if (text.type == TextNode && text.textarray[text.start] == (sbyte) ' ' && (text.start < text.end)) { if (((element.tag.model & Dict.CM_INLINE) != 0) && !((element.tag.model & Dict.CM_FIELD) != 0) && element.parent.content != element) { prev = element.prev; if (prev != null && prev.type == TextNode) { if (prev.textarray[prev.end - 1] != (sbyte) ' ') prev.textarray[prev.end++] = (sbyte) ' '; ++element.start; } /* create new node */ else { node = lexer.newNode(); // Local fix for bug 228486 (GLP). This handles the case // where we need to create a preceeding text node but there are // no "slots" in textarray that we can steal from the current // element. Therefore, we create a new textarray containing // just the blank. When Tidy is fixed, this should be removed. if (element.start >= element.end) { node.start = 0; node.end = 1; node.textarray = new sbyte[1]; } else { node.start = element.start++; node.end = element.start; node.textarray = element.textarray; } node.textarray[node.start] = (sbyte) ' '; node.prev = prev; if (prev != null) prev.next = node; node.next = element; element.prev = node; node.parent = element.parent; } } /* discard the space in current node */ ++text.start; } } /* Move initial and trailing space out. This routine maps: hello<em> world</em> to hello <em>world</em> and <em>hello </em><strong>world</strong> to <em>hello</em> <strong>world</strong> */ public static void trimSpaces(Lexer lexer, Node element) { Node text = element.content; TagTable tt = lexer.configuration.tt; if (text != null && text.type == Node.TextNode && element.tag != tt.tagPre) trimInitialSpace(lexer, element, text); text = element.last; if (text != null && text.type == Node.TextNode) trimTrailingSpace(lexer, element, text); } public virtual bool isDescendantOf(Dict tag) { Node parent; for (parent = this.parent; parent != null; parent = parent.parent) { if (parent.tag == tag) return true; } return false; } /* the doctype has been found after other tags, and needs moving to before the html element */ public static void insertDocType(Lexer lexer, Node element, Node doctype) { TagTable tt = lexer.configuration.tt; Report.Warning(lexer, element, doctype, Report.DOCTYPE_AFTER_TAGS); while (element.tag != tt.tagHtml) element = element.parent; insertNodeBeforeElement(element, doctype); } public virtual Node findBody(TagTable tt) { Node node; node = this.content; while (node != null && node.tag != tt.tagHtml) node = node.next; if (node == null) return null; node = node.content; while (node != null && node.tag != tt.tagBody) node = node.next; return node; } /* unexpected content in table row is moved to just before the table in accordance with Netscape and IE. This code assumes that node hasn't been inserted into the row. */ public static void moveBeforeTable(Node row, Node node, TagTable tt) { Node table; /* first find the table element */ for (table = row.parent; table != null; table = table.parent) { if (table.tag == tt.tagTable) { if (table.parent.content == table) table.parent.content = node; node.prev = table.prev; node.next = table; table.prev = node; node.parent = table.parent; if (node.prev != null) node.prev.next = node; break; } } } /* if a table row is empty then insert an empty cell this practice is consistent with browser behavior and avoids potential problems with row spanning cells */ public static void fixEmptyRow(Lexer lexer, Node row) { Node cell; if (row.content == null) { cell = lexer.inferredTag("td"); insertNodeAtEnd(row, cell); Report.Warning(lexer, row, cell, Report.MISSING_STARTTAG); } } public static void coerceNode(Lexer lexer, Node node, Dict tag) { Node tmp = lexer.inferredTag(tag.name); Report.Warning(lexer, node, tmp, Report.OBSOLETE_ELEMENT); node.was = node.tag; node.tag = tag; node.type = StartTag; node.implicit_Renamed = true; node.element = tag.name; } /* extract a node and its children from a markup tree */ public static void removeNode(Node node) { if (node.prev != null) node.prev.next = node.next; if (node.next != null) node.next.prev = node.prev; if (node.parent != null) { if (node.parent.content == node) node.parent.content = node.next; if (node.parent.last == node) node.parent.last = node.prev; } node.parent = node.prev = node.next = null; } public static bool insertMisc(Node element, Node node) { if (node.type == CommentTag || node.type == ProcInsTag || node.type == CDATATag || node.type == SectionTag || node.type == AspTag || node.type == JsteTag || node.type == PhpTag) { insertNodeAtEnd(element, node); return true; } return false; } /* used to determine how attributes without values should be printed this was introduced to deal with user defined tags e.g. Cold Fusion */ public static bool isNewNode(Node node) { if (node != null && node.tag != null) { return ((node.tag.model & Dict.CM_NEW) != 0); } return true; } public virtual bool hasOneChild() { return (this.content != null && this.content.next == null); } /* find html element */ public virtual Node findHTML(TagTable tt) { Node node; for (node = this.content; node != null && node.tag != tt.tagHtml; node = node.next) ; return node; } public virtual Node findHEAD(TagTable tt) { Node node; node = this.findHTML(tt); if (node != null) { for (node = node.content; node != null && node.tag != tt.tagHead; node = node.next) ; } return node; } public virtual bool checkNodeIntegrity() { Node child; bool found = false; if (this.prev != null) { if (this.prev.next != this) return false; } if (this.next != null) { if (this.next.prev != this) return false; } if (this.parent != null) { if (this.prev == null && this.parent.content != this) return false; if (this.next == null && this.parent.last != this) return false; for (child = this.parent.content; child != null; child = child.next) if (child == this) { found = true; break; } if (!found) return false; } for (child = this.content; child != null; child = child.next) if (!child.checkNodeIntegrity()) return false; return true; } /* Add class="foo" to node */ public static void addClass(Node node, System.String classname) { AttVal classattr = node.getAttrByName("class"); /* if there already is a class attribute then append class name after a space */ if (classattr != null) { classattr.value_Renamed = classattr.value_Renamed + " " + classname; } /* create new class attribute */ else node.addAttribute("class", classname); } /* --------------------- DEBUG -------------------------- */ //UPGRADE_NOTE: Final was removed from the declaration of 'nodeTypeString'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly System.String[] nodeTypeString = new System.String[]{"RootNode", "DocTypeTag", "CommentTag", "ProcInsTag", "TextNode", "StartTag", "EndTag", "StartEndTag", "SectionTag", "AspTag", "PhpTag"}; public override System.String ToString() { System.String s = ""; Node n = this; while (n != null) { s += "[Node type="; s += nodeTypeString[n.type]; s += ",element="; if (n.element != null) s += n.element; else s += "null"; if (n.type == TextNode || n.type == CommentTag || n.type == ProcInsTag) { s += ",text="; if (n.textarray != null && n.start <= n.end) { s += "\""; s += Lexer.getString(n.textarray, n.start, n.end - n.start); s += "\""; } else { s += "null"; } } s += ",content="; if (n.content != null) { s += n.content.ToString(); } else s += "null"; s += "]"; if (n.next != null) s += ","; n = n.next; } return s; } /* --------------------- END DEBUG ---------------------- */ /* --------------------- DOM ---------------------------- */ protected internal Comzept.Genesis.Tidy.Dom.Node adapter = null; protected internal virtual Node cloneNode(bool deep) { Node node = (Node) this.Clone(); if (deep) { Node child; Node newChild; for (child = this.content; child != null; child = child.next) { newChild = child.cloneNode(deep); insertNodeAtEnd(node, newChild); } } return node; } } }
// 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.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); [|((IComparable)c).CompareTo(null)|]; } } ", "c.CompareTo(null)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); [|((IComparable)c).CompareTo(null)|]; } } ", "c.CompareTo(null)", false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { return null; } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } protected override SyntaxTree Parse(string text) { return SyntaxFactory.ParseSyntaxTree(text); } protected override bool IsExpressionNode(SyntaxNode node) { return node is ExpressionSyntax; } protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePair.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; Func<Diagnostic, bool> isProblem = d => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) { return new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { #if HTTP_DLL internal enum WindowsProxyUsePolicy #else public enum WindowsProxyUsePolicy #endif { DoNotUseProxy = 0, // Don't use a proxy at all. UseWinHttpProxy = 1, // Use configuration as specified by "netsh winhttp" machine config command. Automatic detect not supported. UseWinInetProxy = 2, // WPAD protocol and PAC files supported. UseCustomProxy = 3 // Use the custom proxy specified in the Proxy property. } #if HTTP_DLL internal enum CookieUsePolicy #else public enum CookieUsePolicy #endif { IgnoreCookies = 0, UseInternalCookieStoreOnly = 1, UseSpecifiedCookieContainer = 2 } #if HTTP_DLL internal class WinHttpHandler : HttpMessageHandler #else public class WinHttpHandler : HttpMessageHandler #endif { private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private object _lockObject = new object(); private bool _doManualDecompressionCheck = false; private WinInetProxyHelper _proxyHelper = null; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private CookieUsePolicy _cookieUsePolicy = CookieUsePolicy.UseInternalCookieStoreOnly; private CookieContainer _cookieContainer = null; private SslProtocols _sslProtocols = SslProtocols.None; // Use most secure protocols available. private Func< HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback = null; private bool _checkCertificateRevocationList = false; private ClientCertificateOption _clientCertificateOption = ClientCertificateOption.Manual; private X509Certificate2Collection _clientCertificates = null; // Only create collection when required. private ICredentials _serverCredentials = null; private bool _preAuthenticate = false; private WindowsProxyUsePolicy _windowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinHttpProxy; private ICredentials _defaultProxyCredentials = null; private IWebProxy _proxy = null; private int _maxConnectionsPerServer = int.MaxValue; private TimeSpan _sendTimeout = TimeSpan.FromSeconds(30); private TimeSpan _receiveHeadersTimeout = TimeSpan.FromSeconds(30); private TimeSpan _receiveDataTimeout = TimeSpan.FromSeconds(30); private int _maxResponseHeadersLength = 64 * 1024; private int _maxResponseDrainSize = 64 * 1024; private IDictionary<String, Object> _properties; // Only create dictionary when required. private volatile bool _operationStarted; private volatile bool _disposed; private SafeWinHttpHandle _sessionHandle; private WinHttpAuthHelper _authHelper = new WinHttpAuthHelper(); private static readonly DiagnosticListener s_diagnosticListener = new DiagnosticListener(HttpHandlerLoggingStrings.DiagnosticListenerName); public WinHttpHandler() { } #region Properties public bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } public int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } public DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } public CookieUsePolicy CookieUsePolicy { get { return _cookieUsePolicy; } set { if (value != CookieUsePolicy.IgnoreCookies && value != CookieUsePolicy.UseInternalCookieStoreOnly && value != CookieUsePolicy.UseSpecifiedCookieContainer) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _cookieUsePolicy = value; } } public CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } public SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } public Func< HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } public bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } public ClientCertificateOption ClientCertificateOption { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } public X509Certificate2Collection ClientCertificates { get { if (_clientCertificates == null) { _clientCertificates = new X509Certificate2Collection(); } return _clientCertificates; } } public bool PreAuthenticate { get { return _preAuthenticate; } set { _preAuthenticate = value; } } public ICredentials ServerCredentials { get { return _serverCredentials; } set { _serverCredentials = value; } } public WindowsProxyUsePolicy WindowsProxyUsePolicy { get { return _windowsProxyUsePolicy; } set { if (value != WindowsProxyUsePolicy.DoNotUseProxy && value != WindowsProxyUsePolicy.UseWinHttpProxy && value != WindowsProxyUsePolicy.UseWinInetProxy && value != WindowsProxyUsePolicy.UseCustomProxy) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _windowsProxyUsePolicy = value; } } public ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } public IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } public int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { // In WinHTTP, setting this to 0 results in it being reset to 2. // So, we'll only allow settings above 0. throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } public TimeSpan SendTimeout { get { return _sendTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _sendTimeout = value; } } public TimeSpan ReceiveHeadersTimeout { get { return _receiveHeadersTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _receiveHeadersTimeout = value; } } public TimeSpan ReceiveDataTimeout { get { return _receiveDataTimeout; } set { if (value != Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value > s_maxTimeout)) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _receiveDataTimeout = value; } } public int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } public int MaxResponseDrainSize { get { return _maxResponseDrainSize; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseDrainSize = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; if (disposing && _sessionHandle != null) { SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle); } } base.Dispose(disposing); } #if HTTP_DLL protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) #else protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) #endif { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } // Check for invalid combinations of properties. if (_proxy != null && _windowsProxyUsePolicy != WindowsProxyUsePolicy.UseCustomProxy) { throw new InvalidOperationException(SR.net_http_invalid_proxyusepolicy); } if (_windowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy && _proxy == null) { throw new InvalidOperationException(SR.net_http_invalid_proxy); } if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); Guid loggingRequestId = s_diagnosticListener.LogHttpRequest(request); SetOperationStarted(); TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>(); // Create state object and save current values of handler settings. var state = new WinHttpRequestState(); state.Tcs = tcs; state.CancellationToken = cancellationToken; state.RequestMessage = request; state.Handler = this; state.CheckCertificateRevocationList = _checkCertificateRevocationList; state.ServerCertificateValidationCallback = _serverCertificateValidationCallback; state.WindowsProxyUsePolicy = _windowsProxyUsePolicy; state.Proxy = _proxy; state.ServerCredentials = _serverCredentials; state.DefaultProxyCredentials = _defaultProxyCredentials; state.PreAuthenticate = _preAuthenticate; Task.Factory.StartNew( s => ((WinHttpRequestState)s).Handler.StartRequest(s), state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); s_diagnosticListener.LogHttpResponse(tcs.Task, loggingRequestId); return tcs.Task; } private static bool IsChunkedModeForSend(HttpRequestMessage requestMessage) { bool chunkedMode = requestMessage.Headers.TransferEncodingChunked.HasValue && requestMessage.Headers.TransferEncodingChunked.Value; HttpContent requestContent = requestMessage.Content; if (requestContent != null) { if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // Current .NET Desktop HttpClientHandler allows both headers to be specified but ends up // stripping out 'Content-Length' and using chunked semantics. WinHttpHandler will maintain // the same behavior. requestContent.Headers.ContentLength = null; } } else { if (!chunkedMode) { // Neither 'Content-Length' nor 'Transfer-Encoding: chunked' semantics was given. // Current .NET Desktop HttpClientHandler uses 'Content-Length' semantics and // buffers the content as well in some cases. But the WinHttpHandler can't access // the protected internal TryComputeLength() method of the content. So, it // will use'Transfer-Encoding: chunked' semantics. chunkedMode = true; requestMessage.Headers.TransferEncodingChunked = true; } } } else if (chunkedMode) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } return chunkedMode; } private static void AddRequestHeaders( SafeWinHttpHandle requestHandle, HttpRequestMessage requestMessage, CookieContainer cookies) { var requestHeadersBuffer = new StringBuilder(); // Manually add cookies. if (cookies != null) { string cookieHeader = WinHttpCookieContainerAdapter.GetCookieHeader(requestMessage.RequestUri, cookies); if (!string.IsNullOrEmpty(cookieHeader)) { requestHeadersBuffer.AppendLine(cookieHeader); } } // Serialize general request headers. requestHeadersBuffer.AppendLine(requestMessage.Headers.ToString()); // Serialize entity-body (content) headers. if (requestMessage.Content != null) { // TODO (#5523): Content-Length header isn't getting correctly placed using ToString() // This is a bug in HttpContentHeaders that needs to be fixed. if (requestMessage.Content.Headers.ContentLength.HasValue) { long contentLength = requestMessage.Content.Headers.ContentLength.Value; requestMessage.Content.Headers.ContentLength = null; requestMessage.Content.Headers.ContentLength = contentLength; } requestHeadersBuffer.AppendLine(requestMessage.Content.Headers.ToString()); } // Add request headers to WinHTTP request handle. if (!Interop.WinHttp.WinHttpAddRequestHeaders( requestHandle, requestHeadersBuffer, (uint)requestHeadersBuffer.Length, Interop.WinHttp.WINHTTP_ADDREQ_FLAG_ADD)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void EnsureSessionHandleExists(WinHttpRequestState state) { if (_sessionHandle == null) { lock (_lockObject) { if (_sessionHandle == null) { SafeWinHttpHandle sessionHandle; uint accessType; // If a custom proxy is specified and it is really the system web proxy // (initial WebRequest.DefaultWebProxy) then we need to update the settings // since that object is only a sentinel. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { Debug.Assert(state.Proxy != null); try { state.Proxy.GetProxy(state.RequestMessage.RequestUri); } catch (PlatformNotSupportedException) { // This is the system web proxy. state.WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy; state.Proxy = null; } } if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.DoNotUseProxy || state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy) { // Either no proxy at all or a custom IWebProxy proxy is specified. // For a custom IWebProxy, we'll need to calculate and set the proxy // on a per request handle basis using the request Uri. For now, // we set the session handle to have no proxy. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; } else if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinHttpProxy) { // Use WinHTTP per-machine proxy settings which are set using the "netsh winhttp" command. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_DEFAULT_PROXY; } else { // Use WinInet per-user proxy settings. accessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY; } WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: proxy accessType={0}", accessType); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, accessType, Interop.WinHttp.WINHTTP_NO_PROXY_NAME, Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); if (sessionHandle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); WinHttpTraceHelper.Trace("WinHttpHandler.EnsureSessionHandleExists: error={0}", lastError); if (lastError != Interop.WinHttp.ERROR_INVALID_PARAMETER) { ThrowOnInvalidHandle(sessionHandle); } // We must be running on a platform earlier than Win8.1/Win2K12R2 which doesn't support // WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY. So, we'll need to read the Wininet style proxy // settings ourself using our WinInetProxyHelper object. _proxyHelper = new WinInetProxyHelper(); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, _proxyHelper.ManualSettingsOnly ? Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY : Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, _proxyHelper.ManualSettingsOnly ? _proxyHelper.Proxy : Interop.WinHttp.WINHTTP_NO_PROXY_NAME, _proxyHelper.ManualSettingsOnly ? _proxyHelper.ProxyBypass : Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); ThrowOnInvalidHandle(sessionHandle); } uint optionAssuredNonBlockingTrue = 1; // TRUE if (!Interop.WinHttp.WinHttpSetOption( sessionHandle, Interop.WinHttp.WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS, ref optionAssuredNonBlockingTrue, (uint)Marshal.SizeOf<uint>())) { // This option is not available on downlevel Windows versions. While it improves // performance, we can ignore the error that the option is not available. int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION) { throw WinHttpException.CreateExceptionUsingError(lastError); } } SetSessionHandleOptions(sessionHandle); _sessionHandle = sessionHandle; } } } } private async void StartRequest(object obj) { WinHttpRequestState state = (WinHttpRequestState)obj; bool secureConnection = false; HttpResponseMessage responseMessage = null; Exception savedException = null; SafeWinHttpHandle connectHandle = null; if (state.CancellationToken.IsCancellationRequested) { state.Tcs.TrySetCanceled(state.CancellationToken); state.ClearSendRequestState(); return; } try { EnsureSessionHandleExists(state); // Specify an HTTP server. connectHandle = Interop.WinHttp.WinHttpConnect( _sessionHandle, state.RequestMessage.RequestUri.Host, (ushort)state.RequestMessage.RequestUri.Port, 0); ThrowOnInvalidHandle(connectHandle); connectHandle.SetParentHandle(_sessionHandle); if (state.RequestMessage.RequestUri.Scheme == UriScheme.Https) { secureConnection = true; } else { secureConnection = false; } // Try to use the requested version if a known/supported version was explicitly requested. // Otherwise, we simply use winhttp's default. string httpVersion = null; if (state.RequestMessage.Version == HttpVersion.Version10) { httpVersion = "HTTP/1.0"; } else if (state.RequestMessage.Version == HttpVersion.Version11) { httpVersion = "HTTP/1.1"; } // Create an HTTP request handle. state.RequestHandle = Interop.WinHttp.WinHttpOpenRequest( connectHandle, state.RequestMessage.Method.Method, state.RequestMessage.RequestUri.PathAndQuery, httpVersion, Interop.WinHttp.WINHTTP_NO_REFERER, Interop.WinHttp.WINHTTP_DEFAULT_ACCEPT_TYPES, secureConnection ? Interop.WinHttp.WINHTTP_FLAG_SECURE : 0); ThrowOnInvalidHandle(state.RequestHandle); state.RequestHandle.SetParentHandle(connectHandle); // Set callback function. SetStatusCallback(state.RequestHandle, WinHttpRequestCallback.StaticCallbackDelegate); // Set needed options on the request handle. SetRequestHandleOptions(state); bool chunkedModeForSend = IsChunkedModeForSend(state.RequestMessage); AddRequestHeaders( state.RequestHandle, state.RequestMessage, _cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer ? _cookieContainer : null); uint proxyAuthScheme = 0; uint serverAuthScheme = 0; state.RetryRequest = false; // The only way to abort pending async operations in WinHTTP is to close the WinHTTP handle. // We will detect a cancellation request on the cancellation token by registering a callback. // If the callback is invoked, then we begin the abort process by disposing the handle. This // will have the side-effect of WinHTTP cancelling any pending I/O and accelerating its callbacks // on the handle and thus releasing the awaiting tasks in the loop below. This helps to provide // a more timely, cooperative, cancellation pattern. using (state.CancellationToken.Register(s => ((WinHttpRequestState)s).RequestHandle.Dispose(), state)) { do { _authHelper.PreAuthenticateRequest(state, proxyAuthScheme); await InternalSendRequestAsync(state).ConfigureAwait(false); if (state.RequestMessage.Content != null) { await InternalSendRequestBodyAsync(state, chunkedModeForSend).ConfigureAwait(false); } bool receivedResponse = await InternalReceiveResponseHeadersAsync(state).ConfigureAwait(false); if (receivedResponse) { // If we're manually handling cookies, we need to add them to the container after // each response has been received. if (state.Handler.CookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer) { WinHttpCookieContainerAdapter.AddResponseCookiesToContainer(state); } _authHelper.CheckResponseForAuthentication( state, ref proxyAuthScheme, ref serverAuthScheme); } } while (state.RetryRequest); } state.CancellationToken.ThrowIfCancellationRequested(); responseMessage = WinHttpResponseParser.CreateResponseMessage(state, _doManualDecompressionCheck); // Since the headers have been read, set the "receive" timeout to be based on each read // call of the response body data. WINHTTP_OPTION_RECEIVE_TIMEOUT sets a timeout on each // lower layer winsock read. uint optionData = (uint)_receiveDataTimeout.TotalMilliseconds; SetWinHttpOption(state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_RECEIVE_TIMEOUT, ref optionData); } catch (Exception ex) { if (state.SavedException != null) { savedException = state.SavedException; } else { savedException = ex; } } finally { SafeWinHttpHandle.DisposeAndClearHandle(ref connectHandle); } // Move the main task to a terminal state. This releases any callers of SendAsync() that are awaiting. if (responseMessage != null) { state.Tcs.TrySetResult(responseMessage); } else { HandleAsyncException(state, savedException); } state.ClearSendRequestState(); } private void SetSessionHandleOptions(SafeWinHttpHandle sessionHandle) { SetSessionHandleConnectionOptions(sessionHandle); SetSessionHandleTlsOptions(sessionHandle); SetSessionHandleTimeoutOptions(sessionHandle); } private void SetSessionHandleConnectionOptions(SafeWinHttpHandle sessionHandle) { uint optionData = (uint)_maxConnectionsPerServer; SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_SERVER, ref optionData); SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_CONNS_PER_1_0_SERVER, ref optionData); } private void SetSessionHandleTlsOptions(SafeWinHttpHandle sessionHandle) { uint optionData = 0; SslProtocols sslProtocols = (_sslProtocols == SslProtocols.None) ? SecurityProtocol.DefaultSecurityProtocols : _sslProtocols; if ((sslProtocols & SslProtocols.Tls) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1; } if ((sslProtocols & SslProtocols.Tls11) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1; } if ((sslProtocols & SslProtocols.Tls12) != 0) { optionData |= Interop.WinHttp.WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2; } SetWinHttpOption(sessionHandle, Interop.WinHttp.WINHTTP_OPTION_SECURE_PROTOCOLS, ref optionData); } private void SetSessionHandleTimeoutOptions(SafeWinHttpHandle sessionHandle) { if (!Interop.WinHttp.WinHttpSetTimeouts( sessionHandle, 0, 0, (int)_sendTimeout.TotalMilliseconds, (int)_receiveHeadersTimeout.TotalMilliseconds)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void SetRequestHandleOptions(WinHttpRequestState state) { SetRequestHandleProxyOptions(state); SetRequestHandleDecompressionOptions(state.RequestHandle); SetRequestHandleRedirectionOptions(state.RequestHandle); SetRequestHandleCookieOptions(state.RequestHandle); SetRequestHandleTlsOptions(state.RequestHandle); SetRequestHandleClientCertificateOptions(state.RequestHandle, state.RequestMessage.RequestUri); SetRequestHandleCredentialsOptions(state); SetRequestHandleBufferingOptions(state.RequestHandle); } private void SetRequestHandleProxyOptions(WinHttpRequestState state) { // We've already set the proxy on the session handle if we're using no proxy or default proxy settings. // We only need to change it on the request handle if we have a specific IWebProxy or need to manually // implement Wininet-style auto proxy detection. if (state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy || state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseWinInetProxy) { var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO(); bool updateProxySettings = false; Uri uri = state.RequestMessage.RequestUri; try { if (state.Proxy != null) { Debug.Assert(state.WindowsProxyUsePolicy == WindowsProxyUsePolicy.UseCustomProxy); updateProxySettings = true; if (state.Proxy.IsBypassed(uri)) { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY; } else { proxyInfo.AccessType = Interop.WinHttp.WINHTTP_ACCESS_TYPE_NAMED_PROXY; Uri proxyUri = state.Proxy.GetProxy(uri); string proxyString = string.Format( CultureInfo.InvariantCulture, "{0}://{1}", proxyUri.Scheme, proxyUri.Authority); proxyInfo.Proxy = Marshal.StringToHGlobalUni(proxyString); } } else if (_proxyHelper != null && _proxyHelper.AutoSettingsUsed) { if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo)) { updateProxySettings = true; } } if (updateProxySettings) { GCHandle pinnedHandle = GCHandle.Alloc(proxyInfo, GCHandleType.Pinned); try { SetWinHttpOption( state.RequestHandle, Interop.WinHttp.WINHTTP_OPTION_PROXY, pinnedHandle.AddrOfPinnedObject(), (uint)Marshal.SizeOf(proxyInfo)); } finally { pinnedHandle.Free(); } } } finally { Marshal.FreeHGlobal(proxyInfo.Proxy); Marshal.FreeHGlobal(proxyInfo.ProxyBypass); } } } private void SetRequestHandleDecompressionOptions(SafeWinHttpHandle requestHandle) { uint optionData = 0; if (_automaticDecompression != DecompressionMethods.None) { if ((_automaticDecompression & DecompressionMethods.GZip) != 0) { optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_GZIP; } if ((_automaticDecompression & DecompressionMethods.Deflate) != 0) { optionData |= Interop.WinHttp.WINHTTP_DECOMPRESSION_FLAG_DEFLATE; } try { SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DECOMPRESSION, ref optionData); } catch (WinHttpException ex) { if (ex.NativeErrorCode != (int)Interop.WinHttp.ERROR_WINHTTP_INVALID_OPTION) { throw; } // We are running on a platform earlier than Win8.1 for which WINHTTP.DLL // doesn't support this option. So, we'll have to do the decompression // manually. _doManualDecompressionCheck = true; } } } private void SetRequestHandleRedirectionOptions(SafeWinHttpHandle requestHandle) { uint optionData = 0; if (_automaticRedirection) { optionData = (uint)_maxAutomaticRedirections; SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_HTTP_AUTOMATIC_REDIRECTS, ref optionData); } optionData = _automaticRedirection ? Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_DISALLOW_HTTPS_TO_HTTP : Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY_NEVER; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_REDIRECT_POLICY, ref optionData); } private void SetRequestHandleCookieOptions(SafeWinHttpHandle requestHandle) { if (_cookieUsePolicy == CookieUsePolicy.UseSpecifiedCookieContainer || _cookieUsePolicy == CookieUsePolicy.IgnoreCookies) { uint optionData = Interop.WinHttp.WINHTTP_DISABLE_COOKIES; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_DISABLE_FEATURE, ref optionData); } } private void SetRequestHandleTlsOptions(SafeWinHttpHandle requestHandle) { // If we have a custom server certificate validation callback method then // we need to have WinHTTP ignore some errors so that the callback method // will have a chance to be called. uint optionData; if (_serverCertificateValidationCallback != null) { optionData = Interop.WinHttp.SECURITY_FLAG_IGNORE_UNKNOWN_CA | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_WRONG_USAGE | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_CN_INVALID | Interop.WinHttp.SECURITY_FLAG_IGNORE_CERT_DATE_INVALID; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_SECURITY_FLAGS, ref optionData); } else if (_checkCertificateRevocationList) { // If no custom validation method, then we let WinHTTP do the revocation check itself. optionData = Interop.WinHttp.WINHTTP_ENABLE_SSL_REVOCATION; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_ENABLE_FEATURE, ref optionData); } } private void SetRequestHandleClientCertificateOptions(SafeWinHttpHandle requestHandle, Uri requestUri) { if (requestUri.Scheme != UriScheme.Https) { return; } X509Certificate2 clientCertificate = null; if (_clientCertificateOption == ClientCertificateOption.Manual) { clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(ClientCertificates); } else { clientCertificate = WinHttpCertificateHelper.GetEligibleClientCertificate(); } if (clientCertificate != null) { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, clientCertificate.Handle, (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CONTEXT>()); } else { SetNoClientCertificate(requestHandle); } } internal static void SetNoClientCertificate(SafeWinHttpHandle requestHandle) { SetWinHttpOption( requestHandle, Interop.WinHttp.WINHTTP_OPTION_CLIENT_CERT_CONTEXT, IntPtr.Zero, 0); } private void SetRequestHandleCredentialsOptions(WinHttpRequestState state) { // By default, WinHTTP sets the default credentials policy such that it automatically sends default credentials // (current user's logged on Windows credentials) to a proxy when needed (407 response). It only sends // default credentials to a server (401 response) if the server is considered to be on the Intranet. // WinHttpHandler uses a more granual opt-in model for using default credentials that can be different between // proxy and server credentials. It will explicitly allow default credentials to be sent at a later stage in // the request processing (after getting a 401/407 response) when the proxy or server credential is set as // CredentialCache.DefaultNetworkCredential. For now, we set the policy to prevent any default credentials // from being automatically sent until we get a 401/407 response. _authHelper.ChangeDefaultCredentialsPolicy( state.RequestHandle, Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER, allowDefaultCredentials:false); } private void SetRequestHandleBufferingOptions(SafeWinHttpHandle requestHandle) { uint optionData = (uint)_maxResponseHeadersLength; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, ref optionData); optionData = (uint)_maxResponseDrainSize; SetWinHttpOption(requestHandle, Interop.WinHttp.WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, ref optionData); } private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, ref uint optionData) { if (!Interop.WinHttp.WinHttpSetOption( handle, option, ref optionData)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void SetWinHttpOption(SafeWinHttpHandle handle, uint option, string optionData) { if (!Interop.WinHttp.WinHttpSetOption( handle, option, optionData, (uint)optionData.Length)) { WinHttpException.ThrowExceptionUsingLastError(); } } private static void SetWinHttpOption( SafeWinHttpHandle handle, uint option, IntPtr optionData, uint optionSize) { if (!Interop.WinHttp.WinHttpSetOption( handle, option, optionData, optionSize)) { WinHttpException.ThrowExceptionUsingLastError(); } } private void HandleAsyncException(WinHttpRequestState state, Exception ex) { if (state.CancellationToken.IsCancellationRequested) { // If the exception was due to the cancellation token being canceled, throw cancellation exception. state.Tcs.TrySetCanceled(state.CancellationToken); } else if (ex is WinHttpException || ex is IOException) { // Wrap expected exceptions as HttpRequestExceptions since this is considered an error during // execution. All other exception types, including ArgumentExceptions and ProtocolViolationExceptions // are 'unexpected' or caused by user error and should not be wrapped. state.Tcs.TrySetException(new HttpRequestException(SR.net_http_client_execution_error, ex)); } else { state.Tcs.TrySetException(ex); } } private void SetOperationStarted() { if (!_operationStarted) { _operationStarted = true; } } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_operationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private void SetStatusCallback( SafeWinHttpHandle requestHandle, Interop.WinHttp.WINHTTP_STATUS_CALLBACK callback) { const uint notificationFlags = Interop.WinHttp.WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_HANDLES | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_REDIRECT | Interop.WinHttp.WINHTTP_CALLBACK_FLAG_SEND_REQUEST; IntPtr oldCallback = Interop.WinHttp.WinHttpSetStatusCallback( requestHandle, callback, notificationFlags, IntPtr.Zero); if (oldCallback == new IntPtr(Interop.WinHttp.WINHTTP_INVALID_STATUS_CALLBACK)) { int lastError = Marshal.GetLastWin32Error(); if (lastError != Interop.WinHttp.ERROR_INVALID_HANDLE) // Ignore error if handle was already closed. { throw WinHttpException.CreateExceptionUsingError(lastError); } } } private void ThrowOnInvalidHandle(SafeWinHttpHandle handle) { if (handle.IsInvalid) { int lastError = Marshal.GetLastWin32Error(); WinHttpTraceHelper.Trace("WinHttpHandler.ThrowOnInvalidHandle: error={0}", lastError); throw WinHttpException.CreateExceptionUsingError(lastError); } } private Task<bool> InternalSendRequestAsync(WinHttpRequestState state) { state.TcsSendRequest = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); lock (state.Lock) { if (!Interop.WinHttp.WinHttpSendRequest( state.RequestHandle, null, 0, IntPtr.Zero, 0, 0, state.ToIntPtr())) { WinHttpException.ThrowExceptionUsingLastError(); } } return state.TcsSendRequest.Task; } private async Task InternalSendRequestBodyAsync(WinHttpRequestState state, bool chunkedModeForSend) { using (var requestStream = new WinHttpRequestStream(state, chunkedModeForSend)) { await state.RequestMessage.Content.CopyToAsync( requestStream, state.TransportContext).ConfigureAwait(false); await requestStream.EndUploadAsync(state.CancellationToken).ConfigureAwait(false); } } private Task<bool> InternalReceiveResponseHeadersAsync(WinHttpRequestState state) { state.TcsReceiveResponseHeaders = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); lock (state.Lock) { if (!Interop.WinHttp.WinHttpReceiveResponse(state.RequestHandle, IntPtr.Zero)) { throw WinHttpException.CreateExceptionUsingLastError(); } } return state.TcsReceiveResponseHeaders.Task; } } }
using Microsoft.Build.Construction; using Microsoft.Build.Execution; using Microsoft.CodeAnalysis; using OmniSharp.Services; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Threading.Tasks; using TestUtility; using Xunit; using Xunit.Abstractions; namespace OmniSharp.MSBuild.Tests { public partial class ProjectLoadListenerTests : AbstractMSBuildTestFixture { private readonly VsTfmAndFileExtHashingAlgorithm _tfmAndFileHashingAlgorithm; private readonly VsReferenceHashingAlgorithm _referenceHashingAlgorithm; public ProjectLoadListenerTests(ITestOutputHelper output) : base(output) { _tfmAndFileHashingAlgorithm = new VsTfmAndFileExtHashingAlgorithm(); _referenceHashingAlgorithm = new VsReferenceHashingAlgorithm(); } [Fact] public void GetTargetFramework_ReturnsTargetFramework() { // Arrange const string targetFramework = "net461"; var projectInstance = new ProjectInstance(ProjectRootElement.Create()); projectInstance.SetProperty(ProjectLoadListener.TargetFramework, targetFramework); // Act var tfm = ProjectLoadListener.GetTargetFrameworks(projectInstance); // Assert Assert.Equal(targetFramework, tfm.First()); } [Fact] public void GetTargetFramework_NoTFM_ReturnsTargetFrameworkVersion() { // Arrange const string targetFramework = "v4.6.1"; var projectInstance = new ProjectInstance(ProjectRootElement.Create()); projectInstance.SetProperty(ProjectLoadListener.TargetFrameworkVersion, targetFramework); // Act var tfm = ProjectLoadListener.GetTargetFrameworks(projectInstance); // Assert Assert.Equal(targetFramework, tfm.First()); } [Fact] public void GetTargetFramework_PrioritizesTargetFrameworkOverVersion() { // Arrange const string targetFramework = "v4.6.1"; var projectInstance = new ProjectInstance(ProjectRootElement.Create()); projectInstance.SetProperty(ProjectLoadListener.TargetFramework, targetFramework); projectInstance.SetProperty(ProjectLoadListener.TargetFrameworkVersion, "Unexpected"); // Act var tfm = ProjectLoadListener.GetTargetFrameworks(projectInstance); // Assert Assert.Equal(targetFramework, tfm.First()); } [Fact] public void GetTargetFramework_NoTFM_ReturnsEmpty() { // Arrange var projectInstance = new ProjectInstance(ProjectRootElement.Create()); // Act var tfm = ProjectLoadListener.GetTargetFrameworks(projectInstance); // Assert Assert.Empty(tfm); } [Fact] public async Task The_target_framework_is_emitted() { // Arrange var expectedTFM = "netcoreapp3.1"; var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); Assert.Equal(emitter.ReceivedMessages[0].TargetFrameworks.First(), expectedTFM); } [Fact] public async Task If_there_is_a_solution_file_the_project_guid_present_in_it_is_emitted() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("ProjectAndSolution"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); var expectedGuid = "A4C2694D-AEB4-4CB1-8951-5290424EF883".ToLower(); Assert.Single(emitter.ReceivedMessages); Assert.Equal(emitter.ReceivedMessages[0].ProjectId, expectedGuid); } [Fact] public async Task If_there_is_no_solution_file_the_hash_of_project_file_content_and_name_is_emitted() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); var projectFileContent = File.ReadAllText(Directory.GetFiles(testProject.Directory, "*.csproj").Single()); var expectedGuid = GetHashedReference($"Filename: HelloWorld.csproj\n{projectFileContent}"); Assert.Single(emitter.ReceivedMessages); Assert.Equal(emitter.ReceivedMessages[0].ProjectId, expectedGuid); } [Fact] public async Task Given_a_restored_project_the_references_are_emitted() { var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); var dotnetCliService = host.GetExport<IDotNetCliService>(); await dotnetCliService.RestoreAsync(testProject.Directory); Assert.Single(emitter.ReceivedMessages); Assert.NotEmpty(emitter.ReceivedMessages[0].References.Where(reference => reference == GetHashedReference("system.core"))); } [Fact] public async Task If_there_are_multiple_target_frameworks_they_are_emitted() { var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("ProjectWithMultiTFMLib/Lib"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); var tfm = emitter.ReceivedMessages[0].TargetFrameworks.ToArray(); Assert.Equal(2, tfm.Count()); Assert.Equal("netstandard1.3", tfm[0]); Assert.Equal("netstandard2.0", tfm[1]); } [Fact] public async Task The_hashed_references_of_the_source_files_are_emitted() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("HelloWorld"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); Assert.Single(emitter.ReceivedMessages[0].FileExtensions); Assert.Equal(emitter.ReceivedMessages[0].FileExtensions.First(), GetHashedFileExtension(".cs")); } [Fact] public async Task The_output_kind_is_emitted() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("NetCore31Project"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); Assert.Equal((int)OutputKind.ConsoleApplication, emitter.ReceivedMessages[0].OutputKind); } [Fact] public async Task The_correct_project_capablities_is_emitted() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("NetCore31Project"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); Assert.Equal("GenerateDocumentationFile CSharp Managed ReferencesFolder LanguageService RelativePathDerivedDefaultNamespace AssemblyReferences COMReferences ProjectReferences SharedProjectReferences OutputGroups AllTargetOutputGroups VisualStudioWellKnownOutputGroups SingleFileGenerators DeclaredSourceItems UserSourceItems BuildWindowsDesktopTarget CrossPlatformExecutable Pack", string.Join(" ", emitter.ReceivedMessages[0].ProjectCapabilities)); } [Fact] public async Task The_correct_sdk_version_is_emitted_NETCore3_1() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("NetCore31Project"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); Assert.Equal(GetHashedFileExtension("3.1.415"), emitter.ReceivedMessages[0].SdkVersion); } [Fact] public async Task The_correct_sdk_version_is_emitted_NET5() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("Net50Project"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Equal(2, emitter.ReceivedMessages.Length); Assert.Equal(GetHashedFileExtension("5.0.403"), emitter.ReceivedMessages[0].SdkVersion); } [ConditionalFact(typeof(DesktopRuntimeOnly))] public async Task The_correct_sdk_version_is_emitted_NET6() { // Arrange var emitter = new ProjectLoadTestEventEmitter(); using var testProject = await TestAssets.Instance.GetTestProjectAsync("Net60Project"); using var host = CreateMSBuildTestHost(testProject.Directory, emitter.AsExportDescriptionProvider(LoggerFactory)); Assert.Single(emitter.ReceivedMessages); Assert.Equal(GetHashedFileExtension("6.0.100"), emitter.ReceivedMessages[0].SdkVersion); } private string GetHashedFileExtension(string fileExtension) { return _tfmAndFileHashingAlgorithm.HashInput(fileExtension).Value; } private string GetHashedReference(string reference) { return _referenceHashingAlgorithm.HashInput(reference).Value; } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 602985 $ * $Date: 2007-12-10 11:25:11 -0700 (Mon, 10 Dec 2007) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * 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 #region Using using System.Collections; #if dotnet2 using System.Collections.Generic; #endif using System.Data; using IBatisNet.DataMapper.Commands; using IBatisNet.DataMapper.Configuration.Cache; using IBatisNet.DataMapper.Configuration.Statements; using IBatisNet.DataMapper.Scope; #endregion namespace IBatisNet.DataMapper.MappedStatements { /// <summary> /// Summary description for CachingStatement. /// </summary> public sealed class CachingStatement : IMappedStatement { private readonly MappedStatement _mappedStatement = null; /// <summary> /// Event launch on exceute query /// </summary> public event ExecuteEventHandler Execute; /// <summary> /// Constructor /// </summary> /// <param name="statement"></param> public CachingStatement(MappedStatement statement) { _mappedStatement = statement; } #region IMappedStatement Members /// <summary> /// The IPreparedCommand to use /// </summary> public IPreparedCommand PreparedCommand { get { return _mappedStatement.PreparedCommand; } } /// <summary> /// Name used to identify the MappedStatement amongst the others. /// This the name of the SQL statment by default. /// </summary> public string Id { get { return _mappedStatement.Id; } } /// <summary> /// The SQL statment used by this MappedStatement /// </summary> public IStatement Statement { get { return _mappedStatement.Statement; } } /// <summary> /// The SqlMap used by this MappedStatement /// </summary> public ISqlMapper SqlMap { get { return _mappedStatement.SqlMap; } } /// <summary> /// Executes the SQL and retuns all rows selected in a map that is keyed on the property named /// in the keyProperty parameter. The value at each key will be the value of the property specified /// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered. /// </summary> /// <param name="session">The session used to execute the statement</param> /// <param name="parameterObject">The object used to set the parameters in the SQL. </param> /// <param name="keyProperty">The property of the result object to be used as the key. </param> /// <param name="valueProperty">The property of the result object to be used as the value (or null)</param> /// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns> ///<exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception> public IDictionary ExecuteQueryForMap(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty) { IDictionary map = new Hashtable(); RequestScope request = this.Statement.Sql.GetRequestScope(this, parameterObject, session); _mappedStatement.PreparedCommand.Create(request, session, this.Statement, parameterObject); CacheKey cacheKey = this.GetCacheKey(request); cacheKey.Update("ExecuteQueryForMap"); if (keyProperty != null) { cacheKey.Update(keyProperty); } if (valueProperty != null) { cacheKey.Update(valueProperty); } map = this.Statement.CacheModel[cacheKey] as IDictionary; if (map == null) { map = _mappedStatement.RunQueryForMap(request, session, parameterObject, keyProperty, valueProperty, null); this.Statement.CacheModel[cacheKey] = map; } return map; } #region ExecuteQueryForMap .NET 2.0 #if dotnet2 /// <summary> /// Executes the SQL and retuns all rows selected in a map that is keyed on the property named /// in the keyProperty parameter. The value at each key will be the value of the property specified /// in the valueProperty parameter. If valueProperty is null, the entire result object will be entered. /// </summary> /// <param name="session">The session used to execute the statement</param> /// <param name="parameterObject">The object used to set the parameters in the SQL. </param> /// <param name="keyProperty">The property of the result object to be used as the key. </param> /// <param name="valueProperty">The property of the result object to be used as the value (or null)</param> /// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns> ///<exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception> public IDictionary<K, V> ExecuteQueryForDictionary<K, V>(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty) { IDictionary<K, V> map = new Dictionary<K, V>(); RequestScope request = this.Statement.Sql.GetRequestScope(this, parameterObject, session); _mappedStatement.PreparedCommand.Create(request, session, this.Statement, parameterObject); CacheKey cacheKey = this.GetCacheKey(request); cacheKey.Update("ExecuteQueryForMap"); if (keyProperty != null) { cacheKey.Update(keyProperty); } if (valueProperty != null) { cacheKey.Update(valueProperty); } map = this.Statement.CacheModel[cacheKey] as IDictionary<K, V>; if (map == null) { map = _mappedStatement.RunQueryForDictionary<K, V>(request, session, parameterObject, keyProperty, valueProperty, null); this.Statement.CacheModel[cacheKey] = map; } return map; } /// <summary> /// Runs a query with a custom object that gets a chance /// to deal with each row as it is processed. /// </summary> /// <param name="session">The session used to execute the statement</param> /// <param name="parameterObject">The object used to set the parameters in the SQL. </param> /// <param name="keyProperty">The property of the result object to be used as the key. </param> /// <param name="valueProperty">The property of the result object to be used as the value (or null)</param> /// <param name="rowDelegate"></param> /// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns> /// <exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception> public IDictionary<K, V> ExecuteQueryForDictionary<K, V>(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate<K, V> rowDelegate) { return _mappedStatement.ExecuteQueryForDictionary<K, V>(session, parameterObject, keyProperty, valueProperty, rowDelegate); } #endif #endregion /// <summary> /// Execute an update statement. Also used for delete statement. /// Return the number of row effected. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>The number of row effected.</returns> public int ExecuteUpdate(ISqlMapSession session, object parameterObject) { return _mappedStatement.ExecuteUpdate(session, parameterObject); } /// <summary> /// Execute an insert statement. Fill the parameter object with /// the ouput parameters if any, also could return the insert generated key /// </summary> /// <param name="session">The session</param> /// <param name="parameterObject">The parameter object used to fill the statement.</param> /// <returns>Can return the insert generated key.</returns> public object ExecuteInsert(ISqlMapSession session, object parameterObject) { return _mappedStatement.ExecuteInsert(session, parameterObject); } #region ExecuteQueryForList /// <summary> /// Executes the SQL and and fill a strongly typed collection. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="resultObject">A strongly typed collection of result objects.</param> public void ExecuteQueryForList(ISqlMapSession session, object parameterObject, IList resultObject) { _mappedStatement.ExecuteQueryForList(session, parameterObject, resultObject); } /// <summary> /// Executes the SQL and retuns a subset of the rows selected. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="skipResults">The number of rows to skip over.</param> /// <param name="maxResults">The maximum number of rows to return.</param> /// <returns>A List of result objects.</returns> public IList ExecuteQueryForList(ISqlMapSession session, object parameterObject, int skipResults, int maxResults) { IList list = null; RequestScope request = this.Statement.Sql.GetRequestScope(this, parameterObject, session); _mappedStatement.PreparedCommand.Create(request, session, this.Statement, parameterObject); CacheKey cacheKey = this.GetCacheKey(request); cacheKey.Update("ExecuteQueryForList"); cacheKey.Update(skipResults); cacheKey.Update(maxResults); list = this.Statement.CacheModel[cacheKey] as IList; if (list == null) { list = _mappedStatement.RunQueryForList(request, session, parameterObject, skipResults, maxResults); this.Statement.CacheModel[cacheKey] = list; } return list; } /// <summary> /// Executes the SQL and retuns all rows selected. This is exactly the same as /// calling ExecuteQueryForList(session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS). /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>A List of result objects.</returns> public IList ExecuteQueryForList(ISqlMapSession session, object parameterObject) { return this.ExecuteQueryForList(session, parameterObject, MappedStatement.NO_SKIPPED_RESULTS, MappedStatement.NO_MAXIMUM_RESULTS); } #endregion #region ExecuteQueryForList .NET 2.0 #if dotnet2 /// <summary> /// Executes the SQL and and fill a strongly typed collection. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="resultObject">A strongly typed collection of result objects.</param> public void ExecuteQueryForList<T>(ISqlMapSession session, object parameterObject, IList<T> resultObject) { _mappedStatement.ExecuteQueryForList(session, parameterObject, resultObject); } /// <summary> /// Executes the SQL and retuns a subset of the rows selected. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="skipResults">The number of rows to skip over.</param> /// <param name="maxResults">The maximum number of rows to return.</param> /// <returns>A List of result objects.</returns> public IList<T> ExecuteQueryForList<T>(ISqlMapSession session, object parameterObject, int skipResults, int maxResults) { IList<T> list = null; RequestScope request = this.Statement.Sql.GetRequestScope(this, parameterObject, session); _mappedStatement.PreparedCommand.Create(request, session, this.Statement, parameterObject); CacheKey cacheKey = this.GetCacheKey(request); cacheKey.Update("ExecuteQueryForList"); cacheKey.Update(skipResults); cacheKey.Update(maxResults); list = this.Statement.CacheModel[cacheKey] as IList<T>; if (list == null) { list = _mappedStatement.RunQueryForList<T>(request, session, parameterObject, skipResults, maxResults); this.Statement.CacheModel[cacheKey] = list; } return list; } /// <summary> /// Executes the SQL and retuns all rows selected. This is exactly the same as /// calling ExecuteQueryForList(session, parameterObject, NO_SKIPPED_RESULTS, NO_MAXIMUM_RESULTS). /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>A List of result objects.</returns> public IList<T> ExecuteQueryForList<T>(ISqlMapSession session, object parameterObject) { return this.ExecuteQueryForList<T>(session, parameterObject, MappedStatement.NO_SKIPPED_RESULTS, MappedStatement.NO_MAXIMUM_RESULTS); } #endif #endregion #region ExecuteQueryForObject /// <summary> /// Executes an SQL statement that returns a single row as an Object. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>The object</returns> public object ExecuteQueryForObject(ISqlMapSession session, object parameterObject) { return this.ExecuteQueryForObject(session, parameterObject, null); } /// <summary> /// Executes an SQL statement that returns a single row as an Object of the type of /// the resultObject passed in as a parameter. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="resultObject">The result object.</param> /// <returns>The object</returns> public object ExecuteQueryForObject(ISqlMapSession session, object parameterObject, object resultObject) { object obj = null; RequestScope request = this.Statement.Sql.GetRequestScope(this, parameterObject, session); _mappedStatement.PreparedCommand.Create(request, session, this.Statement, parameterObject); CacheKey cacheKey = this.GetCacheKey(request); cacheKey.Update("ExecuteQueryForObject"); obj = this.Statement.CacheModel[cacheKey]; // check if this query has alreay been run if (obj == CacheModel.NULL_OBJECT) { // convert the marker object back into a null value obj = null; } else if (obj == null) { obj = _mappedStatement.RunQueryForObject(request, session, parameterObject, resultObject); this.Statement.CacheModel[cacheKey] = obj; } return obj; } #region ExecuteQueryForObject .NET 2.0 #if dotnet2 /// <summary> /// Executes an SQL statement that returns a single row as an Object. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <returns>The object</returns> public T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject) { return this.ExecuteQueryForObject<T>(session, parameterObject, default(T)); } /// <summary> /// Executes an SQL statement that returns a single row as an Object of the type of /// the resultObject passed in as a parameter. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="resultObject">The result object.</param> /// <returns>The object</returns> public T ExecuteQueryForObject<T>(ISqlMapSession session, object parameterObject, T resultObject) { T obj = default(T); RequestScope request = this.Statement.Sql.GetRequestScope(this, parameterObject, session); _mappedStatement.PreparedCommand.Create(request, session, this.Statement, parameterObject); CacheKey cacheKey = this.GetCacheKey(request); cacheKey.Update("ExecuteQueryForObject"); object cacheObjet = this.Statement.CacheModel[cacheKey]; // check if this query has alreay been run if (cacheObjet is T) { obj = (T)cacheObjet; } else if (cacheObjet == CacheModel.NULL_OBJECT) { // convert the marker object back into a null value obj = default(T); } else { obj = (T)_mappedStatement.RunQueryForObject(request, session, parameterObject, resultObject); this.Statement.CacheModel[cacheKey] = obj; } return obj; } #endif #endregion /// <summary> /// Runs a query with a custom object that gets a chance /// to deal with each row as it is processed. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="rowDelegate"></param> public IList ExecuteQueryForRowDelegate(ISqlMapSession session, object parameterObject, RowDelegate rowDelegate) { return _mappedStatement.ExecuteQueryForRowDelegate(session, parameterObject, rowDelegate); } #if dotnet2 /// <summary> /// Runs a query with a custom object that gets a chance /// to deal with each row as it is processed. /// </summary> /// <param name="session">The session used to execute the statement.</param> /// <param name="parameterObject">The object used to set the parameters in the SQL.</param> /// <param name="rowDelegate"></param> public IList<T> ExecuteQueryForRowDelegate<T>(ISqlMapSession session, object parameterObject, RowDelegate<T> rowDelegate) { return _mappedStatement.ExecuteQueryForRowDelegate<T>(session, parameterObject, rowDelegate); } #endif /// <summary> /// Runs a query with a custom object that gets a chance /// to deal with each row as it is processed. /// </summary> /// <param name="session">The session used to execute the statement</param> /// <param name="parameterObject">The object used to set the parameters in the SQL. </param> /// <param name="keyProperty">The property of the result object to be used as the key. </param> /// <param name="valueProperty">The property of the result object to be used as the value (or null)</param> /// <param name="rowDelegate"></param> /// <returns>A hashtable of object containing the rows keyed by keyProperty.</returns> /// <exception cref="IBatisNet.DataMapper.Exceptions.DataMapperException">If a transaction is not in progress, or the database throws an exception.</exception> public IDictionary ExecuteQueryForMapWithRowDelegate(ISqlMapSession session, object parameterObject, string keyProperty, string valueProperty, DictionaryRowDelegate rowDelegate) { return _mappedStatement.ExecuteQueryForMapWithRowDelegate(session, parameterObject, keyProperty, valueProperty, rowDelegate); } #endregion #endregion /// <summary> /// Gets a percentage of successful cache hits achieved /// </summary> /// <returns>The percentage of hits (0-1), or -1 if cache is disabled.</returns> public double GetDataCacheHitRatio() { if (_mappedStatement.Statement.CacheModel != null) { return _mappedStatement.Statement.CacheModel.HitRatio; } else { return -1; } } /// <summary> /// Gets the cache key. /// </summary> /// <param name="request">The request.</param> /// <returns>the cache key</returns> private CacheKey GetCacheKey(RequestScope request) { CacheKey cacheKey = new CacheKey(); int count = request.IDbCommand.Parameters.Count; for (int i = 0; i < count; i++) { IDataParameter dataParameter = (IDataParameter)request.IDbCommand.Parameters[i]; if (dataParameter.Value != null) { cacheKey.Update(dataParameter.Value); } } cacheKey.Update(_mappedStatement.Id); cacheKey.Update(_mappedStatement.SqlMap.DataSource.ConnectionString); cacheKey.Update(request.IDbCommand.CommandText); CacheModel cacheModel = _mappedStatement.Statement.CacheModel; if (!cacheModel.IsReadOnly && !cacheModel.IsSerializable) { // read/write, nonserializable cache models need to use per-session caching cacheKey.Update(request.Session); } return cacheKey; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Linq; using AutoRest.Core.Validation; using AutoRest.Swagger.Validation; using System.Collections.Generic; using AutoRest.Core.Utilities; namespace AutoRest.Swagger.Model { /// <summary> /// Describes a single API operation on a path. /// </summary> [Rule(typeof(OperationDescriptionRequired))] public class Operation : SwaggerBase { private string _description; private string _summary; public Operation() { Consumes = new List<string>(); Produces = new List<string>(); } /// <summary> /// A list of tags for API documentation control. /// </summary> public IList<string> Tags { get; set; } /// <summary> /// A friendly serviceTypeName for the operation. The id MUST be unique among all /// operations described in the API. Tools and libraries MAY use the /// operation id to uniquely identify an operation. /// </summary> [Rule(typeof(OneUnderscoreInOperationId))] [Rule(typeof(OperationIdNounInVerb))] public string OperationId { get; set; } public string Summary { get { return _summary; } set { _summary = value.StripControlCharacters(); } } public string Description { get { return _description; } set { _description = value.StripControlCharacters(); } } /// <summary> /// Additional external documentation for this operation. /// </summary> public ExternalDoc ExternalDocs { get; set; } /// <summary> /// A list of MIME types the operation can consume. /// </summary> public IList<string> Consumes { get; set; } /// <summary> /// A list of MIME types the operation can produce. /// </summary> public IList<string> Produces { get; set; } /// <summary> /// A list of parameters that are applicable for this operation. /// If a parameter is already defined at the Path Item, the /// new definition will override it, but can never remove it. /// </summary> [CollectionRule(typeof(OperationParametersValidation))] [CollectionRule(typeof(AnonymousParameterTypes))] public IList<SwaggerParameter> Parameters { get; set; } /// <summary> /// The list of possible responses as they are returned from executing this operation. /// </summary> [Rule(typeof(ResponseRequired))] public Dictionary<string, OperationResponse> Responses { get; set; } /// <summary> /// The transfer protocol for the operation. /// </summary> public IList<TransferProtocolScheme> Schemes { get; set; } public bool Deprecated { get; set; } /// <summary> /// A declaration of which security schemes are applied for this operation. /// The list of values describes alternative security schemes that can be used /// (that is, there is a logical OR between the security requirements). /// This definition overrides any declared top-level security. To remove a /// top-level security declaration, an empty array can be used. /// </summary> public IList<Dictionary<string, List<string>>> Security { get; set; } /// <summary> /// Compare a modified document node (this) to a previous one and look for breaking as well as non-breaking changes. /// </summary> /// <param name="context">The modified document context.</param> /// <param name="previous">The original document model.</param> /// <returns>A list of messages from the comparison.</returns> public override IEnumerable<ComparisonMessage> Compare(ComparisonContext context, SwaggerBase previous) { var priorOperation = previous as Operation; var currentRoot = (context.CurrentRoot as ServiceDefinition); var previousRoot = (context.PreviousRoot as ServiceDefinition); if (priorOperation == null) { throw new ArgumentException("previous"); } base.Compare(context, previous); if (!OperationId.Equals(priorOperation.OperationId)) { context.LogBreakingChange(ComparisonMessages.ModifiedOperationId); } CheckParameters(context, priorOperation); if (Responses != null && priorOperation.Responses != null) { foreach (var response in Responses) { var oldResponse = priorOperation.FindResponse(response.Key, priorOperation.Responses); context.Push(response.Key); if (oldResponse == null) { context.LogBreakingChange(ComparisonMessages.AddingResponseCode, response.Key); } else { response.Value.Compare(context, oldResponse); } context.Pop(); } foreach (var response in priorOperation.Responses) { var newResponse = this.FindResponse(response.Key, this.Responses); if (newResponse == null) { context.Push(response.Key); context.LogBreakingChange(ComparisonMessages.RemovedResponseCode, response.Key); context.Pop(); } } } return context.Messages; } private void CheckParameters(ComparisonContext context, Operation priorOperation) { // Check that no parameters were removed or reordered, and compare them if it's not the case. var currentRoot = (context.CurrentRoot as ServiceDefinition); var previousRoot = (context.PreviousRoot as ServiceDefinition); foreach (var oldParam in priorOperation.Parameters .Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, previousRoot.Parameters))) { SwaggerParameter newParam = FindParameter(oldParam.Name, Parameters, currentRoot.Parameters); context.Push(oldParam.Name); if (newParam != null) { newParam.Compare(context, oldParam); } else if (oldParam.IsRequired) { context.LogBreakingChange(ComparisonMessages.RemovedRequiredParameter, oldParam.Name); } context.Pop(); } // Check that no required parameters were added. foreach (var newParam in Parameters .Select(p => string.IsNullOrEmpty(p.Reference) ? p : FindReferencedParameter(p.Reference, currentRoot.Parameters)) .Where(p => p != null && p.IsRequired)) { if (newParam == null) continue; SwaggerParameter oldParam = FindParameter(newParam.Name, priorOperation.Parameters, previousRoot.Parameters); if (oldParam == null) { context.Push(newParam.Name); context.LogBreakingChange(ComparisonMessages.AddingRequiredParameter, newParam.Name); context.Pop(); } } } private SwaggerParameter FindParameter(string name, IEnumerable<SwaggerParameter> operationParameters, IDictionary<string, SwaggerParameter> clientParameters) { if (Parameters != null) { foreach (var param in operationParameters) { if (name.Equals(param.Name)) return param; var pRef = FindReferencedParameter(param.Reference, clientParameters); if (pRef != null && name.Equals(pRef.Name)) { return pRef; } } } return null; } private OperationResponse FindResponse(string name, IDictionary<string, OperationResponse> responses) { OperationResponse response = null; this.Responses.TryGetValue(name, out response); return response; } private static SwaggerParameter FindReferencedParameter(string reference, IDictionary<string, SwaggerParameter> parameters) { if (reference != null && reference.StartsWith("#", StringComparison.Ordinal)) { var parts = reference.Split('/'); if (parts.Length == 3 && parts[1].Equals("parameters")) { SwaggerParameter p = null; if (parameters.TryGetValue(parts[2], out p)) { return p; } } } return null; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using UnityEngine; using UnityEngine.Serialization; namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers { /// <summary> /// The base abstract class for all Solvers to derive from. It provides state tracking, smoothing parameters /// and implementation, automatic solver system integration, and update order. Solvers may be used without a link, /// as long as updateLinkedTransform is false. /// </summary> [RequireComponent(typeof(SolverHandler))] [HelpURL("https://docs.microsoft.com/windows/mixed-reality/mrtk-unity/features/ux-building-blocks/solvers/solver")] public abstract class Solver : MonoBehaviour { [SerializeField] [Tooltip("If true, the position and orientation will be calculated, but not applied, for other components to use")] private bool updateLinkedTransform = false; /// <summary> /// If true, the position and orientation will be calculated, but not applied, for other components to use /// </summary> public bool UpdateLinkedTransform { get => updateLinkedTransform; set => updateLinkedTransform = value; } [SerializeField] [Tooltip("If 0, the position will update immediately. Otherwise, the greater this attribute the slower the position updates")] private float moveLerpTime = 0.1f; /// <summary> /// If 0, the position will update immediately. Otherwise, the greater this attribute the slower the position updates /// </summary> public float MoveLerpTime { get => moveLerpTime; set => moveLerpTime = value; } [SerializeField] [Tooltip("If 0, the rotation will update immediately. Otherwise, the greater this attribute the slower the rotation updates")] private float rotateLerpTime = 0.1f; /// <summary> /// If 0, the rotation will update immediately. Otherwise, the greater this attribute the slower the rotation updates")] /// </summary> public float RotateLerpTime { get => rotateLerpTime; set => rotateLerpTime = value; } [SerializeField] [Tooltip("If 0, the scale will update immediately. Otherwise, the greater this attribute the slower the scale updates")] private float scaleLerpTime = 0; /// <summary> /// If 0, the scale will update immediately. Otherwise, the greater this attribute the slower the scale updates /// </summary> public float ScaleLerpTime { get => scaleLerpTime; set => scaleLerpTime = value; } [SerializeField] [Tooltip("If true, the Solver will respect the object's original scale values on initialization")] [FormerlySerializedAs("maintainScale")] private bool maintainScaleOnInitialization = true; [SerializeField] [Tooltip("If true, updates are smoothed to the target. Otherwise, they are snapped to the target")] private bool smoothing = true; /// <summary> /// If true, updates are smoothed to the target. Otherwise, they are snapped to the target /// </summary> public bool Smoothing { get => smoothing; set => smoothing = value; } [SerializeField] [Tooltip("If > 0, this solver will deactivate after this much time, even if the state is still active")] private float lifetime = 0; private float currentLifetime; /// <summary> /// The handler reference for this solver that's attached to this <see href="https://docs.unity3d.com/ScriptReference/GameObject.html">GameObject</see> /// </summary> [HideInInspector] protected SolverHandler SolverHandler; /// <summary> /// The final position to be attained /// </summary> protected Vector3 GoalPosition { get { return SolverHandler.GoalPosition; } set { SolverHandler.GoalPosition = value; } } /// <summary> /// The final rotation to be attained /// </summary> protected Quaternion GoalRotation { get { return SolverHandler.GoalRotation; } set { SolverHandler.GoalRotation = value; } } /// <summary> /// The final scale to be attained /// </summary> protected Vector3 GoalScale { get { return SolverHandler.GoalScale; } set { SolverHandler.GoalScale = value; } } /// <summary> /// Automatically uses the shared position if the solver is set to use the 'linked transform'. /// UpdateLinkedTransform may be set to false, and a solver will automatically update the object directly, /// and not inherit work done by other solvers to the shared position /// </summary> public Vector3 WorkingPosition { get { return updateLinkedTransform ? GoalPosition : transform.position; } protected set { if (updateLinkedTransform) { GoalPosition = value; } else { transform.position = value; } } } /// <summary> /// Rotation version of WorkingPosition /// </summary> public Quaternion WorkingRotation { get { return updateLinkedTransform ? GoalRotation : transform.rotation; } protected set { if (updateLinkedTransform) { GoalRotation = value; } else { transform.rotation = value; } } } /// <summary> /// Scale version of WorkingPosition /// </summary> public Vector3 WorkingScale { get { return updateLinkedTransform ? GoalScale : transform.localScale; } protected set { if (updateLinkedTransform) { GoalScale = value; } else { transform.localScale = value; } } } #region MonoBehaviour Implementation protected virtual void Awake() { if (SolverHandler == null) { SolverHandler = GetComponent<SolverHandler>(); } if (updateLinkedTransform && SolverHandler == null) { Debug.LogError("No SolverHandler component found on " + name + " when UpdateLinkedTransform was set to true! Disabling UpdateLinkedTransform."); updateLinkedTransform = false; } GoalScale = maintainScaleOnInitialization ? transform.localScale : Vector3.one; } /// <summary> /// Typically when a solver becomes enabled, it should update its internal state to the system, in case it was disabled far away /// </summary> protected virtual void OnEnable() { if (SolverHandler != null) { SnapGoalTo(GoalPosition, GoalRotation, GoalScale); } currentLifetime = 0; } protected virtual void Start() { if (SolverHandler != null) { SolverHandler.RegisterSolver(this); } } protected virtual void OnDestroy() { if (SolverHandler != null) { SolverHandler.UnregisterSolver(this); } } #endregion MonoBehaviour Implementation /// <summary> /// Should be implemented in derived classes, but Solver can be used to flush shared transform to real transform /// </summary> public abstract void SolverUpdate(); /// <summary> /// Tracks lifetime of the solver, disabling it when expired, and finally runs the orientation update logic /// </summary> public void SolverUpdateEntry() { currentLifetime += SolverHandler.DeltaTime; if (lifetime > 0 && currentLifetime >= lifetime) { enabled = false; return; } SolverUpdate(); UpdateWorkingToGoal(); } /// <summary> /// Snaps the solver to the desired pose. /// </summary> /// <remarks> /// SnapTo may be used to bypass smoothing to a certain position if the object is teleported or spawned. /// </remarks> public virtual void SnapTo(Vector3 position, Quaternion rotation, Vector3 scale) { SnapGoalTo(position, rotation, scale); WorkingPosition = position; WorkingRotation = rotation; WorkingScale = scale; } /// <summary> /// SnapGoalTo only sets the goal orientation. Not really useful. /// </summary> public virtual void SnapGoalTo(Vector3 position, Quaternion rotation, Vector3 scale) { GoalPosition = position; GoalRotation = rotation; GoalScale = scale; } /// <summary> /// Snaps the solver to the desired pose. /// </summary> /// <remarks> /// SnapTo may be used to bypass smoothing to a certain position if the object is teleported or spawned. /// </remarks> [Obsolete("Use SnapTo(Vector3, Quaternion, Vector3) instead.")] public virtual void SnapTo(Vector3 position, Quaternion rotation) { SnapGoalTo(position, rotation); WorkingPosition = position; WorkingRotation = rotation; } /// <summary> /// SnapGoalTo only sets the goal orientation. Not really useful. /// </summary> [Obsolete("Use SnapGoalTo(Vector3, Quaternion, Vector3) instead.")] public virtual void SnapGoalTo(Vector3 position, Quaternion rotation) { GoalPosition = position; GoalRotation = rotation; } /// <summary> /// Add an offset position to the target goal position. /// </summary> public virtual void AddOffset(Vector3 offset) { GoalPosition += offset; } /// <summary> /// Lerps Vector3 source to goal. /// </summary> /// <remarks> /// Handles lerpTime of 0. /// </remarks> public static Vector3 SmoothTo(Vector3 source, Vector3 goal, float deltaTime, float lerpTime) { return Vector3.Lerp(source, goal, lerpTime.Equals(0.0f) ? 1f : deltaTime / lerpTime); } /// <summary> /// Slerps Quaternion source to goal, handles lerpTime of 0 /// </summary> public static Quaternion SmoothTo(Quaternion source, Quaternion goal, float deltaTime, float lerpTime) { return Quaternion.Slerp(source, goal, lerpTime.Equals(0.0f) ? 1f : deltaTime / lerpTime); } /// <summary> /// Updates all object orientations to the goal orientation for this solver, with smoothing accounted for (smoothing may be off) /// </summary> protected void UpdateTransformToGoal() { if (smoothing) { Vector3 pos = transform.position; Quaternion rot = transform.rotation; Vector3 scale = transform.localScale; pos = SmoothTo(pos, GoalPosition, SolverHandler.DeltaTime, moveLerpTime); rot = SmoothTo(rot, GoalRotation, SolverHandler.DeltaTime, rotateLerpTime); scale = SmoothTo(scale, GoalScale, SolverHandler.DeltaTime, scaleLerpTime); transform.position = pos; transform.rotation = rot; transform.localScale = scale; } else { transform.position = GoalPosition; transform.rotation = GoalRotation; transform.localScale = GoalScale; } } /// <summary> /// Updates the Working orientation (which may be the object, or the shared orientation) to the goal with smoothing, if enabled /// </summary> public void UpdateWorkingToGoal() { UpdateWorkingPositionToGoal(); UpdateWorkingRotationToGoal(); UpdateWorkingScaleToGoal(); } /// <summary> /// Updates only the working position to goal with smoothing, if enabled /// </summary> public void UpdateWorkingPositionToGoal() { WorkingPosition = smoothing ? SmoothTo(WorkingPosition, GoalPosition, SolverHandler.DeltaTime, moveLerpTime) : GoalPosition; } /// <summary> /// Updates only the working rotation to goal with smoothing, if enabled /// </summary> public void UpdateWorkingRotationToGoal() { WorkingRotation = smoothing ? SmoothTo(WorkingRotation, GoalRotation, SolverHandler.DeltaTime, rotateLerpTime) : GoalRotation; } /// <summary> /// Updates only the working scale to goal with smoothing, if enabled /// </summary> public void UpdateWorkingScaleToGoal() { WorkingScale = smoothing ? SmoothTo(WorkingScale, GoalScale, SolverHandler.DeltaTime, scaleLerpTime) : GoalScale; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.StorSimple; using Microsoft.WindowsAzure.Management.StorSimple.Models; namespace Microsoft.WindowsAzure.Management.StorSimple { /// <summary> /// All Operations related to Device Public keys /// </summary> internal partial class DevicePublicKeyOperations : IServiceOperations<StorSimpleManagementClient>, IDevicePublicKeyOperations { /// <summary> /// Initializes a new instance of the DevicePublicKeyOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DevicePublicKeyOperations(StorSimpleManagementClient client) { this._client = client; } private StorSimpleManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient. /// </summary> public StorSimpleManagementClient Client { get { return this._client; } } /// <param name='deviceId'> /// Required. The Device Id for which we need to Fetch the Device /// Public Key /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for Device PublicKey. /// </returns> public async Task<GetDevicePublicKeyResponse> GetAsync(string deviceId, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/publickey"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GetDevicePublicKeyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetDevicePublicKeyResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement stringElement = responseDoc.Element(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/")); if (stringElement != null) { string stringInstance = stringElement.Value; result.DevicePublicKey = stringInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.ServiceDirectory.V1 { /// <summary>Settings for <see cref="LookupServiceClient"/> instances.</summary> public sealed partial class LookupServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="LookupServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="LookupServiceSettings"/>.</returns> public static LookupServiceSettings GetDefault() => new LookupServiceSettings(); /// <summary>Constructs a new <see cref="LookupServiceSettings"/> object with default settings.</summary> public LookupServiceSettings() { } private LookupServiceSettings(LookupServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ResolveServiceSettings = existing.ResolveServiceSettings; OnCopy(existing); } partial void OnCopy(LookupServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>LookupServiceClient.ResolveService</c> and <c>LookupServiceClient.ResolveServiceAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 1000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: 5</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.Unknown"/>. /// </description> /// </item> /// <item><description>Timeout: 15 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ResolveServiceSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(15000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 5, initialBackoff: sys::TimeSpan.FromMilliseconds(1000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.Unknown))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="LookupServiceSettings"/> object.</returns> public LookupServiceSettings Clone() => new LookupServiceSettings(this); } /// <summary> /// Builder class for <see cref="LookupServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class LookupServiceClientBuilder : gaxgrpc::ClientBuilderBase<LookupServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public LookupServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public LookupServiceClientBuilder() { UseJwtAccessWithScopes = LookupServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref LookupServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<LookupServiceClient> task); /// <summary>Builds the resulting client.</summary> public override LookupServiceClient Build() { LookupServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<LookupServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<LookupServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private LookupServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return LookupServiceClient.Create(callInvoker, Settings); } private async stt::Task<LookupServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return LookupServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => LookupServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => LookupServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => LookupServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>LookupService client wrapper, for convenient use.</summary> /// <remarks> /// Service Directory API for looking up service data at runtime. /// </remarks> public abstract partial class LookupServiceClient { /// <summary> /// The default endpoint for the LookupService service, which is a host of "servicedirectory.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "servicedirectory.googleapis.com:443"; /// <summary>The default LookupService scopes.</summary> /// <remarks> /// The default LookupService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="LookupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="LookupServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="LookupServiceClient"/>.</returns> public static stt::Task<LookupServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new LookupServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="LookupServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="LookupServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="LookupServiceClient"/>.</returns> public static LookupServiceClient Create() => new LookupServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="LookupServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="LookupServiceSettings"/>.</param> /// <returns>The created <see cref="LookupServiceClient"/>.</returns> internal static LookupServiceClient Create(grpccore::CallInvoker callInvoker, LookupServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } LookupService.LookupServiceClient grpcClient = new LookupService.LookupServiceClient(callInvoker); return new LookupServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC LookupService client</summary> public virtual LookupService.LookupServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ResolveServiceResponse ResolveService(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ResolveServiceResponse> ResolveServiceAsync(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ResolveServiceResponse> ResolveServiceAsync(ResolveServiceRequest request, st::CancellationToken cancellationToken) => ResolveServiceAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>LookupService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service Directory API for looking up service data at runtime. /// </remarks> public sealed partial class LookupServiceClientImpl : LookupServiceClient { private readonly gaxgrpc::ApiCall<ResolveServiceRequest, ResolveServiceResponse> _callResolveService; /// <summary> /// Constructs a client wrapper for the LookupService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="LookupServiceSettings"/> used within this client.</param> public LookupServiceClientImpl(LookupService.LookupServiceClient grpcClient, LookupServiceSettings settings) { GrpcClient = grpcClient; LookupServiceSettings effectiveSettings = settings ?? LookupServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callResolveService = clientHelper.BuildApiCall<ResolveServiceRequest, ResolveServiceResponse>(grpcClient.ResolveServiceAsync, grpcClient.ResolveService, effectiveSettings.ResolveServiceSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callResolveService); Modify_ResolveServiceApiCall(ref _callResolveService); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ResolveServiceApiCall(ref gaxgrpc::ApiCall<ResolveServiceRequest, ResolveServiceResponse> call); partial void OnConstruction(LookupService.LookupServiceClient grpcClient, LookupServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC LookupService client</summary> public override LookupService.LookupServiceClient GrpcClient { get; } partial void Modify_ResolveServiceRequest(ref ResolveServiceRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ResolveServiceResponse ResolveService(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ResolveServiceRequest(ref request, ref callSettings); return _callResolveService.Sync(request, callSettings); } /// <summary> /// Returns a [service][google.cloud.servicedirectory.v1.Service] and its /// associated endpoints. /// Resolving a service is not considered an active developer method. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ResolveServiceResponse> ResolveServiceAsync(ResolveServiceRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ResolveServiceRequest(ref request, ref callSettings); return _callResolveService.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using NDiagnostics.Metering.Attributes; using NDiagnostics.Metering.Extensions; using NDiagnostics.Metering.Meters; namespace NDiagnostics.Metering { public static class MeterCategory { #region Public Methods public static IMeterCategory<TEnum> Create<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable { var typeT = typeof(TEnum).ThrowIfNotEnum(); var meterCategoryAttribute = typeT.GetMeterCategoryAttribute() .ThrowIfNull(new NotSupportedException($"Enum '{typeT.ToName()}' must be decorated by a MeterCategory attribute.", null)); var values = Enum.GetValues(typeT) .ThrowIfEmpty(new NotSupportedException($"Enum '{typeT.ToName()}' must contain at least one value.", null)); var meterAttributes = new Dictionary<TEnum, MeterAttribute>(); foreach(TEnum value in values) { var meterAttribute = typeT.GetMeterAttribute(value) .ThrowIfNull(new NotSupportedException($"Value '{value}' of enum '{typeT.ToName()}' must de decorated by a Meter attribute.", null)); meterAttributes.Add(value, meterAttribute); } return new MeterCategory<TEnum>(meterCategoryAttribute, meterAttributes); } public static void Install<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable { var typeT = typeof(TEnum).ThrowIfNotEnum(); var meterCategoryAttribute = typeT.GetMeterCategoryAttribute() .ThrowIfNull(new NotSupportedException($"Enum '{typeT.ToName()}' must be decorated by a MeterCategory attribute.", null)); var values = Enum.GetValues(typeT) .ThrowIfEmpty(new NotSupportedException($"Enum '{typeT.ToName()}' must contain at least one value.", null)); var meterAttributes = new List<MeterAttribute>(); foreach(TEnum value in values) { var meterAttribute = typeT.GetMeterAttribute(value) .ThrowIfNull(new NotSupportedException($"Value '{value}' of enum '{typeT.ToName()}' must de decorated by a Meter attribute.", null)); meterAttributes.Add(meterAttribute); } if(PerformanceCounterCategory.Exists(meterCategoryAttribute.Name)) { PerformanceCounterCategory.Delete(meterCategoryAttribute.Name); } var counterCreationDataCollection = new CounterCreationDataCollection(); foreach(var meterAttribute in meterAttributes) { var counterType = meterAttribute.GetPerformanceCounterType(); if(counterType.HasValue) { var counterCreationData = new CounterCreationData(meterAttribute.Name, meterAttribute.Description, counterType.Value); counterCreationDataCollection.Add(counterCreationData); var baseType = counterCreationData.CounterType.GetBaseType(); if(baseType.HasValue) { counterCreationDataCollection.Add(new CounterCreationData(meterAttribute.Name.GetNameForBaseType(), $"Base for {meterAttribute.Name}", baseType.Value)); } } } PerformanceCounterCategory.Create(meterCategoryAttribute.Name, meterCategoryAttribute.Description, (PerformanceCounterCategoryType) meterCategoryAttribute.MeterCategoryType, counterCreationDataCollection); } public static void Uninstall<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable { var typeT = typeof(TEnum).ThrowIfNotEnum(); var meterCategoryAttribute = typeT.GetMeterCategoryAttribute() .ThrowIfNull(new NotSupportedException($"Enum '{typeT.ToName()}' must be decorated by a MeterCategory attribute.", null)); var values = Enum.GetValues(typeT) .ThrowIfEmpty(new NotSupportedException($"Enum '{typeT.ToName()}' must contain at least one value.", null)); foreach (TEnum value in values) { typeT.GetMeterAttribute(value) .ThrowIfNull(new NotSupportedException($"Value '{value}' of enum '{typeT.ToName()}' must de decorated by a Meter attribute.", null)); } if (PerformanceCounterCategory.Exists(meterCategoryAttribute.Name)) { PerformanceCounterCategory.Delete(meterCategoryAttribute.Name); } } [DebuggerStepThrough] public static T As<T>(this IMeter obj) where T : class, IMeter { if(obj is T) { return (T) obj; } return default(T); } #endregion } internal sealed class MeterCategory<TEnum> : DisposableObject, IMeterCategory<TEnum> where TEnum : struct, IConvertible, IComparable, IFormattable { #region Constants and Fields private readonly IDictionary<string, IDictionary<TEnum, IMeter>> meters; private readonly IDictionary<TEnum, MeterAttribute> meterAttributes; #endregion #region Constructors and Destructors internal MeterCategory(MeterCategoryAttribute meterCategoryAttribute, IDictionary<TEnum, MeterAttribute> meterAttributes) { this.meters = new Dictionary<string, IDictionary<TEnum, IMeter>>(); this.CategoryName = meterCategoryAttribute.Name; this.CategoryType = meterCategoryAttribute.MeterCategoryType; this.meterAttributes = meterAttributes; if(meterCategoryAttribute.MeterCategoryType == MeterCategoryType.SingleInstance) { var instanceMeters = CreateMeters(meterCategoryAttribute.Name, meterCategoryAttribute.MeterCategoryType, meterAttributes, SingleInstance.DefaultName, InstanceLifetime.Global); this.meters.Add(SingleInstance.DefaultName, instanceMeters); } } #endregion #region IMeterCategory public string CategoryName { get; } public MeterCategoryType CategoryType { get; } public string[] InstanceNames => this.meters.Keys.ToArray(); #endregion #region IMeterCategory<T> public IMeter this[TEnum meterName] => this.GetMeter(meterName); public IMeter this[TEnum meterName, string instanceName] => this.GetMeter(meterName, instanceName); public void CreateInstance(string instanceName, InstanceLifetime lifetime = InstanceLifetime.Global) { this.ThrowIfDisposed(); if (this.CategoryType == MeterCategoryType.SingleInstance) { throw new InvalidOperationException("Instances cannot be created on meter categories of type \'SingleInstance\'.", null); } var instanceMeters = CreateMeters(this.CategoryName, this.CategoryType, this.meterAttributes, instanceName, lifetime); this.meters.Add(instanceName, instanceMeters); } public void RemoveInstance(string instanceName) { this.ThrowIfDisposed(); if (this.CategoryType == MeterCategoryType.SingleInstance) { throw new InvalidOperationException("Instances cannot be removed on meter categories of type \'SingleInstance\'.", null); } var instances = this.meters[instanceName]; if(instances == null) { return; } this.meters.Remove(instanceName); foreach(var instance in instances.Values) { instance.TryDispose(); } } #endregion #region Methods protected override void OnDisposing() { if((this.meters != null) && (this.meters.Count > 0)) { var instanceMeters = this.meters.Values.ToList(); this.meters.Clear(); foreach(var instanceMeter in instanceMeters) { if(instanceMeter != null) { foreach(var meter in instanceMeter.Values) { meter.Dispose(); } } } } } private static IDictionary<TEnum, IMeter> CreateMeters(string meterCategoryName, MeterCategoryType meterCategoryType, IEnumerable<KeyValuePair<TEnum, MeterAttribute>> meterAttributes, string instanceName, InstanceLifetime instanceLifetime) { var instanceMeters = new Dictionary<TEnum, IMeter>(); var enumerator = meterAttributes.GetEnumerator(); while(enumerator.MoveNext()) { var meterAttribute = enumerator.Current.Value; var meter = CreateMeter(meterCategoryName, meterCategoryType, meterAttribute.Name, meterAttribute.MeterType, instanceName, instanceLifetime, meterAttribute.IsReadOnly); instanceMeters.Add(enumerator.Current.Key, meter); } return instanceMeters; } private static IMeter CreateMeter(string meterCategoryName, MeterCategoryType meterCategoryType, string meterName, MeterType meterType, string instanceName, InstanceLifetime instanceLifetime, bool isReadOnly) { IMeter meter = null; switch(meterType) { // Instant Meters case MeterType.InstantValue: meter = new InstantValueMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.InstantPercentage: meter = new InstantPercentageMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; // Average Meters case MeterType.AverageValue: meter = new AverageValueMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.AverageTime: meter = new AverageTimeMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; // Difference Meters case MeterType.DifferentialValue: meter = new DifferentialValueMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.InstantTime: meter = new InstantTimeMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.SampleRate: meter = new SampleRateMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.SamplePercentage: meter = new SamplePercentageMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.Timer: meter = new TimerMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.TimerInverse: meter = new TimerInverseMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.Timer100Ns: meter = new Timer100nsMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.Timer100NsInverse: meter = new Timer100nsInverseMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.MultiTimer: meter = new MultiTimerMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.MultiTimerInverse: meter = new MultiTimerInverseMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.MultiTimer100Ns: meter = new MultiTimer100NsMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; case MeterType.MultiTimer100NsInverse: meter = new MultiTimer100NsInverseMeter(meterCategoryName, meterCategoryType, meterName, meterType, instanceName, instanceLifetime, isReadOnly); break; } return meter; } private IMeter GetMeter(TEnum meterName, string instanceName = null) { instanceName = instanceName ?? (this.CategoryType == MeterCategoryType.SingleInstance ? SingleInstance.DefaultName : MultiInstance.DefaultName); if(this.meters.ContainsKey(instanceName) && this.meters[instanceName].ContainsKey(meterName)) { return this.meters[instanceName][meterName]; } return null; } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdOrganization : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); private String ParentId; private String Id; private int GetIndexOfVisibility (string s) { return (lstVis.Items.IndexOf (lstVis.Items.FindByValue(s))); } /*private int GetIndexOfLocs (string s) { return (lstLocations.Items.IndexOf (lstLocations.Items.FindByValue(s))); } private int GetIndexProfile (string s) { return (lstProfile.Items.IndexOf (lstProfile.Items.FindByValue(s))); }*/ protected void Page_Load(object sender, System.EventArgs e) { Id=Request.Params["Id"]; if (!IsPostBack) { //loadProfiles(); loadLicVisibility(); loadVisibility(); //loadLocations(); btnAction.Text= Session["btnAction"].ToString(); lblTitle.Text=btnAction.Text + " Organization"; if (Session["btnAction"].ToString() == "Update") { loadData(); } else { lstVis.SelectedIndex = 0; } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveOrg"; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Request.Params["Id"]; cmd.Connection=this.epsDbConn; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"OO"); txtName.Text=ds.Tables["OO"].Rows[0][0].ToString(); txtDesc.Text=ds.Tables["OO"].Rows[0][1].ToString(); txtPhone.Text=ds.Tables["OO"].Rows[0][2].ToString(); txtEmail.Text=ds.Tables["OO"].Rows[0][3].ToString(); txtAddr.Text=ds.Tables["OO"].Rows[0][4].ToString(); //lstLocations.SelectedIndex = GetIndexOfLocs (ds.Tables["OO"].Rows[0][5].ToString()); lstVis.SelectedIndex = GetIndexOfVisibility (ds.Tables["OO"].Rows[0][6].ToString()); //lstProfile.SelectedIndex = GetIndexOfLocs (ds.Tables["OO"].Rows[0][7].ToString()); } /*private void loadProfiles() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.Text; cmd.CommandText="Select Id, Name from Profiles" + " Where Type = 'Producer'" + " Order by Name"; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Profiles"); lstProfile.DataSource = ds; lstProfile.DataMember = "Profiles"; lstProfile.DataTextField = "Name"; lstProfile.DataValueField = "Id"; lstProfile.DataBind(); }*/ private void loadLicVisibility() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="ams_RetrieveLicVis"; cmd.Parameters.Add("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"LicVis"); Session["LicOrg"]=ds.Tables["LicVis"].Rows[0][1].ToString(); Session["LicVis"]=ds.Tables["LicVis"].Rows[0][0].ToString(); } private void loadVisibility() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="ams_RetrieveVisibility"; cmd.Parameters.Add ("@Vis",SqlDbType.Int); if (Session["LicOrg"].ToString() != Session["OrgId"].ToString()) { cmd.Parameters["@Vis"].Value=Session["OrgVis"].ToString(); } else { cmd.Parameters["@Vis"].Value=Session["LicVis"].ToString(); } DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Visibility"); lstVis.DataSource = ds; lstVis.DataMember= "Visibility"; lstVis.DataTextField = "Name"; lstVis.DataValueField = "Id"; lstVis.DataBind(); } /*private void loadLocations() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_RetrieveLocations"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Locations"); lstLocations.DataSource = ds; lstLocations.DataMember= "Locations"; lstLocations.DataTextField = "Name"; lstLocations.DataValueField = "Id"; lstLocations.DataBind(); }*/ protected void btnAction_Click(object sender, System.EventArgs e) { if (btnAction.Text == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_UpdateOrg"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=Int32.Parse(Id); cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value=txtName.Text; cmd.Parameters.Add ("@Desc",SqlDbType.NText); cmd.Parameters["@Desc"].Value=txtDesc.Text; cmd.Parameters.Add ("@Addr",SqlDbType.NText); cmd.Parameters["@Addr"].Value=txtAddr.Text; cmd.Parameters.Add ("@Phone",SqlDbType.NVarChar); cmd.Parameters["@Phone"].Value=txtPhone.Text; cmd.Parameters.Add ("@Email",SqlDbType.NVarChar); cmd.Parameters["@Email"].Value=txtEmail.Text; /*cmd.Parameters.Add ("@LocId", SqlDbType.Int); cmd.Parameters["@LocId"].Value=lstLocations.SelectedItem.Value;*/ cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=lstVis.SelectedItem.Value; /*cmd.Parameters.Add ("@ProfileId",SqlDbType.Int); cmd.Parameters["@ProfileId"].Value=lstProfile.SelectedItem.Value;*/ cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } else if (btnAction.Text == "Add") { ParentId = Session["OrgId"].ToString(); SqlCommand cmd1=new SqlCommand(); cmd1.CommandType=CommandType.StoredProcedure; cmd1.CommandText="ams_AddOrg"; cmd1.Connection=this.epsDbConn; cmd1.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd1.Parameters["@Name"].Value= txtName.Text; cmd1.Parameters.Add ("@Desc",SqlDbType.NText); cmd1.Parameters["@Desc"].Value= txtDesc.Text; cmd1.Parameters.Add ("@Phone",SqlDbType.NVarChar); cmd1.Parameters["@Phone"].Value= txtPhone.Text; cmd1.Parameters.Add ("@Email",SqlDbType.NVarChar); cmd1.Parameters["@Email"].Value=txtEmail.Text; cmd1.Parameters.Add ("@Addr",SqlDbType.NText); cmd1.Parameters["@Addr"].Value=txtAddr.Text; cmd1.Parameters.Add ("@ParentOrg",SqlDbType.Int); cmd1.Parameters["@ParentOrg"].Value=ParentId; cmd1.Parameters.Add ("@Vis",SqlDbType.Int); cmd1.Parameters["@Vis"].Value=lstVis.SelectedItem.Value; cmd1.Parameters.Add ("@Creator",SqlDbType.Int); cmd1.Parameters["@Creator"].Value=Session["OrgId"].ToString(); cmd1.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd1.Parameters["@LicenseId"].Value= Session["LicenseId"]; cmd1.Parameters.Add ("@OrgType",SqlDbType.NVarChar); cmd1.Parameters["@OrgType"].Value="na"; /*cmd1.Parameters.Add ("@LocId", SqlDbType.Int); cmd1.Parameters.Add ("@ProfileId",SqlDbType.Int); cmd1.Parameters["@ProfileId"].Value=lstProfile.SelectedItem.Value; cmd1.Parameters["@LocId"].Value=lstLocations.SelectedItem.Value;*/ cmd1.Connection.Open(); cmd1.ExecuteNonQuery(); cmd1.Connection.Close(); //retrieveOrgId(); //addService(); Done(); } else if (btnAction.Text == "OK") { Done(); } } /*private void retrieveOrgId() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.Text; cmd.CommandText="Select Max(Id) From Organizations" + " Where CreatorOrg=" + "'" + Session["OrgId"] + "'"; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"OrgIdSP"); Session["OrgIdSP"]=(ds.Tables["OrgIdSP"].Rows[0][0]); }*/ /*private void addService() { SqlCommand cmd = new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_AddService"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Name",SqlDbType.NVarChar); cmd.Parameters["@Name"].Value=Session["ServiceName"].ToString(); cmd.Parameters.Add ("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgIdSP"].ToString(); cmd.Parameters.Add ("@Desc",SqlDbType.NText); cmd.Parameters["@Desc"].Value=txtDesc.Text; cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=lstVis.SelectedItem.Value; cmd.Parameters.Add ("@Type",SqlDbType.Int); cmd.Parameters["@Type"].Value=Session["ServiceTypesId"].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); }*/ private void Done() { Response.Redirect (strURL + Session["CUO"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Reflection; using System.Text; using Microsoft.PowerShell.Commands; using Dbg = System.Diagnostics.Debug; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation { /// <summary> /// Defines session capabilities provided by a PowerShell session. /// </summary> /// <seealso cref="System.Management.Automation.Runspaces.InitialSessionState.CreateRestricted"/> /// <seealso cref="System.Management.Automation.CommandMetadata.GetRestrictedCommands"/> [Flags] public enum SessionCapabilities { /// <summary> /// Session with <see cref="RemoteServer"/> capabilities can be made available on a server /// that wants to provide a full user experience to PowerShell clients. /// Clients connecting to the server will be able to use implicit remoting /// (Import-PSSession, Export-PSSession) as well as interactive remoting (Enter-PSSession, Exit-PSSession). /// </summary> RemoteServer = 0x1, /// <summary> /// Include language capabilities. /// </summary> Language = 0x4 } /// <summary> /// This class represents the compiled metadata for a command type. /// </summary> [DebuggerDisplay("CommandName = {Name}; Type = {CommandType}")] public sealed class CommandMetadata { #region Public Constructor /// <summary> /// Constructs a CommandMetadata object for the given CLS complaint type /// <paramref name="commandType"/>. /// </summary> /// <param name="commandType"> /// CLS complaint type to inspect for Cmdlet metadata. /// </param> /// <exception cref="ArgumentNullException"> /// commandType is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> public CommandMetadata(Type commandType) { Init(null, null, commandType, false); } /// <summary> /// Construct a CommandMetadata object for the given commandInfo. /// </summary> /// <param name="commandInfo"> /// The commandInfo object to construct CommandMetadata for /// </param> /// <exception cref="ArgumentNullException"> /// commandInfo is null. /// </exception> /// <exception cref="PSNotSupportedException"> /// If the commandInfo is an alias to an unknown command, or if the commandInfo /// is an unsupported command type. /// </exception> public CommandMetadata(CommandInfo commandInfo) : this(commandInfo, false) { } /// <summary> /// Construct a CommandMetadata object for the given commandInfo. /// </summary> /// <param name="commandInfo"> /// The commandInfo object to construct CommandMetadata for /// </param> /// <param name="shouldGenerateCommonParameters"> /// Should common parameters be included in the metadata? /// </param> /// <exception cref="ArgumentNullException"> /// commandInfo is null. /// </exception> /// <exception cref="PSNotSupportedException"> /// If the commandInfo is an alias to an unknown command, or if the commandInfo /// is an unsupported command type. /// </exception> public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParameters) { if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException(nameof(commandInfo)); } while (commandInfo is AliasInfo) { commandInfo = ((AliasInfo)commandInfo).ResolvedCommand; if (commandInfo == null) { throw PSTraceSource.NewNotSupportedException(); } } CmdletInfo cmdletInfo; ExternalScriptInfo scriptInfo; FunctionInfo funcInfo; if ((cmdletInfo = commandInfo as CmdletInfo) != null) { Init(commandInfo.Name, cmdletInfo.FullName, cmdletInfo.ImplementingType, shouldGenerateCommonParameters); } else if ((scriptInfo = commandInfo as ExternalScriptInfo) != null) { // Accessing the script block property here reads and parses the script Init(scriptInfo.ScriptBlock, scriptInfo.Path, shouldGenerateCommonParameters); _wrappedCommandType = CommandTypes.ExternalScript; } else if ((funcInfo = commandInfo as FunctionInfo) != null) { Init(funcInfo.ScriptBlock, funcInfo.Name, shouldGenerateCommonParameters); _wrappedCommandType = commandInfo.CommandType; } else { throw PSTraceSource.NewNotSupportedException(); } } /// <summary> /// Construct a CommandMetadata object for a script file. /// </summary> /// <param name="path">The path to the script file.</param> public CommandMetadata(string path) { string scriptName = IO.Path.GetFileName(path); ExternalScriptInfo scriptInfo = new ExternalScriptInfo(scriptName, path); Init(scriptInfo.ScriptBlock, path, false); _wrappedCommandType = CommandTypes.ExternalScript; } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> CommandMetadata object. /// Instances of Attribute and Type classes are copied by reference. /// </summary> /// <param name="other">Object to copy.</param> public CommandMetadata(CommandMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException(nameof(other)); } Name = other.Name; ConfirmImpact = other.ConfirmImpact; _defaultParameterSetFlag = other._defaultParameterSetFlag; _defaultParameterSetName = other._defaultParameterSetName; _implementsDynamicParameters = other._implementsDynamicParameters; SupportsShouldProcess = other.SupportsShouldProcess; SupportsPaging = other.SupportsPaging; SupportsTransactions = other.SupportsTransactions; this.CommandType = other.CommandType; _wrappedAnyCmdlet = other._wrappedAnyCmdlet; _wrappedCommand = other._wrappedCommand; _wrappedCommandType = other._wrappedCommandType; _parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase); // deep copy foreach (KeyValuePair<string, ParameterMetadata> entry in other.Parameters) { _parameters.Add(entry.Key, new ParameterMetadata(entry.Value)); } // deep copy of the collection, collection items (Attributes) copied by reference if (other._otherAttributes == null) { _otherAttributes = null; } else { _otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count)); foreach (Attribute attribute in other._otherAttributes) { _otherAttributes.Add(attribute); } } // not copying those fields/members as they are untouched (and left set to null) // by public constructors, so we can't rely on those fields/members to be set // when CommandMetadata comes from a user _staticCommandParameterMetadata = null; } /// <summary> /// Constructor used by implicit remoting. /// </summary> internal CommandMetadata( string name, CommandTypes commandType, bool isProxyForCmdlet, string defaultParameterSetName, bool supportsShouldProcess, ConfirmImpact confirmImpact, bool supportsPaging, bool supportsTransactions, bool positionalBinding, Dictionary<string, ParameterMetadata> parameters) { Name = _wrappedCommand = name; _wrappedCommandType = commandType; _wrappedAnyCmdlet = isProxyForCmdlet; _defaultParameterSetName = defaultParameterSetName; SupportsShouldProcess = supportsShouldProcess; SupportsPaging = supportsPaging; ConfirmImpact = confirmImpact; SupportsTransactions = supportsTransactions; PositionalBinding = positionalBinding; this.Parameters = parameters; } private void Init(string name, string fullyQualifiedName, Type commandType, bool shouldGenerateCommonParameters) { Name = name; this.CommandType = commandType; if (commandType != null) { ConstructCmdletMetadataUsingReflection(); _shouldGenerateCommonParameters = shouldGenerateCommonParameters; } // Use fully qualified name if available. _wrappedCommand = !string.IsNullOrEmpty(fullyQualifiedName) ? fullyQualifiedName : Name; _wrappedCommandType = CommandTypes.Cmdlet; _wrappedAnyCmdlet = true; } private void Init(ScriptBlock scriptBlock, string name, bool shouldGenerateCommonParameters) { if (scriptBlock.UsesCmdletBinding) { _wrappedAnyCmdlet = true; } else { // Ignore what was passed in, there are no common parameters if cmdlet binding is not used. shouldGenerateCommonParameters = false; } CmdletBindingAttribute cmdletBindingAttribute = scriptBlock.CmdletBindingAttribute; if (cmdletBindingAttribute != null) { ProcessCmdletAttribute(cmdletBindingAttribute); } else if (scriptBlock.UsesCmdletBinding) { _defaultParameterSetName = null; } Obsolete = scriptBlock.ObsoleteAttribute; _scriptBlock = scriptBlock; _wrappedCommand = Name = name; _shouldGenerateCommonParameters = shouldGenerateCommonParameters; } #endregion #region ctor /// <summary> /// Gets the metadata for the specified cmdlet from the cache or creates /// a new instance if its not in the cache. /// </summary> /// <param name="commandName"> /// The name of the command that this metadata represents. /// </param> /// <param name="cmdletType"> /// The cmdlet to get the metadata for. /// </param> /// <param name="context"> /// The current engine context. /// </param> /// <returns> /// The CommandMetadata for the specified cmdlet. /// </returns> /// <exception cref="ArgumentException"> /// If <paramref name="commandName"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdletType"/> is null. /// </exception> /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal static CommandMetadata Get(string commandName, Type cmdletType, ExecutionContext context) { if (string.IsNullOrEmpty(commandName)) { throw PSTraceSource.NewArgumentException(nameof(commandName)); } CommandMetadata result = null; if ((context != null) && (cmdletType != null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; s_commandMetadataCache.TryGetValue(cmdletTypeName, out result); } if (result == null) { result = new CommandMetadata(commandName, cmdletType, context); if ((context != null) && (cmdletType != null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; s_commandMetadataCache.TryAdd(cmdletTypeName, result); } } return result; } /// <summary> /// Constructs an instance of CommandMetadata using reflection against a bindable object. /// </summary> /// <param name="commandName"> /// The name of the command that this metadata represents. /// </param> /// <param name="cmdletType"> /// An instance of an object type that can be used to bind MSH parameters. A type is /// considered bindable if it has at least one field and/or property that is decorated /// with the ParameterAttribute. /// </param> /// <param name="context"> /// The current engine context. If null, the command and type metadata will be generated /// and will not be cached. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdletType"/> is null. /// </exception> /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext context) { if (string.IsNullOrEmpty(commandName)) { throw PSTraceSource.NewArgumentException(nameof(commandName)); } Name = commandName; this.CommandType = cmdletType; if (cmdletType != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(cmdletType, context, false); ConstructCmdletMetadataUsingReflection(); _staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, true); _defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); _staticCommandParameterMetadata.MakeReadOnly(); } } /// <summary> /// Constructor for creating command metadata from a script block. /// </summary> /// <param name="scriptblock"></param> /// <param name="context"></param> /// <param name="commandName"></param> /// <remarks> /// Unlike cmdlet based on a C# type where cmdlet metadata and parameter /// metadata is created through reflecting the implementation type, script /// cmdlet has different way for constructing metadata. /// /// 1. Metadata for cmdlet itself comes from cmdlet statement, which /// is parsed into CmdletDeclarationNode and then converted into /// a CmdletAttribute object. /// 2. Metadata for parameter comes from parameter declaration statement, /// which is parsed into parameter nodes with parameter annotations. /// Information in ParameterNodes is eventually transformed into a /// dictionary of RuntimeDefinedParameters. /// /// By the time this constructor is called, information about CmdletAttribute /// and RuntimeDefinedParameters for the script block has been setup with /// the scriptblock object. /// </remarks> internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionContext context) { if (scriptblock == null) { throw PSTraceSource.NewArgumentException(nameof(scriptblock)); } CmdletBindingAttribute cmdletBindingAttribute = scriptblock.CmdletBindingAttribute; if (cmdletBindingAttribute != null) { ProcessCmdletAttribute(cmdletBindingAttribute); } else { _defaultParameterSetName = null; } Obsolete = scriptblock.ObsoleteAttribute; Name = commandName; this.CommandType = typeof(PSScriptCmdlet); if (scriptblock.HasDynamicParameters) { _implementsDynamicParameters = true; } InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(scriptblock.RuntimeDefinedParameters, false, scriptblock.UsesCmdletBinding); _staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, scriptblock.UsesCmdletBinding); _defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); _staticCommandParameterMetadata.MakeReadOnly(); } #endregion ctor #region Public Properties /// <summary> /// Gets the name of the command this metadata represents. /// </summary> public string Name { get; set; } = string.Empty; /// <summary> /// The Type which this CommandMetadata represents. /// </summary> public Type CommandType { get; private set; } // The ScriptBlock which this CommandMetadata represents. private ScriptBlock _scriptBlock; /// <summary> /// Gets/Sets the default parameter set name. /// </summary> public string DefaultParameterSetName { get { return _defaultParameterSetName; } set { if (string.IsNullOrEmpty(value)) { value = ParameterAttribute.AllParameterSets; } _defaultParameterSetName = value; } } private string _defaultParameterSetName = ParameterAttribute.AllParameterSets; /// <summary> /// True if the cmdlet declared that it supports ShouldProcess, false otherwise. /// </summary> /// <value></value> public bool SupportsShouldProcess { get; set; } /// <summary> /// True if the cmdlet declared that it supports Paging, false otherwise. /// </summary> /// <value></value> public bool SupportsPaging { get; set; } /// <summary> /// When true, the command will auto-generate appropriate parameter metadata to support positional /// parameters if the script hasn't already specified multiple parameter sets or specified positions /// explicitly via the <see cref="ParameterAttribute"/>. /// </summary> public bool PositionalBinding { get; set; } = true; /// <summary> /// True if the cmdlet declared that it supports transactions, false otherwise. /// </summary> /// <value></value> public bool SupportsTransactions { get; set; } /// <summary> /// Related link URI for Get-Help -Online. /// </summary> [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string HelpUri { get; set; } = string.Empty; /// <summary> /// The remoting capabilities of this cmdlet, when exposed in a context /// with ambient remoting. /// </summary> public RemotingCapability RemotingCapability { get { RemotingCapability currentRemotingCapability = _remotingCapability; if ((currentRemotingCapability == Automation.RemotingCapability.PowerShell) && ((this.Parameters != null) && this.Parameters.ContainsKey("ComputerName"))) { _remotingCapability = Automation.RemotingCapability.SupportedByCommand; } return _remotingCapability; } set { _remotingCapability = value; } } private RemotingCapability _remotingCapability = RemotingCapability.PowerShell; /// <summary> /// Indicates the "destructiveness" of the command operation and /// when it should be confirmed. This is only effective when /// the command calls ShouldProcess, which should only occur when /// SupportsShouldProcess is specified. /// </summary> /// <value></value> public ConfirmImpact ConfirmImpact { get; set; } = ConfirmImpact.Medium; /// <summary> /// Gets the parameter data for this command. /// </summary> public Dictionary<string, ParameterMetadata> Parameters { get { if (_parameters == null) { // Return parameters for a script block if (_scriptBlock != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(_scriptBlock.RuntimeDefinedParameters, false, _scriptBlock.UsesCmdletBinding); MergedCommandParameterMetadata mergedCommandParameterMetadata = MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters); _parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata); } else if (this.CommandType != null) { // Construct compiled parameter metadata from this InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(this.CommandType, null, false); MergedCommandParameterMetadata mergedCommandParameterMetadata = MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters); // Construct parameter metadata from compiled parameter metadata // compiled parameter metadata is used for internal purposes. It has lots of information // which is used by ParameterBinder. _parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata); } } return _parameters; } private set { _parameters = value; } } private Dictionary<string, ParameterMetadata> _parameters; private bool _shouldGenerateCommonParameters; /// <summary> /// Gets or sets the obsolete attribute on the command. /// </summary> /// <value></value> internal ObsoleteAttribute Obsolete { get; set; } #endregion #region internal members /// <summary> /// Gets the merged metadata for the command including cmdlet declared parameters, /// common parameters, and (optionally) ShouldProcess and Transactions parameters. /// </summary> /// <value></value> internal MergedCommandParameterMetadata StaticCommandParameterMetadata { get { return _staticCommandParameterMetadata; } } private readonly MergedCommandParameterMetadata _staticCommandParameterMetadata; /// <summary> /// True if the cmdlet implements dynamic parameters, or false otherwise. /// </summary> /// <value></value> internal bool ImplementsDynamicParameters { get { return _implementsDynamicParameters; } } private bool _implementsDynamicParameters; /// <summary> /// Gets the bit in the parameter set map for the default parameter set. /// </summary> internal uint DefaultParameterSetFlag { get { return _defaultParameterSetFlag; } set { _defaultParameterSetFlag = value; } } private uint _defaultParameterSetFlag; /// <summary> /// A collection of attributes that were declared at the cmdlet level but were not /// recognized by the engine. /// </summary> private readonly Collection<Attribute> _otherAttributes = new Collection<Attribute>(); // command this CommandMetadata instance is intended to wrap private string _wrappedCommand; // the type of command this CommandMetadata instance is intended to wrap private CommandTypes _wrappedCommandType; // The CommandType for a script cmdlet is not CommandTypes.Cmdlet, yet // proxy generation needs to know the difference between script and script cmdlet. private bool _wrappedAnyCmdlet; internal bool WrappedAnyCmdlet { get { return _wrappedAnyCmdlet; } } internal CommandTypes WrappedCommandType { get { return _wrappedCommandType; } } #endregion internal members #region helper methods /// <summary> /// Constructs the command metadata by using reflection against the /// CLR type. /// </summary> /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> private void ConstructCmdletMetadataUsingReflection() { Diagnostics.Assert( CommandType != null, "This method should only be called when constructed with the Type"); // Determine if the cmdlet implements dynamic parameters by looking for the interface Type dynamicParametersType = CommandType.GetInterface(nameof(IDynamicParameters), true); if (dynamicParametersType != null) { _implementsDynamicParameters = true; } // Process the attributes on the cmdlet var customAttributes = CommandType.GetCustomAttributes(false); foreach (Attribute attribute in customAttributes) { CmdletAttribute cmdletAttribute = attribute as CmdletAttribute; if (cmdletAttribute != null) { ProcessCmdletAttribute(cmdletAttribute); this.Name = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName; } else if (attribute is ObsoleteAttribute) { Obsolete = (ObsoleteAttribute)attribute; } else { _otherAttributes.Add(attribute); } } } /// <summary> /// Extracts the cmdlet data from the CmdletAttribute. /// </summary> /// <param name="attribute"> /// The CmdletAttribute to process /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="attribute"/> is null. /// </exception> /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute) { if (attribute == null) { throw PSTraceSource.NewArgumentNullException(nameof(attribute)); } // Process the default parameter set name _defaultParameterSetName = attribute.DefaultParameterSetName; // Check to see if the cmdlet supports ShouldProcess SupportsShouldProcess = attribute.SupportsShouldProcess; // Determine the cmdlet's impact confirmation ConfirmImpact = attribute.ConfirmImpact; // Check to see if the cmdlet supports paging SupportsPaging = attribute.SupportsPaging; // Check to see if the cmdlet supports transactions SupportsTransactions = attribute.SupportsTransactions; // Grab related link HelpUri = attribute.HelpUri; // Remoting support _remotingCapability = attribute.RemotingCapability; // Check to see if the cmdlet uses positional binding var cmdletBindingAttribute = attribute as CmdletBindingAttribute; if (cmdletBindingAttribute != null) { PositionalBinding = cmdletBindingAttribute.PositionalBinding; } } /// <summary> /// Merges parameter metadata from different sources: those that are coming from Type, /// CommonParameters, should process etc. /// </summary> /// <param name="context"></param> /// <param name="parameterMetadata"></param> /// <param name="shouldGenerateCommonParameters"> /// true if metadata info about Verbose,Debug etc needs to be generated. /// false otherwise. /// </param> private MergedCommandParameterMetadata MergeParameterMetadata(ExecutionContext context, InternalParameterMetadata parameterMetadata, bool shouldGenerateCommonParameters) { // Create an instance of the static metadata class MergedCommandParameterMetadata staticCommandParameterMetadata = new MergedCommandParameterMetadata(); // First add the metadata for the formal cmdlet parameters staticCommandParameterMetadata.AddMetadataForBinder( parameterMetadata, ParameterBinderAssociation.DeclaredFormalParameters); // Now add the common parameters metadata if (shouldGenerateCommonParameters) { InternalParameterMetadata commonParametersMetadata = InternalParameterMetadata.Get(typeof(CommonParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( commonParametersMetadata, ParameterBinderAssociation.CommonParameters); // If the command supports ShouldProcess, add the metadata for // those parameters if (this.SupportsShouldProcess) { InternalParameterMetadata shouldProcessParametersMetadata = InternalParameterMetadata.Get(typeof(ShouldProcessParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( shouldProcessParametersMetadata, ParameterBinderAssociation.ShouldProcessParameters); } // If the command supports paging, add the metadata for // those parameters if (this.SupportsPaging) { InternalParameterMetadata pagingParametersMetadata = InternalParameterMetadata.Get(typeof(PagingParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( pagingParametersMetadata, ParameterBinderAssociation.PagingParameters); } // If the command supports transactions, add the metadata for // those parameters if (this.SupportsTransactions) { InternalParameterMetadata transactionParametersMetadata = InternalParameterMetadata.Get(typeof(TransactionParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( transactionParametersMetadata, ParameterBinderAssociation.TransactionParameters); } } return staticCommandParameterMetadata; } #endregion helper methods #region Proxy Command generation /// <summary> /// Gets the ScriptCmdlet in string format. /// </summary> /// <returns></returns> internal string GetProxyCommand(string helpComment, bool generateDynamicParameters) { if (string.IsNullOrEmpty(helpComment)) { helpComment = string.Format(CultureInfo.InvariantCulture, @" .ForwardHelpTargetName {0} .ForwardHelpCategory {1} ", _wrappedCommand, _wrappedCommandType); } string dynamicParamblock = string.Empty; if (generateDynamicParameters && this.ImplementsDynamicParameters) { dynamicParamblock = string.Format(CultureInfo.InvariantCulture, @" dynamicparam {{{0}}} ", GetDynamicParamBlock()); } string result = string.Format(CultureInfo.InvariantCulture, @"{0} param({1}) {2}begin {{{3}}} process {{{4}}} end {{{5}}} <# {6} #> ", GetDecl(), GetParamBlock(), dynamicParamblock, GetBeginBlock(), GetProcessBlock(), GetEndBlock(), CodeGeneration.EscapeBlockCommentContent(helpComment)); return result; } internal string GetDecl() { string result = string.Empty; string separator = string.Empty; if (_wrappedAnyCmdlet) { StringBuilder decl = new StringBuilder("[CmdletBinding("); if (!string.IsNullOrEmpty(_defaultParameterSetName)) { decl.Append(separator); decl.Append("DefaultParameterSetName='"); decl.Append(CodeGeneration.EscapeSingleQuotedStringContent(_defaultParameterSetName)); decl.Append('\''); separator = ", "; } if (SupportsShouldProcess) { decl.Append(separator); decl.Append("SupportsShouldProcess=$true"); separator = ", "; decl.Append(separator); decl.Append("ConfirmImpact='"); decl.Append(ConfirmImpact); decl.Append('\''); } if (SupportsPaging) { decl.Append(separator); decl.Append("SupportsPaging=$true"); separator = ", "; } if (SupportsTransactions) { decl.Append(separator); decl.Append("SupportsTransactions=$true"); separator = ", "; } if (!PositionalBinding) { decl.Append(separator); decl.Append("PositionalBinding=$false"); separator = ", "; } if (!string.IsNullOrEmpty(HelpUri)) { decl.Append(separator); decl.Append("HelpUri='"); decl.Append(CodeGeneration.EscapeSingleQuotedStringContent(HelpUri)); decl.Append('\''); separator = ", "; } if (_remotingCapability != RemotingCapability.PowerShell) { decl.Append(separator); decl.Append("RemotingCapability='"); decl.Append(_remotingCapability); decl.Append('\''); separator = ", "; } decl.Append(")]"); result = decl.ToString(); } return result; } internal string GetParamBlock() { if (Parameters.Keys.Count > 0) { StringBuilder parameters = new StringBuilder(); string prefix = string.Concat(Environment.NewLine, " "); string paramDataPrefix = null; foreach (var pair in Parameters) { if (paramDataPrefix != null) { parameters.Append(paramDataPrefix); } else { // syntax for parameter separation : comma followed by new-line. paramDataPrefix = string.Concat(",", Environment.NewLine); } // generate the parameter proxy and append to the list string paramData = pair.Value.GetProxyParameterData(prefix, pair.Key, _wrappedAnyCmdlet); parameters.Append(paramData); } return parameters.ToString(); } return string.Empty; } internal string GetBeginBlock() { string result; if (string.IsNullOrEmpty(_wrappedCommand)) { string error = ProxyCommandStrings.CommandMetadataMissingCommandName; throw new InvalidOperationException(error); } string commandOrigin = "$myInvocation.CommandOrigin"; // For functions, don't proxy the command origin, otherwise they will // be subject to the runspace restrictions if (_wrappedCommandType == CommandTypes.Function) { commandOrigin = string.Empty; } if (_wrappedAnyCmdlet) { result = string.Format(CultureInfo.InvariantCulture, @" try {{ $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ $PSBoundParameters['OutBuffer'] = 1 }} $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) $steppablePipeline.Begin($PSCmdlet) }} catch {{ throw }} ", CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), _wrappedCommandType, commandOrigin ); } else { result = string.Format(CultureInfo.InvariantCulture, @" try {{ $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) $PSBoundParameters.Add('$args', $args) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext) }} catch {{ throw }} ", CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), _wrappedCommandType, commandOrigin ); } return result; } internal string GetProcessBlock() { return @" try { $steppablePipeline.Process($_) } catch { throw } "; } internal string GetDynamicParamBlock() { return string.Format(CultureInfo.InvariantCulture, @" try {{ $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}, $PSBoundParameters) $dynamicParams = @($targetCmd.Parameters.GetEnumerator() | Microsoft.PowerShell.Core\Where-Object {{ $_.Value.IsDynamic }}) if ($dynamicParams.Length -gt 0) {{ $paramDictionary = [Management.Automation.RuntimeDefinedParameterDictionary]::new() foreach ($param in $dynamicParams) {{ $param = $param.Value if(-not $MyInvocation.MyCommand.Parameters.ContainsKey($param.Name)) {{ $dynParam = [Management.Automation.RuntimeDefinedParameter]::new($param.Name, $param.ParameterType, $param.Attributes) $paramDictionary.Add($param.Name, $dynParam) }} }} return $paramDictionary }} }} catch {{ throw }} ", CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), _wrappedCommandType); } internal string GetEndBlock() { return @" try { $steppablePipeline.End() } catch { throw } "; } #endregion #region Helper methods for restricting commands needed by implicit and interactive remoting internal const string isSafeNameOrIdentifierRegex = @"^[-._:\\\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Lm}]{1,100}$"; private static CommandMetadata GetRestrictedCmdlet(string cmdletName, string defaultParameterSet, string helpUri, params ParameterMetadata[] parameters) { Dictionary<string, ParameterMetadata> parametersDictionary = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (ParameterMetadata parameter in parameters) { parametersDictionary.Add(parameter.Name, parameter); } // isProxyForCmdlet: // 1a. we would want to set it to false to get rid of unused common parameters // (like OutBuffer - see bug Windows 7: #402213) // 1b. otoh common parameters are going to be present anyway on all proxy functions // that the host generates for its cmdlets that need cmdletbinding, so // we should make sure that common parameters are safe, not hide them // 2. otoh without cmdletbinding() unspecified parameters get bound to $null which might // unnecessarily trigger validation attribute failures - see bug Windows 7: #477218 CommandMetadata metadata = new CommandMetadata( name: cmdletName, commandType: CommandTypes.Cmdlet, isProxyForCmdlet: true, defaultParameterSetName: defaultParameterSet, supportsShouldProcess: false, confirmImpact: ConfirmImpact.None, supportsPaging: false, supportsTransactions: false, positionalBinding: true, parameters: parametersDictionary); metadata.HelpUri = helpUri; return metadata; } private static CommandMetadata GetRestrictedGetCommand() { // remote Get-Command called by Import/Export-PSSession to get metadata for remote commands that user wants to import // remote Get-Command is also called by interactive remoting before entering the remote session to verify // that Out-Default and Exit-PSSession commands are present in the remote session // value passed directly from Import-PSSession -CommandName to Get-Command -Name // can't really restrict beyond basics ParameterMetadata nameParameter = new ParameterMetadata("Name", typeof(string[])); nameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); nameParameter.Attributes.Add(new ValidateCountAttribute(0, 1000)); // value passed directly from Import-PSSession -PSSnapIn to Get-Command -Module // can't really restrict beyond basics ParameterMetadata moduleParameter = new ParameterMetadata("Module", typeof(string[])); moduleParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); moduleParameter.Attributes.Add(new ValidateCountAttribute(0, 100)); // value passed directly from Import-PSSession -ArgumentList to Get-Command -ArgumentList // can't really restrict beyond basics ParameterMetadata argumentListParameter = new ParameterMetadata("ArgumentList", typeof(object[])); argumentListParameter.Attributes.Add(new ValidateCountAttribute(0, 100)); // value passed directly from Import-PSSession -CommandType to Get-Command -CommandType // can't really restrict beyond basics ParameterMetadata commandTypeParameter = new ParameterMetadata("CommandType", typeof(CommandTypes)); // we do allow -ListImported switch ParameterMetadata listImportedParameter = new ParameterMetadata("ListImported", typeof(SwitchParameter)); // Need to expose ShowCommandInfo parameter for remote ShowCommand support. ParameterMetadata showCommandInfo = new ParameterMetadata("ShowCommandInfo", typeof(SwitchParameter)); return GetRestrictedCmdlet( "Get-Command", null, // defaultParameterSet "https://go.microsoft.com/fwlink/?LinkID=113309", // helpUri nameParameter, moduleParameter, argumentListParameter, commandTypeParameter, listImportedParameter, showCommandInfo); } private static CommandMetadata GetRestrictedGetFormatData() { // remote Get-FormatData called by Import/Export-PSSession to get F&O metadata from remote session // value passed directly from Import-PSSession -FormatTypeName to Get-FormatData -TypeName // can't really restrict beyond basics ParameterMetadata typeNameParameter = new ParameterMetadata("TypeName", typeof(string[])); typeNameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); typeNameParameter.Attributes.Add(new ValidateCountAttribute(0, 1000)); // This parameter is required for implicit remoting in PS V5.1. ParameterMetadata powershellVersionParameter = new ParameterMetadata("PowerShellVersion", typeof(Version)); return GetRestrictedCmdlet("Get-FormatData", null, "https://go.microsoft.com/fwlink/?LinkID=144303", typeNameParameter, powershellVersionParameter); } private static CommandMetadata GetRestrictedGetHelp() { // remote Get-Help is called when help for implicit remoting proxy tries to fetch help content for a remote command // This should only be called with 1 "safe" command name (unless ipsn is called with -Force) // (it seems ok to disallow getting help for "unsafe" commands [possible when ipsn is called with -Force] // - host can always generate its own proxy for Get-Help if it cares about "unsafe" command names) ParameterMetadata nameParameter = new ParameterMetadata("Name", typeof(string)); nameParameter.Attributes.Add(new ValidatePatternAttribute(isSafeNameOrIdentifierRegex)); nameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); // This should only be called with 1 valid category ParameterMetadata categoryParameter = new ParameterMetadata("Category", typeof(string[])); categoryParameter.Attributes.Add(new ValidateSetAttribute(Enum.GetNames(typeof(HelpCategory)))); categoryParameter.Attributes.Add(new ValidateCountAttribute(0, 1)); return GetRestrictedCmdlet("Get-Help", null, "https://go.microsoft.com/fwlink/?LinkID=113316", nameParameter, categoryParameter); } private static CommandMetadata GetRestrictedSelectObject() { // remote Select-Object is called by Import/Export-PSSession to // 1) restrict what properties are serialized // 2) artificially increase serialization depth of selected properties (especially "Parameters" property) // only called with a fixed set of values string[] validPropertyValues = new string[] { "ModuleName", "Namespace", "OutputType", "Count", "HelpUri", "Name", "CommandType", "ResolvedCommandName", "DefaultParameterSet", "CmdletBinding", "Parameters" }; ParameterMetadata propertyParameter = new ParameterMetadata("Property", typeof(string[])); propertyParameter.Attributes.Add(new ValidateSetAttribute(validPropertyValues)); propertyParameter.Attributes.Add(new ValidateCountAttribute(1, validPropertyValues.Length)); // needed for pipeline input if cmdlet binding has to be used (i.e. if Windows 7: #477218 is not fixed) ParameterMetadata inputParameter = new ParameterMetadata("InputObject", typeof(object)); inputParameter.ParameterSets.Add( ParameterAttribute.AllParameterSets, new ParameterSetMetadata( int.MinValue, // not positional ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, null)); // no help message return GetRestrictedCmdlet("Select-Object", null, "https://go.microsoft.com/fwlink/?LinkID=2096716", propertyParameter, inputParameter); } private static CommandMetadata GetRestrictedMeasureObject() { // remote Measure-Object is called by Import/Export-PSSession to measure how many objects // it is going to receive and to display a nice progress bar // needed for pipeline input if cmdlet binding has to be used (i.e. if Windows 7: #477218 is not fixed) ParameterMetadata inputParameter = new ParameterMetadata("InputObject", typeof(object)); inputParameter.ParameterSets.Add( ParameterAttribute.AllParameterSets, new ParameterSetMetadata( int.MinValue, // not positional ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, null)); // no help message return GetRestrictedCmdlet("Measure-Object", null, "https://go.microsoft.com/fwlink/?LinkID=113349", inputParameter); } private static CommandMetadata GetRestrictedOutDefault() { // remote Out-Default is called by interactive remoting (without any parameters, only using pipelines to pass data) // needed for pipeline input if cmdlet binding has to be used (i.e. if Windows 7: #477218 is not fixed) ParameterMetadata inputParameter = new ParameterMetadata("InputObject", typeof(object)); inputParameter.ParameterSets.Add( ParameterAttribute.AllParameterSets, new ParameterSetMetadata( int.MinValue, // not positional ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, null)); // no help message return GetRestrictedCmdlet("Out-Default", null, "https://go.microsoft.com/fwlink/?LinkID=113362", inputParameter); } private static CommandMetadata GetRestrictedExitPSSession() { // remote Exit-PSSession is not called by PowerShell, but is needed so that users // can exit an interactive remoting session return GetRestrictedCmdlet("Exit-PSSession", null, "https://go.microsoft.com/fwlink/?LinkID=2096787"); // no parameters are used } /// <summary> /// Returns a dictionary from a command name to <see cref="CommandMetadata"/> describing /// how that command can be restricted to limit attack surface while still being usable /// by features included in <paramref name="sessionCapabilities"/>. /// /// For example the implicit remoting feature /// (included in <see cref="SessionCapabilities.RemoteServer"/>) /// doesn't use all parameters of Get-Help /// and uses only a limited set of argument values for the parameters it does use. /// <see cref="CommandMetadata"/> can be passed to <see cref="ProxyCommand.Create(CommandMetadata)"/> method to generate /// a body of a proxy function that forwards calls to the actual cmdlet, while exposing only the parameters /// listed in <see cref="CommandMetadata"/>. Exposing only the restricted proxy function while making /// the actual cmdlet and its aliases private can help in reducing attack surface of the remoting server. /// </summary> /// <returns></returns> /// <seealso cref="System.Management.Automation.Runspaces.InitialSessionState.CreateRestricted(SessionCapabilities)"/> public static Dictionary<string, CommandMetadata> GetRestrictedCommands(SessionCapabilities sessionCapabilities) { List<CommandMetadata> restrictedCommands = new List<CommandMetadata>(); // all remoting cmdlets need to be included for workflow scenarios as wel if ((sessionCapabilities & SessionCapabilities.RemoteServer) == SessionCapabilities.RemoteServer) { restrictedCommands.AddRange(GetRestrictedRemotingCommands()); } Dictionary<string, CommandMetadata> result = new Dictionary<string, CommandMetadata>(StringComparer.OrdinalIgnoreCase); foreach (CommandMetadata restrictedCommand in restrictedCommands) { result.Add(restrictedCommand.Name, restrictedCommand); } return result; } private static Collection<CommandMetadata> GetRestrictedRemotingCommands() { Collection<CommandMetadata> remotingCommands = new Collection<CommandMetadata> { GetRestrictedGetCommand(), GetRestrictedGetFormatData(), GetRestrictedSelectObject(), GetRestrictedGetHelp(), GetRestrictedMeasureObject(), GetRestrictedExitPSSession(), GetRestrictedOutDefault() }; return remotingCommands; } #if !CORECLR // Not referenced on CSS private static Collection<CommandMetadata> GetRestrictedJobCommands() { // all the job cmdlets take a Name parameter. This needs to be // restricted to safenames in order to allow only valid wildcards // construct the parameterset metadata ParameterSetMetadata nameParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata instanceIdParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata idParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata stateParameterSet = new ParameterSetMetadata(int.MinValue, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata commandParameterSet = new ParameterSetMetadata(int.MinValue, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata filterParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata jobParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, string.Empty); ParameterSetMetadata computerNameParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata locationParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); Dictionary<string, ParameterSetMetadata> parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.NameParameterSet, nameParameterSet); Collection<string> emptyCollection = new Collection<string>(); ParameterMetadata nameParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.NameParameter, parameterSets, typeof(string[])); nameParameter.Attributes.Add(new ValidatePatternAttribute(isSafeNameOrIdentifierRegex)); nameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); // all the other parameters can be safely allowed parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.InstanceIdParameterSet, instanceIdParameterSet); ParameterMetadata instanceIdParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.InstanceIdParameter, parameterSets, typeof(Guid[])); instanceIdParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.SessionIdParameterSet, idParameterSet); ParameterMetadata idParameter = new ParameterMetadata(emptyCollection, false, "Id", parameterSets, typeof(int[])); idParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.StateParameterSet, stateParameterSet); ParameterMetadata stateParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.StateParameter, parameterSets, typeof(JobState)); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.CommandParameterSet, commandParameterSet); ParameterMetadata commandParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.CommandParameter, parameterSets, typeof(string[])); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.FilterParameterSet, filterParameterSet); ParameterMetadata filterParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.FilterParameter, parameterSets, typeof(Hashtable)); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.JobParameter, jobParameterSet); ParameterMetadata jobParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.JobParameter, parameterSets, typeof(Job[])); jobParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add("ComputerName", computerNameParameterSet); parameterSets.Add("Location", locationParameterSet); ParameterMetadata jobParameter2 = new ParameterMetadata(emptyCollection, false, JobCmdletBase.JobParameter, parameterSets, typeof(Job[])); // Start-Job is not really required since the user will be using the name // of the workflow to launch them Collection<CommandMetadata> restrictedJobCommands = new Collection<CommandMetadata>(); // Stop-Job cmdlet ParameterMetadata passThruParameter = new ParameterMetadata("PassThru", typeof(SwitchParameter)); ParameterMetadata anyParameter = new ParameterMetadata("Any", typeof(SwitchParameter)); CommandMetadata stopJob = GetRestrictedCmdlet("Stop-Job", JobCmdletBase.SessionIdParameterSet, "https://go.microsoft.com/fwlink/?LinkID=2096795", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, passThruParameter); restrictedJobCommands.Add(stopJob); // Wait-Job cmdlet ParameterMetadata timeoutParameter = new ParameterMetadata("Timeout", typeof(int)); timeoutParameter.Attributes.Add(new ValidateRangeAttribute(-1, Int32.MaxValue)); CommandMetadata waitJob = GetRestrictedCmdlet("Wait-Job", JobCmdletBase.SessionIdParameterSet, "https://go.microsoft.com/fwlink/?LinkID=2096902", nameParameter, instanceIdParameter, idParameter, jobParameter, stateParameter, filterParameter, anyParameter, timeoutParameter); restrictedJobCommands.Add(waitJob); // Get-Job cmdlet CommandMetadata getJob = GetRestrictedCmdlet("Get-Job", JobCmdletBase.SessionIdParameterSet, "https://go.microsoft.com/fwlink/?LinkID=113328", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, commandParameter); restrictedJobCommands.Add(getJob); // Receive-Job cmdlet parameterSets = new Dictionary<string, ParameterSetMetadata>(); computerNameParameterSet = new ParameterSetMetadata(1, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); parameterSets.Add("ComputerName", computerNameParameterSet); ParameterMetadata computerNameParameter = new ParameterMetadata(emptyCollection, false, "ComputerName", parameterSets, typeof(string[])); computerNameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); computerNameParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); locationParameterSet = new ParameterSetMetadata(1, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); parameterSets.Add("Location", locationParameterSet); ParameterMetadata locationParameter = new ParameterMetadata(emptyCollection, false, "Location", parameterSets, typeof(string[])); locationParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); locationParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); ParameterMetadata norecurseParameter = new ParameterMetadata("NoRecurse", typeof(SwitchParameter)); ParameterMetadata keepParameter = new ParameterMetadata("Keep", typeof(SwitchParameter)); ParameterMetadata waitParameter = new ParameterMetadata("Wait", typeof(SwitchParameter)); ParameterMetadata writeEventsParameter = new ParameterMetadata("WriteEvents", typeof(SwitchParameter)); ParameterMetadata writeJobParameter = new ParameterMetadata("WriteJobInResults", typeof(SwitchParameter)); ParameterMetadata autoRemoveParameter = new ParameterMetadata("AutoRemoveJob", typeof(SwitchParameter)); CommandMetadata receiveJob = GetRestrictedCmdlet("Receive-Job", "Location", "https://go.microsoft.com/fwlink/?LinkID=2096965", nameParameter, instanceIdParameter, idParameter, stateParameter, jobParameter2, computerNameParameter, locationParameter, norecurseParameter, keepParameter, waitParameter, writeEventsParameter, writeJobParameter, autoRemoveParameter); restrictedJobCommands.Add(receiveJob); // Remove-Job cmdlet ParameterMetadata forceParameter = new ParameterMetadata("Force", typeof(SwitchParameter)); CommandMetadata removeJob = GetRestrictedCmdlet("Remove-Job", JobCmdletBase.SessionIdParameterSet, "https://go.microsoft.com/fwlink/?LinkID=2096868", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, forceParameter); restrictedJobCommands.Add(removeJob); // Suspend-Job cmdlet CommandMetadata suspendJob = GetRestrictedCmdlet("Suspend-Job", JobCmdletBase.SessionIdParameterSet, "https://go.microsoft.com/fwlink/?LinkID=210613", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, passThruParameter); restrictedJobCommands.Add(suspendJob); // Suspend-Job cmdlet CommandMetadata resumeJob = GetRestrictedCmdlet("Resume-Job", JobCmdletBase.SessionIdParameterSet, "https://go.microsoft.com/fwlink/?LinkID=210611", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, passThruParameter); restrictedJobCommands.Add(resumeJob); return restrictedJobCommands; } #endif #endregion #region Command Metadata cache /// <summary> /// The command metadata cache. This is separate from the parameterMetadata cache /// because it is specific to cmdlets. /// </summary> private static readonly System.Collections.Concurrent.ConcurrentDictionary<string, CommandMetadata> s_commandMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary<string, CommandMetadata>(StringComparer.OrdinalIgnoreCase); #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.Composition; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Microsoft.Win32; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ExportLanguageSpecificOptionSerializer( LanguageNames.CSharp, OrganizerOptions.FeatureName, AddImportOptions.FeatureName, CompletionOptions.FeatureName, CSharpCompletionOptions.FeatureName, CSharpCodeStyleOptions.FeatureName, SimplificationOptions.PerLanguageFeatureName, ExtractMethodOptions.FeatureName, CSharpFormattingOptions.IndentFeatureName, CSharpFormattingOptions.NewLineFormattingFeatureName, CSharpFormattingOptions.SpacingFeatureName, CSharpFormattingOptions.WrappingFeatureName, FormattingOptions.InternalTabFeatureName, FeatureOnOffOptions.OptionName, ServiceFeatureOnOffOptions.OptionName), Shared] internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer { [ImportingConstructor] public CSharpSettingsManagerOptionSerializer(SVsServiceProvider serviceProvider, IOptionService optionService) : base(serviceProvider, optionService) { } private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators); private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator); private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels); private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft); private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo) { var value = (IOption)fieldInfo.GetValue(obj: null); return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value); } private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo) { return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null)); } protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap() { var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder(); result.AddRange(new[] { new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.IncludeKeywords), CompletionOptions.IncludeKeywords), new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters), }); Type[] types = new[] { typeof(OrganizerOptions), typeof(AddImportOptions), typeof(CSharpCompletionOptions), typeof(SimplificationOptions), typeof(CSharpCodeStyleOptions), typeof(ExtractMethodOptions), typeof(ServiceFeatureOnOffOptions), typeof(CSharpFormattingOptions) }; var bindingFlags = BindingFlags.Public | BindingFlags.Static; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo)); types = new[] { typeof(FeatureOnOffOptions) }; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption)); return result.ToImmutable(); } protected override string LanguageName { get { return LanguageNames.CSharp; } } protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } } protected override string GetStorageKeyForOption(IOption option) { var name = option.Name; if (option == ServiceFeatureOnOffOptions.ClosedFileDiagnostic) { // ClosedFileDiagnostics has been deprecated in favor of CSharpClosedFileDiagnostics. // ClosedFileDiagnostics had a default value of 'true', while CSharpClosedFileDiagnostics has a default value of 'false'. // We want to ensure that we don't fetch the setting store value for the old flag, as that can cause the default value for this option to change. name = nameof(AutomationObject.CSharpClosedFileDiagnostics); } return SettingStorageRoot + name; } protected override bool SupportsOption(IOption option, string languageName) { if (option == OrganizerOptions.PlaceSystemNamespaceFirst || option == AddImportOptions.SuggestForTypesInReferenceAssemblies || option == AddImportOptions.SuggestForTypesInNuGetPackages || option == CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord || option == CSharpCompletionOptions.IncludeSnippets || option.Feature == CSharpCodeStyleOptions.FeatureName || option.Feature == CSharpFormattingOptions.WrappingFeatureName || option.Feature == CSharpFormattingOptions.IndentFeatureName || option.Feature == CSharpFormattingOptions.SpacingFeatureName || option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName) { return true; } else if (languageName == LanguageNames.CSharp) { if (option == CompletionOptions.IncludeKeywords || option == CompletionOptions.TriggerOnTypingLetters || option.Feature == SimplificationOptions.PerLanguageFeatureName || option.Feature == ExtractMethodOptions.FeatureName || option.Feature == ServiceFeatureOnOffOptions.OptionName || option.Feature == FormattingOptions.InternalTabFeatureName) { return true; } else if (option.Feature == FeatureOnOffOptions.OptionName) { return SupportsOnOffOption(option); } } return false; } private bool SupportsOnOffOption(IOption option) { return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace || option == FeatureOnOffOptions.AutoFormattingOnSemicolon || option == FeatureOnOffOptions.LineSeparator || option == FeatureOnOffOptions.Outlining || option == FeatureOnOffOptions.ReferenceHighlighting || option == FeatureOnOffOptions.KeywordHighlighting || option == FeatureOnOffOptions.FormatOnPaste || option == FeatureOnOffOptions.AutoXmlDocCommentGeneration || option == FeatureOnOffOptions.AutoInsertBlockCommentStartString || option == FeatureOnOffOptions.RefactoringVerification || option == FeatureOnOffOptions.RenameTracking || option == FeatureOnOffOptions.RenameTrackingPreview; } public override bool TryFetch(OptionKey optionKey, out object value) { value = null; if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0); if (ignoreSpacesAroundBinaryObjectValue.Equals(1)) { value = BinaryOperatorSpacingOptions.Ignore; return true; } object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1); if (spaceAroundBinaryOperatorObjectValue.Equals(0)) { value = BinaryOperatorSpacingOptions.Remove; return true; } value = BinaryOperatorSpacingOptions.Single; return true; } if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0); if (flushLabelLeftObjectValue.Equals(1)) { value = LabelPositionOptions.LeftMost; return true; } object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1); if (unindentLabelsObjectValue.Equals(0)) { value = LabelPositionOptions.NoIndent; return true; } value = LabelPositionOptions.OneLess; return true; } return base.TryFetch(optionKey, out value); } public override bool TryPersist(OptionKey optionKey, object value) { if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 switch ((BinaryOperatorSpacingOptions)value) { case BinaryOperatorSpacingOptions.Remove: { this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Ignore: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Single: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); return true; } } } else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { switch ((LabelPositionOptions)value) { case LabelPositionOptions.LeftMost: { this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false); return true; } case LabelPositionOptions.NoIndent: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false); return true; } case LabelPositionOptions.OneLess: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); return true; } } } return base.TryPersist(optionKey, value); } } }
// 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 // // 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. using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using UnityEngine; namespace TiltBrushToolkit { public enum GltfSchemaVersion { GLTF1, GLTF2 } public class BadJson : Exception { public BadJson(string message) : base(message) {} public BadJson(string fmt, params System.Object[] args) : base(string.Format(fmt, args)) {} public BadJson(Exception inner, string fmt, params System.Object[] args) : base(string.Format(fmt, args), inner) {} } // // JSON.net magic for reading in a Matrix4x4 from a json float-array // public class JsonVectorConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(Vector3) || objectType == typeof(Matrix4x4?) || objectType == typeof(Matrix4x4) || objectType == typeof(Color)); } private static float ReadFloat(JsonReader reader) { reader.Read(); if (reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Integer) { return Convert.ToSingle(reader.Value); } throw new BadJson("Expected numeric value"); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartArray) { throw new BadJson("Expected array"); } object result; if (objectType == typeof(Vector3)) { result = new Vector3( ReadFloat(reader), ReadFloat(reader), ReadFloat(reader)); } else if (objectType == typeof(Matrix4x4) || objectType == typeof(Matrix4x4?)) { // Matrix members are m<row><col> // Gltf stores matrices in column-major order result = new Matrix4x4 { m00=ReadFloat(reader), m10=ReadFloat(reader), m20=ReadFloat(reader), m30=ReadFloat(reader), m01=ReadFloat(reader), m11=ReadFloat(reader), m21=ReadFloat(reader), m31=ReadFloat(reader), m02=ReadFloat(reader), m12=ReadFloat(reader), m22=ReadFloat(reader), m32=ReadFloat(reader), m03=ReadFloat(reader), m13=ReadFloat(reader), m23=ReadFloat(reader), m33=ReadFloat(reader) }; } else if (objectType == typeof(Color) || objectType == typeof(Color?)) { result = new Color( ReadFloat(reader), ReadFloat(reader), ReadFloat(reader), ReadFloat(reader)); } else { Debug.Assert(false, "Converter registered with bad type"); throw new BadJson("Internal error"); } reader.Read(); if (reader.TokenType != JsonToken.EndArray) { throw new BadJson("Expected array end"); } return result; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } // Specify converter for types that we can't annotate public class GltfJsonContractResolver : DefaultContractResolver { protected override JsonContract CreateContract(Type objectType) { JsonContract contract = base.CreateContract(objectType); if (objectType == typeof(Vector3) || objectType == typeof(Matrix4x4) || objectType == typeof(Matrix4x4?) || objectType == typeof(Color?) || objectType == typeof(Color)) { contract.Converter = new JsonVectorConverter(); } return contract; } } // // C# classes corresponding to the gltf json schema // [Serializable] public class GltfAsset { public Dictionary<string, string> extensions; public Dictionary<string, string> extras; public string copyright; public string generator; public bool premultipliedAlpha; // public GltfProfile profile; not currently needed public string version; } /// A bucket of mesh data in the format that Unity wants it /// (or as close to it as possible) public class MeshPrecursor { public Vector3[] vertices; public Vector3[] normals; public Color[] colors; public Color32[] colors32; public Vector4[] tangents; public Array[] uvSets = new Array[4]; public int[] triangles; } // Note about the *Base classes: these are the base classes for the GLTF 1 and GLTF 2 versions // of each entity. The fields that are common to both versions of the format go in the base // class. The fields that differ (in name or type) between versions go in the subclasses. // The version-specific subclasses are in Gltf{1,2}Schema.cs. // For more info on the spec, see: // https://github.com/KhronosGroup/glTF/ [Serializable] public abstract class GltfRootBase : IDisposable { public GltfAsset asset; // Tilt Brush/Blocks version that generated the gltf; null if not generated by that program [JsonIgnore] public Version? tiltBrushVersion; [JsonIgnore] public Version? blocksVersion; public abstract GltfSceneBase ScenePtr { get; } public abstract IEnumerable<GltfImageBase> Images { get; } public abstract IEnumerable<GltfTextureBase> Textures { get; } public abstract IEnumerable<GltfMaterialBase> Materials { get; } public abstract IEnumerable<GltfMeshBase> Meshes { get; } public abstract void Dereference(bool isGlb, IUriLoader uriLoader = null); // Disposable pattern, with Dispose(void) and Dispose(bool), as recommended by: // https://docs.microsoft.com/en-us/dotnet/api/system.idisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Subclasses should override Dispose(bool) and call base class implementation. protected virtual void Dispose(bool disposing) {} } [Serializable] public abstract class GltfBufferBase { public long byteLength; public string uri; [JsonIgnore] public IBufferReader data; } [Serializable] public abstract class GltfAccessorBase { [Serializable] public enum ComponentType { BYTE = 5120, UNSIGNED_BYTE = 5121, SHORT = 5122, UNSIGNED_SHORT = 5123, UNSIGNED_INT = 5125, FLOAT = 5126 } public int byteOffset; public int byteStride; public ComponentType componentType; public int count; public List<float> max; public List<float> min; public string type; public abstract GltfBufferViewBase BufferViewPtr { get; } } [Serializable] public abstract class GltfBufferViewBase { public int byteLength; public int byteOffset; public int target; public abstract GltfBufferBase BufferPtr { get; } } [Serializable] public abstract class GltfPrimitiveBase { [Serializable] public enum Mode { TRIANGLES = 4 } public Mode mode = Mode.TRIANGLES; // Not part of the schema; this is for lazy-creation convenience // There may be more than one if the gltf primitive is too big for Unity [JsonIgnore] public List<MeshPrecursor> precursorMeshes; [JsonIgnore] public List<Mesh> unityMeshes; public abstract GltfMaterialBase MaterialPtr { get; } public abstract GltfAccessorBase IndicesPtr { get; } public abstract GltfAccessorBase GetAttributePtr(string attributeName); // Rename attribute from original -> replacement. // ie, attrs[replacement] = attrs.pop(original) public abstract void ReplaceAttribute(string original, string replacement); public abstract HashSet<string> GetAttributeNames(); } [Serializable] public abstract class GltfImageBase { public string uri; [JsonIgnore] public RawImage data; } [Serializable] public abstract class GltfTextureBase { [JsonIgnore] public Texture2D unityTexture; public abstract object GltfId { get; } public abstract GltfImageBase SourcePtr { get; } } [Serializable] public abstract class GltfMaterialBase { public string name; public abstract Dictionary<string,string> TechniqueExtras { get; } public abstract IEnumerable<GltfTextureBase> ReferencedTextures { get; } } [Serializable] public abstract class GltfMeshBase { public string name; public abstract IEnumerable<GltfPrimitiveBase> Primitives { get ; } public abstract int PrimitiveCount { get; } public abstract GltfPrimitiveBase GetPrimitiveAt(int i); } [Serializable] public abstract class GltfNodeBase { public string name; public Matrix4x4? matrix; // May return null public abstract GltfMeshBase Mesh { get; } public abstract IEnumerable<GltfNodeBase> Children { get; } } [Serializable] public abstract class GltfSceneBase { public Dictionary<string, string> extras; public abstract IEnumerable<GltfNodeBase> Nodes { get; } } }
// Copyright (c) 2015 SharpYaml - 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. // // ------------------------------------------------------------------------------- // SharpYaml is a fork of YamlDotNet https://github.com/aaubry/YamlDotNet // published with the following license: // ------------------------------------------------------------------------------- // // Copyright (c) 2008, 2009, 2010, 2011, 2012 Antoine Aubry // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Text; using SharpYaml; using SharpYaml.Events; namespace SharpYaml.Serialization { /// <summary> /// Represents a mapping node in the YAML document. /// </summary> public class YamlMappingNode : YamlNode, IEnumerable<KeyValuePair<YamlNode, YamlNode>> { private readonly IOrderedDictionary<YamlNode, YamlNode> children = new OrderedDictionary<YamlNode, YamlNode>(); /// <summary> /// Gets the children of the current node. /// </summary> /// <value>The children.</value> public IOrderedDictionary<YamlNode, YamlNode> Children { get { return children; } } /// <summary> /// Gets or sets the style of the node. /// </summary> /// <value>The style.</value> public YamlStyle Style { get; set; } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="events">The events.</param> /// <param name="state">The state.</param> internal YamlMappingNode(EventReader events, DocumentLoadingState state) { MappingStart mapping = events.Expect<MappingStart>(); Load(mapping, state); Style = mapping.Style; bool hasUnresolvedAliases = false; while (!events.Accept<MappingEnd>()) { YamlNode key = ParseNode(events, state); YamlNode value = ParseNode(events, state); try { children.Add(key, value); } catch (ArgumentException err) { throw new YamlException(key.Start, key.End, "Duplicate key", err); } hasUnresolvedAliases |= key is YamlAliasNode || value is YamlAliasNode; } if (hasUnresolvedAliases) { state.AddNodeWithUnresolvedAliases(this); } #if DEBUG else { foreach (var child in children) { if (child.Key is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } if (child.Value is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } } } #endif events.Expect<MappingEnd>(); } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode() { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(params KeyValuePair<YamlNode, YamlNode>[] children) : this((IEnumerable<KeyValuePair<YamlNode, YamlNode>>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> public YamlMappingNode(IEnumerable<KeyValuePair<YamlNode, YamlNode>> children) { foreach (var child in children) { this.children.Add(child); } } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(params YamlNode[] children) : this((IEnumerable<YamlNode>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlMappingNode"/> class. /// </summary> /// <param name="children">A sequence of <see cref="YamlNode"/> where even elements are keys and odd elements are values.</param> public YamlMappingNode(IEnumerable<YamlNode> children) { using (var enumerator = children.GetEnumerator()) { while (enumerator.MoveNext()) { var key = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(key, enumerator.Current); } } } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } /// <summary> /// Adds the specified mapping to the <see cref="Children"/> collection. /// </summary> /// <param name="key">The key node.</param> /// <param name="value">The value node.</param> public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } /// <summary> /// Resolves the aliases that could not be resolved when the node was created. /// </summary> /// <param name="state">The state of the document.</param> internal override void ResolveAliases(DocumentLoadingState state) { Dictionary<YamlNode, YamlNode> keysToUpdate = null; Dictionary<YamlNode, YamlNode> valuesToUpdate = null; foreach (var entry in children) { if (entry.Key is YamlAliasNode) { if (keysToUpdate == null) { keysToUpdate = new Dictionary<YamlNode, YamlNode>(); } keysToUpdate.Add(entry.Key, state.GetNode(entry.Key.Anchor, true, entry.Key.Start, entry.Key.End)); } if (entry.Value is YamlAliasNode) { if (valuesToUpdate == null) { valuesToUpdate = new Dictionary<YamlNode, YamlNode>(); } valuesToUpdate.Add(entry.Key, state.GetNode(entry.Value.Anchor, true, entry.Value.Start, entry.Value.End)); } } if (valuesToUpdate != null) { foreach (var entry in valuesToUpdate) { children[entry.Key] = entry.Value; } } if (keysToUpdate != null) { foreach (var entry in keysToUpdate) { YamlNode value = children[entry.Key]; children.Remove(entry.Key); children.Add(entry.Value, value); } } } /// <summary> /// Saves the current node to the specified emitter. /// </summary> /// <param name="emitter">The emitter where the node is to be saved.</param> /// <param name="state">The state.</param> internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(Anchor, Tag, string.IsNullOrEmpty(Tag), Style)); foreach (var entry in children) { entry.Key.Save(emitter, state); entry.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } /// <summary> /// Accepts the specified visitor by calling the appropriate Visit method on it. /// </summary> /// <param name="visitor"> /// A <see cref="IYamlVisitor"/>. /// </param> public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } /// <summary /> public override bool Equals(object other) { var obj = other as YamlMappingNode; if (obj == null || !Equals(obj) || children.Count != obj.children.Count) { return false; } foreach (var entry in children) { YamlNode otherNode; if (!obj.children.TryGetValue(entry.Key, out otherNode) || !SafeEquals(entry.Value, otherNode)) { return false; } } return true; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { var hashCode = base.GetHashCode(); foreach (var entry in children) { hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Key)); hashCode = CombineHashCodes(hashCode, GetHashCode(entry.Value)); } return hashCode; } /// <summary> /// Gets all nodes from the document, starting on the current node. /// </summary> public override IEnumerable<YamlNode> AllNodes { get { yield return this; foreach (var child in children) { foreach (var node in child.Key.AllNodes) { yield return node; } foreach (var node in child.Value.AllNodes) { yield return node; } } } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { var text = new StringBuilder("{ "); foreach (var child in children) { if (text.Length > 2) { text.Append(", "); } text.Append("{ ").Append(child.Key).Append(", ").Append(child.Value).Append(" }"); } text.Append(" }"); return text.ToString(); } #region IEnumerable<KeyValuePair<YamlNode,YamlNode>> Members /// <summary /> public IEnumerator<KeyValuePair<YamlNode, YamlNode>> GetEnumerator() { return children.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Mozu.Api.Contracts.Inventory { /// <summary> /// /// </summary> [DataContract] public class InventoryResponse : BaseResponse { /// <summary> /// Location Name /// </summary> /// <value>Location Name</value> [DataMember(Name="locationName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "locationName")] public string LocationName { get; set; } /// <summary> /// Location Code /// </summary> /// <value>Location Code</value> [DataMember(Name="locationCode", EmitDefaultValue=false)] [JsonProperty(PropertyName = "locationCode")] public string LocationCode { get; set; } /// <summary> /// Tenant Identifier /// </summary> /// <value>Tenant Identifier</value> [DataMember(Name="tenantID", EmitDefaultValue=false)] [JsonProperty(PropertyName = "tenantID")] public int? TenantID { get; set; } /// <summary> /// The quantity the location has in its possession /// </summary> /// <value>The quantity the location has in its possession</value> [DataMember(Name="onHand", EmitDefaultValue=false)] [JsonProperty(PropertyName = "onHand")] public int? OnHand { get; set; } /// <summary> /// The quantity the location has that are available for purchase /// </summary> /// <value>The quantity the location has that are available for purchase</value> [DataMember(Name="available", EmitDefaultValue=false)] [JsonProperty(PropertyName = "available")] public int? Available { get; set; } /// <summary> /// The quantity the location has that are already allocated. /// </summary> /// <value>The quantity the location has that are already allocated.</value> [DataMember(Name="allocated", EmitDefaultValue=false)] [JsonProperty(PropertyName = "allocated")] public int? Allocated { get; set; } /// <summary> /// The quantity the location has that are pending. /// </summary> /// <value>The quantity the location has that are pending.</value> [DataMember(Name="pending", EmitDefaultValue=false)] [JsonProperty(PropertyName = "pending")] public int? Pending { get; set; } /// <summary> /// Part/Product Number /// </summary> /// <value>Part/Product Number</value> [DataMember(Name="partNumber", EmitDefaultValue=false)] [JsonProperty(PropertyName = "partNumber")] public string PartNumber { get; set; } /// <summary> /// Universal Product Code /// </summary> /// <value>Universal Product Code</value> [DataMember(Name="upc", EmitDefaultValue=false)] [JsonProperty(PropertyName = "upc")] public string Upc { get; set; } /// <summary> /// Stock Keeping Unit /// </summary> /// <value>Stock Keeping Unit</value> [DataMember(Name="sku", EmitDefaultValue=false)] [JsonProperty(PropertyName = "sku")] public string Sku { get; set; } /// <summary> /// Whether or not the product is blocked for assignment /// </summary> /// <value>Whether or not the product is blocked for assignment</value> [DataMember(Name="blockAssignment", EmitDefaultValue=false)] [JsonProperty(PropertyName = "blockAssignment")] public bool? BlockAssignment { get; set; } /// <summary> /// Custom field used for store prioritization /// </summary> /// <value>Custom field used for store prioritization</value> [DataMember(Name="ltd", EmitDefaultValue=false)] [JsonProperty(PropertyName = "ltd")] public decimal? Ltd { get; set; } /// <summary> /// Absolute minimum quantity of this item that should be in stock at any time /// </summary> /// <value>Absolute minimum quantity of this item that should be in stock at any time</value> [DataMember(Name="floor", EmitDefaultValue=false)] [JsonProperty(PropertyName = "floor")] public int? Floor { get; set; } /// <summary> /// Quantity of this item the location wants to keep in stock to ensure stock isn't completely depleted /// </summary> /// <value>Quantity of this item the location wants to keep in stock to ensure stock isn't completely depleted</value> [DataMember(Name="safetyStock", EmitDefaultValue=false)] [JsonProperty(PropertyName = "safetyStock")] public int? SafetyStock { get; set; } /// <summary> /// The distance in miles from this location to the item's destination /// </summary> /// <value>The distance in miles from this location to the item's destination</value> [DataMember(Name="distance", EmitDefaultValue=false)] [JsonProperty(PropertyName = "distance")] public decimal? Distance { get; set; } /// <summary> /// Whether this location can ship to a consumer /// </summary> /// <value>Whether this location can ship to a consumer</value> [DataMember(Name="directShip", EmitDefaultValue=false)] [JsonProperty(PropertyName = "directShip")] public bool? DirectShip { get; set; } /// <summary> /// Whether the location can ship to another location (store), thus restocking that location. /// </summary> /// <value>Whether the location can ship to another location (store), thus restocking that location.</value> [DataMember(Name="transferEnabled", EmitDefaultValue=false)] [JsonProperty(PropertyName = "transferEnabled")] public bool? TransferEnabled { get; set; } /// <summary> /// Whether a consumer can pick up product at this location (store) /// </summary> /// <value>Whether a consumer can pick up product at this location (store)</value> [DataMember(Name="pickup", EmitDefaultValue=false)] [JsonProperty(PropertyName = "pickup")] public bool? Pickup { get; set; } /// <summary> /// The country code of this location /// </summary> /// <value>The country code of this location</value> [DataMember(Name="countryCode", EmitDefaultValue=false)] [JsonProperty(PropertyName = "countryCode")] public string CountryCode { get; set; } /// <summary> /// The currency identifier for the retailPrice /// </summary> /// <value>The currency identifier for the retailPrice</value> [DataMember(Name="currencyID", EmitDefaultValue=false)] [JsonProperty(PropertyName = "currencyID")] public int? CurrencyID { get; set; } /// <summary> /// The price of the product at this location /// </summary> /// <value>The price of the product at this location</value> [DataMember(Name="retailPrice", EmitDefaultValue=false)] [JsonProperty(PropertyName = "retailPrice")] public decimal? RetailPrice { get; set; } /// <summary> /// The inventory locator name of the individual item /// </summary> /// <value>The inventory locator name of the individual item</value> [DataMember(Name="inventoryLocatorName", EmitDefaultValue=false)] [JsonProperty(PropertyName = "inventoryLocatorName")] public string InventoryLocatorName { get; set; } /// <summary> /// List of Inventory Attributes /// </summary> /// <value>List of Inventory Attributes</value> [DataMember(Name="attributes", EmitDefaultValue=false)] [JsonProperty(PropertyName = "attributes")] public List<string> Attributes { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class InventoryResponse {\n"); sb.Append(" LocationName: ").Append(LocationName).Append("\n"); sb.Append(" LocationCode: ").Append(LocationCode).Append("\n"); sb.Append(" TenantID: ").Append(TenantID).Append("\n"); sb.Append(" OnHand: ").Append(OnHand).Append("\n"); sb.Append(" Available: ").Append(Available).Append("\n"); sb.Append(" Allocated: ").Append(Allocated).Append("\n"); sb.Append(" Pending: ").Append(Pending).Append("\n"); sb.Append(" PartNumber: ").Append(PartNumber).Append("\n"); sb.Append(" Upc: ").Append(Upc).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append(" BlockAssignment: ").Append(BlockAssignment).Append("\n"); sb.Append(" Ltd: ").Append(Ltd).Append("\n"); sb.Append(" Floor: ").Append(Floor).Append("\n"); sb.Append(" SafetyStock: ").Append(SafetyStock).Append("\n"); sb.Append(" Distance: ").Append(Distance).Append("\n"); sb.Append(" DirectShip: ").Append(DirectShip).Append("\n"); sb.Append(" TransferEnabled: ").Append(TransferEnabled).Append("\n"); sb.Append(" Pickup: ").Append(Pickup).Append("\n"); sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); sb.Append(" CurrencyID: ").Append(CurrencyID).Append("\n"); sb.Append(" RetailPrice: ").Append(RetailPrice).Append("\n"); sb.Append(" InventoryLocatorName: ").Append(InventoryLocatorName).Append("\n"); sb.Append(" Attributes: ").Append(Attributes).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public new string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
/* * CP20285.cs - IBM EBCDIC (United Kingdom) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-285.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP20285 : ByteEncoding { public CP20285() : base(20285, ToChars, "IBM EBCDIC (United Kingdom)", "IBM285", "IBM285", "IBM285", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u009C', '\u0009', '\u0086', '\u007F', '\u0097', '\u008D', '\u008E', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u009D', '\u0085', '\u0008', '\u0087', '\u0018', '\u0019', '\u0092', '\u008F', '\u001C', '\u001D', '\u001E', '\u001F', '\u0080', '\u0081', '\u0082', '\u0083', '\u0084', '\u000A', '\u0017', '\u001B', '\u0088', '\u0089', '\u008A', '\u008B', '\u008C', '\u0005', '\u0006', '\u0007', '\u0090', '\u0091', '\u0016', '\u0093', '\u0094', '\u0095', '\u0096', '\u0004', '\u0098', '\u0099', '\u009A', '\u009B', '\u0014', '\u0015', '\u009E', '\u001A', '\u0020', '\u00A0', '\u00E2', '\u00E4', '\u00E0', '\u00E1', '\u00E3', '\u00E5', '\u00E7', '\u00F1', '\u0024', '\u002E', '\u003C', '\u0028', '\u002B', '\u007C', '\u0026', '\u00E9', '\u00EA', '\u00EB', '\u00E8', '\u00ED', '\u00EE', '\u00EF', '\u00EC', '\u00DF', '\u0021', '\u00A3', '\u002A', '\u0029', '\u003B', '\u00AC', '\u002D', '\u002F', '\u00C2', '\u00C4', '\u00C0', '\u00C1', '\u00C3', '\u00C5', '\u00C7', '\u00D1', '\u00A6', '\u002C', '\u0025', '\u005F', '\u003E', '\u003F', '\u00F8', '\u00C9', '\u00CA', '\u00CB', '\u00C8', '\u00CD', '\u00CE', '\u00CF', '\u00CC', '\u0060', '\u003A', '\u0023', '\u0040', '\u0027', '\u003D', '\u0022', '\u00D8', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u00AB', '\u00BB', '\u00F0', '\u00FD', '\u00FE', '\u00B1', '\u00B0', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u00AA', '\u00BA', '\u00E6', '\u00B8', '\u00C6', '\u00A4', '\u00B5', '\u00AF', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u00A1', '\u00BF', '\u00D0', '\u00DD', '\u00DE', '\u00AE', '\u00A2', '\u005B', '\u00A5', '\u00B7', '\u00A9', '\u00A7', '\u00B6', '\u00BC', '\u00BD', '\u00BE', '\u005E', '\u005D', '\u007E', '\u00A8', '\u00B4', '\u00D7', '\u007B', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u00AD', '\u00F4', '\u00F6', '\u00F2', '\u00F3', '\u00F5', '\u007D', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u00B9', '\u00FB', '\u00FC', '\u00F9', '\u00FA', '\u00FF', '\u005C', '\u00F7', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u00B2', '\u00D4', '\u00D6', '\u00D2', '\u00D3', '\u00D5', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u00B3', '\u00DB', '\u00DC', '\u00D9', '\u00DA', '\u009F', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x5A; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0x7B; break; case 0x0024: ch = 0x4A; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x7C; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0xB1; break; case 0x005C: ch = 0xE0; break; case 0x005D: ch = 0xBB; break; case 0x005E: ch = 0xBA; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x79; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0xC0; break; case 0x007C: ch = 0x4F; break; case 0x007D: ch = 0xD0; break; case 0x007E: ch = 0xBC; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0x5B; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x6A; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0x5F; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xA1; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0x48; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xA1; break; case 0xFF01: ch = 0x5A; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0x7B; break; case 0xFF04: ch = 0x4A; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x7C; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0xB1; break; case 0xFF3C: ch = 0xE0; break; case 0xFF3D: ch = 0xBB; break; case 0xFF3E: ch = 0xBA; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x79; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0xC0; break; case 0xFF5C: ch = 0x4F; break; case 0xFF5D: ch = 0xD0; break; case 0xFF5E: ch = 0xBC; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 4) switch(ch) { case 0x000B: case 0x000C: case 0x000D: case 0x000E: case 0x000F: case 0x0010: case 0x0011: case 0x0012: case 0x0013: case 0x0018: case 0x0019: case 0x001C: case 0x001D: case 0x001E: case 0x001F: case 0x00B6: break; case 0x0004: ch = 0x37; break; case 0x0005: ch = 0x2D; break; case 0x0006: ch = 0x2E; break; case 0x0007: ch = 0x2F; break; case 0x0008: ch = 0x16; break; case 0x0009: ch = 0x05; break; case 0x000A: ch = 0x25; break; case 0x0014: ch = 0x3C; break; case 0x0015: ch = 0x3D; break; case 0x0016: ch = 0x32; break; case 0x0017: ch = 0x26; break; case 0x001A: ch = 0x3F; break; case 0x001B: ch = 0x27; break; case 0x0020: ch = 0x40; break; case 0x0021: ch = 0x5A; break; case 0x0022: ch = 0x7F; break; case 0x0023: ch = 0x7B; break; case 0x0024: ch = 0x4A; break; case 0x0025: ch = 0x6C; break; case 0x0026: ch = 0x50; break; case 0x0027: ch = 0x7D; break; case 0x0028: ch = 0x4D; break; case 0x0029: ch = 0x5D; break; case 0x002A: ch = 0x5C; break; case 0x002B: ch = 0x4E; break; case 0x002C: ch = 0x6B; break; case 0x002D: ch = 0x60; break; case 0x002E: ch = 0x4B; break; case 0x002F: ch = 0x61; break; case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: ch += 0x00C0; break; case 0x003A: ch = 0x7A; break; case 0x003B: ch = 0x5E; break; case 0x003C: ch = 0x4C; break; case 0x003D: ch = 0x7E; break; case 0x003E: ch = 0x6E; break; case 0x003F: ch = 0x6F; break; case 0x0040: ch = 0x7C; break; case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: ch += 0x0080; break; case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: ch += 0x0087; break; case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: ch += 0x008F; break; case 0x005B: ch = 0xB1; break; case 0x005C: ch = 0xE0; break; case 0x005D: ch = 0xBB; break; case 0x005E: ch = 0xBA; break; case 0x005F: ch = 0x6D; break; case 0x0060: ch = 0x79; break; case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: ch += 0x0020; break; case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: ch += 0x0027; break; case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: ch += 0x002F; break; case 0x007B: ch = 0xC0; break; case 0x007C: ch = 0x4F; break; case 0x007D: ch = 0xD0; break; case 0x007E: ch = 0xBC; break; case 0x007F: ch = 0x07; break; case 0x0080: case 0x0081: case 0x0082: case 0x0083: case 0x0084: ch -= 0x0060; break; case 0x0085: ch = 0x15; break; case 0x0086: ch = 0x06; break; case 0x0087: ch = 0x17; break; case 0x0088: case 0x0089: case 0x008A: case 0x008B: case 0x008C: ch -= 0x0060; break; case 0x008D: ch = 0x09; break; case 0x008E: ch = 0x0A; break; case 0x008F: ch = 0x1B; break; case 0x0090: ch = 0x30; break; case 0x0091: ch = 0x31; break; case 0x0092: ch = 0x1A; break; case 0x0093: case 0x0094: case 0x0095: case 0x0096: ch -= 0x0060; break; case 0x0097: ch = 0x08; break; case 0x0098: case 0x0099: case 0x009A: case 0x009B: ch -= 0x0060; break; case 0x009C: ch = 0x04; break; case 0x009D: ch = 0x14; break; case 0x009E: ch = 0x3E; break; case 0x009F: ch = 0xFF; break; case 0x00A0: ch = 0x41; break; case 0x00A1: ch = 0xAA; break; case 0x00A2: ch = 0xB0; break; case 0x00A3: ch = 0x5B; break; case 0x00A4: ch = 0x9F; break; case 0x00A5: ch = 0xB2; break; case 0x00A6: ch = 0x6A; break; case 0x00A7: ch = 0xB5; break; case 0x00A8: ch = 0xBD; break; case 0x00A9: ch = 0xB4; break; case 0x00AA: ch = 0x9A; break; case 0x00AB: ch = 0x8A; break; case 0x00AC: ch = 0x5F; break; case 0x00AD: ch = 0xCA; break; case 0x00AE: ch = 0xAF; break; case 0x00AF: ch = 0xA1; break; case 0x00B0: ch = 0x90; break; case 0x00B1: ch = 0x8F; break; case 0x00B2: ch = 0xEA; break; case 0x00B3: ch = 0xFA; break; case 0x00B4: ch = 0xBE; break; case 0x00B5: ch = 0xA0; break; case 0x00B7: ch = 0xB3; break; case 0x00B8: ch = 0x9D; break; case 0x00B9: ch = 0xDA; break; case 0x00BA: ch = 0x9B; break; case 0x00BB: ch = 0x8B; break; case 0x00BC: ch = 0xB7; break; case 0x00BD: ch = 0xB8; break; case 0x00BE: ch = 0xB9; break; case 0x00BF: ch = 0xAB; break; case 0x00C0: ch = 0x64; break; case 0x00C1: ch = 0x65; break; case 0x00C2: ch = 0x62; break; case 0x00C3: ch = 0x66; break; case 0x00C4: ch = 0x63; break; case 0x00C5: ch = 0x67; break; case 0x00C6: ch = 0x9E; break; case 0x00C7: ch = 0x68; break; case 0x00C8: ch = 0x74; break; case 0x00C9: ch = 0x71; break; case 0x00CA: ch = 0x72; break; case 0x00CB: ch = 0x73; break; case 0x00CC: ch = 0x78; break; case 0x00CD: ch = 0x75; break; case 0x00CE: ch = 0x76; break; case 0x00CF: ch = 0x77; break; case 0x00D0: ch = 0xAC; break; case 0x00D1: ch = 0x69; break; case 0x00D2: ch = 0xED; break; case 0x00D3: ch = 0xEE; break; case 0x00D4: ch = 0xEB; break; case 0x00D5: ch = 0xEF; break; case 0x00D6: ch = 0xEC; break; case 0x00D7: ch = 0xBF; break; case 0x00D8: ch = 0x80; break; case 0x00D9: ch = 0xFD; break; case 0x00DA: ch = 0xFE; break; case 0x00DB: ch = 0xFB; break; case 0x00DC: ch = 0xFC; break; case 0x00DD: ch = 0xAD; break; case 0x00DE: ch = 0xAE; break; case 0x00DF: ch = 0x59; break; case 0x00E0: ch = 0x44; break; case 0x00E1: ch = 0x45; break; case 0x00E2: ch = 0x42; break; case 0x00E3: ch = 0x46; break; case 0x00E4: ch = 0x43; break; case 0x00E5: ch = 0x47; break; case 0x00E6: ch = 0x9C; break; case 0x00E7: ch = 0x48; break; case 0x00E8: ch = 0x54; break; case 0x00E9: ch = 0x51; break; case 0x00EA: ch = 0x52; break; case 0x00EB: ch = 0x53; break; case 0x00EC: ch = 0x58; break; case 0x00ED: ch = 0x55; break; case 0x00EE: ch = 0x56; break; case 0x00EF: ch = 0x57; break; case 0x00F0: ch = 0x8C; break; case 0x00F1: ch = 0x49; break; case 0x00F2: ch = 0xCD; break; case 0x00F3: ch = 0xCE; break; case 0x00F4: ch = 0xCB; break; case 0x00F5: ch = 0xCF; break; case 0x00F6: ch = 0xCC; break; case 0x00F7: ch = 0xE1; break; case 0x00F8: ch = 0x70; break; case 0x00F9: ch = 0xDD; break; case 0x00FA: ch = 0xDE; break; case 0x00FB: ch = 0xDB; break; case 0x00FC: ch = 0xDC; break; case 0x00FD: ch = 0x8D; break; case 0x00FE: ch = 0x8E; break; case 0x00FF: ch = 0xDF; break; case 0x0110: ch = 0xAC; break; case 0x203E: ch = 0xA1; break; case 0xFF01: ch = 0x5A; break; case 0xFF02: ch = 0x7F; break; case 0xFF03: ch = 0x7B; break; case 0xFF04: ch = 0x4A; break; case 0xFF05: ch = 0x6C; break; case 0xFF06: ch = 0x50; break; case 0xFF07: ch = 0x7D; break; case 0xFF08: ch = 0x4D; break; case 0xFF09: ch = 0x5D; break; case 0xFF0A: ch = 0x5C; break; case 0xFF0B: ch = 0x4E; break; case 0xFF0C: ch = 0x6B; break; case 0xFF0D: ch = 0x60; break; case 0xFF0E: ch = 0x4B; break; case 0xFF0F: ch = 0x61; break; case 0xFF10: case 0xFF11: case 0xFF12: case 0xFF13: case 0xFF14: case 0xFF15: case 0xFF16: case 0xFF17: case 0xFF18: case 0xFF19: ch -= 0xFE20; break; case 0xFF1A: ch = 0x7A; break; case 0xFF1B: ch = 0x5E; break; case 0xFF1C: ch = 0x4C; break; case 0xFF1D: ch = 0x7E; break; case 0xFF1E: ch = 0x6E; break; case 0xFF1F: ch = 0x6F; break; case 0xFF20: ch = 0x7C; break; case 0xFF21: case 0xFF22: case 0xFF23: case 0xFF24: case 0xFF25: case 0xFF26: case 0xFF27: case 0xFF28: case 0xFF29: ch -= 0xFE60; break; case 0xFF2A: case 0xFF2B: case 0xFF2C: case 0xFF2D: case 0xFF2E: case 0xFF2F: case 0xFF30: case 0xFF31: case 0xFF32: ch -= 0xFE59; break; case 0xFF33: case 0xFF34: case 0xFF35: case 0xFF36: case 0xFF37: case 0xFF38: case 0xFF39: case 0xFF3A: ch -= 0xFE51; break; case 0xFF3B: ch = 0xB1; break; case 0xFF3C: ch = 0xE0; break; case 0xFF3D: ch = 0xBB; break; case 0xFF3E: ch = 0xBA; break; case 0xFF3F: ch = 0x6D; break; case 0xFF40: ch = 0x79; break; case 0xFF41: case 0xFF42: case 0xFF43: case 0xFF44: case 0xFF45: case 0xFF46: case 0xFF47: case 0xFF48: case 0xFF49: ch -= 0xFEC0; break; case 0xFF4A: case 0xFF4B: case 0xFF4C: case 0xFF4D: case 0xFF4E: case 0xFF4F: case 0xFF50: case 0xFF51: case 0xFF52: ch -= 0xFEB9; break; case 0xFF53: case 0xFF54: case 0xFF55: case 0xFF56: case 0xFF57: case 0xFF58: case 0xFF59: case 0xFF5A: ch -= 0xFEB1; break; case 0xFF5B: ch = 0xC0; break; case 0xFF5C: ch = 0x4F; break; case 0xFF5D: ch = 0xD0; break; case 0xFF5E: ch = 0xBC; break; default: ch = 0x3F; break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP20285 public class ENCibm285 : CP20285 { public ENCibm285() : base() {} }; // class ENCibm285 }; // namespace I18N.Rare
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.ExpressRoute; using Microsoft.WindowsAzure.Management.ExpressRoute.Models; namespace Microsoft.WindowsAzure.Management.ExpressRoute { internal partial class DedicatedCircuitLinkOperations : IServiceOperations<ExpressRouteManagementClient>, IDedicatedCircuitLinkOperations { /// <summary> /// Initializes a new instance of the DedicatedCircuitLinkOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DedicatedCircuitLinkOperations(ExpressRouteManagementClient client) { this._client = client; } private ExpressRouteManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ExpressRoute.ExpressRouteManagementClient. /// </summary> public ExpressRouteManagementClient Client { get { return this._client; } } /// <summary> /// The New Dedicated Circuit Link operation creates a new dedicated /// circuit link. /// </summary> /// <param name='serviceKey'> /// Required. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<ExpressRouteOperationResponse> BeginNewAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (vnetName == null) { throw new ArgumentNullException("vnetName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "BeginNewAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; url = url + Uri.EscapeDataString(serviceKey); url = url + "/vnets/"; url = url + Uri.EscapeDataString(vnetName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Remove Dedicated Circuit Link operation deletes an existing /// dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Required. Service key representing the dedicated circuit. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<ExpressRouteOperationResponse> BeginRemoveAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (vnetName == null) { throw new ArgumentNullException("vnetName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "BeginRemoveAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; url = url + Uri.EscapeDataString(serviceKey); url = url + "/vnets/"; url = url + Uri.EscapeDataString(vnetName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationAsyncResponseElement = responseDoc.Element(XName.Get("GatewayOperationAsyncResponse", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationAsyncResponseElement != null) { XElement idElement = gatewayOperationAsyncResponseElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.OperationId = idInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Dedicated Circuit Link operation retrieves the specified /// dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Dedicated Circuit Link operation response. /// </returns> public async Task<DedicatedCircuitLinkGetResponse> GetAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } if (vnetName == null) { throw new ArgumentNullException("vnetName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; url = url + Uri.EscapeDataString(serviceKey); url = url + "/vnets/"; url = url + Uri.EscapeDataString(vnetName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinkElement = responseDoc.Element(XName.Get("DedicatedCircuitLink", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinkElement != null) { AzureDedicatedCircuitLink dedicatedCircuitLinkInstance = new AzureDedicatedCircuitLink(); result.DedicatedCircuitLink = dedicatedCircuitLinkInstance; XElement stateElement = dedicatedCircuitLinkElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { DedicatedCircuitLinkState stateInstance = ((DedicatedCircuitLinkState)Enum.Parse(typeof(DedicatedCircuitLinkState), stateElement.Value, true)); dedicatedCircuitLinkInstance.State = stateInstance; } XElement vnetNameElement = dedicatedCircuitLinkElement.Element(XName.Get("VnetName", "http://schemas.microsoft.com/windowsazure")); if (vnetNameElement != null) { string vnetNameInstance = vnetNameElement.Value; dedicatedCircuitLinkInstance.VnetName = vnetNameInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken) { // Validate if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationId", operationId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/operation/"; url = url + Uri.EscapeDataString(operationId); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationElement != null) { XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { string dataInstance = dataElement.Value; result.Data = dataInstance; } XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Dedicated Circuit Links operation retrieves a list of /// Vnets that are linked to the circuit with the specified service /// key. /// </summary> /// <param name='serviceKey'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Dedicated Circuit Link operation response. /// </returns> public async Task<DedicatedCircuitLinkListResponse> ListAsync(string serviceKey, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; if (serviceKey != null) { url = url + Uri.EscapeDataString(serviceKey); } url = url + "/vnets"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinksSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuitLinks", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinksSequenceElement != null) { foreach (XElement dedicatedCircuitLinksElement in dedicatedCircuitLinksSequenceElement.Elements(XName.Get("DedicatedCircuitLink", "http://schemas.microsoft.com/windowsazure"))) { AzureDedicatedCircuitLink dedicatedCircuitLinkInstance = new AzureDedicatedCircuitLink(); result.DedicatedCircuitLinks.Add(dedicatedCircuitLinkInstance); XElement stateElement = dedicatedCircuitLinksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { DedicatedCircuitLinkState stateInstance = ((DedicatedCircuitLinkState)Enum.Parse(typeof(DedicatedCircuitLinkState), stateElement.Value, true)); dedicatedCircuitLinkInstance.State = stateInstance; } XElement vnetNameElement = dedicatedCircuitLinksElement.Element(XName.Get("VnetName", "http://schemas.microsoft.com/windowsazure")); if (vnetNameElement != null) { string vnetNameInstance = vnetNameElement.Value; dedicatedCircuitLinkInstance.VnetName = vnetNameInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The New Dedicated Circuit Link operation creates a new dedicated /// circuit link. /// </summary> /// <param name='serviceKey'> /// Required. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ExpressRouteOperationStatusResponse> NewAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "NewAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse response = await client.DedicatedCircuitLinks.BeginNewAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != ExpressRouteOperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != ExpressRouteOperationStatus.Successful) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Remove Dedicated Circuit Link operation deletes an existing /// dedicated circuit link. /// </summary> /// <param name='serviceKey'> /// Required. Service Key associated with the dedicated circuit. /// </param> /// <param name='vnetName'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ExpressRouteOperationStatusResponse> RemoveAsync(string serviceKey, string vnetName, CancellationToken cancellationToken) { ExpressRouteManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("vnetName", vnetName); TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationResponse response = await client.DedicatedCircuitLinks.BeginRemoveAsync(serviceKey, vnetName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); ExpressRouteOperationStatusResponse result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != ExpressRouteOperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.DedicatedCircuitLinks.GetOperationStatusAsync(response.OperationId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != ExpressRouteOperationStatus.Successful) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
namespace FakeItEasy.Specs { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using FakeItEasy.Configuration; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public delegate void CustomEventHandler(object sender, CustomEventArgs e); public delegate void ReferenceTypeEventHandler(ReferenceType arg); public delegate void ValueTypeEventHandler(int arg); public class CustomEventArgs : EventArgs { } public class ReferenceType { } public class DerivedReferenceType : ReferenceType { } public class EventRaisingSpecs { private readonly EventArgs eventArgs = new EventArgs(); private readonly CustomEventArgs customEventArgs = new CustomEventArgs(); private readonly ReferenceType referenceTypeEventArgs = new ReferenceType(); private readonly DerivedReferenceType derivedReferenceTypeEventArgs = new DerivedReferenceType(); public interface IEvents { event EventHandler UnsubscribedEvent; event EventHandler SubscribedEvent; event EventHandler<CustomEventArgs> GenericEvent; event EventHandler<ReferenceType> EventHandlerOfNonEventArgsEvent; event CustomEventHandler CustomEvent; event ReferenceTypeEventHandler ReferenceTypeEvent; event ValueTypeEventHandler ValueTypeEvent; [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Test.")] event Action<int, bool> ActionEvent; } private static IEvents? fake; private static object? sampleSender; private static IEvents Fake { get => fake ?? throw new InvalidOperationException(nameof(Fake) + " is not initialized"); } private static object SampleSender { get => sampleSender ?? throw new InvalidOperationException(nameof(SampleSender) + " is not initialized"); } private static object? CapturedSender { get; set; } private static object? CapturedArgs1 { get; set; } private static object? CapturedArgs2 { get; set; } [Background] public void Background() { fake = A.Fake<IEvents>(); sampleSender = new object(); Fake.SubscribedEvent += (sender, e) => { CapturedSender = sender; CapturedArgs1 = e; }; Fake.EventHandlerOfNonEventArgsEvent += (sender, e) => { CapturedSender = sender; CapturedArgs1 = e; }; Fake.GenericEvent += (sender, e) => { CapturedSender = sender; CapturedArgs1 = e; }; Fake.CustomEvent += (sender, e) => { CapturedSender = sender; CapturedArgs1 = e; }; Fake.ReferenceTypeEvent += arg => { CapturedArgs1 = arg; }; Fake.ValueTypeEvent += arg => { CapturedArgs1 = arg; }; Fake.ActionEvent += (arg1, arg2) => { CapturedArgs1 = arg1; CapturedArgs2 = arg2; }; } [Scenario] public void UnsubscribedEvent( Exception exception) { "Given an event with no subscribers" .See(() => nameof(Fake.UnsubscribedEvent)); "When I raise the event" .x(() => exception = Record.Exception(() => Fake.UnsubscribedEvent += Raise.WithEmpty())); "Then the call doesn't throw" .x(() => exception.Should().BeNull()); } [Scenario] public void WithEmpty() { "Given an event of type EventHandler" .See(() => nameof(Fake.SubscribedEvent)); "When I raise the event without specifying sender or arguments" .x(() => Fake.SubscribedEvent += Raise.WithEmpty()); "Then the fake is passed as the sender" .x(() => CapturedSender.Should().BeSameAs(Fake)); "And an empty EventArgs is passed as the event arguments" .x(() => CapturedArgs1.Should().Be(EventArgs.Empty)); } [Scenario] public void EventArguments() { "Given an event of type EventHandler" .See(() => nameof(Fake.SubscribedEvent)); "When I raise the event specifying only the event arguments" .x(() => Fake.SubscribedEvent += Raise.With(this.eventArgs)); "Then the fake is passed as the sender" .x(() => CapturedSender.Should().BeSameAs(Fake)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.eventArgs)); } [Scenario] public void SenderAndEventArguments() { "Given an event of type EventHandler" .See(() => nameof(Fake.SubscribedEvent)); "When I raise the event specifying the sender and the event arguments" .x(() => Fake.SubscribedEvent += Raise.With(SampleSender, this.eventArgs)); "Then the supplied sender is passed as the event sender" .x(() => CapturedSender.Should().BeSameAs(SampleSender)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.eventArgs)); } [Scenario] public void NullSenderAndEventArguments() { "Given an event of type EventHandler" .See(() => nameof(Fake.SubscribedEvent)); "When I raise the event specifying the event arguments and a null sender" .x(() => Fake.SubscribedEvent += Raise.With(null, this.eventArgs)); "Then null is passed as the event sender" .x(() => CapturedSender.Should().BeNull()); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.eventArgs)); } [Scenario] public void MultipleSubscribers( int handler1InvocationCount, int handler2InvocationCount) { "Given an event of type EventHandler" .See(() => nameof(Fake.SubscribedEvent)); "And the event has multiple subscribers" .x(() => { Fake.SubscribedEvent += (s, e) => handler1InvocationCount++; Fake.SubscribedEvent += (s, e) => handler2InvocationCount++; }); "When I raise the event" .x(() => Fake.SubscribedEvent += Raise.WithEmpty()); "Then the first subscriber is invoked once" .x(() => handler1InvocationCount.Should().Be(1)); "And the second subscriber is invoked once" .x(() => handler2InvocationCount.Should().Be(1)); } [Scenario] public void CustomEventArguments() { "Given an event of type EventHandler with custom event arguments type" .See(() => nameof(Fake.GenericEvent)); "When I raise the event specifying only the event arguments" .x(() => Fake.GenericEvent += Raise.With(this.customEventArgs)); "Then the fake is passed as the sender" .x(() => CapturedSender.Should().BeSameAs(Fake)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.customEventArgs)); } [Scenario] public void SenderAndCustomEventArguments() { "Given an event of type EventHandler with custom event arguments type" .See(() => nameof(Fake.GenericEvent)); "When I raise the event specifying the sender and the event arguments" .x(() => Fake.GenericEvent += Raise.With(SampleSender, this.customEventArgs)); "Then the supplied sender is passed as the event sender" .x(() => CapturedSender.Should().BeSameAs(SampleSender)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.customEventArgs)); } [Scenario] public void NullSenderAndCustomEventArguments() { "Given an event of type EventHandler with custom event arguments type" .See(() => nameof(Fake.GenericEvent)); "When I raise the event specifying the event arguments and a null sender" .x(() => Fake.GenericEvent += Raise.With(null, this.customEventArgs)); "Then null is passed as the event sender" .x(() => CapturedSender.Should().BeNull()); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.customEventArgs)); } [Scenario] public void EventArgumentsThatDoNotExtendEventArg() { "Given an event of type EventHandler with custom event arguments type that does not extend EventArgs" .See(() => nameof(Fake.EventHandlerOfNonEventArgsEvent)); "When I raise the event specifying only the event arguments" .x(() => Fake.EventHandlerOfNonEventArgsEvent += Raise.With(this.referenceTypeEventArgs)); "Then the fake is passed as the sender" .x(() => CapturedSender.Should().BeSameAs(Fake)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.referenceTypeEventArgs)); } [Scenario] public void FreeformEventHandler() { "Given an event of a custom delegate type that takes a sender and event arguments" .See(() => nameof(Fake.CustomEvent)); "When I raise the specifying the sender and the event arguments" .x(() => Fake.CustomEvent += Raise.FreeForm<CustomEventHandler>.With(SampleSender, this.customEventArgs)); "Then the supplied sender is passed as the event sender" .x(() => CapturedSender.Should().BeSameAs(SampleSender)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.customEventArgs)); } [Scenario] public void FreeformReferenceTypeEventHandler() { "Given an event of a custom delegate type taking only a reference type as an argument" .See(() => nameof(Fake.ReferenceTypeEvent)); "When I raise the event as freeform specifying the arguments" .x(() => Fake.ReferenceTypeEvent += Raise.FreeForm<ReferenceTypeEventHandler>.With(this.referenceTypeEventArgs)); "Then the supplied value is passed as the event argument" .x(() => CapturedArgs1.Should().BeSameAs(this.referenceTypeEventArgs)); } [Scenario] public void FreeformReferenceTypeEventHandlerWithDerivedArguments() { "Given an event of a custom delegate type taking only a reference type as an argument" .See(() => nameof(Fake.ReferenceTypeEvent)); "When I raise the event as freeform specifying an argument of a derived type" .x(() => Fake.ReferenceTypeEvent += Raise.FreeForm<ReferenceTypeEventHandler>.With(this.derivedReferenceTypeEventArgs)); "Then the supplied value is passed as the event argument" .x(() => CapturedArgs1.Should().BeSameAs(this.derivedReferenceTypeEventArgs)); } [Scenario] public void FreeformReferenceTypeEventHandlerWithInvalidArgumentType( Exception exception) { const string ExpectedMessage = "The event has the signature (FakeItEasy.Specs.ReferenceType), " + "but the provided arguments have types (System.Collections.Hashtable)."; "Given an event of a custom delegate type taking only a reference type as an argument" .See(() => nameof(Fake.ReferenceTypeEvent)); "When I raise the event as freeform specifying an argument of an invalid type" .x(() => exception = Record.Exception(() => Fake.ReferenceTypeEvent += Raise.FreeForm<ReferenceTypeEventHandler>.With(new Hashtable()))); "Then the call fails with a meaningful message" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And .Message.Should().Be(ExpectedMessage)); } [Scenario] public void FreeformValueTypeEventHandlerWithNullValue( Exception exception) { "Given an event of a custom delegate type taking only a value type as an argument" .See(() => nameof(Fake.ValueTypeEvent)); "When I raise the event as freeform specifying a null argument" .x(() => exception = Record.Exception(() => Fake.ValueTypeEvent += Raise.FreeForm<ValueTypeEventHandler>.With((object?)null))); "Then the call fails with a meaningful message" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .And.Message.Should().Be( "The event has the signature (System.Int32), but the provided arguments have types (NULL).")); } [Scenario] public void FreeformActionEvent() { "Given an event of type Action" .See(() => nameof(Fake.ActionEvent)); "When I raise the event as freeform specifying the arguments" .x(() => Fake.ActionEvent += Raise.FreeForm<Action<int, bool>>.With(19, true)); "Then the first value is passed as the first event argument" .x(() => CapturedArgs1.Should().Be(19)); "Then the second value is passed as the second event argument" .x(() => CapturedArgs2.Should().Be(true)); } [Scenario] public void DynamicCustomEventHandler() { "Given an event of a custom delegate type that takes a sender and event arguments" .See(() => nameof(Fake.CustomEvent)); "When I raise the event specifying the sender and the event arguments" .x(() => Fake.CustomEvent += Raise.FreeForm.With(SampleSender, this.customEventArgs)); "Then the supplied sender is passed as the event sender" .x(() => CapturedSender.Should().BeSameAs(SampleSender)); "And the supplied value is passed as the event arguments" .x(() => CapturedArgs1.Should().BeSameAs(this.customEventArgs)); } [Scenario] public void DynamicReferenceTypeEventHandler() { "Given an event of a custom delegate type taking only a reference type as an argument" .See(() => nameof(Fake.ReferenceTypeEvent)); "When I raise the event specifying the arguments" .x(() => Fake.ReferenceTypeEvent += Raise.FreeForm.With(this.referenceTypeEventArgs)); "Then the supplied value is passed as the event argument" .x(() => CapturedArgs1.Should().BeSameAs(this.referenceTypeEventArgs)); } [Scenario] public void DynamicReferenceTypeEventHandlerWithDerivedArguments() { "Given an event of a custom delegate type taking only a reference type as an argument" .See(() => nameof(Fake.ReferenceTypeEvent)); "When I raise the event specifying an argument of a derived type" .x(() => Fake.ReferenceTypeEvent += Raise.FreeForm.With(this.derivedReferenceTypeEventArgs)); "Then the supplied value is passed as the event argument" .x(() => CapturedArgs1.Should().BeSameAs(this.derivedReferenceTypeEventArgs)); } [Scenario] public void DynamicReferenceTypeEventHandlerWithInvalidArgumentType( Exception exception) { const string ExpectedMessage = "The event has the signature (FakeItEasy.Specs.ReferenceType), " + "but the provided arguments have types (System.Collections.Hashtable)."; "Given an event of a custom delegate type taking only a reference type as an argument" .See(() => nameof(Fake.ReferenceTypeEvent)); "When I raise the event specifying an argument of an invalid type" .x(() => exception = Record.Exception(() => Fake.ReferenceTypeEvent += Raise.FreeForm.With(new Hashtable()))); "Then the call fails with a meaningful message" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>().And .Message.Should().Be(ExpectedMessage)); } [Scenario] public void DynamicValueTypeEventHandlerWithNullValue( Exception exception) { "Given an event of a custom delegate type taking only a value type as an argument" .See(() => nameof(Fake.ValueTypeEvent)); "When I raise the event specifying a null argument" .x(() => exception = Record.Exception(() => Fake.ValueTypeEvent += Raise.FreeForm.With((object?)null))); "Then the call fails with a meaningful message" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>() .And.Message.Should().Be( "The event has the signature (System.Int32), but the provided arguments have types (NULL).")); } [Scenario] public void DynamicActionEvent() { "Given an event of type Action" .See(() => nameof(Fake.ActionEvent)); "When I raise the event specifying the arguments" .x(() => Fake.ActionEvent += Raise.FreeForm.With(19, true)); "Then the first value is passed as the first event argument" .x(() => CapturedArgs1.Should().Be(19)); "Then the second value is passed as the second event argument" .x(() => CapturedArgs2.Should().Be(true)); } [Scenario] public void DynamicRaiseAssignmentToNonDelegate(string s, Exception exception) { "When I assign Raise.FreeForm.With to something that isn't a delegate" .x(() => exception = Record.Exception(() => s = Raise.FreeForm.With("foo", 42))); "Then it throws an InvalidCastException" .x(() => exception.Should().BeAnExceptionOfType<InvalidCastException>()); "And the exception message describes the attempted cast" .x(() => exception.Message.Should().Be( "Unable to cast object of type 'FakeItEasy.Core.DynamicRaiser' to type 'System.String'.")); } [Scenario] public void DynamicRaiseWithWrongArguments(Exception exception) { "Given an event of a custom delegate type that takes a sender and event arguments" .See(() => nameof(Fake.CustomEvent)); "When I raise the event specifying incorrect arguments" .x(() => exception = Record.Exception(() => Fake.CustomEvent += Raise.FreeForm.With("foo", 42, true))); "Then it throws a FakeConfigurationException" .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()); "And the exception message describes the expected and actual arguments" .x(() => exception.Message.Should().Be( "The event has the signature (System.Object, FakeItEasy.Specs.CustomEventArgs), but the provided arguments have types (System.String, System.Int32, System.Boolean).")); } [Scenario] public void RaisingInternalEvent(ClassWithInternalEventVisibleToDynamicProxy fake, EventHandler handler) { "Given a fake of a class with an internal event" .x(() => fake = A.Fake<ClassWithInternalEventVisibleToDynamicProxy>()); "And a fake event handler" .x(() => handler = A.Fake<EventHandler>()); "And the fake handler is subscribed to the fake's event" .x(() => fake.TheEvent += handler); "When I raise the event" .x(() => fake.TheEvent += Raise.WithEmpty()); "Then the handler is called" .x(() => A.CallTo(handler).MustHaveHappened()); } } }
namespace Macabresoft.Macabre2D.Tests.Framework.Physics; using Macabresoft.Macabre2D.Framework; using Microsoft.Xna.Framework; using NSubstitute; using NUnit.Framework; [TestFixture] public static class CircleColliderTests { [Test] [Category("Unit Tests")] [TestCase(0f, 0f, 1f, 0f, 0f, 0.5f, true, TestName = "Circle to Circle Collision - First Contains Second")] [TestCase(0.5f, 0f, 1f, 0f, 0f, 1f, true, TestName = "Circle to Circle Collision - Right Collision")] [TestCase(-0.5f, 0f, 1f, 0f, 0f, 1f, true, TestName = "Circle to Circle Collision - Left Collision")] [TestCase(3f, 3f, 1f, 0f, 0f, 1f, false, TestName = "Circle to Circle Collision - No Collision")] public static void CircleCollider_CollidesWithCircleTest( float x1, float y1, float r1, float x2, float y2, float r2, bool collisionOccured) { var circleBody1 = new DynamicPhysicsBody(); var circleBody2 = new DynamicPhysicsBody(); var scene = Substitute.For<IScene>(); circleBody1.Initialize(scene, new Entity()); circleBody2.Initialize(scene, new Entity()); circleBody1.SetWorldPosition(new Vector2(x1, y1)); circleBody1.Collider = new CircleCollider(r1); circleBody2.SetWorldPosition(new Vector2(x2, y2)); circleBody2.Collider = new CircleCollider(r2); Assert.AreEqual(collisionOccured, circleBody1.Collider.CollidesWith(circleBody2.Collider, out var collision1)); Assert.AreEqual(collisionOccured, circleBody2.Collider.CollidesWith(circleBody1.Collider, out var collision2)); if (collisionOccured) { Assert.AreEqual(collision1.MinimumTranslationVector.Length(), collision2.MinimumTranslationVector.Length(), 0.0001f); Assert.AreEqual(collision1.FirstCollider, collision2.SecondCollider); Assert.AreEqual(collision1.SecondCollider, collision2.FirstCollider); Assert.AreEqual(collision1.FirstContainsSecond, collision2.SecondContainsFirst); Assert.AreEqual(collision1.SecondContainsFirst, collision2.FirstContainsSecond); var originalPosition = circleBody1.Transform.Position; circleBody1.SetWorldPosition(originalPosition + collision1.MinimumTranslationVector); Assert.False(circleBody1.Collider.CollidesWith(circleBody2.Collider, out collision1)); circleBody1.SetWorldPosition(originalPosition); circleBody2.SetWorldPosition(circleBody2.Transform.Position + collision2.MinimumTranslationVector); Assert.False(circleBody2.Collider.CollidesWith(circleBody1.Collider, out collision2)); } else { Assert.Null(collision1); Assert.Null(collision2); } } [Test] [Category("Unit Tests")] [TestCase(0f, 0f, 1f, 0f, 0f, 0.5f, 0.5f, true, TestName = "Circle to Quad Collision - Circle Contains Square")] [TestCase(0f, 0f, 0.5f, 0f, 0f, 1f, 1f, true, TestName = "Circle to Quad Collision - Square Contains Circle")] [TestCase(0.5f, 0f, 0.5f, 0f, 0f, 1f, 1f, true, TestName = "Circle to Quad Collision - Right Collision")] [TestCase(-0.5f, 0f, 0.5f, 0f, 0f, 1f, 1f, true, TestName = "Circle to Quad Collision - Left Collision")] [TestCase(3f, 3f, 1f, 0f, 0f, 1f, 1f, false, TestName = "Circle to Quad Collision - No Collision")] [TestCase(0f, -130f, 50f, 0f, -200f, 500f, 50f, true, TestName = "Circle to Quad Collision - Physics Test Failure")] public static void CircleCollider_CollidesWithQuadTest( float x1, float y1, float r1, float x2, float y2, float w, float h, bool collisionOccured) { var circleBody = new DynamicPhysicsBody(); var quadBody = new DynamicPhysicsBody(); var scene = Substitute.For<IScene>(); circleBody.Initialize(scene, new Entity()); quadBody.Initialize(scene, new Entity()); circleBody.SetWorldPosition(new Vector2(x1, y1)); circleBody.Collider = new CircleCollider(r1); quadBody.SetWorldPosition(new Vector2(x2, y2)); quadBody.Collider = PolygonCollider.CreateRectangle(w, h); Assert.AreEqual(collisionOccured, circleBody.Collider.CollidesWith(quadBody.Collider, out var collision1)); Assert.AreEqual(collisionOccured, quadBody.Collider.CollidesWith(circleBody.Collider, out var collision2)); if (collisionOccured) { Assert.AreEqual(collision1.MinimumTranslationVector.Length(), collision2.MinimumTranslationVector.Length(), 0.0001f); Assert.AreEqual(collision1.FirstCollider, collision2.SecondCollider); Assert.AreEqual(collision1.SecondCollider, collision2.FirstCollider); Assert.AreEqual(collision1.FirstContainsSecond, collision2.SecondContainsFirst); Assert.AreEqual(collision1.SecondContainsFirst, collision2.FirstContainsSecond); var originalPosition = circleBody.Transform.Position; circleBody.SetWorldPosition(originalPosition + collision1.MinimumTranslationVector); Assert.False(circleBody.Collider.CollidesWith(quadBody.Collider, out collision1)); circleBody.SetWorldPosition(originalPosition); quadBody.SetWorldPosition(quadBody.Transform.Position + collision2.MinimumTranslationVector); Assert.False(quadBody.Collider.CollidesWith(circleBody.Collider, out collision2)); } else { Assert.Null(collision1); Assert.Null(collision2); } } [Test] [Category("Unit Tests")] [TestCase(0f, 0f, 1f, 0f, 0f, 1f, false, TestName = "Circle Contains Circle - Same Circle")] [TestCase(0f, 0f, 1f, 0f, 0f, 0.5f, true, TestName = "Circle Contains Circle - Inside at Center")] [TestCase(0f, 0f, 1f, 0.25f, -0.25f, 0.25f, true, TestName = "Circle Contains Circle - Inside Offset")] [TestCase(0f, 0f, 1f, 0.25f, -0.25f, 1f, false, TestName = "Circle Contains Circle - Inside But Does Not Contain")] [TestCase(0f, 0f, 1f, 3f, 3f, 1f, false, TestName = "Circle Contains Circle - Outside")] [TestCase(0f, 0f, 1f, 2f, 0f, 1f, false, TestName = "Circle Contains Circle - Edges Touch")] public static void CircleCollider_ContainsCircleTest( float x1, float y1, float r1, float x2, float y2, float r2, bool shouldContain) { var circleBody1 = new DynamicPhysicsBody(); var circleBody2 = new DynamicPhysicsBody(); var scene = Substitute.For<IScene>(); circleBody1.Initialize(scene, new Entity()); circleBody2.Initialize(scene, new Entity()); circleBody1.SetWorldPosition(new Vector2(x1, y1)); circleBody1.Collider = new CircleCollider(r1); circleBody2.SetWorldPosition(new Vector2(x2, y2)); circleBody2.Collider = new CircleCollider(r2); Assert.AreEqual(shouldContain, circleBody1.Collider.Contains(circleBody2.Collider)); } [Test] [Category("Unit Tests")] [TestCase(0f, 0f, 1f, 0f, 0f, true, TestName = "Circle Contains Point - Point is Center")] [TestCase(0f, 0f, 1f, 0f, 1f, true, TestName = "Circle Contains Point - Point is on Edge")] [TestCase(0f, 0f, 1f, 0.25f, 0.25f, true, TestName = "Circle Contains Point - Point is Inside")] [TestCase(0f, 0f, 1f, 1f, 1f, false, TestName = "Circle Contains Point - Point is Outside")] [TestCase(0f, 0f, 1f, 100f, 100f, false, TestName = "Circle Contains Point - Point is Way Outside")] public static void CircleCollider_ContainsPointTest( float x1, float y1, float r1, float x2, float y2, bool shouldContain) { var circleBody = new DynamicPhysicsBody(); var scene = Substitute.For<IScene>(); circleBody.Initialize(scene, new Entity()); circleBody.SetWorldPosition(new Vector2(x1, y1)); circleBody.Collider = new CircleCollider(r1); var circle = circleBody.Collider as CircleCollider; Assert.AreEqual(shouldContain, circle.Contains(new Vector2(x2, y2))); } [Test] [Category("Unit Tests")] [TestCase(0f, 0f, 1f, 0f, 0f, 1f, 1f, true, TestName = "Circle Contains Quad - Inside at Center")] [TestCase(0f, 0f, 1f, 0.25f, -0.25f, 0.25f, 0.5f, true, TestName = "Circle Contains Quad - Inside Offset")] [TestCase(0f, 0f, 1f, 0.25f, -0.25f, 2f, 1f, false, TestName = "Circle Contains Quad - Inside But Does Not Contain")] [TestCase(0f, 0f, 1f, 3f, 3f, 1f, 1f, false, TestName = "Circle Contains Quad - Outside")] [TestCase(0f, 0f, 1f, 2f, 0f, 2f, 2f, false, TestName = "Circle Contains Quad - Edges Touch")] public static void CircleCollider_ContainsQuadTest( float x1, float y1, float r1, float x2, float y2, float w, float h, bool shouldContain) { var circleBody = new DynamicPhysicsBody(); var quadBody = new DynamicPhysicsBody(); var scene = Substitute.For<IScene>(); circleBody.Initialize(scene, new Entity()); quadBody.Initialize(scene, new Entity()); circleBody.SetWorldPosition(new Vector2(x1, y1)); circleBody.Collider = new CircleCollider(r1); quadBody.SetWorldPosition(new Vector2(x2, y2)); quadBody.Collider = PolygonCollider.CreateRectangle(w, h); Assert.AreEqual(shouldContain, circleBody.Collider.Contains(quadBody.Collider)); } [Test] [Category("Unit Tests")] [TestCase(0f, 0f, 1f, 0f, -2f, 0f, 1f, 5f, true, 0f, -1f, 0f, -1f, TestName = "Raycast on Circle - Ray Hits From Bottom")] [TestCase(0f, 0f, 1f, 0f, 2f, 0f, -1f, 5f, true, 0f, 1f, 0f, 1f, TestName = "Raycast on Circle - Ray Hits From Top")] [TestCase(0f, 0f, 1f, -2f, 0f, 1f, 0f, 5f, true, -1f, 0f, -1f, 0f, TestName = "Raycast on Circle - Ray Hits From Left")] [TestCase(0f, 0f, 1f, 2f, 0f, -1f, 0f, 5f, true, 1f, 0f, 1f, 0f, TestName = "Raycast on Circle - Ray Hits From Right")] [TestCase(0f, 0f, 1f, 2f, 2f, -1f, 0f, 5f, false, TestName = "Raycast on Circle - Ray Misses")] [TestCase(0f, 0f, 1f, -2f, 1f, 1f, 0f, 5f, true, 0f, 1f, 0f, 1f, TestName = "Raycast on Circle - Ray Hits Top Most Point")] public static void CircleCollider_IsHitByTest( float cx, float cy, float r, float rx, float ry, float directionX, float directionY, float distance, bool shouldHit, float ix = 0f, float iy = 0f, float nx = 0f, float ny = 0f) { var circleBody = new DynamicPhysicsBody(); circleBody.SetWorldPosition(new Vector2(cx, cy)); circleBody.Collider = new CircleCollider(r); var ray = new LineSegment(new Vector2(rx, ry), new Vector2(directionX, directionY), distance); Assert.AreEqual(shouldHit, circleBody.Collider.IsHitBy(ray, out var hit)); if (shouldHit) { var normal = new Vector2(nx, ny); var intersection = new Vector2(ix, iy); Assert.AreEqual(normal.X, hit.Normal.X, 0.0001f); Assert.AreEqual(normal.Y, hit.Normal.Y, 0.0001f); Assert.AreEqual(intersection.X, hit.ContactPoint.X, 0.0001f); Assert.AreEqual(intersection.Y, hit.ContactPoint.Y, 0.0001f); Assert.AreEqual(circleBody.Collider, hit.Collider); } } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using CALI.Database.Contracts; using CALI.Database.Contracts.Data; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace CALI.Database.Logic.Data { [Serializable] public abstract partial class BinaryDataLogicBase : LogicBase<BinaryDataLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<BinaryDataContract> Results; public BinaryDataLogicBase() { Results = new List<BinaryDataContract>(); } /// <summary> /// Run BinaryData_Insert. /// </summary> /// <param name="fldDataType">Value for DataType</param> /// <param name="fldHash">Value for Hash</param> /// <param name="fldData">Value for Data</param> /// <param name="fldDateCreated">Value for DateCreated</param> /// <returns>The new ID</returns> public virtual int? Insert(string fldDataType , string fldHash , byte[] fldData , DateTime fldDateCreated ) { int? result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@DataType", fldDataType) , new SqlParameter("@Hash", fldHash) , new SqlParameter("@Data", fldData) , new SqlParameter("@DateCreated", fldDateCreated) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run BinaryData_Insert. /// </summary> /// <param name="fldDataType">Value for DataType</param> /// <param name="fldHash">Value for Hash</param> /// <param name="fldData">Value for Data</param> /// <param name="fldDateCreated">Value for DateCreated</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(string fldDataType , string fldHash , byte[] fldData , DateTime fldDateCreated , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[BinaryData_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@DataType", fldDataType) , new SqlParameter("@Hash", fldHash) , new SqlParameter("@Data", fldData) , new SqlParameter("@DateCreated", fldDateCreated) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(BinaryDataContract row) { int? result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@DataType", row.DataType) , new SqlParameter("@Hash", row.Hash) , new SqlParameter("@Data", row.Data) , new SqlParameter("@DateCreated", row.DateCreated) }); result = (int?)cmd.ExecuteScalar(); row.BinaryDataId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(BinaryDataContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Data].[BinaryData_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@DataType", row.DataType) , new SqlParameter("@Hash", row.Hash) , new SqlParameter("@Data", row.Data) , new SqlParameter("@DateCreated", row.DateCreated) }); result = (int?)cmd.ExecuteScalar(); row.BinaryDataId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<BinaryDataContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<BinaryDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run BinaryData_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <param name="fldDataType">Value for DataType</param> /// <param name="fldHash">Value for Hash</param> /// <param name="fldData">Value for Data</param> /// <param name="fldDateCreated">Value for DateCreated</param> public virtual int Update(int fldBinaryDataId , string fldDataType , string fldHash , byte[] fldData , DateTime fldDateCreated ) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) , new SqlParameter("@DataType", fldDataType) , new SqlParameter("@Hash", fldHash) , new SqlParameter("@Data", fldData) , new SqlParameter("@DateCreated", fldDateCreated) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run BinaryData_Update. /// </summary> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <param name="fldDataType">Value for DataType</param> /// <param name="fldHash">Value for Hash</param> /// <param name="fldData">Value for Data</param> /// <param name="fldDateCreated">Value for DateCreated</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldBinaryDataId , string fldDataType , string fldHash , byte[] fldData , DateTime fldDateCreated , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[BinaryData_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) , new SqlParameter("@DataType", fldDataType) , new SqlParameter("@Hash", fldHash) , new SqlParameter("@Data", fldData) , new SqlParameter("@DateCreated", fldDateCreated) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(BinaryDataContract row) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", row.BinaryDataId) , new SqlParameter("@DataType", row.DataType) , new SqlParameter("@Hash", row.Hash) , new SqlParameter("@Data", row.Data) , new SqlParameter("@DateCreated", row.DateCreated) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(BinaryDataContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[BinaryData_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", row.BinaryDataId) , new SqlParameter("@DataType", row.DataType) , new SqlParameter("@Hash", row.Hash) , new SqlParameter("@Data", row.Data) , new SqlParameter("@DateCreated", row.DateCreated) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<BinaryDataContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<BinaryDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run BinaryData_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> public virtual int Delete(int fldBinaryDataId ) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run BinaryData_Delete. /// </summary> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldBinaryDataId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[BinaryData_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(BinaryDataContract row) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", row.BinaryDataId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(BinaryDataContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Data].[BinaryData_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", row.BinaryDataId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<BinaryDataContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<BinaryDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldBinaryDataId ) { bool result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldBinaryDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[BinaryData_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run BinaryData_Search, and return results as a list of BinaryDataRow. /// </summary> /// <param name="fldDataType">Value for DataType</param> /// <param name="fldHash">Value for Hash</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool Search(string fldDataType , string fldHash ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_Search]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@DataType", fldDataType) , new SqlParameter("@Hash", fldHash) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run BinaryData_Search, and return results as a list of BinaryDataRow. /// </summary> /// <param name="fldDataType">Value for DataType</param> /// <param name="fldHash">Value for Hash</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool Search(string fldDataType , string fldHash , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[BinaryData_Search]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@DataType", fldDataType) , new SqlParameter("@Hash", fldHash) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run BinaryData_SelectAll, and return results as a list of BinaryDataRow. /// </summary> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool SelectAll() { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run BinaryData_SelectAll, and return results as a list of BinaryDataRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[BinaryData_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run BinaryData_SelectBy_BinaryDataId, and return results as a list of BinaryDataRow. /// </summary> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool SelectBy_BinaryDataId(int fldBinaryDataId ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_SelectBy_BinaryDataId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run BinaryData_SelectBy_BinaryDataId, and return results as a list of BinaryDataRow. /// </summary> /// <param name="fldBinaryDataId">Value for BinaryDataId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool SelectBy_BinaryDataId(int fldBinaryDataId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[BinaryData_SelectBy_BinaryDataId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@BinaryDataId", fldBinaryDataId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run BinaryData_SelectBy_Hash, and return results as a list of BinaryDataRow. /// </summary> /// <param name="fldHash">Value for Hash</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool SelectBy_Hash(string fldHash ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Data].[BinaryData_SelectBy_Hash]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@Hash", fldHash) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run BinaryData_SelectBy_Hash, and return results as a list of BinaryDataRow. /// </summary> /// <param name="fldHash">Value for Hash</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of BinaryDataRow.</returns> public virtual bool SelectBy_Hash(string fldHash , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Data].[BinaryData_SelectBy_Hash]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@Hash", fldHash) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new BinaryDataContract { BinaryDataId = reader.GetInt32(0), DataType = reader.GetString(1), Hash = reader.IsDBNull(2) ? null : reader.GetString(2), Data = (byte[])reader.GetValue(3), DateCreated = reader.GetDateTime(4), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(BinaryDataContract row) { if(row == null) return 0; if(row.BinaryDataId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(BinaryDataContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.BinaryDataId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<BinaryDataContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<BinaryDataContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
// // System.Web.UI.WebControls.Style.cs // // Authors: // Gaurav Vaish (gvaish@iitk.ac.in) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // (C) Gaurav Vaish (2002) // (C) 2003 Andreas Nahr // // // 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.Text; using System.Collections; using System.Drawing; using System.Globalization; using System.ComponentModel; using System.Web; using System.Web.UI; namespace System.Web.UI.WebControls { [ToolboxItem(false)] [TypeConverter(typeof(ExpandableObjectConverter))] public class Style : Component , IStateManager { internal static int MARKED = (0x01 << 0); internal static int BACKCOLOR = (0x01 << 1); internal static int BORDERCOLOR = (0x01 << 2); internal static int BORDERSTYLE = (0x01 << 3); internal static int BORDERWIDTH = (0x01 << 4); internal static int CSSCLASS = (0x01 << 5); internal static int FORECOLOR = (0x01 << 6); internal static int HEIGHT = (0x01 << 7); internal static int WIDTH = (0x01 << 8); internal static int FONT_BOLD = (0x01 << 9); internal static int FONT_ITALIC = (0x01 << 10); internal static int FONT_NAMES = (0x01 << 11); internal static int FONT_SIZE = (0x01 << 12); internal static int FONT_STRIKE = (0x01 << 13); internal static int FONT_OLINE = (0x01 << 14); internal static int FONT_ULINE = (0x01 << 15); internal static string selectionBitString = "_SBS"; StateBag viewState; int selectionBits; bool selfStateBag; bool marked; #if NET_2_0 string regClass; #endif private FontInfo font; public Style () { Initialize(null); selfStateBag = true; } public Style (StateBag bag) { Initialize (bag); selfStateBag = false; } private void Initialize (StateBag bag) { viewState = bag; selectionBits = 0x00; } [Browsable (false)] [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] protected internal StateBag ViewState { get { if (viewState == null) { viewState = new StateBag (false); if (IsTrackingViewState) viewState.TrackViewState (); } return viewState; } } internal bool IsSet (int bit) { return ((selectionBits & bit) != 0x00); } internal virtual void Set (int bit) { selectionBits |= bit; if (IsTrackingViewState) selectionBits |= MARKED; } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (null), WebCategory ("Appearance")] [TypeConverter (typeof (WebColorConverter))] [WebSysDescription ("The background color for the WebControl.")] public Color BackColor { get { if(IsSet(BACKCOLOR)) return (Color)ViewState["BackColor"]; return Color.Empty; } set { ViewState["BackColor"] = value; Set(BACKCOLOR); } } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (null), WebCategory ("Appearance")] [TypeConverter (typeof (WebColorConverter))] [WebSysDescription ("The border color for the WebControl.")] public Color BorderColor { get { if (IsSet (BORDERCOLOR)) return (Color) ViewState ["BorderColor"]; return Color.Empty; } set { ViewState ["BorderColor"] = value; Set (BORDERCOLOR); } } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (typeof(BorderStyle), "NotSet"), WebCategory ("Appearance")] [WebSysDescription ("The style/type of the border used for the WebControl.")] public BorderStyle BorderStyle { get { if (IsSet (BORDERSTYLE)) return (BorderStyle) ViewState ["BorderStyle"]; return BorderStyle.NotSet; } set { ViewState ["BorderStyle"] = value; Set (BORDERSTYLE); } } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (null), WebCategory ("Appearance")] [WebSysDescription ("The width of the border used for the WebControl.")] public Unit BorderWidth { get { if (IsSet (BORDERWIDTH)) return (Unit) ViewState ["BorderWidth"]; return Unit.Empty; } set { ViewState ["BorderWidth"] = value; Set (BORDERWIDTH); } } [NotifyParentProperty (true)] [DefaultValue (""), WebCategory ("Appearance")] [WebSysDescription ("The cascading stylesheet class that is associated with this WebControl.")] public string CssClass { get { if (IsSet (CSSCLASS)) return (string) ViewState["CssClass"]; return string.Empty; } set { ViewState ["CssClass"] = value; Set (CSSCLASS); } } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (null), WebCategory ("Appearance")] [TypeConverter (typeof (WebColorConverter))] [WebSysDescription ("The color that is used to paint the primary display of the WebControl.")] public Color ForeColor { get { if (IsSet (FORECOLOR)) return (Color) ViewState ["ForeColor"]; return Color.Empty; } set { ViewState ["ForeColor"] = value; Set (FORECOLOR); } } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (null), WebCategory ("Layout")] [WebSysDescription ("The height of this WebControl.")] public Unit Height { get { if (IsSet (HEIGHT)) return (Unit) ViewState ["Height"]; return Unit.Empty; } set { ViewState ["Height"] = value; Set (HEIGHT); } } #if !NET_2_0 [Bindable (true)] #endif [NotifyParentProperty (true)] [DefaultValue (null), WebCategory ("Layout")] [WebSysDescription ("The width of this WebControl.")] public Unit Width { get { if (IsSet(WIDTH)) return (Unit) ViewState ["Width"]; return Unit.Empty; } set { ViewState ["Width"] = value; Set (WIDTH); } } [NotifyParentProperty (true)] [WebCategory ("Appearance")] [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)] [WebSysDescription ("The font of this WebControl.")] public FontInfo Font { get { if (font==null) font = new FontInfo (this); return font; } } protected internal virtual bool IsEmpty { get { return (selectionBits == 0); } } private void AddColor (CssStyleCollection attributes, HtmlTextWriterStyle style, Color color) { if (!color.IsEmpty) attributes.Add (style, ColorTranslator.ToHtml (color)); } private static string StringArrayToString (string [] array, char separator) { if (array.Length == 0) return String.Empty; StringBuilder sb = new StringBuilder (); for (int i = 0; i < array.Length; i++) { if (i == 0) { sb.Append (array [0]); } else { sb.Append (separator); sb.Append (array [i]); } } return sb.ToString (); } public void AddAttributesToRender (HtmlTextWriter writer) { AddAttributesToRender (writer, null); } public virtual void AddAttributesToRender (HtmlTextWriter writer, WebControl owner) { if (IsSet (CSSCLASS)) { string cssClass = (string) ViewState ["CssClass"]; if (cssClass.Length > 0) writer.AddAttribute (HtmlTextWriterAttribute.Class, cssClass); } CssStyleCollection ats = new CssStyleCollection (); #if NET_2_0 FillStyleAttributes (ats, owner); #else FillAttributes (ats); #endif foreach (string key in ats.Keys) writer.AddStyleAttribute (key, ats [key]); } #if NET_2_0 public CssStyleCollection GetStyleAttributes (IUrlResolutionService urlResolver) { CssStyleCollection ats = new CssStyleCollection (); FillStyleAttributes (ats, urlResolver); return ats; } protected virtual void FillStyleAttributes (CssStyleCollection attributes, IUrlResolutionService urlResolver) { FillAttributes (attributes); } #endif void FillAttributes (CssStyleCollection attributes) { if (IsSet (BACKCOLOR)) AddColor (attributes, HtmlTextWriterStyle.BackgroundColor, BackColor); if (IsSet(BORDERCOLOR)) AddColor (attributes, HtmlTextWriterStyle.BorderColor, BorderColor); if (IsSet (FORECOLOR)) AddColor (attributes, HtmlTextWriterStyle.Color, ForeColor); if (!BorderWidth.IsEmpty) { attributes.Add (HtmlTextWriterStyle.BorderWidth, BorderWidth.ToString (CultureInfo.InvariantCulture)); if (BorderStyle != BorderStyle.NotSet) { attributes.Add (HtmlTextWriterStyle.BorderStyle, Enum.Format (typeof (BorderStyle), BorderStyle, "G")); } else { if (BorderWidth.Value != 0.0) attributes.Add (HtmlTextWriterStyle.BorderStyle, "solid"); } } else { if (BorderStyle != BorderStyle.NotSet) attributes.Add (HtmlTextWriterStyle.BorderStyle, Enum.Format (typeof (BorderStyle), BorderStyle, "G")); } if (Font.Names.Length > 0) attributes.Add (HtmlTextWriterStyle.FontFamily, StringArrayToString (Font.Names, ',')); if (!Font.Size.IsEmpty) attributes.Add (HtmlTextWriterStyle.FontSize, Font.Size.ToString (CultureInfo.InvariantCulture)); if (Font.Bold) attributes.Add (HtmlTextWriterStyle.FontWeight, "bold"); if (Font.Italic) attributes.Add (HtmlTextWriterStyle.FontStyle, "italic"); string textDecoration = String.Empty; if (Font.Strikeout) textDecoration += " line-through"; if (Font.Underline) textDecoration += " underline"; if (Font.Overline) textDecoration += " overline"; if (textDecoration.Length > 0) attributes.Add (HtmlTextWriterStyle.TextDecoration, textDecoration); Unit u = Unit.Empty; if (IsSet (HEIGHT)) { u = (Unit) ViewState ["Height"]; if (!u.IsEmpty) attributes.Add (HtmlTextWriterStyle.Height, u.ToString (CultureInfo.InvariantCulture)); } if (IsSet (WIDTH)) { u = (Unit) ViewState ["Width"]; if (!u.IsEmpty) attributes.Add (HtmlTextWriterStyle.Width, u.ToString (CultureInfo.InvariantCulture)); } } public virtual void CopyFrom (Style source) { if (source == null || source.IsEmpty) return; Font.CopyFrom (source.Font); if (source.IsSet (HEIGHT)&& (source.Height != Unit.Empty)) Height = source.Height; if (source.IsSet (WIDTH)&& (source.Width != Unit.Empty)) Width = source.Width; if (source.IsSet (BORDERCOLOR)&& (source.BorderColor != Color.Empty)) BorderColor = source.BorderColor; if (source.IsSet (BORDERWIDTH)&& (source.BorderWidth != Unit.Empty)) BorderWidth = source.BorderWidth; if (source.IsSet (BORDERSTYLE)) BorderStyle = source.BorderStyle; if (source.IsSet (BACKCOLOR)&& (source.BackColor != Color.Empty)) BackColor = source.BackColor; if (source.IsSet (CSSCLASS)) CssClass = source.CssClass; if (source.IsSet (FORECOLOR)&& (source.ForeColor != Color.Empty)) ForeColor = source.ForeColor; } public virtual void MergeWith (Style with) { if (with == null || with.IsEmpty) return; if (IsEmpty) { CopyFrom (with); return; } Font.MergeWith (with.Font); if (!IsSet (HEIGHT) && with.Height != Unit.Empty) Height = with.Height; if (!IsSet(WIDTH) && with.Width != Unit.Empty) Width = with.Width; if (!IsSet (BORDERCOLOR) && with.BorderColor != Color.Empty) BorderColor = with.BorderColor; if (!IsSet (BORDERWIDTH) && with.BorderWidth != Unit.Empty) BorderWidth = with.BorderWidth; if (!IsSet (BORDERSTYLE) && with.BorderStyle != BorderStyle.NotSet) BorderStyle = with.BorderStyle; if (!IsSet (BACKCOLOR) && with.BackColor != Color.Empty) BackColor = with.BackColor; if (!IsSet (CSSCLASS) && with.CssClass != String.Empty) CssClass = with.CssClass; if (!IsSet (FORECOLOR) && with.ForeColor != Color.Empty) ForeColor = with.ForeColor; } public virtual void Reset () { if (IsSet (BACKCOLOR)) ViewState.Remove ("BackColor"); if (IsSet (BORDERCOLOR)) ViewState.Remove ("BorderColor"); if (IsSet (BORDERSTYLE)) ViewState.Remove ("BorderStyle"); if (IsSet (BORDERWIDTH)) ViewState.Remove ("BorderWidth"); if (IsSet (CSSCLASS)) ViewState.Remove ("CssClass"); if (IsSet (FORECOLOR)) ViewState.Remove ("ForeColor"); if (IsSet (HEIGHT)) ViewState.Remove ("Height"); if (IsSet (WIDTH)) ViewState.Remove( "Width"); if (font != null) font.Reset (); selectionBits = 0x00; } protected bool IsTrackingViewState { get { return marked; } } protected internal virtual void TrackViewState () { if (selfStateBag) ViewState.TrackViewState (); marked = true; } protected internal virtual object SaveViewState () { if (viewState != null) { if (marked && IsSet (MARKED)) ViewState [selectionBitString] = selectionBits; if (selfStateBag) return ViewState.SaveViewState (); } return null; } protected internal void LoadViewState (object state) { if (state != null && selfStateBag) ViewState.LoadViewState (state); if (viewState != null) { object o = ViewState [selectionBitString]; if (o != null) selectionBits = (int) o; } } void IStateManager.LoadViewState(object state) { LoadViewState(state); } object IStateManager.SaveViewState () { return SaveViewState (); } void IStateManager.TrackViewState () { TrackViewState (); } bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } #if !NET_2_0 public override string ToString () { return String.Empty; } #endif protected internal void SetBit (int bit) { Set (bit); } internal virtual void CopyTextStylesFrom (Style source) { if (source.IsSet (FORECOLOR)&& (source.ForeColor != Color.Empty)) ForeColor = source.ForeColor; } #if NET_2_0 public void SetDirty () { if (selectionBits != 0x00) Set (MARKED); if (viewState != null) viewState.SetDirty (); } [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)] [BrowsableAttribute (false)] [EditorBrowsableAttribute (EditorBrowsableState.Advanced)] public string RegisteredCssClass { get { return regClass; } } internal void SetRegisteredCssClass (string name) { regClass = name; } #endif } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.Runtime.Remoting; using System.Security; using System.ServiceModel; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Dispatcher; abstract class ServiceChannelFactory : ChannelFactoryBase { string bindingName; List<IChannel> channelsList; ClientRuntime clientRuntime; RequestReplyCorrelator requestReplyCorrelator = new RequestReplyCorrelator(); IDefaultCommunicationTimeouts timeouts; MessageVersion messageVersion; public ServiceChannelFactory(ClientRuntime clientRuntime, Binding binding) : base() { if (clientRuntime == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientRuntime"); } this.bindingName = binding.Name; this.channelsList = new List<IChannel>(); this.clientRuntime = clientRuntime; this.timeouts = new DefaultCommunicationTimeouts(binding); this.messageVersion = binding.MessageVersion; } public ClientRuntime ClientRuntime { get { this.ThrowIfDisposed(); return this.clientRuntime; } } internal RequestReplyCorrelator RequestReplyCorrelator { get { ThrowIfDisposed(); return this.requestReplyCorrelator; } } protected override TimeSpan DefaultCloseTimeout { get { return this.timeouts.CloseTimeout; } } protected override TimeSpan DefaultReceiveTimeout { get { return this.timeouts.ReceiveTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return this.timeouts.OpenTimeout; } } protected override TimeSpan DefaultSendTimeout { get { return this.timeouts.SendTimeout; } } public MessageVersion MessageVersion { get { return this.messageVersion; } } // special overload for security only public static ServiceChannelFactory BuildChannelFactory(ChannelBuilder channelBuilder, ClientRuntime clientRuntime) { if (channelBuilder.CanBuildChannelFactory<IDuplexChannel>()) { return new ServiceChannelFactoryOverDuplex(channelBuilder.BuildChannelFactory<IDuplexChannel>(), clientRuntime, channelBuilder.Binding); } else if (channelBuilder.CanBuildChannelFactory<IDuplexSessionChannel>()) { return new ServiceChannelFactoryOverDuplexSession(channelBuilder.BuildChannelFactory<IDuplexSessionChannel>(), clientRuntime, channelBuilder.Binding, false); } else { return new ServiceChannelFactoryOverRequestSession(channelBuilder.BuildChannelFactory<IRequestSessionChannel>(), clientRuntime, channelBuilder.Binding, false); } } public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint) { return BuildChannelFactory(serviceEndpoint, false); } public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint, bool useActiveAutoClose) { if (serviceEndpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceEndpoint"); } serviceEndpoint.EnsureInvariants(); serviceEndpoint.ValidateForClient(); ChannelRequirements requirements; ContractDescription contractDescription = serviceEndpoint.Contract; ChannelRequirements.ComputeContractRequirements(contractDescription, out requirements); BindingParameterCollection parameters; ClientRuntime clientRuntime = DispatcherBuilder.BuildProxyBehavior(serviceEndpoint, out parameters); Binding binding = serviceEndpoint.Binding; Type[] requiredChannels = ChannelRequirements.ComputeRequiredChannels(ref requirements); CustomBinding customBinding = new CustomBinding(binding); BindingContext context = new BindingContext(customBinding, parameters); InternalDuplexBindingElement internalDuplexBindingElement = null; InternalDuplexBindingElement.AddDuplexFactorySupport(context, ref internalDuplexBindingElement); customBinding = new CustomBinding(context.RemainingBindingElements); customBinding.CopyTimeouts(serviceEndpoint.Binding); foreach (Type type in requiredChannels) { if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory<IOutputChannel>(parameters)) { return new ServiceChannelFactoryOverOutput(customBinding.BuildChannelFactory<IOutputChannel>(parameters), clientRuntime, binding); } if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory<IRequestChannel>(parameters)) { return new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory<IRequestChannel>(parameters), clientRuntime, binding); } if (type == typeof(IDuplexChannel) && customBinding.CanBuildChannelFactory<IDuplexChannel>(parameters)) { if (requirements.usesReply && binding.CreateBindingElements().Find<TransportBindingElement>().ManualAddressing) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.CantCreateChannelWithManualAddressing))); } return new ServiceChannelFactoryOverDuplex(customBinding.BuildChannelFactory<IDuplexChannel>(parameters), clientRuntime, binding); } if (type == typeof(IOutputSessionChannel) && customBinding.CanBuildChannelFactory<IOutputSessionChannel>(parameters)) { return new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory<IOutputSessionChannel>(parameters), clientRuntime, binding, false); } if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory<IRequestSessionChannel>(parameters)) { return new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory<IRequestSessionChannel>(parameters), clientRuntime, binding, false); } if (type == typeof(IDuplexSessionChannel) && customBinding.CanBuildChannelFactory<IDuplexSessionChannel>(parameters)) { if (requirements.usesReply && binding.CreateBindingElements().Find<TransportBindingElement>().ManualAddressing) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.CantCreateChannelWithManualAddressing))); } return new ServiceChannelFactoryOverDuplexSession(customBinding.BuildChannelFactory<IDuplexSessionChannel>(parameters), clientRuntime, binding, useActiveAutoClose); } } foreach (Type type in requiredChannels) { // For SessionMode.Allowed or SessionMode.NotAllowed we will accept session-ful variants as well if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory<IOutputSessionChannel>(parameters)) { return new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory<IOutputSessionChannel>(parameters), clientRuntime, binding, true); } if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory<IRequestSessionChannel>(parameters)) { return new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory<IRequestSessionChannel>(parameters), clientRuntime, binding, true); } // and for SessionMode.Required, it is possible that the InstanceContextProvider is handling the session management, so // accept datagram variants if that is the case if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory<IRequestChannel>(parameters) && customBinding.GetProperty<IContextSessionProvider>(parameters) != null) { return new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory<IRequestChannel>(parameters), clientRuntime, binding); } } // we put a lot of work into creating a good error message, as this is a common case Dictionary<Type, byte> supportedChannels = new Dictionary<Type, byte>(); if (customBinding.CanBuildChannelFactory<IOutputChannel>(parameters)) { supportedChannels.Add(typeof(IOutputChannel), 0); } if (customBinding.CanBuildChannelFactory<IRequestChannel>(parameters)) { supportedChannels.Add(typeof(IRequestChannel), 0); } if (customBinding.CanBuildChannelFactory<IDuplexChannel>(parameters)) { supportedChannels.Add(typeof(IDuplexChannel), 0); } if (customBinding.CanBuildChannelFactory<IOutputSessionChannel>(parameters)) { supportedChannels.Add(typeof(IOutputSessionChannel), 0); } if (customBinding.CanBuildChannelFactory<IRequestSessionChannel>(parameters)) { supportedChannels.Add(typeof(IRequestSessionChannel), 0); } if (customBinding.CanBuildChannelFactory<IDuplexSessionChannel>(parameters)) { supportedChannels.Add(typeof(IDuplexSessionChannel), 0); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ChannelRequirements.CantCreateChannelException( supportedChannels.Keys, requiredChannels, binding.Name)); } protected override void OnAbort() { IChannel channel = null; lock (ThisLock) { channel = (channelsList.Count > 0) ? channelsList[channelsList.Count - 1] : null; } while (channel != null) { channel.Abort(); lock (ThisLock) { channelsList.Remove(channel); channel = (channelsList.Count > 0) ? channelsList[channelsList.Count - 1] : null; } } } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); while (true) { int count; IChannel channel; lock (ThisLock) { count = channelsList.Count; if (count == 0) return; channel = channelsList[0]; } channel.Close(timeoutHelper.RemainingTime()); } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { List<ICommunicationObject> objectList; lock (ThisLock) { objectList = new List<ICommunicationObject>(); for (int index = 0; index < channelsList.Count; index++) objectList.Add(channelsList[index]); } return new CloseCollectionAsyncResult(timeout, callback, state, objectList); } protected override void OnEndClose(IAsyncResult result) { CloseCollectionAsyncResult.End(result); } protected override void OnOpened() { base.OnOpened(); this.clientRuntime.LockDownProperties(); } public void ChannelCreated(IChannel channel) { if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.ChannelCreated, SR.GetString(SR.TraceCodeChannelCreated, TraceUtility.CreateSourceString(channel)), this); } lock (ThisLock) { ThrowIfDisposed(); channelsList.Add(channel); } } public void ChannelDisposed(IChannel channel) { if (DiagnosticUtility.ShouldTraceVerbose) { TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.ChannelDisposed, SR.GetString(SR.TraceCodeChannelDisposed, TraceUtility.CreateSourceString(channel)), this); } lock (ThisLock) { channelsList.Remove(channel); } } public virtual ServiceChannel CreateServiceChannel(EndpointAddress address, Uri via) { IChannelBinder binder = this.CreateInnerChannelBinder(address, via); ServiceChannel serviceChannel = new ServiceChannel(this, binder); if (binder is DuplexChannelBinder) { DuplexChannelBinder duplexChannelBinder = binder as DuplexChannelBinder; duplexChannelBinder.ChannelHandler = new ChannelHandler(this.messageVersion, binder, serviceChannel); duplexChannelBinder.DefaultCloseTimeout = this.DefaultCloseTimeout; duplexChannelBinder.DefaultSendTimeout = this.DefaultSendTimeout; duplexChannelBinder.IdentityVerifier = this.clientRuntime.IdentityVerifier; } return serviceChannel; } public TChannel CreateChannel<TChannel>(EndpointAddress address) { return this.CreateChannel<TChannel>(address, null); } public TChannel CreateChannel<TChannel>(EndpointAddress address, Uri via) { if (!this.CanCreateChannel<TChannel>()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.CouldnTCreateChannelForChannelType2, this.bindingName, typeof(TChannel).Name))); } return (TChannel)this.CreateChannel(typeof(TChannel), address, via); } public abstract bool CanCreateChannel<TChannel>(); public object CreateChannel(Type channelType, EndpointAddress address) { return this.CreateChannel(channelType, address, null); } public object CreateChannel(Type channelType, EndpointAddress address, Uri via) { if (via == null) { via = this.ClientRuntime.Via; if (via == null) { via = address.Uri; } } ServiceChannel serviceChannel = this.CreateServiceChannel(address, via); serviceChannel.Proxy = CreateProxy(channelType, channelType, MessageDirection.Input, serviceChannel); serviceChannel.ClientRuntime.GetRuntime().InitializeChannel((IClientChannel)serviceChannel.Proxy); OperationContext current = OperationContext.Current; if ((current != null) && (current.InstanceContext != null)) { current.InstanceContext.WmiChannels.Add((IChannel)serviceChannel.Proxy); serviceChannel.WmiInstanceContext = current.InstanceContext; } return serviceChannel.Proxy; } [Fx.Tag.SecurityNote(Critical = "Constructs a ServiceChannelProxy, which is Critical.", Safe = "Returns the TP, but does not return the RealProxy -- caller can't get from TP to RP without an elevation.")] [SecuritySafeCritical] internal static object CreateProxy(Type interfaceType, Type proxiedType, MessageDirection direction, ServiceChannel serviceChannel) { if (!proxiedType.IsInterface) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString("SFxChannelFactoryTypeMustBeInterface"))); } ServiceChannelProxy proxy = new ServiceChannelProxy(interfaceType, proxiedType, direction, serviceChannel); return proxy.GetTransparentProxy(); } [Fx.Tag.SecurityNote(Critical = "Calls LinkDemand method RemotingServices.GetRealProxy and access critical class ServiceChannelProxy.", Safe = "Gets the ServiceChannel (which is not critical) and discards the RealProxy.")] [SecuritySafeCritical] internal static ServiceChannel GetServiceChannel(object transparentProxy) { IChannelBaseProxy cb = transparentProxy as IChannelBaseProxy; if (cb != null) return cb.GetServiceChannel(); ServiceChannelProxy proxy = RemotingServices.GetRealProxy(transparentProxy) as ServiceChannelProxy; if (proxy != null) return proxy.GetServiceChannel(); else return null; } protected abstract IChannelBinder CreateInnerChannelBinder(EndpointAddress address, Uri via); abstract class TypedServiceChannelFactory<TChannel> : ServiceChannelFactory where TChannel : class, IChannel { IChannelFactory<TChannel> innerChannelFactory; protected TypedServiceChannelFactory(IChannelFactory<TChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding) : base(clientRuntime, binding) { this.innerChannelFactory = innerChannelFactory; } protected IChannelFactory<TChannel> InnerChannelFactory { get { return this.innerChannelFactory; } } protected override void OnAbort() { base.OnAbort(); this.innerChannelFactory.Abort(); } protected override void OnOpen(TimeSpan timeout) { this.innerChannelFactory.Open(timeout); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.innerChannelFactory.BeginOpen(timeout, callback, state); } protected override void OnEndOpen(IAsyncResult result) { this.innerChannelFactory.EndOpen(result); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnClose(timeoutHelper.RemainingTime()); this.innerChannelFactory.Close(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.innerChannelFactory.BeginClose, this.innerChannelFactory.EndClose); } protected override void OnEndClose(IAsyncResult result) { ChainedAsyncResult.End(result); } public override T GetProperty<T>() { if (typeof(T) == typeof(TypedServiceChannelFactory<TChannel>)) { return (T)(object)this; } T baseProperty = base.GetProperty<T>(); if (baseProperty != null) { return baseProperty; } return this.innerChannelFactory.GetProperty<T>(); } } class ServiceChannelFactoryOverOutput : TypedServiceChannelFactory<IOutputChannel> { public ServiceChannelFactoryOverOutput(IChannelFactory<IOutputChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding) : base(innerChannelFactory, clientRuntime, binding) { } protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via) { return new OutputChannelBinder(this.InnerChannelFactory.CreateChannel(to, via)); } public override bool CanCreateChannel<TChannel>() { return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IRequestChannel)); } } class ServiceChannelFactoryOverDuplex : TypedServiceChannelFactory<IDuplexChannel> { public ServiceChannelFactoryOverDuplex(IChannelFactory<IDuplexChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding) : base(innerChannelFactory, clientRuntime, binding) { } protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via) { return new DuplexChannelBinder(this.InnerChannelFactory.CreateChannel(to, via), this.RequestReplyCorrelator); } public override bool CanCreateChannel<TChannel>() { return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IRequestChannel) || typeof(TChannel) == typeof(IDuplexChannel)); } } class ServiceChannelFactoryOverRequest : TypedServiceChannelFactory<IRequestChannel> { public ServiceChannelFactoryOverRequest(IChannelFactory<IRequestChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding) : base(innerChannelFactory, clientRuntime, binding) { } protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via) { return new RequestChannelBinder(this.InnerChannelFactory.CreateChannel(to, via)); } public override bool CanCreateChannel<TChannel>() { return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IRequestChannel)); } } class ServiceChannelFactoryOverOutputSession : TypedServiceChannelFactory<IOutputSessionChannel> { bool datagramAdapter; public ServiceChannelFactoryOverOutputSession(IChannelFactory<IOutputSessionChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding, bool datagramAdapter) : base(innerChannelFactory, clientRuntime, binding) { this.datagramAdapter = datagramAdapter; } protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via) { IOutputChannel channel; if (this.datagramAdapter) { channel = DatagramAdapter.GetOutputChannel( delegate() { return this.InnerChannelFactory.CreateChannel(to, via); }, timeouts); } else { channel = this.InnerChannelFactory.CreateChannel(to, via); } return new OutputChannelBinder(channel); } public override bool CanCreateChannel<TChannel>() { return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IOutputSessionChannel) || typeof(TChannel) == typeof(IRequestChannel) || typeof(TChannel) == typeof(IRequestSessionChannel)); } } class ServiceChannelFactoryOverDuplexSession : TypedServiceChannelFactory<IDuplexSessionChannel> { bool useActiveAutoClose; public ServiceChannelFactoryOverDuplexSession(IChannelFactory<IDuplexSessionChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding, bool useActiveAutoClose) : base(innerChannelFactory, clientRuntime, binding) { this.useActiveAutoClose = useActiveAutoClose; } protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via) { return new DuplexChannelBinder(this.InnerChannelFactory.CreateChannel(to, via), this.RequestReplyCorrelator, useActiveAutoClose); } public override bool CanCreateChannel<TChannel>() { return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IRequestChannel) || typeof(TChannel) == typeof(IDuplexChannel) || typeof(TChannel) == typeof(IOutputSessionChannel) || typeof(TChannel) == typeof(IRequestSessionChannel) || typeof(TChannel) == typeof(IDuplexSessionChannel)); } } class ServiceChannelFactoryOverRequestSession : TypedServiceChannelFactory<IRequestSessionChannel> { bool datagramAdapter = false; public ServiceChannelFactoryOverRequestSession(IChannelFactory<IRequestSessionChannel> innerChannelFactory, ClientRuntime clientRuntime, Binding binding, bool datagramAdapter) : base(innerChannelFactory, clientRuntime, binding) { this.datagramAdapter = datagramAdapter; } protected override IChannelBinder CreateInnerChannelBinder(EndpointAddress to, Uri via) { IRequestChannel channel; if (this.datagramAdapter) { channel = DatagramAdapter.GetRequestChannel( delegate() { return this.InnerChannelFactory.CreateChannel(to, via); }, this.timeouts); } else { channel = this.InnerChannelFactory.CreateChannel(to, via); } return new RequestChannelBinder(channel); } public override bool CanCreateChannel<TChannel>() { return (typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IOutputSessionChannel) || typeof(TChannel) == typeof(IRequestChannel) || typeof(TChannel) == typeof(IRequestSessionChannel)); } } class DefaultCommunicationTimeouts : IDefaultCommunicationTimeouts { TimeSpan closeTimeout; TimeSpan openTimeout; TimeSpan receiveTimeout; TimeSpan sendTimeout; public DefaultCommunicationTimeouts(IDefaultCommunicationTimeouts timeouts) { this.closeTimeout = timeouts.CloseTimeout; this.openTimeout = timeouts.OpenTimeout; this.receiveTimeout = timeouts.ReceiveTimeout; this.sendTimeout = timeouts.SendTimeout; } public TimeSpan CloseTimeout { get { return this.closeTimeout; } } public TimeSpan OpenTimeout { get { return this.openTimeout; } } public TimeSpan ReceiveTimeout { get { return this.receiveTimeout; } } public TimeSpan SendTimeout { get { return this.sendTimeout; } } } } }
namespace Nancy { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Nancy.Configuration; using Nancy.ModelBinding; using Nancy.Responses.Negotiation; using Nancy.Routing; using Nancy.Session; using Nancy.Validation; using Nancy.ViewEngines; /// <summary> /// Basic class containing the functionality for defining routes and actions in Nancy. /// </summary> [Obsolete("LegacyNancyModule is a compatibility shim that will be removed in a future release. Please migrate to the 'async only' NancyModule.")] public abstract class LegacyNancyModule : INancyModule, IHideObjectMembers { private readonly List<Route> routes; /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> protected LegacyNancyModule() : this(String.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> /// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param> protected LegacyNancyModule(string modulePath) { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); this.ModulePath = modulePath; this.routes = new List<Route>(); } /// <summary> /// Non-model specific data for rendering in the response /// </summary> public dynamic ViewBag { get { return this.Context == null ? null : this.Context.ViewBag; } } public dynamic Text { get { return this.Context.Text; } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for DELETE requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Delete { get { return new LegacyRouteBuilder("DELETE", this); } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for GET requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Get { get { return new LegacyRouteBuilder("GET", this); } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for HEAD requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Head { get { return new LegacyRouteBuilder("HEAD", this); } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for OPTIONS requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Options { get { return new LegacyRouteBuilder("OPTIONS", this); } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for PATCH requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Patch { get { return new LegacyRouteBuilder("PATCH", this); } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for POST requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Post { get { return new LegacyRouteBuilder("POST", this); } } /// <summary> /// Gets <see cref="LegacyRouteBuilder"/> for declaring actions for PUT requests. /// </summary> /// <value>A <see cref="LegacyRouteBuilder"/> instance.</value> public LegacyRouteBuilder Put { get { return new LegacyRouteBuilder("PUT", this); } } /// <summary> /// Get the root path of the routes in the current module. /// </summary> /// <value> /// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" /> /// if no root path should be used.</value><remarks>All routes will be relative to this root path. /// </remarks> public string ModulePath { get; protected set; } /// <summary> /// Gets all declared routes by the module. /// </summary> /// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public virtual IEnumerable<Route> Routes { get { return this.routes.AsReadOnly(); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get { return this.Request.Session; } } /// <summary> /// Renders a view from inside a route handler. /// </summary> /// <value>A <see cref="ViewRenderer"/> instance that is used to determine which view that should be rendered.</value> public ViewRenderer View { get { return new ViewRenderer(this); } } /// <summary> /// Used to negotiate the content returned based on Accepts header. /// </summary> /// <value>A <see cref="Negotiator"/> instance that is used to negotiate the content returned.</value> public Negotiator Negotiate { get { return new Negotiator(this.Context); } } /// <summary> /// Gets or sets the validator locator. /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelValidatorLocator ValidatorLocator { get; set; } /// <summary> /// Gets or sets an <see cref="Request"/> instance that represents the current request. /// </summary> /// <value>An <see cref="Request"/> instance.</value> public virtual Request Request { get { return this.Context.Request; } set { this.Context.Request = value; } } /// <summary> /// The extension point for accessing the view engines in Nancy. /// </summary><value>An <see cref="IViewFactory" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IViewFactory ViewFactory { get; set; } /// <summary><para> /// The post-request hook /// </para><para> /// The post-request hook is called after the response is created by the route execution. /// It can be used to rewrite the response or add/remove items from the context. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public AfterPipeline After { get; set; } /// <summary> /// <para> /// The pre-request hook /// </para> /// <para> /// The PreRequest hook is called prior to executing a route. If any item in the /// pre-request pipeline returns a response then the route is not executed and the /// response is returned. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public BeforePipeline Before { get; set; } /// <summary> /// <para> /// The error hook /// </para> /// <para> /// The error hook is called if an exception is thrown at any time during executing /// the PreRequest hook, a route and the PostRequest hook. It can be used to set /// the response and/or finish any ongoing tasks (close database session, etc). /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public ErrorPipeline OnError { get; set; } /// <summary> /// Gets or sets the current Nancy context /// </summary> /// <value>A <see cref="NancyContext" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> public NancyContext Context { get; set; } /// <summary> /// An extension point for adding support for formatting response contents. /// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks> public IResponseFormatter Response { get; set; } /// <summary> /// Gets or sets the model binder locator /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelBinderLocator ModelBinderLocator { get; set; } /// <summary> /// Gets or sets the model validation result /// </summary> /// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks> public virtual ModelValidationResult ModelValidationResult { get { return this.Context == null ? null : this.Context.ModelValidationResult; } set { if (this.Context != null) { this.Context.ModelValidationResult = value; } } } /// <summary> /// Helper class for configuring a route handler in a module. /// </summary> public class LegacyRouteBuilder : IHideObjectMembers { private readonly string method; private readonly LegacyNancyModule parentModule; /// <summary> /// Initializes a new instance of the <see cref="LegacyRouteBuilder"/> class. /// </summary> /// <param name="method">The HTTP request method that the route should be available for.</param> /// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param> public LegacyRouteBuilder(string method, LegacyNancyModule parentModule) { this.method = method; this.parentModule = parentModule; } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string path] { set { this.AddRoute(string.Empty, path, null, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string path, Func<NancyContext, bool> condition] { set { this.AddRoute(string.Empty, path, condition, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, bool runAsync] { set { this.AddRoute(string.Empty, path, null, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, Func<NancyContext, bool> condition, bool runAsync] { set { this.AddRoute(string.Empty, path, condition, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="name"/> /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string name, string path] { set { this.AddRoute(name, path, null, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/> /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string name, string path, Func<NancyContext, bool> condition] { set { this.AddRoute(name, path, condition, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> and <paramref name="name"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, bool runAsync] { set { this.AddRoute(name, path, null, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, Func<NancyContext, bool> condition, bool runAsync] { set { this.AddRoute(name, path, condition, value); } } protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, dynamic> value) { var fullPath = GetFullPath(path); this.parentModule.routes.Add(Route.FromSync(name, this.method, fullPath, condition, value)); } protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, CancellationToken, Task<dynamic>> value) { var fullPath = GetFullPath(path); this.parentModule.routes.Add(new Route(name, this.method, fullPath, condition, value)); } private string GetFullPath(string path) { var relativePath = (path ?? string.Empty).Trim('/'); var parentPath = (this.parentModule.ModulePath ?? string.Empty).Trim('/'); if (string.IsNullOrEmpty(parentPath)) { return string.Concat("/", relativePath); } if (string.IsNullOrEmpty(relativePath)) { return string.Concat("/", parentPath); } return string.Concat("/", parentPath, "/", relativePath); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ServiceStack.Script { public partial class DefaultScripts { public int push(IList list, object item) { list.Add(item); return list.Count; } public object pop(IList list) { if (list.Count > 0) { var ret = list[list.Count - 1]; list.RemoveAt(list.Count - 1); return ret; } return null; } public object shift(IList list) => splice(list, 0); public object unshift(IList list, object item) { if (item is IList addItems) { for (var i = addItems.Count - 1; i >= 0; i--) { list.Insert(0, addItems[i]); } } else { list.Insert(0, item); } return list.Count; } public int indexOf(object target, object item) { if (target is string s) return item is char c ? s.IndexOf(c) : item is string str ? s.IndexOf(str, (StringComparison)Context.Args[ScriptConstants.DefaultStringComparison]) : throw new NotSupportedException($"{item.GetType().Name} not supported in indexOf"); if (target is IList list) return list.IndexOf(item); throw new NotSupportedException($"{target.GetType().Name} not supported in indexOf"); } public int indexOf(object target, object item, int startIndex) { if (target is string s) return item is char c ? s.IndexOf(c, startIndex) : item is string str ? s.IndexOf(str, startIndex, (StringComparison)Context.Args[ScriptConstants.DefaultStringComparison]) : throw new NotSupportedException($"{item.GetType().Name} not supported in indexOf"); if (target is List<object> list) return list.IndexOf(item, startIndex); throw new NotSupportedException($"{target.GetType().Name} not supported in indexOf"); } public int lastIndexOf(object target, object item) { if (target is string s) return item is char c ? s.LastIndexOf(c) : item is string str ? s.LastIndexOf(str, (StringComparison)Context.Args[ScriptConstants.DefaultStringComparison]) : throw new NotSupportedException($"{item.GetType().Name} not supported in indexOf"); if (target is List<object> list) return list.LastIndexOf(item); if (target is IList iList) return iList.Cast<object>().ToList().LastIndexOf(item); throw new NotSupportedException($"{target.GetType().Name} not supported in indexOf"); } public int lastIndexOf(object target, object item, int startIndex) { if (target is string s) return item is char c ? s.LastIndexOf(c, startIndex) : item is string str ? s.LastIndexOf(str, startIndex, (StringComparison)Context.Args[ScriptConstants.DefaultStringComparison]) : throw new NotSupportedException($"{item.GetType().Name} not supported in indexOf"); if (target is List<object> list) return list.LastIndexOf(item, startIndex); throw new NotSupportedException($"{target.GetType().Name} not supported in indexOf"); } public object splice(IList list, int removeAt) { if (list.Count > 0) { var ret = list[removeAt]; list.RemoveAt(removeAt); return ret; } return null; } public List<object> splice(IList list, int removeAt, int deleteCount) => splice(list, removeAt, deleteCount, null); public List<object> splice(IList list, int removeAt, int deleteCount, List<object> insertItems) { if (list.Count > 0) { var ret = new List<object>(); for (var i = 0; i<deleteCount; i++) { ret.Add(list[removeAt]); list.RemoveAt(removeAt); } if (insertItems != null) { foreach (var item in insertItems.AsEnumerable().Reverse()) { list.Insert(removeAt, item); } } return ret; } return new List<object>(); } public List<object> slice(IList list) => list.Map(x => x); public List<object> slice(IList list, int begin) => list.Map(x => x).Skip(begin).ToList(); public List<object> slice(IList list, int begin, int end) => list.Map(x => x).Skip(begin).Take(end - begin).ToList(); public IgnoreResult forEach(ScriptScopeContext scope, object target, JsArrowFunctionExpression arrowExpr) { var token = arrowExpr.Body; if (target is IList list) { var itemBinding = arrowExpr.Params[0].Name; var indexBinding = arrowExpr.Params.Length > 1 ? arrowExpr.Params[1].Name : ScriptConstants.Index; var arrayBinding = arrowExpr.Params.Length > 2 ? arrowExpr.Params[2].Name : null; for (var i = 0; i < list.Count; i++) { scope.ScopedParams[indexBinding] = i; if (arrayBinding != null) scope.ScopedParams[arrayBinding] = list; scope = scope.AddItemToScope(itemBinding, list[i]); token.Evaluate(scope); } } else if (target is IDictionary d) { if (arrowExpr.Params.Length != 2) throw new NotSupportedException("Dictionary.forEach requires 2 lambda params"); var keyBinding = arrowExpr.Params[0].Name; var valueBinding = arrowExpr.Params[1].Name; foreach (var key in d.Keys) { scope.ScopedParams[keyBinding] = key; scope.ScopedParams[valueBinding] = d[key]; token.Evaluate(scope); } } else throw new NotSupportedException("Can only use forEach on Lists or Dictionaries"); return IgnoreResult.Value; } public bool every(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression) => all(scope, list, expression, null); public bool some(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression) => any(scope, list, expression, null); public object find(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression) => first(scope, list, expression, null); public int findIndex(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression) { var items = list.AssertEnumerable(nameof(findIndex)); var itemBinding = expression.Params[0].Name; var expr = expression.Body; var i = 0; foreach (var item in items) { scope.AddItemToScope(itemBinding, item, i); var result = expr.EvaluateToBool(scope); if (result) return i; i++; } return -1; } public List<object> filter(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression) => where(scope, list, expression, null).ToList(); public List<object> flat(IList list) => flatten(list, 1); public List<object> flat(IList list, int depth) => flatten(list, depth); public List<object> flatMap(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression) => flat((IList)map(scope, list, expression, null)); public List<object> flatMap(ScriptScopeContext scope, IList list, JsArrowFunctionExpression expression, int depth) => flat((IList)map(scope, list, expression, null), depth); public bool includes(IList list, object item) => includes(list, item, 0); public bool includes(IList list, object item, int fromIndex) { for (var i = fromIndex; i < list.Count; i++) { if (list[i].Equals(item)) return true; } return false; } public List<object> sort(List<object> list) { list.Sort(); return list; } } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace SourceCode.Clay { /// <summary> /// Represents a <see cref="Sha256"/> value. /// </summary> /// <seealso cref="System.Security.Cryptography.SHA256" /> /// <seealso cref="System.IEquatable{T}" /> /// <seealso cref="System.IComparable{T}" /> [DebuggerDisplay("{ToString(\"D\"),nq,ac}")] [StructLayout(LayoutKind.Sequential, Size = ByteLength)] public readonly struct Sha256 : IEquatable<Sha256>, IComparable<Sha256> { /// <summary> /// The standard byte length of a <see cref="Sha256"/> value. /// </summary> public const byte ByteLength = 32; /// <summary> /// The number of hex characters required to represent a <see cref="Sha256"/> value. /// </summary> public const byte HexLength = ByteLength * 2; // We choose to use value types for primary storage so that we can live on the stack // TODO: In C#8 we can use 'readonly fixed byte' // https://github.com/dotnet/csharplang/issues/1502 [StructLayout(LayoutKind.Sequential, Pack = 1, Size = ByteLength)] private unsafe struct Block // Avoids making main struct unsafe { #pragma warning disable IDE0044 // Add readonly modifier public fixed byte Bytes[ByteLength]; #pragma warning restore IDE0044 // Add readonly modifier } private readonly Block _block; /// <summary> /// Deserializes a <see cref="Sha256"/> value from the provided <see cref="ReadOnlySpan{T}"/>. /// </summary> /// <param name="source">The buffer.</param> public Sha256(ReadOnlySpan<byte> source) : this() // Compiler doesn't know we're indirectly setting all the fields { if (source.Length < ByteLength) throw new ArgumentOutOfRangeException(nameof(source)); ReadOnlySpan<byte> src = source.Slice(0, ByteLength); unsafe { fixed (byte* ptr = _block.Bytes) { var dst = new Span<byte>(ptr, ByteLength); src.CopyTo(dst); } } } /// <summary> /// Deserializes a <see cref="Sha1"/> value from the provided array. /// </summary> /// <param name="source">The buffer.</param> public Sha256(byte[] source) : this(new ReadOnlySpan<byte>(source)) { if (source == null) throw new ArgumentNullException(nameof(source)); } /// <summary> /// Copies the <see cref="Sha256"/> value to the provided buffer. /// </summary> /// <param name="destination">The buffer to copy to.</param> public void CopyTo(Span<byte> destination) { unsafe { fixed (byte* ptr = _block.Bytes) { var src = new ReadOnlySpan<byte>(ptr, ByteLength); src.CopyTo(destination); } } } /// <summary> /// Tries to copy the <see cref="Sha256"/> value to the provided buffer. /// </summary> /// <param name="destination">The buffer to copy to.</param> /// <returns>True if successful</returns> public bool TryCopyTo(Span<byte> destination) { unsafe { fixed (byte* ptr = _block.Bytes) { var src = new ReadOnlySpan<byte>(ptr, ByteLength); return src.TryCopyTo(destination); } } } /// <summary> /// Returns a string representation of the <see cref="Sha256"/> instance using the 'n' format. /// </summary> /// <returns></returns> public override string ToString() => ToString("n"); /// <summary> /// Returns a string representation of the <see cref="Sha256"/> instance. /// n: cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0, /// d: cdc76e5c-9914fb92-81a1c7e2-84d73e67-f1809a48-a497200e-046d39cc-c7112cd0, /// s: cdc76e5c 9914fb92 81a1c7e2 84d73e67 f1809a48 a497200e 046d39cc c7112cd0 /// </summary> /// <param name="format"></param> /// <returns></returns> public string ToString(string format) { if (string.IsNullOrWhiteSpace(format)) throw new FormatException($"Empty format specification"); if (format.Length != 1) throw new FormatException($"Invalid format specification length {format.Length}"); unsafe { fixed (byte* ptr = _block.Bytes) { var sha = new ReadOnlySpan<byte>(ptr, ByteLength); switch (format[0]) { // cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 case 'n': return ShaUtil.ToString(sha, ShaUtil.HexCasing.Lower); case 'N': return ShaUtil.ToString(sha, ShaUtil.HexCasing.Upper); // cdc76e5c-9914fb92-81a1c7e2-84d73e67-f1809a48-a497200e-046d39cc-c7112cd0 case 'd': return ShaUtil.ToString(sha, '-', ShaUtil.HexCasing.Lower); case 'D': return ShaUtil.ToString(sha, '-', ShaUtil.HexCasing.Upper); // cdc76e5c 9914fb92 81a1c7e2 84d73e67 f1809a48 a497200e 046d39cc c7112cd0 case 's': return ShaUtil.ToString(sha, ' ', ShaUtil.HexCasing.Lower); case 'S': return ShaUtil.ToString(sha, ' ', ShaUtil.HexCasing.Upper); } } } throw new FormatException($"Invalid format specification '{format}'"); } /// <summary> /// Converts the <see cref="Sha256"/> instance to a string using the 'n' or 'N' format, /// and returns the value split into two tokens. /// </summary> /// <param name="prefixLength">The length of the first token.</param> /// <param name="uppercase">If True, output uppercase, else output lowercase.</param> public KeyValuePair<string, string> Split(int prefixLength, bool uppercase = false) { ShaUtil.HexCasing casing = uppercase ? ShaUtil.HexCasing.Upper : ShaUtil.HexCasing.Lower; unsafe { fixed (byte* ptr = _block.Bytes) { var sha = new ReadOnlySpan<byte>(ptr, ByteLength); KeyValuePair<string, string> kvp = ShaUtil.Split(sha, prefixLength, casing); return kvp; } } } /// <summary> /// Tries to parse the specified hexadecimal. /// </summary> /// <param name="hex">The hexadecimal.</param> /// <param name="value">The value.</param> public static bool TryParse(ReadOnlySpan<char> hex, out Sha256 value) { value = default; Span<byte> sha = stackalloc byte[ByteLength]; if (!ShaUtil.TryParse(hex, sha)) return false; value = new Sha256(sha); return true; } /// <summary> /// Tries to parse the specified hexadecimal. /// </summary> /// <param name="hex">The hexadecimal.</param> /// <param name="value">The value.</param> /// <returns></returns> public static bool TryParse(string hex, out Sha256 value) { value = default; if (hex is null || hex.Length < HexLength) return false; Span<byte> sha = stackalloc byte[ByteLength]; if (!ShaUtil.TryParse(hex.AsSpan(), sha)) return false; value = new Sha256(sha); return true; } /// <summary> /// Parses the specified hexadecimal. /// </summary> /// <param name="hex">The hexadecimal.</param> /// <returns></returns> /// <exception cref="FormatException">Sha256</exception> public static Sha256 Parse(ReadOnlySpan<char> hex) { Span<byte> sha = stackalloc byte[ByteLength]; if (!ShaUtil.TryParse(hex, sha)) throw new FormatException($"Input was not recognized as a valid {nameof(Sha256)}"); var value = new Sha256(sha); return value; } /// <summary> /// Parses the specified hexadecimal. /// </summary> /// <param name="hex">The hexadecimal.</param> /// <returns></returns> /// <exception cref="FormatException">Sha256</exception> public static Sha256 Parse(string hex) { if (hex is null) throw new ArgumentNullException(nameof(hex)); if (hex.Length < HexLength) throw new FormatException($"Input was not recognized as a valid {nameof(Sha256)}"); Span<byte> sha = stackalloc byte[ByteLength]; if (!ShaUtil.TryParse(hex.AsSpan(), sha)) throw new FormatException($"Input was not recognized as a valid {nameof(Sha256)}"); var value = new Sha256(sha); return value; } public bool Equals(Sha256 other) => CompareTo(other) == 0; public override bool Equals(object obj) => obj is Sha256 other && Equals(other); public override int GetHashCode() { unsafe { fixed (byte* b = _block.Bytes) { #if !NETSTANDARD2_0 int hc = HashCode.Combine(b[00], b[01], b[02], b[03], b[04], b[05], b[06], b[07]); hc = HashCode.Combine(hc, b[08], b[09], b[10], b[11], b[12], b[13], b[14]); hc = HashCode.Combine(hc, b[15], b[16], b[17], b[18], b[19], b[20], b[21]); hc = HashCode.Combine(hc, b[22], b[23], b[24], b[25], b[26], b[27], b[28]); hc = HashCode.Combine(hc, b[29], b[30], b[31]); #else int hc = 11; unchecked { hc = hc * 7 + b[00]; hc = hc * 7 + b[01]; hc = hc * 7 + b[02]; hc = hc * 7 + b[03]; hc = hc * 7 + b[04]; hc = hc * 7 + b[05]; hc = hc * 7 + b[06]; hc = hc * 7 + b[07]; hc = hc * 7 + b[08]; hc = hc * 7 + b[09]; hc = hc * 7 + b[10]; hc = hc * 7 + b[11]; hc = hc * 7 + b[12]; hc = hc * 7 + b[13]; hc = hc * 7 + b[14]; hc = hc * 7 + b[15]; hc = hc * 7 + b[16]; hc = hc * 7 + b[17]; hc = hc * 7 + b[18]; hc = hc * 7 + b[19]; hc = hc * 7 + b[20]; hc = hc * 7 + b[21]; hc = hc * 7 + b[22]; hc = hc * 7 + b[23]; hc = hc * 7 + b[24]; hc = hc * 7 + b[25]; hc = hc * 7 + b[26]; hc = hc * 7 + b[27]; hc = hc * 7 + b[28]; hc = hc * 7 + b[29]; hc = hc * 7 + b[30]; hc = hc * 7 + b[31]; } #endif return hc; } } } public int CompareTo(Sha256 other) { unsafe { fixed (Block* src = &_block) { Block* dst = &other._block; int cmp = ShaUtil.NativeMethods.MemCompare((byte*)src, (byte*)dst, ByteLength); return cmp; } } } public static bool operator ==(Sha256 x, Sha256 y) => x.Equals(y); public static bool operator !=(Sha256 x, Sha256 y) => !(x == y); public static bool operator >=(Sha256 x, Sha256 y) => x.CompareTo(y) >= 0; public static bool operator >(Sha256 x, Sha256 y) => x.CompareTo(y) > 0; public static bool operator <=(Sha256 x, Sha256 y) => x.CompareTo(y) <= 0; public static bool operator <(Sha256 x, Sha256 y) => x.CompareTo(y) < 0; } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Dynamic; using System.Text; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Actions.Calls; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; namespace IronPython.Runtime.Types { using Ast = Expression; using AstUtils = Microsoft.Scripting.Ast.Utils; /// <summary> /// BuiltinFunction represents any standard CLR function exposed to Python. /// This is used for both methods on standard Python types such as list or tuple /// and for methods from arbitrary .NET assemblies. /// /// All calls are made through the optimizedTarget which is created lazily. /// /// TODO: Back BuiltinFunction's by MethodGroup's. /// </summary> [PythonType("builtin_function_or_method"), DontMapGetMemberNamesToDir] public partial class BuiltinFunction : PythonTypeSlot, ICodeFormattable, IDynamicMetaObjectProvider, IDelegateConvertible, IFastInvokable { internal readonly BuiltinFunctionData/*!*/ _data; // information describing the BuiltinFunction internal readonly object _instance; // the bound instance or null if unbound private static readonly object _noInstance = new object(); #region Static factories /// <summary> /// Creates a new builtin function for a static .NET function. This is used for module methods /// and well-known __new__ methods. /// </summary> internal static BuiltinFunction/*!*/ MakeFunction(string name, MethodBase[] infos, Type declaringType) { #if DEBUG foreach (MethodBase mi in infos) { Debug.Assert(!mi.ContainsGenericParameters); } #endif return new BuiltinFunction(name, infos, declaringType, FunctionType.AlwaysVisible | FunctionType.Function); } /// <summary> /// Creates a built-in function for a .NET method declared on a type. /// </summary> internal static BuiltinFunction/*!*/ MakeMethod(string name, MethodBase[] infos, Type declaringType, FunctionType ft) { foreach (MethodBase mi in infos) { if (mi.ContainsGenericParameters) { return new GenericBuiltinFunction(name, infos, declaringType, ft); } } return new BuiltinFunction(name, infos, declaringType, ft); } internal virtual BuiltinFunction/*!*/ BindToInstance(object instance) { return new BuiltinFunction(instance, _data); } #endregion #region Constructors internal BuiltinFunction(string/*!*/ name, MethodBase/*!*/[]/*!*/ originalTargets, Type/*!*/ declaringType, FunctionType functionType) { Assert.NotNull(name); Assert.NotNull(declaringType); Assert.NotNullItems(originalTargets); _data = new BuiltinFunctionData(name, originalTargets, declaringType, functionType); _instance = _noInstance; } /// <summary> /// Creates a bound built-in function. The instance may be null for built-in functions /// accessed for None. /// </summary> internal BuiltinFunction(object instance, BuiltinFunctionData/*!*/ data) { Assert.NotNull(data); _instance = instance; _data = data; } #endregion #region Internal API Surface internal void AddMethod(MethodInfo mi) { _data.AddMethod(mi); } internal bool TestData(object data) { return _data == data; } internal bool IsUnbound { get { return _instance == _noInstance; } } internal string Name { get { return _data.Name; } set { _data.Name = value; } } internal object Call(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], object>>> storage, object instance, object[] args) { storage = GetInitializedStorage(context, storage); object callable; if (!GetDescriptor().TryGetValue(context, instance, DynamicHelpers.GetPythonTypeFromType(DeclaringType), out callable)) { callable = this; } return storage.Data.Target(storage.Data, context, callable, args); } internal object Call0(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object>>> storage, object instance) { storage = GetInitializedStorage(context, storage); object callable; if (!GetDescriptor().TryGetValue(context, instance, DynamicHelpers.GetPythonTypeFromType(DeclaringType), out callable)) { callable = this; } return storage.Data.Target(storage.Data, context, callable); } private static SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], object>>> GetInitializedStorage(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], object>>> storage) { if (storage == null) { storage = PythonContext.GetContext(context).GetGenericCallSiteStorage(); } if (storage.Data == null) { storage.Data = PythonContext.GetContext(context).MakeSplatSite(); } return storage; } private static SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object>>> GetInitializedStorage(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object>>> storage) { if (storage.Data == null) { storage.Data = CallSite<Func<CallSite, CodeContext, object, object>>.Create( PythonContext.GetContext(context).InvokeNone ); } return storage; } internal object Call(CodeContext context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], IDictionary<object, object>, object>>> storage, object instance, object[] args, IDictionary<object, object> keywordArgs) { if (storage == null) { storage = PythonContext.GetContext(context).GetGenericKeywordCallSiteStorage(); } if (storage.Data == null) { storage.Data = PythonContext.GetContext(context).MakeKeywordSplatSite(); } if (instance != null) { return storage.Data.Target(storage.Data, context, this, ArrayUtils.Insert(instance, args), keywordArgs); } return storage.Data.Target(storage.Data, context, this, args, keywordArgs); } /// <summary> /// Returns a BuiltinFunction bound to the provided type arguments. Returns null if the binding /// cannot be performed. /// </summary> internal BuiltinFunction MakeGenericMethod(Type[] types) { TypeList tl = new TypeList(types); // check for cached method first... BuiltinFunction bf; if (_data.BoundGenerics != null) { lock (_data.BoundGenerics) { if (_data.BoundGenerics.TryGetValue(tl, out bf)) { return bf; } } } // Search for generic targets with the correct arity (number of type parameters). // Compatible targets must be MethodInfos by definition (constructors never take // type arguments). List<MethodBase> targets = new List<MethodBase>(Targets.Count); foreach (MethodBase mb in Targets) { MethodInfo mi = mb as MethodInfo; if (mi == null) continue; if (mi.ContainsGenericParameters && mi.GetGenericArguments().Length == types.Length) targets.Add(mi.MakeGenericMethod(types)); } if (targets.Count == 0) { return null; } // Build a new ReflectedMethod that will contain targets with bound type arguments & cache it. bf = new BuiltinFunction(Name, targets.ToArray(), DeclaringType, FunctionType); EnsureBoundGenericDict(); lock (_data.BoundGenerics) { _data.BoundGenerics[tl] = bf; } return bf; } /// <summary> /// Returns a descriptor for the built-in function if one is /// neededed /// </summary> internal PythonTypeSlot/*!*/ GetDescriptor() { if ((FunctionType & FunctionType.Method) != 0) { return new BuiltinMethodDescriptor(this); } return this; } public Type DeclaringType { [PythonHidden] get { return _data.DeclaringType; } } /// <summary> /// Gets the target methods that we'll be calling. /// </summary> public IList<MethodBase> Targets { [PythonHidden] get { return _data.Targets; } } /// <summary> /// True if the method should be visible to non-CLS opt-in callers /// </summary> internal override bool IsAlwaysVisible { get { return (_data.Type & FunctionType.AlwaysVisible) != 0; } } internal bool IsReversedOperator { get { return (FunctionType & FunctionType.ReversedOperator) != 0; } } internal bool IsBinaryOperator { get { return (FunctionType & FunctionType.BinaryOperator) != 0; } } internal FunctionType FunctionType { get { return _data.Type; } set { _data.Type = value; } } /// <summary> /// Makes a test for the built-in function against the private _data /// which is unique per built-in function. /// </summary> internal Expression/*!*/ MakeBoundFunctionTest(Expression/*!*/ functionTarget) { Debug.Assert(functionTarget.Type == typeof(BuiltinFunction)); return Ast.Call( typeof(PythonOps).GetMethod("TestBoundBuiltinFunction"), functionTarget, AstUtils.Constant(_data, typeof(object)) ); } #endregion #region PythonTypeSlot Overrides internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { value = this; return true; } internal override bool GetAlwaysSucceeds { get { return true; } } internal override void MakeGetExpression(PythonBinder/*!*/ binder, Expression/*!*/ codeContext, DynamicMetaObject instance, DynamicMetaObject/*!*/ owner, ConditionalBuilder/*!*/ builder) { builder.FinishCondition(Ast.Constant(this)); } #endregion #region ICodeFormattable members public string/*!*/ __repr__(CodeContext/*!*/ context) { if (IsUnbound || IsBuiltinModuleMethod) { return string.Format("<built-in function {0}>", Name); } return string.Format("<built-in method {0} of {1} object at {2}>", __name__, PythonOps.GetPythonTypeName(__self__), PythonOps.HexId(__self__)); } #endregion #region IDynamicMetaObjectProvider Members DynamicMetaObject/*!*/ IDynamicMetaObjectProvider.GetMetaObject(Expression/*!*/ parameter) { return new Binding.MetaBuiltinFunction(parameter, BindingRestrictions.Empty, this); } internal class BindingResult { public readonly BindingTarget Target; public readonly DynamicMetaObject MetaObject; public BindingResult(BindingTarget target, DynamicMetaObject meta) { Target = target; MetaObject = meta; } } /// <summary> /// Helper for generating the call to a builtin function. This is used for calls from built-in method /// descriptors and built-in functions w/ and w/o a bound instance. /// /// This provides all sorts of common checks on top of the call while the caller provides a delegate /// to do the actual call. The common checks include: /// check for generic-only methods /// reversed operator support /// transforming arguments so the default binder can understand them (currently user defined mapping types to PythonDictionary) /// returning NotImplemented from binary operators /// Warning when calling certain built-in functions /// /// </summary> /// <param name="call">The call binder we're doing the call for</param> /// <param name="codeContext">An expression which points to the code context</param> /// <param name="function">the meta object for the built in function</param> /// <param name="hasSelf">true if we're calling with an instance</param> /// <param name="args">The arguments being passed to the function</param> /// <param name="functionRestriction">A restriction for the built-in function, method desc, etc...</param> /// <param name="bind">A delegate to perform the actual call to the method.</param> internal DynamicMetaObject/*!*/ MakeBuiltinFunctionCall(DynamicMetaObjectBinder/*!*/ call, Expression/*!*/ codeContext, DynamicMetaObject/*!*/ function, DynamicMetaObject/*!*/[] args, bool hasSelf, BindingRestrictions/*!*/ functionRestriction, Func<DynamicMetaObject/*!*/[]/*!*/, BindingResult/*!*/> bind) { DynamicMetaObject res = null; // if we have a user defined operator for **args then transform it into a PythonDictionary DynamicMetaObject translated = TranslateArguments(call, codeContext, new DynamicMetaObject(function.Expression, functionRestriction, function.Value), args, hasSelf, Name); if (translated != null) { return translated; } // swap the arguments if we have a reversed operator if (IsReversedOperator) { ArrayUtils.SwapLastTwo(args); } // do the appropriate calling logic BindingResult result = bind(args); // validate the result BindingTarget target = result.Target; res = result.MetaObject; if (target.Overload != null && target.Overload.IsProtected) { // report an error when calling a protected member res = new DynamicMetaObject( BindingHelpers.TypeErrorForProtectedMember( target.Overload.DeclaringType, target.Overload.Name ), res.Restrictions ); } else if (IsBinaryOperator && args.Length == 2 && IsThrowException(res.Expression)) { // Binary Operators return NotImplemented on failure. res = new DynamicMetaObject( Ast.Property(null, typeof(PythonOps), "NotImplemented"), res.Restrictions ); } else if (target.Overload != null) { // Add profiling information for this builtin function, if applicable IPythonSite pythonSite = (call as IPythonSite); if (pythonSite != null) { var pc = pythonSite.Context; var po = pc.Options as PythonOptions; if (po != null && po.EnableProfiler) { Profiler profiler = Profiler.GetProfiler(pc); res = new DynamicMetaObject( profiler.AddProfiling(res.Expression, target.Overload.ReflectionInfo), res.Restrictions ); } } } // add any warnings that are applicable for calling this function WarningInfo info; if (target.Overload != null && BindingWarnings.ShouldWarn(PythonContext.GetPythonContext(call), target.Overload, out info)) { res = info.AddWarning(codeContext, res); } // finally add the restrictions for the built-in function and return the result. res = new DynamicMetaObject( res.Expression, functionRestriction.Merge(res.Restrictions) ); // The function can return something typed to boolean or int. // If that happens, we need to apply Python's boxing rules. if (res.Expression.Type.IsValueType()) { res = BindingHelpers.AddPythonBoxing(res); } else if (res.Expression.Type == typeof(void)) { res = new DynamicMetaObject( Expression.Block( res.Expression, Expression.Constant(null) ), res.Restrictions ); } return res; } internal static DynamicMetaObject TranslateArguments(DynamicMetaObjectBinder call, Expression codeContext, DynamicMetaObject function, DynamicMetaObject/*!*/[] args, bool hasSelf, string name) { if (hasSelf) { args = ArrayUtils.RemoveFirst(args); } CallSignature sig = BindingHelpers.GetCallSignature(call); if (sig.HasDictionaryArgument()) { int index = sig.IndexOf(ArgumentType.Dictionary); DynamicMetaObject dict = args[index]; if (!(dict.Value is IDictionary) && dict.Value != null) { // The DefaultBinder only handles types that implement IDictionary. Here we have an // arbitrary user-defined mapping type. We'll convert it into a PythonDictionary // and then have an embedded dynamic site pass that dictionary through to the default // binder. DynamicMetaObject[] dynamicArgs = ArrayUtils.Insert(function, args); dynamicArgs[index + 1] = new DynamicMetaObject( Expression.Call( typeof(PythonOps).GetMethod("UserMappingToPythonDictionary"), codeContext, args[index].Expression, AstUtils.Constant(name) ), BindingRestrictionsHelpers.GetRuntimeTypeRestriction(dict.Expression, dict.GetLimitType()), PythonOps.UserMappingToPythonDictionary(PythonContext.GetPythonContext(call).SharedContext, dict.Value, name) ); if (call is IPythonSite) { dynamicArgs = ArrayUtils.Insert( new DynamicMetaObject(codeContext, BindingRestrictions.Empty), dynamicArgs ); } return new DynamicMetaObject( DynamicExpression.Dynamic( call, typeof(object), DynamicUtils.GetExpressions(dynamicArgs) ), BindingRestrictions.Combine(dynamicArgs).Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(dict.Expression, dict.GetLimitType())) ); } } if (sig.HasListArgument()) { int index = sig.IndexOf(ArgumentType.List); DynamicMetaObject str = args[index]; // TODO: ANything w/ __iter__ that's not an IList<object> if (!(str.Value is IList<object>) && str.Value is IEnumerable) { // The DefaultBinder only handles types that implement IList<object>. Here we have a // string. We'll convert it into a tuple // and then have an embedded dynamic site pass that tuple through to the default // binder. DynamicMetaObject[] dynamicArgs = ArrayUtils.Insert(function, args); dynamicArgs[index + 1] = new DynamicMetaObject( Expression.Call( typeof(PythonOps).GetMethod("MakeTupleFromSequence"), Expression.Convert(args[index].Expression, typeof(object)) ), BindingRestrictions.Empty ); if (call is IPythonSite) { dynamicArgs = ArrayUtils.Insert( new DynamicMetaObject(codeContext, BindingRestrictions.Empty), dynamicArgs ); } return new DynamicMetaObject( DynamicExpression.Dynamic( call, typeof(object), DynamicUtils.GetExpressions(dynamicArgs) ), function.Restrictions.Merge( BindingRestrictions.Combine(args).Merge(BindingRestrictionsHelpers.GetRuntimeTypeRestriction(str.Expression, str.GetLimitType())) ) ); } } return null; } private static bool IsThrowException(Expression expr) { if (expr.NodeType == ExpressionType.Throw) { return true; } else if (expr.NodeType == ExpressionType.Convert) { return IsThrowException(((UnaryExpression)expr).Operand); } else if (expr.NodeType == ExpressionType.Block) { foreach (Expression e in ((BlockExpression)expr).Expressions) { if (IsThrowException(e)) { return true; } } } return false; } #endregion #region Public Python APIs [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "cls")] public static object/*!*/ __new__(object cls, object newFunction, object inst) { return new Method(newFunction, inst, null); } public int __cmp__(CodeContext/*!*/ context, [NotNull]BuiltinFunction/*!*/ other) { if (other == this) { return 0; } if (!IsUnbound && !other.IsUnbound) { int result = PythonOps.Compare(__self__, other.__self__); if (result != 0) { return result; } if (_data == other._data) { return 0; } } int res = String.CompareOrdinal(__name__, other.__name__); if (res != 0) { return res; } res = String.CompareOrdinal(Get__module__(context), other.Get__module__(context)); if (res != 0) { return res; } long lres = IdDispenser.GetId(this) - IdDispenser.GetId(other); return lres > 0 ? 1 : -1; } // these are present in CPython but always return NotImplemented. [return: MaybeNotImplemented] [Python3Warning("builtin_function_or_method order comparisons not supported in 3.x")] public static NotImplementedType operator >(BuiltinFunction self, BuiltinFunction other) { return PythonOps.NotImplemented; } [return: MaybeNotImplemented] [Python3Warning("builtin_function_or_method order comparisons not supported in 3.x")] public static NotImplementedType operator <(BuiltinFunction self, BuiltinFunction other) { return PythonOps.NotImplemented; } [return: MaybeNotImplemented] [Python3Warning("builtin_function_or_method order comparisons not supported in 3.x")] public static NotImplementedType operator >=(BuiltinFunction self, BuiltinFunction other) { return PythonOps.NotImplemented; } [return: MaybeNotImplemented] [Python3Warning("builtin_function_or_method order comparisons not supported in 3.x")] public static NotImplementedType operator <=(BuiltinFunction self, BuiltinFunction other) { return PythonOps.NotImplemented; } public int __hash__(CodeContext/*!*/ context) { return PythonOps.Hash(context, _instance) ^ PythonOps.Hash(context, _data); } [SpecialName, PropertyMethod] public string Get__module__(CodeContext/*!*/ context) { if (Targets.Count > 0) { PythonType declaringType = DynamicHelpers.GetPythonTypeFromType(DeclaringType); string res = PythonTypeOps.GetModuleName(context, declaringType.UnderlyingSystemType); if (res != "builtins" || DeclaringType == typeof(IronPython.Modules.Builtin)) { return res; } } return null; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), SpecialName, PropertyMethod] public void Set__module__(string value) { // Do nothing but don't return an error } /// <summary> /// Provides (for reflected methods) a mapping from a signature to the exact target /// which takes this signature. /// signature with syntax like the following: /// someClass.SomeMethod.Overloads[str, int]("Foo", 123) /// </summary> public virtual BuiltinFunctionOverloadMapper Overloads { [PythonHidden] get { // The mapping is actually provided by a class rather than a dictionary // since it's hard to generate all the keys of the signature mapping when // two type systems are involved. return new BuiltinFunctionOverloadMapper(this, IsUnbound ? null : _instance); } } /// <summary> /// Gets the overload dictionary for the logical function. These overloads /// are never bound to an instance. /// </summary> internal Dictionary<BuiltinFunction.TypeList, BuiltinFunction> OverloadDictionary { get { if (_data.OverloadDictionary == null) { Interlocked.CompareExchange( ref _data.OverloadDictionary, new Dictionary<BuiltinFunction.TypeList, BuiltinFunction>(), null); } return _data.OverloadDictionary; } } public string __name__ { get { return Name; } } public virtual string __doc__ { get { StringBuilder sb = new StringBuilder(); IList<MethodBase> targets = Targets; for (int i = 0; i < targets.Count; i++) { if (targets[i] != null) { if (IsBuiltinModuleMethod) { sb.Append(DocBuilder.DocOneInfo(targets[i], Name, false)); } else { sb.Append(DocBuilder.DocOneInfo(targets[i], Name)); } } } return sb.ToString(); } } public object __self__ { get { if (IsUnbound || IsBuiltinModuleMethod) { return null; } return _instance; } } /// <summary> /// Returns the instance used for binding. This differs on module functions implemented /// using instance methods so the built-in functions there don't expose the instance. /// </summary> internal object BindingSelf { get { if (IsUnbound) { return null; } return _instance; } } private bool IsBuiltinModuleMethod { get { return (FunctionType & FunctionType.ModuleMethod) != 0; } } public object __call__(CodeContext/*!*/ context, SiteLocalStorage<CallSite<Func<CallSite, CodeContext, object, object[], IDictionary<object, object>, object>>> storage, [ParamDictionary]IDictionary<object, object> dictArgs, params object[] args) { return Call(context, storage, null, args, dictArgs); } internal virtual bool IsOnlyGeneric { get { return false; } } #endregion #region Private members private BinderType BinderType { get { return IsBinaryOperator ? BinderType.BinaryOperator : BinderType.Normal; } } private void EnsureBoundGenericDict() { if (_data.BoundGenerics == null) { Interlocked.CompareExchange<Dictionary<TypeList, BuiltinFunction>>( ref _data.BoundGenerics, new Dictionary<TypeList, BuiltinFunction>(1), null); } } internal class TypeList { private Type[] _types; public TypeList(Type[] types) { Debug.Assert(types != null); _types = types; } public override bool Equals(object obj) { TypeList tl = obj as TypeList; if (tl == null || _types.Length != tl._types.Length) return false; for (int i = 0; i < _types.Length; i++) { if (_types[i] != tl._types[i]) return false; } return true; } public override int GetHashCode() { int hc = 6551; foreach (Type t in _types) { hc = (hc << 5) ^ t.GetHashCode(); } return hc; } } #endregion #region IDelegateConvertible Members Delegate IDelegateConvertible.ConvertToDelegate(Type type) { // see if we have any functions which are compatible with the delegate type... ParameterInfo[] delegateParams = type.GetMethod("Invoke").GetParameters(); // if we have overloads then we need to do the overload resolution at runtime if (Targets.Count == 1) { MethodInfo mi = Targets[0] as MethodInfo; if (mi != null) { ParameterInfo[] methodParams = mi.GetParameters(); if (methodParams.Length == delegateParams.Length) { bool match = true; for (int i = 0; i < methodParams.Length; i++) { if (delegateParams[i].ParameterType != methodParams[i].ParameterType) { match = false; break; } } if (match) { if (IsUnbound) { return mi.CreateDelegate(type); } else { return mi.CreateDelegate(type, _instance); } } } } } return null; } #endregion #region BuiltinFunctionData internal sealed class BuiltinFunctionData { public string/*!*/ Name; public MethodBase/*!*/[]/*!*/ Targets; public readonly Type/*!*/ DeclaringType; public FunctionType Type; public Dictionary<TypeList, BuiltinFunction> BoundGenerics; public Dictionary<BuiltinFunction.TypeList, BuiltinFunction> OverloadDictionary; public BuiltinFunctionData(string name, MethodBase[] targets, Type declType, FunctionType functionType) { Name = name; Targets = targets; DeclaringType = declType; Type = functionType; } internal void AddMethod(MethodBase/*!*/ info) { Assert.NotNull(info); MethodBase[] ni = new MethodBase[Targets.Length + 1]; Targets.CopyTo(ni, 0); ni[Targets.Length] = info; Targets = ni; } } #endregion #region IFastInvokable Members FastBindResult<T> IFastInvokable.MakeInvokeBinding<T>(CallSite<T> site, PythonInvokeBinder binder, CodeContext state, object[] args) { return new FastBindResult<T>( binder.LightBind<T>(ArrayUtils.Insert(state, this, args), 100), true ); } #endregion } /// <summary> /// A custom built-in function which supports indexing /// </summary> public class GenericBuiltinFunction : BuiltinFunction { internal GenericBuiltinFunction(string/*!*/ name, MethodBase/*!*/[]/*!*/ originalTargets, Type/*!*/ declaringType, FunctionType functionType) : base(name, originalTargets, declaringType, functionType) { } public BuiltinFunction/*!*/ this[PythonTuple tuple] { get { return this[tuple._data]; } } internal GenericBuiltinFunction(object instance, BuiltinFunctionData/*!*/ data) : base(instance, data) { } internal override BuiltinFunction BindToInstance(object instance) { return new GenericBuiltinFunction(instance, _data); } /// <summary> /// Use indexing on generic methods to provide a new reflected method with targets bound with /// the supplied type arguments. /// </summary> public BuiltinFunction/*!*/ this[params object[] key] { get { // Retrieve the list of type arguments from the index. Type[] types = new Type[key.Length]; for (int i = 0; i < types.Length; i++) { types[i] = Converter.ConvertToType(key[i]); } BuiltinFunction res = MakeGenericMethod(types); if (res == null) { bool hasGenerics = false; foreach (MethodBase mb in Targets) { MethodInfo mi = mb as MethodInfo; if (mi != null && mi.ContainsGenericParameters) { hasGenerics = true; } } if (hasGenerics) { throw PythonOps.TypeError(string.Format("bad type args to this generic method {0}", Name)); } else { throw PythonOps.TypeError(string.Format("{0} is not a generic method and is unsubscriptable", Name)); } } if (IsUnbound) { return res; } return new BuiltinFunction(_instance, res._data); } } internal override bool IsOnlyGeneric { get { foreach (MethodBase mb in Targets) { if (!mb.IsGenericMethod || !mb.ContainsGenericParameters) { return false; } } return true; } } } }
using UnityEngine; using UnityEngine.EventSystems; public class DragAndPlaceObject : MonoBehaviour { public static DragAndPlaceObject Singleton; //References //Public public bool PlacingObject = false; public Transform ObjecTransform; public float ObjectPrice = 0; public FloorTile PreviousTile = null; public Material WhiteMaterial; public Material RedMaterial; public Material GreenMaterial; //Private void Start() { Singleton = this; } void Update() { //Debug.Log(EventSystem.current.IsPointerOverGameObject() + " " + EventSystem.current.currentSelectedGameObject); if (EventSystem.current.IsPointerOverGameObject()) { return; } if (!StoreManager.Singleton.StoreIsOpen) { if (Input.GetKeyDown(KeyCode.S)) { PlaceShelves(); } if (Input.GetKeyDown(KeyCode.F)) { PlaceFridge(); } } if (!PlacingObject || ObjecTransform == null || FloorTile.ActiveTile == null) { return; } if (Input.GetKeyDown(KeyCode.Escape) && ObjectPrice > 0) { CancelPlacement(); return; } //if (Input.GetMouseButtonUp(1)) //{ // ObjecTransform.transform.Rotate(new Vector3(0, 90f, 0), Space.World); //} if (ObjecTransform.position.z == 5f) { ObjecTransform.transform.rotation = Quaternion.Euler(270, 180, 0); } else if (ObjecTransform.position.x == 1f) { ObjecTransform.transform.rotation = Quaternion.Euler(270, 270, 0); } else if (ObjecTransform.position.z == 1f) { ObjecTransform.transform.rotation = Quaternion.Euler(270, 0, 0); } if (!FloorTile.ActiveTile.CanPlaceObjectHere) { ObjecTransform.GetComponent<Renderer>().material = RedMaterial; ObjecTransform.position = FloorTile.ActiveTile.transform.position; //Debug.Log("Hovering over other object"); } else { ObjecTransform.GetComponent<Renderer>().material = GreenMaterial; ObjecTransform.position = FloorTile.ActiveTile.transform.position; } if (Input.GetMouseButtonUp(0)) { //Only if can place if (FloorTile.ActiveTile.CanPlaceObjectHere) { if (ObjectPrice > 0) //New object { if (StoreManager.Singleton.Money >= ObjectPrice) { StoreObjectManager.Singleton.StoreObjects.Add(ObjecTransform.gameObject); StoreManager.Singleton.Money -= ObjectPrice; SoundManager.Singleton.PlayCashRegisterSound(); UIManager.Singleton.ShowFloatingText("- $" + ObjectPrice.ToString("#0.00"), Color.red, ObjecTransform.position + new Vector3(0, 2, 0)); UIManager.Singleton.EnableControlsPanel(false); //First object if (StoreObjectManager.Singleton.StoreObjects.Count == 1) { TutorialManager.Singleton.OnFirstObjectPlaced(); } foreach (var tile in StoreManager.Singleton.FloorTiles) { if (tile.CanPlaceObjectHere) { tile.GetComponent<Renderer>().material = tile.WhiteMaterial; } } } else { UIManager.Singleton.ShowFloatingText("Not enough money!", Color.white, ObjecTransform.position + new Vector3(0, 2, 0)); return; } } ObjecTransform.GetComponent<Renderer>().material = WhiteMaterial; ObjecTransform.SetParent(FloorTile.ActiveTile.transform, true); ObjecTransform.GetComponent<PlaceableObject>().OnPlaced(); //Placed object on same tile again quickly, show menu if (PreviousTile == FloorTile.ActiveTile) { if (!EventSystem.current.IsPointerOverGameObject()) { //UIManager.Singleton.ShowObjectInfoScreen(ObjecTransform); } } PlacingObject = false; ObjecTransform = null; PreviousTile = null; } } } public void CancelPlacement() { UIManager.Singleton.EnableControlsPanel(false); Destroy(ObjecTransform.gameObject); ObjecTransform = null; PlacingObject = false; foreach (var tile in StoreManager.Singleton.FloorTiles) { if (tile.CanPlaceObjectHere) { tile.GetComponent<Renderer>().material = tile.WhiteMaterial; } } } public void CreateObjectToPlace(GameObject placeableObjectPrefab) { if (ObjecTransform != null) { CancelPlacement(); } PlaceableObject placeableObject = placeableObjectPrefab.GetComponent<PlaceableObject>(); if (StoreManager.Singleton.Money < placeableObject.Price) { //Not enough money UIManager.Singleton.ShowMessage("Not enough money!", "Not enough money to buy this " + placeableObject.Name + "!"); return; } TutorialManager.Singleton.OnStartPlacingObject(); GameObject newObject = (GameObject)Instantiate(placeableObjectPrefab); newObject.name = placeableObject.Name; ObjecTransform = newObject.transform; PlacingObject = true; ObjectPrice = placeableObject.Price; UIManager.Singleton.EnableControlsPanel(true); foreach (var tile in StoreManager.Singleton.FloorTiles) { if (tile.CanPlaceObjectHere) { tile.GetComponent<Renderer>().material = tile.GreenMaterial; } } } public void PlaceShelves() { CreateObjectToPlace(StoreObjectManager.Singleton.ShelvesPrefab); } public void PlaceFridge() { CreateObjectToPlace(StoreObjectManager.Singleton.FridgePrefab); } }
using System; using System.Collections.Generic; using System.Reflection; using System.Threading; using OpenQA.Selenium; using RegTesting.Tests.Framework.Elements; using RegTesting.Tests.Framework.Enums; using RegTesting.Tests.Framework.Logic.PageSettings; using RegTesting.Tests.Framework.Properties; namespace RegTesting.Tests.Framework.Logic { public class PageObjectFactory { private static readonly IPageSettingsFactory PageSettingsFactory; static PageObjectFactory() { PageSettingsFactory = new PageSettingsFactory(); } /// <summary> /// Creates the and navigate to. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="webDriver">The web driver.</param> /// <param name="baseUrl">The base URL.</param> /// <param name="suppressLanguageParameter">Supresses the language parameter</param> /// <param name="hashTagParams">hash tag parameters</param> /// <param name="furtherUrlParameters"> /// The further URL param after the lng param. /// The example input value "cpn=2553 would navigate us to: www.hotel.de?lng=de&cpn=2553 /// </param> /// <returns>A PageObject, navigated to the PageUrl.</returns> public static T CreateAndNavigateTo<T>(IWebDriver webDriver, string baseUrl, bool suppressLanguageParameter = false, string[] hashTagParams = null, params string[] furtherUrlParameters) where T : BasePageObject { T pageObject = CreatePageObject<T>(webDriver); Type type = typeof(T); PagePropsAttribute pageAttribute = (PagePropsAttribute)type.GetCustomAttribute(typeof(PagePropsAttribute), true); string pageUrl = baseUrl; if (!pageUrl.EndsWith("/")) pageUrl = pageUrl + "/"; if (pageObject.PageSettings.IsSeoRoute) { pageUrl = CreateSeoRoute(pageUrl, pageAttribute, furtherUrlParameters); } else { pageUrl = CreateRoute(pageUrl, pageAttribute, suppressLanguageParameter, furtherUrlParameters); } if (hashTagParams != null) pageUrl = string.Concat(pageUrl, "#?", string.Join("&", hashTagParams)); TestLog.AddWithoutTime("<br><b>>>>" + type.Name + "</b>"); TestLog.Add("CreateAndNavigate: " + type.Name + " -> " + pageUrl); webDriver.Navigate().GoToUrl(pageUrl); return pageObject; } public static T CreateAndNavigateTo<T>(IWebDriver webDriver, string baseUrl, params string[] furtherUrlParameters) where T : BasePageObject { return CreateAndNavigateTo<T>(webDriver, baseUrl, false, null, furtherUrlParameters); } private static string CreateSeoRoute(string pageUrl, PagePropsAttribute pageAttribute, params string[] furtherUrlParameters) { string seoRoute = pageAttribute != null && pageAttribute.PageUrl != null ? pageAttribute.PageUrl.ToLower() : string.Empty; List<string> remainingParams = new List<string>(); foreach (string param in furtherUrlParameters) { string key = param.Split('=')[0].ToLower(); string value = param.Split('=')[1]; if (seoRoute.Contains("{" + key + "}")) { seoRoute = seoRoute.Replace("{" + key + "}", value); } else { remainingParams.Add(param); } } return string.Concat(pageUrl, Thread.CurrentThread.CurrentUICulture.Name, "/", seoRoute, GetUrlParams(remainingParams.ToArray())); } private static string CreateRoute(string pageUrl, PagePropsAttribute pageAttribute, bool suppressLanguageParameter = false, params string[] furtherUrlParameters) { string returnUrl = string.Concat(pageUrl, pageAttribute != null && pageAttribute.PageUrl != null ? pageAttribute.PageUrl : string.Empty); returnUrl = string.Concat(returnUrl, GetUrlParams(furtherUrlParameters)); if (!suppressLanguageParameter) returnUrl = string.Concat(returnUrl, string.Format("&lng={0}", Thread.CurrentThread.CurrentUICulture.Name)); return returnUrl; } private static string GetUrlParams(string[] urlParameters) { string parameters = string.Join("&", urlParameters); if (!string.IsNullOrEmpty(parameters)) return string.Concat("?", parameters); return String.Empty; } public static T GetPageObjectByType<T>(IWebDriver webDriver) where T : BasePageObject { TestLog.AddWithoutTime("<br><b>>>>" + typeof(T).Name + "</b>"); TestLog.Add("GetPageObjectByType: " + typeof(T).Name); return CreatePageObject<T>(webDriver); } private static T CreatePageObject<T>(IWebDriver webDriver) where T : BasePageObject { try { T pageObject = (T)Activator.CreateInstance(typeof(T), webDriver, PageSettingsFactory); InitElements(webDriver, pageObject); TestLog.Add("Applying Page settings for '" + pageObject.GetType().Name + "'"); pageObject.PageSettings.ApplySettings(); return pageObject; } catch (TargetInvocationException exception) { if (exception.InnerException != null) throw exception.InnerException; throw; } } private static void InitElements(IWebDriver driver, BasePageObject pageObject) { if (pageObject == null) { throw new ArgumentNullException("pageObject"); } Type type = pageObject.GetType(); List<MemberInfo> memberInfos = new List<MemberInfo>(); const BindingFlags publicBindingOptions = BindingFlags.Instance | BindingFlags.Public; memberInfos.AddRange(type.GetFields(publicBindingOptions)); memberInfos.AddRange(type.GetProperties(publicBindingOptions)); while (type != null) { const BindingFlags nonPublicBindingOptions = BindingFlags.Instance | BindingFlags.NonPublic; memberInfos.AddRange(type.GetFields(nonPublicBindingOptions)); memberInfos.AddRange(type.GetProperties(nonPublicBindingOptions)); type = type.BaseType; } Type pageObjectType = pageObject.GetType(); foreach (MemberInfo member in memberInfos) { LocateAttribute locateAttribute = GetAttribute<LocateAttribute>(member); ClickBehaviourAttribute clickBehaviourAttribute = GetAttribute<ClickBehaviourAttribute>(member); ClickBehaviours clickBehaviour = clickBehaviourAttribute != null ? clickBehaviourAttribute.Using : ClickBehaviours.Default; FillBehaviourAttribute fillBehaviourAttribute = GetAttribute<FillBehaviourAttribute>(member); FillBehaviour fillBehaviour = fillBehaviourAttribute != null ? fillBehaviourAttribute.Using : FillBehaviour.Default; WaitAttribute waitAttribute = GetAttribute<WaitAttribute>(member); WaitForElementsOnActionAttribute waitForElementsOnActionAttribute = GetAttribute<WaitForElementsOnActionAttribute>(member); WaitModel waitModel = new WaitModel { WaitBeforeAction = waitAttribute != null ? waitAttribute.BeforePerformAction : Settings.Default.WaitBeforePerformAction, WaitAfterAction = waitAttribute != null ? waitAttribute.AfterPerformAction : Settings.Default.WaitAfterPerformAction, WaitForElementsBeforeAction = CreateLocateOptionsFromAttribute(waitForElementsOnActionAttribute, pageObjectType, When.Before), WaitForElementsAfterAction = CreateLocateOptionsFromAttribute(waitForElementsOnActionAttribute, pageObjectType, When.After), }; if (locateAttribute != null) { By by = CreateLocator(member); object createdElementObject; FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; if (field != null) { createdElementObject = CreateElementObject(field.FieldType, driver, by, waitModel, pageObject, clickBehaviour, fillBehaviour); if (createdElementObject == null) { throw new ArgumentException("Type of field '" + field.Name + "' is not IWebElement or IList<IWebElement>"); } field.SetValue(pageObject, createdElementObject); } else if (property != null) { createdElementObject = CreateElementObject(property.PropertyType, driver, by, waitModel, pageObject, clickBehaviour, fillBehaviour); if (createdElementObject == null) { throw new ArgumentException("Type of property '" + property.Name + "' is not IWebElement or IList<IWebElement>"); } property.SetValue(pageObject, createdElementObject, null); } } PartialPageObjectAttribute partialPageObjectAttribute = GetAttribute<PartialPageObjectAttribute>(member); if (partialPageObjectAttribute != null) { PropertyInfo property = member as PropertyInfo; if (property != null) { MethodInfo castMethod = typeof(PageObjectFactory).GetMethod("CreatePageObject", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(property.PropertyType); object createdElementObject = castMethod.Invoke(null, new object[] { driver }); if (createdElementObject == null) { throw new ArgumentException("Type of property '" + property.Name + "' is not IWebElement or IList<IWebElement>"); } property.SetValue(pageObject, createdElementObject, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,null,null); } } } } internal static BasicPageElement CreateElementObject(Type fieldType, IWebDriver webDriver, By @by, WaitModel waitModel, BasePageObject parentPageObject, ClickBehaviours clickBehaviours = ClickBehaviours.Default, FillBehaviour fillBehaviour = FillBehaviour.Default) { if (fieldType == typeof (Button)) { return new Button(@by, webDriver, waitModel, parentPageObject, clickBehaviours); } if (fieldType == typeof (Link)) { return new Link(@by, webDriver, waitModel, parentPageObject, clickBehaviours); } if (fieldType == typeof(Image)) { return new Image(@by, webDriver, waitModel, parentPageObject, clickBehaviours); } if (fieldType == typeof(BasicPageElement)) { return new BasicPageElement(@by, webDriver, waitModel, parentPageObject); } if (fieldType == typeof(SelectBox)) { return new SelectBox(@by, webDriver, waitModel, parentPageObject); } if (fieldType == typeof(CheckBox)) { return new CheckBox(@by, webDriver, waitModel, parentPageObject, clickBehaviours); } if (fieldType == typeof(Input)) { return new Input(@by, webDriver, waitModel, parentPageObject, clickBehaviours, fillBehaviour); } if (fieldType == typeof(HiddenElement)) { return new HiddenElement(@by, webDriver, waitModel, parentPageObject, clickBehaviours); } return null; } public static T GetAttribute<T>(MemberInfo member) where T : Attribute { Attribute[] attributes = Attribute.GetCustomAttributes(member, typeof(T), true); if (attributes.Length > 1) throw new ArgumentException("Member " + member.Name + " has " + attributes.Length + " Attributes instead of only one."); if (attributes.Length == 0) return null; Attribute attribute = attributes[0]; return (T) attribute; } private static By CreateLocator(MemberInfo member) { LocateAttribute castedAttribute = GetAttribute<LocateAttribute>(member); if (castedAttribute.Using == null) { castedAttribute.Using = member.Name; } return castedAttribute.Finder; } private static By CreateLocatorForRelatedElement(string elementName, Type pageObjectType) { Type type = pageObjectType.GetType(); bool isChildOfBasePageObject = false; while (type != null) { if (type.BaseType != typeof (BasePageObject)) { isChildOfBasePageObject = true; } type = type.BaseType; } if (!isChildOfBasePageObject) throw new ArgumentException("Cannot create a related element from a object that does not inherit from " + typeof(BasePageObject)); MemberInfo[] memberInfos = pageObjectType.GetMembers(); foreach (MemberInfo memberInfo in memberInfos) { if (memberInfo.Name.Equals(elementName)) { return CreateLocator(memberInfo); } } throw new Exception("Could not create related element of the name '" + elementName + "' from the pageobject-type '" + pageObjectType + "'."); } private static IEnumerable<LocateOptions> CreateLocateOptionsFromAttribute(WaitForElementsOnActionAttribute waitForOnActionAttribute, Type pageObjectType, When when) { if (waitForOnActionAttribute != null && waitForOnActionAttribute.When == when) { LocateOptions[] locateOptions = { new LocateOptions { By = CreateLocatorForRelatedElement(waitForOnActionAttribute.WaitForPageElementWithName, pageObjectType), Visibility = waitForOnActionAttribute.Visibility } }; return locateOptions; } return new LocateOptions[0]; } } }
// ReSharper disable All using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Flag Views. /// </summary> [RoutePrefix("api/v1.0/config/flag-view")] public class FlagViewController : FrapidApiController { /// <summary> /// The FlagView repository. /// </summary> private IFlagViewRepository FlagViewRepository; public FlagViewController() { } public FlagViewController(IFlagViewRepository repository) { this.FlagViewRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.FlagViewRepository == null) { this.FlagViewRepository = new Frapid.Config.DataAccess.FlagView { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Counts the number of flag views. /// </summary> /// <returns>Returns the count of the flag views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/flag-view/count")] [RestAuthorize] public long Count() { try { return this.FlagViewRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of flag view for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("all")] [Route("~/api/config/flag-view/export")] [Route("~/api/config/flag-view/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.FlagView> Get() { try { return this.FlagViewRepository.Get(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 flag views on each page, sorted by the property . /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/flag-view")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.FlagView> GetPaginatedResult() { try { return this.FlagViewRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 flag views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/flag-view/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.FlagView> GetPaginatedResult(long pageNumber) { try { return this.FlagViewRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of flag views. /// </summary> /// <returns>Returns an enumerable key/value collection of flag views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/flag-view/display-fields")] [RestAuthorize] public IEnumerable<DisplayField> GetDisplayFields() { try { return this.FlagViewRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of flag views using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered flag views.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/flag-view/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.FlagViewRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 flag views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/flag-view/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.FlagView> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.FlagViewRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of flag views using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered flag views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/flag-view/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.FlagViewRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 flag views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/flag-view/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.FlagView> GetFiltered(long pageNumber, string filterName) { try { return this.FlagViewRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get/{resource}/{userId}")] [Route("~/api/config/flag-view/get/{resource}/{userId}")] public IEnumerable<Frapid.Config.Entities.FlagView> Get(string resource, int userId, [FromUri] object[] resourceIds) { try { return this.FlagViewRepository.Get(resource, userId, resourceIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using System.Threading.Tasks; using Legacy.Support; using Xunit; using Xunit.NetCore.Extensions; namespace System.IO.Ports.Tests { public class ReadTo_Generic : PortsTest { //Set bounds fore random timeout values. //If the min is to low read will not timeout accurately and the testcase will fail private const int minRandomTimeout = 250; //If the max is to large then the testcase will take forever to run private const int maxRandomTimeout = 2000; //If the percentage difference between the expected timeout and the actual timeout //found through Stopwatch is greater then 10% then the timeout value was not correctly //to the read method and the testcase fails. private const double maxPercentageDifference = .15; //The number of random bytes to receive for parity testing private const int numRndBytesParity = 8; //The number of random bytes to receive for BytesToRead testing private const int numRndBytesToRead = 16; //The number of new lines to insert into the string not including the one at the end //For BytesToRead testing private const int DEFAULT_NUMBER_NEW_LINES = 2; private const byte DEFAULT_NEW_LINE = (byte)'\n'; private const int NUM_TRYS = 5; #region Test Cases [Fact] public void ReadWithoutOpen() { using (SerialPort com = new SerialPort()) { Debug.WriteLine("Verifying read method throws exception without a call to Open()"); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterFailedOpen() { using (SerialPort com = new SerialPort("BAD_PORT_NAME")) { Debug.WriteLine("Verifying read method throws exception with a failed call to Open()"); //Since the PortName is set to a bad port name Open will thrown an exception //however we don't care what it is since we are verfifying a read method Assert.ThrowsAny<Exception>(() => com.Open()); VerifyReadException(com, typeof(InvalidOperationException)); } } [ConditionalFact(nameof(HasOneSerialPort))] public void ReadAfterClose() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying read method throws exception after a call to Cloes()"); com.Open(); com.Close(); VerifyReadException(com, typeof(InvalidOperationException)); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void Timeout() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout); com.Open(); VerifyTimeout(com); } } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive [ConditionalFact(nameof(HasOneSerialPort))] public void SuccessiveReadTimeoutNoData() { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); // com.Encoding = new System.Text.UTF7Encoding(); com.Encoding = Encoding.Unicode; Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout); com.Open(); Assert.Throws<TimeoutException>(() => com.ReadTo(com.NewLine)); VerifyTimeout(com); } } [ConditionalFact(nameof(HasNullModem))] public void SuccessiveReadTimeoutSomeData() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Random rndGen = new Random(-55); var t = new Task(WriteToCom1); com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout); com1.Encoding = new UTF8Encoding(); Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout); com1.Open(); //Call WriteToCom1 asynchronously this will write to com1 some time before the following call //to a read method times out t.Start(); try { com1.ReadTo(com1.NewLine); } catch (TimeoutException) { } TCSupport.WaitForTaskCompletion(t); //Make sure there is no bytes in the buffer so the next call to read will timeout com1.DiscardInBuffer(); VerifyTimeout(com1); } } private void WriteToCom1() { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2); //Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1 Thread.Sleep(sleepPeriod); com2.Open(); com2.WriteLine(""); if (com2.IsOpen) com2.Close(); } } [ConditionalFact(nameof(HasNullModem))] public void DefaultParityReplaceByte() { VerifyParityReplaceByte(-1, numRndBytesParity - 2); } [ConditionalFact(nameof(HasNullModem))] public void NoParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesParity - 1)); } [ConditionalFact(nameof(HasNullModem))] public void RNDParityReplaceByte() { Random rndGen = new Random(-55); VerifyParityReplaceByte(rndGen.Next(0, 128), 0); } [ConditionalFact(nameof(HasNullModem))] public void ParityErrorOnLastByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(15); byte[] bytesToWrite = new byte[numRndBytesParity]; char[] expectedChars = new char[numRndBytesParity]; /* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */ Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte"); //Genrate random characters without an parity error for (int i = 0; i < bytesToWrite.Length; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80); //Create a parity error on the last byte expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace; // Set the last expected char to be the ParityReplace Byte com1.Parity = Parity.Space; com1.DataBits = 7; com1.ReadTimeout = 250; com1.Open(); com2.Open(); com2.Write(bytesToWrite, 0, bytesToWrite.Length); com2.Write(com1.NewLine); TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + com1.NewLine.Length); string strRead = com1.ReadTo(com1.NewLine); char[] actualChars = strRead.ToCharArray(); Assert.Equal(expectedChars, actualChars); if (1 < com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead); Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]); } com1.DiscardInBuffer(); bytesToWrite[bytesToWrite.Length - 1] = (byte)'\n'; expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1]; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_RND_Buffer_Size() { Random rndGen = new Random(-55); VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead)); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_1_Buffer_Size() { VerifyBytesToRead(1); } [ConditionalFact(nameof(HasNullModem))] public void BytesToRead_Equal_Buffer_Size() { VerifyBytesToRead(numRndBytesToRead); } #endregion #region Verification for Test Cases private void VerifyTimeout(SerialPort com) { Stopwatch timer = new Stopwatch(); int expectedTime = com.ReadTimeout; int actualTime = 0; double percentageDifference; Assert.Throws<TimeoutException>(() => com.ReadTo(com.NewLine)); Thread.CurrentThread.Priority = ThreadPriority.Highest; for (int i = 0; i < NUM_TRYS; i++) { timer.Start(); Assert.Throws<TimeoutException>(() => com.ReadTo(com.NewLine)); timer.Stop(); actualTime += (int)timer.ElapsedMilliseconds; timer.Reset(); } Thread.CurrentThread.Priority = ThreadPriority.Normal; actualTime /= NUM_TRYS; percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime); //Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference if (maxPercentageDifference < percentageDifference) { Fail("ERROR!!!: The read method timedout in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference); } } private void VerifyReadException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.ReadTo(com.NewLine)); } private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] bytesToWrite = new byte[numRndBytesParity + 1]; //Plus one to accomidate the NewLineByte char[] expectedChars = new char[numRndBytesParity + 1]; //Plus one to accomidate the NewLineByte byte expectedByte; //Genrate random characters without an parity error for (int i = 0; i < numRndBytesParity; i++) { byte randByte = (byte)rndGen.Next(0, 128); bytesToWrite[i] = randByte; expectedChars[i] = (char)randByte; } if (-1 == parityReplace) { //If parityReplace is -1 and we should just use the default value expectedByte = com1.ParityReplace; } else if ('\0' == parityReplace) { //If parityReplace is the null charachater and parity replacement should not occur com1.ParityReplace = (byte)parityReplace; expectedByte = bytesToWrite[parityErrorIndex]; } else { //Else parityReplace was set to a value and we should expect this value to be returned on a parity error com1.ParityReplace = (byte)parityReplace; expectedByte = (byte)parityReplace; } //Create an parity error by setting the highest order bit to true bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80); expectedChars[parityErrorIndex] = (char)expectedByte; Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace, parityErrorIndex); com1.Parity = Parity.Space; com1.DataBits = 7; com1.Open(); com2.Open(); bytesToWrite[numRndBytesParity] = DEFAULT_NEW_LINE; expectedChars[numRndBytesParity] = (char)DEFAULT_NEW_LINE; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } private void VerifyBytesToRead(int numBytesRead) { VerifyBytesToRead(numBytesRead, DEFAULT_NUMBER_NEW_LINES); } private void VerifyBytesToRead(int numBytesRead, int numNewLines) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); byte[] bytesToWrite = new byte[numBytesRead + 1]; //Plus one to accomidate the NewLineByte ASCIIEncoding encoding = new ASCIIEncoding(); //Genrate random characters for (int i = 0; i < numBytesRead; i++) { byte randByte = (byte)rndGen.Next(0, 256); bytesToWrite[i] = randByte; } char[] expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length); for (int i = 0; i < numNewLines; i++) { int newLineIndex; newLineIndex = rndGen.Next(0, numBytesRead); bytesToWrite[newLineIndex] = (byte)'\n'; expectedChars[newLineIndex] = (char)'\n'; } Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead); com1.Open(); com2.Open(); bytesToWrite[numBytesRead] = DEFAULT_NEW_LINE; expectedChars[numBytesRead] = (char)DEFAULT_NEW_LINE; VerifyRead(com1, com2, bytesToWrite, expectedChars); } } private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars) { char[] actualChars = new char[expectedChars.Length]; int totalBytesRead; int totalCharsRead; int bytesToRead; int lastIndexOfNewLine = -1; com2.Write(bytesToWrite, 0, bytesToWrite.Length); com1.ReadTimeout = 250; TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length); totalBytesRead = 0; totalCharsRead = 0; bytesToRead = com1.BytesToRead; while (true) { string rcvString; try { rcvString = com1.ReadTo(com1.NewLine); } catch (TimeoutException) { break; } //While their are more characters to be read char[] rcvBuffer = rcvString.ToCharArray(); int charsRead = rcvBuffer.Length; int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead); int indexOfNewLine = Array.IndexOf(expectedChars, (char)DEFAULT_NEW_LINE, lastIndexOfNewLine + 1); if (indexOfNewLine - (lastIndexOfNewLine + 1) != charsRead) { //If we have not read all of the characters that we should have Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer"); Debug.WriteLine("indexOfNewLine={0} lastIndexOfNewLine={1} charsRead={2}", indexOfNewLine, lastIndexOfNewLine, charsRead); } if (expectedChars.Length < totalCharsRead + charsRead) { //If we have read in more characters then we expect Fail("ERROR!!!: We have received more characters then were sent"); } Array.Copy(rcvBuffer, 0, actualChars, totalCharsRead, charsRead); actualChars[totalCharsRead + charsRead] = (char)DEFAULT_NEW_LINE; //Add the NewLine char into actualChars totalBytesRead += bytesRead + 1; //Plus 1 because we read the NewLine char totalCharsRead += charsRead + 1; //Plus 1 because we read the NewLine char lastIndexOfNewLine = indexOfNewLine; if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead, com1.BytesToRead); } bytesToRead = com1.BytesToRead; }//End while there are more characters to read Assert.Equal(expectedChars, actualChars); } #endregion } }
using System; namespace L4p.Common.FunnelsModel { public partial interface IFunnelsManager { IFunnel GetFunnelBy(string name); IFunnel GetFunnelBy<E>(E enumValue) where E : struct; IFunnel GetFunnelBy(string name, string tag); IFunnel GetFunnelBy(string name, int tag); IFunnel GetFunnelBy(string name, long tag); IFunnel GetFunnelBy(string name, Guid tag); IFunnel GetFunnelBy<T>(string tag) where T : class; IFunnel GetFunnelBy<T>(int tag) where T : class; IFunnel GetFunnelBy<T>(long tag) where T : class; IFunnel GetFunnelBy<T>(Guid tag) where T : class; IFunnel GetFunnelBy<E>(E enumValue, string tag) where E : struct; IFunnel GetFunnelBy<E>(E enumValue, int tag) where E : struct; IFunnel GetFunnelBy<E>(E enumValue, long tag) where E : struct; IFunnel GetFunnelBy<E>(E enumValue, Guid tag) where E : struct; IFunnel NewFunnel(string name); IFunnel NewFunnel(string name, string tag); IFunnel NewFunnel(string name, int tag); IFunnel NewFunnel(string name, long tag); IFunnel NewFunnel(string name, Guid tag); IFunnel NewFunnel<T>() where T : class; IFunnel NewFunnel<T>(string tag) where T : class; IFunnel NewFunnel<T>(int tag) where T : class; IFunnel NewFunnel<T>(long tag) where T : class; IFunnel NewFunnel<T>(Guid tag) where T : class; IFunnel NewFunnel<E>(E enumValue) where E : struct; IFunnel NewFunnel<E>(E enumValue, string tag) where E : struct; IFunnel NewFunnel<E>(E enumValue, int tag) where E : struct; IFunnel NewFunnel<E>(E enumValue, long tag) where E : struct; IFunnel NewFunnel<E>(E enumValue, Guid tag) where E : struct; } partial class FunnelsManager { #region IFunnelsManager IFunnel IFunnelsManager.GetFunnelBy(string name) { return get_funnel(name, null); } IFunnel IFunnelsManager.GetFunnelBy<E>(E enumValue) { var name = enum_to_name(enumValue); return get_funnel(name, null); } IFunnel IFunnelsManager.GetFunnelBy(string name, string tag) { return get_funnel(name, tag); } IFunnel IFunnelsManager.GetFunnelBy(string name, int tag) { return get_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.GetFunnelBy(string name, long tag) { return get_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.GetFunnelBy(string name, Guid tag) { return get_funnel(name, tag.ToString("N")); } IFunnel IFunnelsManager.GetFunnelBy<T>(string tag) { var name = type_to_name(typeof(T)); return get_funnel(name, tag); } IFunnel IFunnelsManager.GetFunnelBy<T>(int tag) { var name = type_to_name(typeof(T)); return get_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.GetFunnelBy<T>(long tag) { var name = type_to_name(typeof(T)); return get_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.GetFunnelBy<T>(Guid tag) { var name = type_to_name(typeof(T)); return get_funnel(name, tag.ToString("N")); } IFunnel IFunnelsManager.GetFunnelBy<E>(E enumValue, string tag) { var name = enum_to_name(enumValue); return get_funnel(name, tag); } IFunnel IFunnelsManager.GetFunnelBy<E>(E enumValue, int tag) { var name = enum_to_name(enumValue); return get_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.GetFunnelBy<E>(E enumValue, long tag) { var name = enum_to_name(enumValue); return get_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.GetFunnelBy<E>(E enumValue, Guid tag) { var name = enum_to_name(enumValue); return get_funnel(name, tag.ToString("N")); } IFunnel IFunnelsManager.NewFunnel(string name) { return make_funnel(name, null); } IFunnel IFunnelsManager.NewFunnel(string name, string tag) { return make_funnel(name, tag); } IFunnel IFunnelsManager.NewFunnel(string name, int tag) { return make_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.NewFunnel(string name, long tag) { return make_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.NewFunnel(string name, Guid tag) { return make_funnel(name, tag.ToString("N")); } IFunnel IFunnelsManager.NewFunnel<T>() { var name = type_to_name(typeof(T)); return make_funnel(name, null); } IFunnel IFunnelsManager.NewFunnel<T>(string tag) { var name = type_to_name(typeof(T)); return make_funnel(name, tag); } IFunnel IFunnelsManager.NewFunnel<T>(int tag) { var name = type_to_name(typeof(T)); return make_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.NewFunnel<T>(long tag) { var name = type_to_name(typeof(T)); return make_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.NewFunnel<T>(Guid tag) { var name = type_to_name(typeof(T)); return make_funnel(name, tag.ToString("N")); } IFunnel IFunnelsManager.NewFunnel<E>(E enumValue) { var name = enum_to_name(enumValue); return make_funnel(name, null); } IFunnel IFunnelsManager.NewFunnel<E>(E enumValue, string tag) { var name = enum_to_name(enumValue); return make_funnel(name, tag); } IFunnel IFunnelsManager.NewFunnel<E>(E enumValue, int tag) { var name = enum_to_name(enumValue); return make_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.NewFunnel<E>(E enumValue, long tag) { var name = enum_to_name(enumValue); return make_funnel(name, tag.ToString()); } IFunnel IFunnelsManager.NewFunnel<E>(E enumValue, Guid tag) { var name = enum_to_name(enumValue); return make_funnel(name, tag.ToString("N")); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Glob { using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Linq; using Microsoft.DocAsCode.Common; [Serializable] public class GlobMatcher : IEquatable<GlobMatcher> { #region Private fields private static readonly StringComparer Comparer = FilePathComparer.OSPlatformSensitiveStringComparer; private static readonly string[] EmptyString = new string[0]; private const char NegateChar = '!'; private const string GlobStar = "**"; private const string ReplacerGroupName = "replacer"; private static readonly HashSet<char> NeedEscapeCharactersInRegex = new HashSet<char>(@"'().*{}+?[]^$\!".ToCharArray()); private static readonly Regex UnescapeGlobRegex = new Regex(@"\\(?<replacer>.)", RegexOptions.Compiled); /// <summary> /// start with * and has more than one * and followed by anything except * or / /// </summary> private static readonly Regex ExpandGlobStarRegex = new Regex(@"^\*{2,}(?=[^/*])", RegexOptions.Compiled); // Never match .abc file unless AllowDotMatch option is set private const string PatternStartWithDotAllowed = @"(?!(?:^|\/)\.{1,2}(?:$|\/))"; private const string PatternStartWithoutDotAllowed = @"(?!\.)"; private static readonly HashSet<char> RegexCharactersWithDotPossible = new HashSet<char>(new char[] { '.', '[', '(' }); /// <summary> /// Any character other than / /// </summary> private const string QuestionMarkToRegex = "[^/]"; /// <summary> /// Any number of character other than /, non-greedy mode /// </summary> private const string SingleStarToRegex = "[^/]*?"; private static readonly Regex GlobStarRegex = new Regex(@"^\*{2,}/?$", RegexOptions.Compiled); private GlobRegexItem[][] _items; private bool _negate = false; private bool _ignoreCase = false; #endregion public const GlobMatcherOptions DefaultOptions = GlobMatcherOptions.AllowNegate | GlobMatcherOptions.IgnoreCase | GlobMatcherOptions.AllowGlobStar | GlobMatcherOptions.AllowExpand | GlobMatcherOptions.AllowEscape; public GlobMatcherOptions Options { get; } public string Raw { get; } public GlobMatcher(string pattern, GlobMatcherOptions options = DefaultOptions) { if (pattern == null) throw new ArgumentNullException(nameof(pattern)); Options = options; Raw = pattern; _ignoreCase = Options.HasFlag(GlobMatcherOptions.IgnoreCase); _negate = ParseNegate(ref pattern, Options); _items = Compile(pattern).ToArray(); } /// <summary> /// Currently not used /// TODO: add test case /// </summary> /// <param name="glob"></param> /// <returns></returns> public Regex GetRegex() { var regexParts = _items.Select(ConvertSingleGlob); var content = string.Join("|", regexParts); // Matches the entire pattern content = $"^(?:{content})$"; if (_negate) { // Matches whatever not current pattern content = $"^(?!{content}).*$"; } if (_ignoreCase) { return new Regex(content, RegexOptions.IgnoreCase); } else { return new Regex(content); } } public bool Match(string file, bool partial = false) { if (file == null) throw new ArgumentNullException(nameof(file)); var fileParts = Split(file, '/', '\\').ToArray(); bool isMatch = false; foreach(var glob in _items) { if (MatchOne(fileParts, glob, partial)) { isMatch = true; break; } } return _negate ^ isMatch; } #region Private methods private IEnumerable<GlobRegexItem[]> Compile(string pattern) { string[] globs; if (Options.HasFlag(GlobMatcherOptions.AllowExpand)) { globs = ExpandGroup(pattern, Options); if (globs.Length == 0) return Enumerable.Empty<GlobRegexItem[]>(); } else { globs = new string[] { pattern }; } // **.cs is a shortcut for **/*.cs var items = globs .Select(glob => ExpandGlobStarShortcut(Split(glob, '/')).Select(ConvertSingleGlobPart).ToArray()); return items; } private IEnumerable<string> Split(string path, params char[] splitter) { var parts = path.Split(splitter, StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) yield break; for (int i = 0; i < parts.Length - 1; i++) { yield return parts[i] + "/"; } yield return path.EndsWith("/", StringComparison.Ordinal) ? parts[parts.Length - 1] + "/" : parts[parts.Length - 1]; } private string ConvertSingleGlob(IEnumerable<GlobRegexItem> regexItems) { var items = regexItems.Select(GlobRegexItemToRegex); return string.Join(@"\/", items); } private bool IsFolderPath(string path) { return path.EndsWith("/", StringComparison.Ordinal); } /// <summary> /// Convert each part to Regex /// </summary> /// <param name="globPart">Part of glob that does not contain '/'</param> /// <returns></returns> private GlobRegexItem ConvertSingleGlobPart(string globPart) { // Return GlobStar for ** if (Options.HasFlag(GlobMatcherOptions.AllowGlobStar) && GlobStarRegex.IsMatch(globPart)) { return IsFolderPath(globPart) ? GlobRegexItem.GlobStar : GlobRegexItem.GlobStarForFileOnly; } StringBuilder builder = new StringBuilder(); bool escaping = false; bool disableEscape = !Options.HasFlag(GlobMatcherOptions.AllowEscape); bool hasMagic = false; CharClass currentCharClass = null; string patternStart = string.Empty; // .abc will not be matched unless . is explicitly specified if (globPart.Length > 0 && globPart[0] != '.') { patternStart = Options.HasFlag(GlobMatcherOptions.AllowDotMatch) ? PatternStartWithDotAllowed : PatternStartWithoutDotAllowed; } for (int i = 0; i < globPart.Length; i++) { var c = globPart[i]; switch (c) { case '\\': if (!disableEscape) { i++; if (i == globPart.Length) { // \ at the end of path part, invalid, not possible for file path, invalid return GlobRegexItem.Empty; } else { c = globPart[i]; if (NeedEscapeCharactersInRegex.Contains(c)) { builder.Append('\\'); } builder.Append(c); } } else { builder.Append("\\\\"); } break; case '?': builder.Append(QuestionMarkToRegex); hasMagic = true; break; case '*': builder.Append(SingleStarToRegex); hasMagic = true; break; case '[': escaping = false; currentCharClass = new CharClass(); int cur = i + 1; while (cur < globPart.Length) { c = globPart[cur]; if (c == '\\') escaping = true; else if (c == ']' && !escaping) { // current char class ends when meeting the first non-escaping ] builder.Append(currentCharClass.ToString()); currentCharClass = null; break; } // simply keeps what it is inside char class currentCharClass.Add(c); if (c != '\\') escaping = false; cur++; } if (currentCharClass != null) { // no closing ] is found, fallback to no char class builder.Append("\\["); } else { i = cur; hasMagic = true; } break; default: if (NeedEscapeCharactersInRegex.Contains(c)) { builder.Append('\\'); } builder.Append(c); break; } } if (hasMagic) { var regexContent = builder.ToString(); if (!string.IsNullOrEmpty(regexContent)) { // when regex is not empty, make sure it does not match against empty path, e.g. a/* should not match a/ // regex: if followed by anything regexContent = "(?=.)" + regexContent; } else { return GlobRegexItem.Empty; } if (RegexCharactersWithDotPossible.Contains(regexContent[0])) { regexContent = patternStart + regexContent; } return new GlobRegexItem(regexContent, null, GlobRegexItemType.Regex, _ignoreCase); } else { // If does not contain any regex character, use the original string for regex // use escaped string as the string to be matched string plainText = UnescapeGlob(globPart); return new GlobRegexItem(globPart, plainText, GlobRegexItemType.PlainText, _ignoreCase); } } private string GlobRegexItemToRegex(GlobRegexItem item) { switch (item.ItemType) { case GlobRegexItemType.GlobStar: case GlobRegexItemType.GlobStarForFileOnly: // If globstar is disabled if (!Options.HasFlag(GlobMatcherOptions.AllowGlobStar)) { return SingleStarToRegex; } if (Options.HasFlag(GlobMatcherOptions.AllowDotMatch)) { // ** when dots are allowed, allows anything except .. and . // not (^ or / followed by one or two dots followed by $ or /) return @"(?:(?!(?:\/|^)(?:\.{1,2})($|\/)).)*?"; } else { // not (^ or / followed by a dot) return @"(?:(?!(?:\/|^)\.).)*?"; } case GlobRegexItemType.PlainText: case GlobRegexItemType.Regex: return item.RegexContent; default: throw new NotSupportedException($"{item.ItemType} is not current supported."); } } /// <summary> /// ** matches everything including "/" only when ** is after / or is the start of the pattern /// ** between characters has the same meaning as * /// **.cs equals to **/*.cs /// a**.cs equals to a*.cs /// </summary> /// <param name="globParts"></param> /// <returns></returns> private IEnumerable<string> ExpandGlobStarShortcut(IEnumerable<string> globParts) { foreach(var part in globParts) { if (ExpandGlobStarRegex.IsMatch(part)) { yield return GlobStar + "/"; yield return ExpandGlobStarRegex.Replace(part, "*"); } else { yield return part; } } } private bool MatchOne(string[] fileParts, GlobRegexItem[] globParts, bool matchPartialGlob) { bool[,] status = new bool[2, globParts.Length + 1]; int prev = 0; int cur = 1; status[0, 0] = true; for (int j = 0; j < globParts.Length; j++) { if (matchPartialGlob) { status[0, j + 1] = true; } else { var globPart = globParts[globParts.Length - j - 1]; if (globPart.ItemType == GlobRegexItemType.GlobStar) status[0, j + 1] = status[0, j]; else status[0, j + 1] = false; } } for(int i = 0; i < fileParts.Length; i++) { status[cur, 0] = false; for (int j = 0; j < globParts.Length; j++) { var filePart = fileParts[fileParts.Length - i - 1]; var globPart = globParts[globParts.Length - j - 1]; switch (globPart.ItemType) { case GlobRegexItemType.GlobStar: if (DisallowedMatchExists(filePart)) status[cur, j + 1] = false; else { var isFolderPath = IsFolderPath(filePart); status[cur, j + 1] = (status[prev, j + 1] && isFolderPath) || (status[prev, j] && isFolderPath || status[cur, j]); } break; case GlobRegexItemType.GlobStarForFileOnly: if (DisallowedMatchExists(filePart)) status[cur, j + 1] = false; else { var isFolderPath = IsFolderPath(filePart); status[cur, j + 1] = status[prev, j + 1] || (status[prev, j] && !isFolderPath); } break; case GlobRegexItemType.PlainText: StringComparison comparison = StringComparison.Ordinal; if (Options.HasFlag(GlobMatcherOptions.IgnoreCase)) { comparison = StringComparison.OrdinalIgnoreCase; } status[cur, j + 1] = string.Equals(filePart, globPart.PlainText, comparison) && status[prev, j]; break; case GlobRegexItemType.Regex: status[cur, j + 1] = globPart.Regex.IsMatch(filePart) && status[prev, j]; break; } } prev ^= 1; cur ^= 1; } return status[prev, globParts.Length]; } private bool DisallowedMatchExists(string filePart) { if (filePart == "." || filePart == ".." || (!Options.HasFlag(GlobMatcherOptions.AllowDotMatch) && filePart.StartsWith(".", StringComparison.Ordinal))) { return true; } return false; } private static string UnescapeGlob(string s) { return UnescapeGlobRegex.Replace(s, new MatchEvaluator(ReplaceReplacerGroup)); } private static string ReplaceReplacerGroup(Match m) { if (m.Success) { return m.Groups[ReplacerGroupName].Value; } return m.Value; } #endregion internal static bool ParseNegate(ref string pattern, GlobMatcherOptions options = DefaultOptions) { if (!options.HasFlag(GlobMatcherOptions.AllowNegate)) { return false; } bool negate = false; int i = 0; while (i < pattern.Length && pattern[i] == NegateChar) { negate = !negate; i++; } if (i <= pattern.Length) { pattern = pattern.Substring(i); } return negate; } /// <summary> /// {a,b}c => [ac, bc] /// </summary> /// <param name="pattern"></param> /// <returns></returns> internal static string[] ExpandGroup(string pattern, GlobMatcherOptions options = DefaultOptions) { GlobUngrouper ungrouper = new GlobUngrouper(); bool escaping = false; bool disableEscape = !options.HasFlag(GlobMatcherOptions.AllowEscape); foreach (char c in pattern) { if (escaping) { if (c != ',' && c != '{' && c != '}') { ungrouper.AddChar('\\'); } ungrouper.AddChar(c); escaping = false; continue; } else if (c == '\\' && !disableEscape) { escaping = true; continue; } switch (c) { case '{': ungrouper.StartLevel(); break; case ',': if (ungrouper.Level < 1) { ungrouper.AddChar(c); } else { ungrouper.AddGroup(); } break; case '}': if (ungrouper.Level < 1) { // Unbalanced closing bracket matches nothing return EmptyString; } ungrouper.FinishLevel(); break; default: ungrouper.AddChar(c); break; } } return ungrouper.Flatten(); } #region Private classes private sealed class GlobUngrouper { public abstract class GlobNode { public readonly GlobNode _parent; protected GlobNode(GlobNode parentNode) { _parent = parentNode ?? this; } abstract public GlobNode AddChar(char c); abstract public GlobNode StartLevel(); abstract public GlobNode AddGroup(); abstract public GlobNode FinishLevel(); abstract public List<StringBuilder> Flatten(); } public class TextNode : GlobNode { private readonly StringBuilder _builder; public TextNode(GlobNode parentNode) : base(parentNode) { _builder = new StringBuilder(); } public override GlobNode AddChar(char c) { if (c != 0) { _builder.Append(c); } return this; } public override GlobNode StartLevel() { return _parent.StartLevel(); } public override GlobNode AddGroup() { return _parent.AddGroup(); } public override GlobNode FinishLevel() { return _parent.FinishLevel(); } public override List<StringBuilder> Flatten() { List<StringBuilder> result = new List<StringBuilder>(1); result.Add(_builder); return result; } } public class ChoiceNode : GlobNode { private readonly List<SequenceNode> _nodes; public ChoiceNode(GlobNode parentNode) : base(parentNode) { _nodes = new List<SequenceNode>(); } public override GlobNode AddChar(char c) { SequenceNode node = new SequenceNode(this); _nodes.Add(node); return node.AddChar(c); } public override GlobNode StartLevel() { SequenceNode node = new SequenceNode(this); _nodes.Add(node); return node.StartLevel(); } public override GlobNode AddGroup() { return AddChar('\0'); } public override GlobNode FinishLevel() { AddChar('\0'); return _parent; } public override List<StringBuilder> Flatten() { List<StringBuilder> result = new List<StringBuilder>(); foreach (GlobNode node in _nodes) { foreach (StringBuilder builder in node.Flatten()) { result.Add(builder); } } return result; } } public class SequenceNode : GlobNode { private readonly List<GlobNode> _nodes; public SequenceNode(GlobNode parentNode) : base(parentNode) { _nodes = new List<GlobNode>(); } public override GlobNode AddChar(char c) { TextNode node = new TextNode(this); _nodes.Add(node); return node.AddChar(c); } public override GlobNode StartLevel() { ChoiceNode node = new ChoiceNode(this); _nodes.Add(node); return node; } public override GlobNode AddGroup() { return _parent; } public override GlobNode FinishLevel() { return _parent._parent; } public override List<StringBuilder> Flatten() { List<StringBuilder> result = new List<StringBuilder>(); result.Add(new StringBuilder()); foreach (GlobNode node in _nodes) { List<StringBuilder> tmp = new List<StringBuilder>(); foreach (StringBuilder builder in node.Flatten()) { foreach (StringBuilder sb in result) { StringBuilder newsb = new StringBuilder(sb.ToString()); newsb.Append(builder.ToString()); tmp.Add(newsb); } } result = tmp; } return result; } } private readonly SequenceNode _rootNode; private GlobNode _currentNode; private int _level; public GlobUngrouper() { _rootNode = new SequenceNode(null); _currentNode = _rootNode; _level = 0; } public void AddChar(char c) { _currentNode = _currentNode.AddChar(c); } public void StartLevel() { _currentNode = _currentNode.StartLevel(); _level++; } public void AddGroup() { _currentNode = _currentNode.AddGroup(); } public void FinishLevel() { _currentNode = _currentNode.FinishLevel(); _level--; } public int Level { get { return _level; } } public string[] Flatten() { if (_level != 0) { return EmptyString; } List<StringBuilder> list = _rootNode.Flatten(); string[] result = new string[list.Count]; for (int i = 0; i < list.Count; i++) { result[i] = list[i].ToString(); } return result; } } /// <summary> /// Represents [] class /// </summary> private sealed class CharClass { private readonly StringBuilder _chars = new StringBuilder(); public void Add(char c) { _chars.Append(c); } public override string ToString() { if (_chars.Length == 0) { return string.Empty; } if (_chars.Length == 1 && _chars[0] == '^') { _chars.Insert(0, "\\"); } return $"[{_chars.ToString()}]"; } } [Serializable] private sealed class GlobRegexItem { public static readonly GlobRegexItem GlobStar = new GlobRegexItem(GlobRegexItemType.GlobStar); public static readonly GlobRegexItem GlobStarForFileOnly = new GlobRegexItem(GlobRegexItemType.GlobStarForFileOnly); public static readonly GlobRegexItem Empty = new GlobRegexItem(string.Empty, string.Empty, GlobRegexItemType.PlainText); public GlobRegexItemType ItemType { get; } public string RegexContent { get; } public string PlainText { get; } public Regex Regex { get; } public GlobRegexItem(string content, string plainText, GlobRegexItemType type, bool ignoreCase = true) { RegexContent = content; ItemType = type; PlainText = plainText; if (type == GlobRegexItemType.Regex) { var regexSegment = $"^{RegexContent}$"; Regex = ignoreCase ? new Regex(regexSegment, RegexOptions.IgnoreCase) : new Regex(regexSegment); } } private GlobRegexItem(GlobRegexItemType itemType) { ItemType = itemType; } } private enum GlobRegexItemType { GlobStarForFileOnly, // ** to match files only GlobStar, // **/ to match files or folders PlainText, Regex, } #endregion #region Compare & Equatable public bool Equals(GlobMatcher other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return Comparer.Equals(Raw, other.Raw) && Options == other.Options; } public override bool Equals(object obj) { return Equals(obj as GlobMatcher); } public override int GetHashCode() { return Options.GetHashCode() ^ (Comparer.GetHashCode(Raw) >> 1); } #endregion } [Flags] public enum GlobMatcherOptions { None = 0x0, IgnoreCase = 0x1, AllowNegate = 0x2, AllowExpand = 0x4, AllowEscape = 0x8, AllowGlobStar = 0x10, /// <summary> /// Allow patterns to match filenames starting with a period even if the pattern does not explicitly have a period. /// By default disabled: a/**/b will **not** match a/.c/d, unless `AllowDotMatch` is set /// </summary> AllowDotMatch = 0x20, } }
using EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSetTableAdapters; namespace EIDSS.Reports.Document.ActiveSurveillance { partial class SessionFarmReport { /// <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 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SessionFarmReport)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.cellNo = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand(); this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); this.MainTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.cellFarm = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.m_SessionFarmReportDataSet = new EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSet(); this.m_SessionFarmAdapter = new EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSetTableAdapters.SessionFarmAdapter(); this.GroupFooter1 = new DevExpress.XtraReports.UI.GroupFooterBand(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.MainTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionFarmReportDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow3}); this.xrTable2.StylePriority.UseBorders = false; this.xrTable2.StylePriority.UseTextAlignment = false; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.cellNo, this.xrTableCell15, this.xrTableCell16, this.xrTableCell17, this.xrTableCell18, this.xrTableCell19, this.xrTableCell20, this.xrTableCell21, this.xrTableCell22, this.xrTableCell23}); resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); this.xrTableRow3.Name = "xrTableRow3"; // // cellNo // resources.ApplyResources(this.cellNo, "cellNo"); this.cellNo.Multiline = true; this.cellNo.Name = "cellNo"; this.cellNo.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellNo_BeforePrint); // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalCode")}); resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); this.xrTableCell15.Multiline = true; this.xrTableCell15.Name = "xrTableCell15"; // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSpeciesType")}); resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); this.xrTableCell16.Multiline = true; this.xrTableCell16.Name = "xrTableCell16"; // // xrTableCell17 // this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalAge")}); resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); this.xrTableCell17.Multiline = true; this.xrTableCell17.Name = "xrTableCell17"; // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalColor")}); resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Multiline = true; this.xrTableCell18.Name = "xrTableCell18"; // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalName")}); resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Multiline = true; this.xrTableCell19.Name = "xrTableCell19"; // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalGender")}); resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Multiline = true; this.xrTableCell20.Name = "xrTableCell20"; // // xrTableCell21 // resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Multiline = true; this.xrTableCell21.Name = "xrTableCell21"; // // xrTableCell22 // this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFieldBarcode")}); resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); this.xrTableCell22.Multiline = true; this.xrTableCell22.Name = "xrTableCell22"; // // xrTableCell23 // this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSpecimenName")}); resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); this.xrTableCell23.Multiline = true; this.xrTableCell23.Name = "xrTableCell23"; // // TopMargin // resources.ApplyResources(this.TopMargin, "TopMargin"); this.TopMargin.Name = "TopMargin"; this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // BottomMargin // resources.ApplyResources(this.BottomMargin, "BottomMargin"); this.BottomMargin.Name = "BottomMargin"; this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // PageHeader // this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.MainTable}); resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; // // MainTable // this.MainTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.MainTable, "MainTable"); this.MainTable.Name = "MainTable"; this.MainTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.MainTable.StylePriority.UseBorders = false; this.MainTable.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell4, this.xrTableCell8, this.xrTableCell1, this.xrTableCell5, this.xrTableCell9, this.xrTableCell10, this.xrTableCell2, this.xrTableCell6, this.xrTableCell3}); resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); this.xrTableRow1.Name = "xrTableRow1"; // // xrTableCell7 // resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Multiline = true; this.xrTableCell7.Name = "xrTableCell7"; // // xrTableCell4 // resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Multiline = true; this.xrTableCell4.Name = "xrTableCell4"; // // xrTableCell8 // resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Multiline = true; this.xrTableCell8.Name = "xrTableCell8"; // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Multiline = true; this.xrTableCell1.Name = "xrTableCell1"; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Multiline = true; this.xrTableCell5.Name = "xrTableCell5"; // // xrTableCell9 // resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Multiline = true; this.xrTableCell9.Name = "xrTableCell9"; // // xrTableCell10 // resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Multiline = true; this.xrTableCell10.Name = "xrTableCell10"; // // xrTableCell2 // resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Multiline = true; this.xrTableCell2.Name = "xrTableCell2"; // // xrTableCell6 // resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Multiline = true; this.xrTableCell6.Name = "xrTableCell6"; // // xrTableCell3 // resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Multiline = true; this.xrTableCell3.Name = "xrTableCell3"; // // GroupHeader1 // this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.GroupHeader1, "GroupHeader1"); this.GroupHeader1.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] { new DevExpress.XtraReports.UI.GroupField("idfFarm", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)}); this.GroupHeader1.Name = "GroupHeader1"; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.cellFarm, this.xrTableCell12, this.xrTableCell13}); resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); this.xrTableRow2.Name = "xrTableRow2"; // // cellFarm // this.cellFarm.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.cellFarm.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFarmCode")}); resources.ApplyResources(this.cellFarm, "cellFarm"); this.cellFarm.Name = "cellFarm"; this.cellFarm.StylePriority.UseBorders = false; this.cellFarm.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellFarm_BeforePrint); // // xrTableCell12 // this.xrTableCell12.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strOwnerName")}); resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseBorders = false; // // xrTableCell13 // this.xrTableCell13.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Right | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFarmAddress")}); resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.StylePriority.UseBorders = false; // // m_SessionFarmReportDataSet // this.m_SessionFarmReportDataSet.DataSetName = "SessionFarmReportDataSet"; this.m_SessionFarmReportDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // m_SessionFarmAdapter // this.m_SessionFarmAdapter.ClearBeforeFill = true; // // GroupFooter1 // resources.ApplyResources(this.GroupFooter1, "GroupFooter1"); this.GroupFooter1.Name = "GroupFooter1"; // // SessionFarmReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.TopMargin, this.BottomMargin, this.PageHeader, this.GroupHeader1, this.GroupFooter1}); this.DataAdapter = this.m_SessionFarmAdapter; this.DataMember = "SessionFarm"; this.DataSource = this.m_SessionFarmReportDataSet; resources.ApplyResources(this, "$this"); this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.MainTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionFarmReportDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.TopMarginBand TopMargin; private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin; private DevExpress.XtraReports.UI.PageHeaderBand PageHeader; private DevExpress.XtraReports.UI.XRTable MainTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell cellFarm; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private SessionFarmReportDataSet m_SessionFarmReportDataSet; private SessionFarmAdapter m_SessionFarmAdapter; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell cellNo; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooter1; } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections; using System.Collections.Generic; using Mono.Cecil; namespace Mono.Collections.Generic { public class Collection<T> : IList<T>, IList { internal T [] items; internal int size; int version; public int Count { get { return size; } } public T this [int index] { get { if (index >= size) throw new ArgumentOutOfRangeException (); return items [index]; } set { CheckIndex (index); if (index == size) throw new ArgumentOutOfRangeException (); OnSet (value, index); items [index] = value; } } public int Capacity { get { return items.Length; } set { if (value < 0 || value < size) throw new ArgumentOutOfRangeException (); Resize (value); } } bool ICollection<T>.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this [int index] { get { return this [index]; } set { CheckIndex (index); try { this [index] = (T) value; return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } } int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } public Collection () { items = Empty<T>.Array; } public Collection (int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException (); items = new T [capacity]; } public Collection (ICollection<T> items) { if (items == null) throw new ArgumentNullException ("items"); this.items = new T [items.Count]; items.CopyTo (this.items, 0); this.size = this.items.Length; } public void Add (T item) { if (size == items.Length) Grow (1); OnAdd (item, size); items [size++] = item; version++; } public void SetCapacity(int capacity) { if (size < capacity) { Grow(capacity-size); } } public bool Contains (T item) { return IndexOf (item) != -1; } public int IndexOf (T item) { return Array.IndexOf (items, item, 0, size); } public void Insert (int index, T item) { CheckIndex (index); if (size == items.Length) Grow (1); OnInsert (item, index); Shift (index, 1); items [index] = item; version++; } public void RemoveAt (int index) { if (index < 0 || index >= size) throw new ArgumentOutOfRangeException (); var item = items [index]; OnRemove (item, index); Shift (index, -1); version++; } public bool Remove (T item) { var index = IndexOf (item); if (index == -1) return false; OnRemove (item, index); Shift (index, -1); version++; return true; } public void Clear () { OnClear (); Array.Clear (items, 0, size); size = 0; version++; } public void CopyTo (T [] array, int arrayIndex) { Array.Copy (items, 0, array, arrayIndex, size); } public T [] ToArray () { var array = new T [size]; Array.Copy (items, 0, array, 0, size); return array; } void CheckIndex (int index) { if (index < 0 || index > size) throw new ArgumentOutOfRangeException (); } void Shift (int start, int delta) { if (delta < 0) start -= delta; if (start < size) Array.Copy (items, start, items, start + delta, size - start); size += delta; if (delta < 0) Array.Clear (items, size, -delta); } protected virtual void OnAdd (T item, int index) { } protected virtual void OnInsert (T item, int index) { } protected virtual void OnSet (T item, int index) { } protected virtual void OnRemove (T item, int index) { } protected virtual void OnClear () { } internal virtual void Grow (int desired) { int new_size = size + desired; if (new_size <= items.Length) return; const int default_capacity = 4; new_size = System.Math.Max ( System.Math.Max (items.Length * 2, default_capacity), new_size); Resize (new_size); } protected void Resize (int new_size) { if (new_size == size) return; if (new_size < size) throw new ArgumentOutOfRangeException (); items = items.Resize (new_size); } int IList.Add (object value) { try { Add ((T) value); return size - 1; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } void IList.Clear () { Clear (); } bool IList.Contains (object value) { return ((IList) this).IndexOf (value) > -1; } int IList.IndexOf (object value) { try { return IndexOf ((T) value); } catch (InvalidCastException) { } catch (NullReferenceException) { } return -1; } void IList.Insert (int index, object value) { CheckIndex (index); try { Insert (index, (T) value); return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } void IList.Remove (object value) { try { Remove ((T) value); } catch (InvalidCastException) { } catch (NullReferenceException) { } } void IList.RemoveAt (int index) { RemoveAt (index); } public void Sort(IComparer<T> cmp) { Array.Sort(items, 0, size, cmp); } void ICollection.CopyTo (Array array, int index) { Array.Copy (items, 0, array, index, size); } public Enumerator GetEnumerator () { return new Enumerator (this); } IEnumerator IEnumerable.GetEnumerator () { return new Enumerator (this); } IEnumerator<T> IEnumerable<T>.GetEnumerator () { return new Enumerator (this); } public struct Enumerator : IEnumerator<T>, IDisposable { Collection<T> collection; T current; int next; readonly int version; public T Current { get { return current; } } object IEnumerator.Current { get { CheckState (); if (next <= 0) throw new InvalidOperationException (); return current; } } internal Enumerator (Collection<T> collection) : this () { this.collection = collection; this.version = collection.version; } public bool MoveNext () { CheckState (); if (next < 0) return false; if (next < collection.size) { current = collection.items [next++]; return true; } next = -1; return false; } public void Reset () { CheckState (); next = 0; } void CheckState () { if (collection == null) throw new ObjectDisposedException (GetType ().FullName); if (version != collection.version) throw new InvalidOperationException (); } public void Dispose () { collection = null; } } } }
// *********************************************************************** // Copyright (c) 2011-2013 Charlie Poole, Terje Sandstrom // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using NUnit.Core; using NUnit.VisualStudio.TestAdapter.Internal; using NUnitTestResult = NUnit.Core.TestResult; using VSTestResult = Microsoft.VisualStudio.TestPlatform.ObjectModel.TestResult; namespace NUnit.VisualStudio.TestAdapter { public class TestConverter { private readonly TestLogger _logger; private readonly Dictionary<string, TestCase> _vsTestCaseMap; private readonly string _sourceAssembly; private NavigationDataProvider _navigationDataProvider; private bool _collectSourceInformation; #region Constructor public TestConverter(TestLogger logger, string sourceAssembly, bool collectSourceInformation) { _logger = logger; _sourceAssembly = sourceAssembly; _vsTestCaseMap = new Dictionary<string, TestCase>(); _collectSourceInformation = collectSourceInformation; if (_collectSourceInformation) { _navigationDataProvider = new NavigationDataProvider(sourceAssembly); } } #endregion #region Public Methods /// <summary> /// Converts an NUnit test into a TestCase for Visual Studio, /// using the best method available according to the exact /// type passed and caching results for efficiency. /// </summary> public TestCase ConvertTestCase(ITest test) { if (test.IsSuite) throw new ArgumentException("The argument must be a test case", "test"); // Return cached value if we have one if (_vsTestCaseMap.ContainsKey(test.TestName.UniqueName)) return _vsTestCaseMap[test.TestName.UniqueName]; // Convert to VS TestCase and cache the result var testCase = MakeTestCaseFromNUnitTest(test); _vsTestCaseMap.Add(test.TestName.UniqueName, testCase); return testCase; } public TestCase GetCachedTestCase(string key) { if (_vsTestCaseMap.ContainsKey(key)) return _vsTestCaseMap[key]; _logger.SendErrorMessage("Test " + key + " not found in cache"); return null; } public VSTestResult ConvertTestResult(NUnitTestResult result) { TestCase ourCase = GetCachedTestCase(result.Test.TestName.UniqueName); if (ourCase == null) return null; VSTestResult ourResult = new VSTestResult(ourCase) { DisplayName = ourCase.DisplayName, Outcome = ResultStateToTestOutcome(result.ResultState), Duration = TimeSpan.FromSeconds(result.Time) }; // TODO: Remove this when NUnit provides a better duration if (ourResult.Duration == TimeSpan.Zero && (ourResult.Outcome == TestOutcome.Passed || ourResult.Outcome == TestOutcome.Failed)) ourResult.Duration = TimeSpan.FromTicks(1); ourResult.ComputerName = Environment.MachineName; // TODO: Stuff we don't yet set // StartTime - not in NUnit result // EndTime - not in NUnit result // Messages - could we add messages other than the error message? Where would they appear? // Attachments - don't exist in NUnit if (result.Message != null) ourResult.ErrorMessage = GetErrorMessage(result); if (!string.IsNullOrEmpty(result.StackTrace)) { string stackTrace = StackTraceFilter.Filter(result.StackTrace); ourResult.ErrorStackTrace = stackTrace; } return ourResult; } #endregion #region Helper Methods /// <summary> /// Makes a TestCase from an NUnit test, adding /// navigation data if it can be found. /// </summary> private TestCase MakeTestCaseFromNUnitTest(ITest nunitTest) { //var testCase = MakeTestCaseFromTestName(nunitTest.TestName); var testCase = new TestCase( nunitTest.TestName.FullName, new Uri(NUnitTestExecutor.ExecutorUri), this._sourceAssembly) { DisplayName = nunitTest.TestName.Name, CodeFilePath = null, LineNumber = 0 }; if (_collectSourceInformation && _navigationDataProvider != null) { var navData = _navigationDataProvider.GetNavigationData(nunitTest.ClassName, nunitTest.MethodName); if (navData.IsValid) { testCase.CodeFilePath = navData.FilePath; testCase.LineNumber = navData.LineNumber; } } testCase.AddTraitsFromNUnitTest(nunitTest); return testCase; } // Public for testing public static TestOutcome ResultStateToTestOutcome(ResultState resultState) { switch (resultState) { case ResultState.Cancelled: return TestOutcome.None; case ResultState.Error: return TestOutcome.Failed; case ResultState.Failure: return TestOutcome.Failed; case ResultState.Ignored: return TestOutcome.Skipped; case ResultState.Inconclusive: return TestOutcome.None; case ResultState.NotRunnable: return TestOutcome.Failed; case ResultState.Skipped: return TestOutcome.Skipped; case ResultState.Success: return TestOutcome.Passed; } return TestOutcome.None; } private string GetErrorMessage(NUnitTestResult result) { string message = result.Message; string NL = Environment.NewLine; // If we're running in the IDE, remove any caret line from the message // since it will be displayed using a variable font and won't make sense. if (message != null && RunningUnderIDE && (result.ResultState == ResultState.Failure || result.ResultState == ResultState.Inconclusive)) { string pattern = NL + " -*\\^" + NL; message = Regex.Replace(message, pattern, NL, RegexOptions.Multiline); } return message; } #endregion #region Private Properties private string exeName; private bool RunningUnderIDE { get { if (exeName == null) { Assembly entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) exeName = Path.GetFileName(AssemblyHelper.GetAssemblyPath(entryAssembly)); } return exeName == "vstest.executionengine.exe"; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A quaternion of type long. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct lquat : IEnumerable<long>, IEquatable<lquat> { #region Fields /// <summary> /// x-component /// </summary> public long x; /// <summary> /// y-component /// </summary> public long y; /// <summary> /// z-component /// </summary> public long z; /// <summary> /// w-component /// </summary> public long w; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public lquat(long x, long y, long z, long w) { this.x = x; this.y = y; this.z = z; this.w = w; } /// <summary> /// all-same-value constructor /// </summary> public lquat(long v) { this.x = v; this.y = v; this.z = v; this.w = v; } /// <summary> /// copy constructor /// </summary> public lquat(lquat q) { this.x = q.x; this.y = q.y; this.z = q.z; this.w = q.w; } /// <summary> /// vector-and-scalar constructor (CAUTION: not angle-axis, use FromAngleAxis instead) /// </summary> public lquat(lvec3 v, long s) { this.x = v.x; this.y = v.y; this.z = v.z; this.w = s; } #endregion #region Implicit Operators /// <summary> /// Implicitly converts this to a decquat. /// </summary> public static implicit operator decquat(lquat v) => new decquat((decimal)v.x, (decimal)v.y, (decimal)v.z, (decimal)v.w); #endregion #region Explicit Operators /// <summary> /// Explicitly converts this to a ivec4. /// </summary> public static explicit operator ivec4(lquat v) => new ivec4((int)v.x, (int)v.y, (int)v.z, (int)v.w); /// <summary> /// Explicitly converts this to a iquat. /// </summary> public static explicit operator iquat(lquat v) => new iquat((int)v.x, (int)v.y, (int)v.z, (int)v.w); /// <summary> /// Explicitly converts this to a uvec4. /// </summary> public static explicit operator uvec4(lquat v) => new uvec4((uint)v.x, (uint)v.y, (uint)v.z, (uint)v.w); /// <summary> /// Explicitly converts this to a uquat. /// </summary> public static explicit operator uquat(lquat v) => new uquat((uint)v.x, (uint)v.y, (uint)v.z, (uint)v.w); /// <summary> /// Explicitly converts this to a vec4. /// </summary> public static explicit operator vec4(lquat v) => new vec4((float)v.x, (float)v.y, (float)v.z, (float)v.w); /// <summary> /// Explicitly converts this to a quat. /// </summary> public static explicit operator quat(lquat v) => new quat((float)v.x, (float)v.y, (float)v.z, (float)v.w); /// <summary> /// Explicitly converts this to a hvec4. /// </summary> public static explicit operator hvec4(lquat v) => new hvec4((Half)v.x, (Half)v.y, (Half)v.z, (Half)v.w); /// <summary> /// Explicitly converts this to a hquat. /// </summary> public static explicit operator hquat(lquat v) => new hquat((Half)v.x, (Half)v.y, (Half)v.z, (Half)v.w); /// <summary> /// Explicitly converts this to a dvec4. /// </summary> public static explicit operator dvec4(lquat v) => new dvec4((double)v.x, (double)v.y, (double)v.z, (double)v.w); /// <summary> /// Explicitly converts this to a dquat. /// </summary> public static explicit operator dquat(lquat v) => new dquat((double)v.x, (double)v.y, (double)v.z, (double)v.w); /// <summary> /// Explicitly converts this to a decvec4. /// </summary> public static explicit operator decvec4(lquat v) => new decvec4((decimal)v.x, (decimal)v.y, (decimal)v.z, (decimal)v.w); /// <summary> /// Explicitly converts this to a lvec4. /// </summary> public static explicit operator lvec4(lquat v) => new lvec4((long)v.x, (long)v.y, (long)v.z, (long)v.w); /// <summary> /// Explicitly converts this to a bvec4. /// </summary> public static explicit operator bvec4(lquat v) => new bvec4(v.x != 0, v.y != 0, v.z != 0, v.w != 0); /// <summary> /// Explicitly converts this to a bquat. /// </summary> public static explicit operator bquat(lquat v) => new bquat(v.x != 0, v.y != 0, v.z != 0, v.w != 0); #endregion #region Indexer /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public long this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; default: throw new ArgumentOutOfRangeException("index"); } } set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; case 3: w = value; break; default: throw new ArgumentOutOfRangeException("index"); } } } #endregion #region Properties /// <summary> /// Returns an array with all values /// </summary> public long[] Values => new[] { x, y, z, w }; /// <summary> /// Returns the number of components (4). /// </summary> public int Count => 4; /// <summary> /// Returns the euclidean length of this quaternion. /// </summary> public double Length => (double)Math.Sqrt(((x*x + y*y) + (z*z + w*w))); /// <summary> /// Returns the squared euclidean length of this quaternion. /// </summary> public long LengthSqr => ((x*x + y*y) + (z*z + w*w)); /// <summary> /// Returns the conjugated quaternion /// </summary> public lquat Conjugate => new lquat(-x, -y, -z, w); /// <summary> /// Returns the inverse quaternion /// </summary> public lquat Inverse => Conjugate / LengthSqr; #endregion #region Static Properties /// <summary> /// Predefined all-zero quaternion /// </summary> public static lquat Zero { get; } = new lquat(0, 0, 0, 0); /// <summary> /// Predefined all-ones quaternion /// </summary> public static lquat Ones { get; } = new lquat(1, 1, 1, 1); /// <summary> /// Predefined identity quaternion /// </summary> public static lquat Identity { get; } = new lquat(0, 0, 0, 1); /// <summary> /// Predefined unit-X quaternion /// </summary> public static lquat UnitX { get; } = new lquat(1, 0, 0, 0); /// <summary> /// Predefined unit-Y quaternion /// </summary> public static lquat UnitY { get; } = new lquat(0, 1, 0, 0); /// <summary> /// Predefined unit-Z quaternion /// </summary> public static lquat UnitZ { get; } = new lquat(0, 0, 1, 0); /// <summary> /// Predefined unit-W quaternion /// </summary> public static lquat UnitW { get; } = new lquat(0, 0, 0, 1); /// <summary> /// Predefined all-MaxValue quaternion /// </summary> public static lquat MaxValue { get; } = new lquat(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue); /// <summary> /// Predefined all-MinValue quaternion /// </summary> public static lquat MinValue { get; } = new lquat(long.MinValue, long.MinValue, long.MinValue, long.MinValue); #endregion #region Operators /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator==(lquat lhs, lquat rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator!=(lquat lhs, lquat rhs) => !lhs.Equals(rhs); /// <summary> /// Returns proper multiplication of two quaternions. /// </summary> public static lquat operator*(lquat p, lquat q) => new lquat(p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y, p.w * q.y + p.y * q.w + p.z * q.x - p.x * q.z, p.w * q.z + p.z * q.w + p.x * q.y - p.y * q.x, p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z); /// <summary> /// Returns a vector rotated by the quaternion. /// </summary> public static lvec3 operator*(lquat q, lvec3 v) { var qv = new lvec3(q.x, q.y, q.z); var uv = lvec3.Cross(qv, v); var uuv = lvec3.Cross(qv, uv); return v + ((uv * q.w) + uuv) * 2; } /// <summary> /// Returns a vector rotated by the quaternion (preserves v.w). /// </summary> public static lvec4 operator*(lquat q, lvec4 v) => new lvec4(q * new lvec3(v), v.w); /// <summary> /// Returns a vector rotated by the inverted quaternion. /// </summary> public static lvec3 operator*(lvec3 v, lquat q) => q.Inverse * v; /// <summary> /// Returns a vector rotated by the inverted quaternion (preserves v.w). /// </summary> public static lvec4 operator*(lvec4 v, lquat q) => q.Inverse * v; #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public IEnumerator<long> GetEnumerator() { yield return x; yield return y; yield return z; yield return w; } /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// Returns a string representation of this quaternion using ', ' as a seperator. /// </summary> public override string ToString() => ToString(", "); /// <summary> /// Returns a string representation of this quaternion using a provided seperator. /// </summary> public string ToString(string sep) => ((x + sep + y) + sep + (z + sep + w)); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format provider for each component. /// </summary> public string ToString(string sep, IFormatProvider provider) => ((x.ToString(provider) + sep + y.ToString(provider)) + sep + (z.ToString(provider) + sep + w.ToString(provider))); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format for each component. /// </summary> public string ToString(string sep, string format) => ((x.ToString(format) + sep + y.ToString(format)) + sep + (z.ToString(format) + sep + w.ToString(format))); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format and format provider for each component. /// </summary> public string ToString(string sep, string format, IFormatProvider provider) => ((x.ToString(format, provider) + sep + y.ToString(format, provider)) + sep + (z.ToString(format, provider) + sep + w.ToString(format, provider))); /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(lquat rhs) => ((x.Equals(rhs.x) && y.Equals(rhs.y)) && (z.Equals(rhs.z) && w.Equals(rhs.w))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is lquat && Equals((lquat) obj); } /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((x.GetHashCode()) * 397) ^ y.GetHashCode()) * 397) ^ z.GetHashCode()) * 397) ^ w.GetHashCode(); } } #endregion #region Static Functions /// <summary> /// Converts the string representation of the quaternion into a quaternion representation (using ', ' as a separator). /// </summary> public static lquat Parse(string s) => Parse(s, ", "); /// <summary> /// Converts the string representation of the quaternion into a quaternion representation (using a designated separator). /// </summary> public static lquat Parse(string s, string sep) { var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts"); return new lquat(long.Parse(kvp[0].Trim()), long.Parse(kvp[1].Trim()), long.Parse(kvp[2].Trim()), long.Parse(kvp[3].Trim())); } /// <summary> /// Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a type provider). /// </summary> public static lquat Parse(string s, string sep, IFormatProvider provider) { var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts"); return new lquat(long.Parse(kvp[0].Trim(), provider), long.Parse(kvp[1].Trim(), provider), long.Parse(kvp[2].Trim(), provider), long.Parse(kvp[3].Trim(), provider)); } /// <summary> /// Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a number style). /// </summary> public static lquat Parse(string s, string sep, NumberStyles style) { var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts"); return new lquat(long.Parse(kvp[0].Trim(), style), long.Parse(kvp[1].Trim(), style), long.Parse(kvp[2].Trim(), style), long.Parse(kvp[3].Trim(), style)); } /// <summary> /// Converts the string representation of the quaternion into a quaternion representation (using a designated separator and a number style and a format provider). /// </summary> public static lquat Parse(string s, string sep, NumberStyles style, IFormatProvider provider) { var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) throw new FormatException("input has not exactly 4 parts"); return new lquat(long.Parse(kvp[0].Trim(), style, provider), long.Parse(kvp[1].Trim(), style, provider), long.Parse(kvp[2].Trim(), style, provider), long.Parse(kvp[3].Trim(), style, provider)); } /// <summary> /// Tries to convert the string representation of the quaternion into a quaternion representation (using ', ' as a separator), returns false if string was invalid. /// </summary> public static bool TryParse(string s, out lquat result) => TryParse(s, ", ", out result); /// <summary> /// Tries to convert the string representation of the quaternion into a quaternion representation (using a designated separator), returns false if string was invalid. /// </summary> public static bool TryParse(string s, string sep, out lquat result) { result = Zero; if (string.IsNullOrEmpty(s)) return false; var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) return false; long x = 0, y = 0, z = 0, w = 0; var ok = ((long.TryParse(kvp[0].Trim(), out x) && long.TryParse(kvp[1].Trim(), out y)) && (long.TryParse(kvp[2].Trim(), out z) && long.TryParse(kvp[3].Trim(), out w))); result = ok ? new lquat(x, y, z, w) : Zero; return ok; } /// <summary> /// Tries to convert the string representation of the quaternion into a quaternion representation (using a designated separator and a number style and a format provider), returns false if string was invalid. /// </summary> public static bool TryParse(string s, string sep, NumberStyles style, IFormatProvider provider, out lquat result) { result = Zero; if (string.IsNullOrEmpty(s)) return false; var kvp = s.Split(new[] { sep }, StringSplitOptions.None); if (kvp.Length != 4) return false; long x = 0, y = 0, z = 0, w = 0; var ok = ((long.TryParse(kvp[0].Trim(), style, provider, out x) && long.TryParse(kvp[1].Trim(), style, provider, out y)) && (long.TryParse(kvp[2].Trim(), style, provider, out z) && long.TryParse(kvp[3].Trim(), style, provider, out w))); result = ok ? new lquat(x, y, z, w) : Zero; return ok; } /// <summary> /// Returns the inner product (dot product, scalar product) of the two quaternions. /// </summary> public static long Dot(lquat lhs, lquat rhs) => ((lhs.x * rhs.x + lhs.y * rhs.y) + (lhs.z * rhs.z + lhs.w * rhs.w)); /// <summary> /// Returns the cross product between two quaternions. /// </summary> public static lquat Cross(lquat q1, lquat q2) => new lquat(q1.w * q2.x + q1.x * q2.w + q1.y * q2.z - q1.z * q2.y, q1.w * q2.y + q1.y * q2.w + q1.z * q2.x - q1.x * q2.z, q1.w * q2.z + q1.z * q2.w + q1.x * q2.y - q1.y * q2.x, q1.w * q2.w - q1.x * q2.x - q1.y * q2.y - q1.z * q2.z); #endregion #region Component-Wise Static Functions /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(lquat lhs, lquat rhs) => new bvec4(lhs.x == rhs.x, lhs.y == rhs.y, lhs.z == rhs.z, lhs.w == rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(lquat lhs, long rhs) => new bvec4(lhs.x == rhs, lhs.y == rhs, lhs.z == rhs, lhs.w == rhs); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(long lhs, lquat rhs) => new bvec4(lhs == rhs.x, lhs == rhs.y, lhs == rhs.z, lhs == rhs.w); /// <summary> /// Returns a bvec from the application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(long lhs, long rhs) => new bvec4(lhs == rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(lquat lhs, lquat rhs) => new bvec4(lhs.x != rhs.x, lhs.y != rhs.y, lhs.z != rhs.z, lhs.w != rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(lquat lhs, long rhs) => new bvec4(lhs.x != rhs, lhs.y != rhs, lhs.z != rhs, lhs.w != rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(long lhs, lquat rhs) => new bvec4(lhs != rhs.x, lhs != rhs.y, lhs != rhs.z, lhs != rhs.w); /// <summary> /// Returns a bvec from the application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(long lhs, long rhs) => new bvec4(lhs != rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(lquat lhs, lquat rhs) => new bvec4(lhs.x > rhs.x, lhs.y > rhs.y, lhs.z > rhs.z, lhs.w > rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(lquat lhs, long rhs) => new bvec4(lhs.x > rhs, lhs.y > rhs, lhs.z > rhs, lhs.w > rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(long lhs, lquat rhs) => new bvec4(lhs > rhs.x, lhs > rhs.y, lhs > rhs.z, lhs > rhs.w); /// <summary> /// Returns a bvec from the application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(long lhs, long rhs) => new bvec4(lhs > rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(lquat lhs, lquat rhs) => new bvec4(lhs.x >= rhs.x, lhs.y >= rhs.y, lhs.z >= rhs.z, lhs.w >= rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(lquat lhs, long rhs) => new bvec4(lhs.x >= rhs, lhs.y >= rhs, lhs.z >= rhs, lhs.w >= rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(long lhs, lquat rhs) => new bvec4(lhs >= rhs.x, lhs >= rhs.y, lhs >= rhs.z, lhs >= rhs.w); /// <summary> /// Returns a bvec from the application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(long lhs, long rhs) => new bvec4(lhs >= rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(lquat lhs, lquat rhs) => new bvec4(lhs.x < rhs.x, lhs.y < rhs.y, lhs.z < rhs.z, lhs.w < rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(lquat lhs, long rhs) => new bvec4(lhs.x < rhs, lhs.y < rhs, lhs.z < rhs, lhs.w < rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(long lhs, lquat rhs) => new bvec4(lhs < rhs.x, lhs < rhs.y, lhs < rhs.z, lhs < rhs.w); /// <summary> /// Returns a bvec from the application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(long lhs, long rhs) => new bvec4(lhs < rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(lquat lhs, lquat rhs) => new bvec4(lhs.x <= rhs.x, lhs.y <= rhs.y, lhs.z <= rhs.z, lhs.w <= rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(lquat lhs, long rhs) => new bvec4(lhs.x <= rhs, lhs.y <= rhs, lhs.z <= rhs, lhs.w <= rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(long lhs, lquat rhs) => new bvec4(lhs <= rhs.x, lhs <= rhs.y, lhs <= rhs.z, lhs <= rhs.w); /// <summary> /// Returns a bvec from the application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(long lhs, long rhs) => new bvec4(lhs <= rhs); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(lquat min, lquat max, lquat a) => new lquat(min.x * (1-a.x) + max.x * a.x, min.y * (1-a.y) + max.y * a.y, min.z * (1-a.z) + max.z * a.z, min.w * (1-a.w) + max.w * a.w); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(lquat min, lquat max, long a) => new lquat(min.x * (1-a) + max.x * a, min.y * (1-a) + max.y * a, min.z * (1-a) + max.z * a, min.w * (1-a) + max.w * a); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(lquat min, long max, lquat a) => new lquat(min.x * (1-a.x) + max * a.x, min.y * (1-a.y) + max * a.y, min.z * (1-a.z) + max * a.z, min.w * (1-a.w) + max * a.w); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(lquat min, long max, long a) => new lquat(min.x * (1-a) + max * a, min.y * (1-a) + max * a, min.z * (1-a) + max * a, min.w * (1-a) + max * a); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(long min, lquat max, lquat a) => new lquat(min * (1-a.x) + max.x * a.x, min * (1-a.y) + max.y * a.y, min * (1-a.z) + max.z * a.z, min * (1-a.w) + max.w * a.w); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(long min, lquat max, long a) => new lquat(min * (1-a) + max.x * a, min * (1-a) + max.y * a, min * (1-a) + max.z * a, min * (1-a) + max.w * a); /// <summary> /// Returns a lquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(long min, long max, lquat a) => new lquat(min * (1-a.x) + max * a.x, min * (1-a.y) + max * a.y, min * (1-a.z) + max * a.z, min * (1-a.w) + max * a.w); /// <summary> /// Returns a lquat from the application of Lerp (min * (1-a) + max * a). /// </summary> public static lquat Lerp(long min, long max, long a) => new lquat(min * (1-a) + max * a); #endregion #region Component-Wise Operator Overloads /// <summary> /// Returns a bvec4 from component-wise application of operator&lt; (lhs &lt; rhs). /// </summary> public static bvec4 operator<(lquat lhs, lquat rhs) => new bvec4(lhs.x < rhs.x, lhs.y < rhs.y, lhs.z < rhs.z, lhs.w < rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&lt; (lhs &lt; rhs). /// </summary> public static bvec4 operator<(lquat lhs, long rhs) => new bvec4(lhs.x < rhs, lhs.y < rhs, lhs.z < rhs, lhs.w < rhs); /// <summary> /// Returns a bvec4 from component-wise application of operator&lt; (lhs &lt; rhs). /// </summary> public static bvec4 operator<(long lhs, lquat rhs) => new bvec4(lhs < rhs.x, lhs < rhs.y, lhs < rhs.z, lhs < rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&lt;= (lhs &lt;= rhs). /// </summary> public static bvec4 operator<=(lquat lhs, lquat rhs) => new bvec4(lhs.x <= rhs.x, lhs.y <= rhs.y, lhs.z <= rhs.z, lhs.w <= rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&lt;= (lhs &lt;= rhs). /// </summary> public static bvec4 operator<=(lquat lhs, long rhs) => new bvec4(lhs.x <= rhs, lhs.y <= rhs, lhs.z <= rhs, lhs.w <= rhs); /// <summary> /// Returns a bvec4 from component-wise application of operator&lt;= (lhs &lt;= rhs). /// </summary> public static bvec4 operator<=(long lhs, lquat rhs) => new bvec4(lhs <= rhs.x, lhs <= rhs.y, lhs <= rhs.z, lhs <= rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&gt; (lhs &gt; rhs). /// </summary> public static bvec4 operator>(lquat lhs, lquat rhs) => new bvec4(lhs.x > rhs.x, lhs.y > rhs.y, lhs.z > rhs.z, lhs.w > rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&gt; (lhs &gt; rhs). /// </summary> public static bvec4 operator>(lquat lhs, long rhs) => new bvec4(lhs.x > rhs, lhs.y > rhs, lhs.z > rhs, lhs.w > rhs); /// <summary> /// Returns a bvec4 from component-wise application of operator&gt; (lhs &gt; rhs). /// </summary> public static bvec4 operator>(long lhs, lquat rhs) => new bvec4(lhs > rhs.x, lhs > rhs.y, lhs > rhs.z, lhs > rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&gt;= (lhs &gt;= rhs). /// </summary> public static bvec4 operator>=(lquat lhs, lquat rhs) => new bvec4(lhs.x >= rhs.x, lhs.y >= rhs.y, lhs.z >= rhs.z, lhs.w >= rhs.w); /// <summary> /// Returns a bvec4 from component-wise application of operator&gt;= (lhs &gt;= rhs). /// </summary> public static bvec4 operator>=(lquat lhs, long rhs) => new bvec4(lhs.x >= rhs, lhs.y >= rhs, lhs.z >= rhs, lhs.w >= rhs); /// <summary> /// Returns a bvec4 from component-wise application of operator&gt;= (lhs &gt;= rhs). /// </summary> public static bvec4 operator>=(long lhs, lquat rhs) => new bvec4(lhs >= rhs.x, lhs >= rhs.y, lhs >= rhs.z, lhs >= rhs.w); /// <summary> /// Returns a lquat from component-wise application of operator+ (identity). /// </summary> public static lquat operator+(lquat v) => v; /// <summary> /// Returns a lquat from component-wise application of operator- (-v). /// </summary> public static lquat operator-(lquat v) => new lquat(-v.x, -v.y, -v.z, -v.w); /// <summary> /// Returns a lquat from component-wise application of operator+ (lhs + rhs). /// </summary> public static lquat operator+(lquat lhs, lquat rhs) => new lquat(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w); /// <summary> /// Returns a lquat from component-wise application of operator+ (lhs + rhs). /// </summary> public static lquat operator+(lquat lhs, long rhs) => new lquat(lhs.x + rhs, lhs.y + rhs, lhs.z + rhs, lhs.w + rhs); /// <summary> /// Returns a lquat from component-wise application of operator+ (lhs + rhs). /// </summary> public static lquat operator+(long lhs, lquat rhs) => new lquat(lhs + rhs.x, lhs + rhs.y, lhs + rhs.z, lhs + rhs.w); /// <summary> /// Returns a lquat from component-wise application of operator- (lhs - rhs). /// </summary> public static lquat operator-(lquat lhs, lquat rhs) => new lquat(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w); /// <summary> /// Returns a lquat from component-wise application of operator- (lhs - rhs). /// </summary> public static lquat operator-(lquat lhs, long rhs) => new lquat(lhs.x - rhs, lhs.y - rhs, lhs.z - rhs, lhs.w - rhs); /// <summary> /// Returns a lquat from component-wise application of operator- (lhs - rhs). /// </summary> public static lquat operator-(long lhs, lquat rhs) => new lquat(lhs - rhs.x, lhs - rhs.y, lhs - rhs.z, lhs - rhs.w); /// <summary> /// Returns a lquat from component-wise application of operator* (lhs * rhs). /// </summary> public static lquat operator*(lquat lhs, long rhs) => new lquat(lhs.x * rhs, lhs.y * rhs, lhs.z * rhs, lhs.w * rhs); /// <summary> /// Returns a lquat from component-wise application of operator* (lhs * rhs). /// </summary> public static lquat operator*(long lhs, lquat rhs) => new lquat(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z, lhs * rhs.w); /// <summary> /// Returns a lquat from component-wise application of operator/ (lhs / rhs). /// </summary> public static lquat operator/(lquat lhs, long rhs) => new lquat(lhs.x / rhs, lhs.y / rhs, lhs.z / rhs, lhs.w / rhs); #endregion } }
namespace k8s.Models { /// <summary>Adds convenient extensions for Kubernetes objects.</summary> public static class ModelExtensions { /// <summary>Adds the given finalizer to a Kubernetes object if it doesn't already exist.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="finalizer">the finalizer</param> /// <returns>Returns true if the finalizer was added and false if it already existed.</returns> public static bool AddFinalizer(this IMetadata<V1ObjectMeta> obj, string finalizer) { if (string.IsNullOrEmpty(finalizer)) { throw new ArgumentNullException(nameof(finalizer)); } if (EnsureMetadata(obj).Finalizers == null) { obj.Metadata.Finalizers = new List<string>(); } if (!obj.Metadata.Finalizers.Contains(finalizer)) { obj.Metadata.Finalizers.Add(finalizer); return true; } return false; } /// <summary>Extracts the Kubernetes API group from the <see cref="IKubernetesObject.ApiVersion"/>.</summary> /// <param name="obj">the kubernetes client <see cref="IKubernetesObject"/></param> /// <returns>api group from server</returns> public static string ApiGroup(this IKubernetesObject obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (obj.ApiVersion != null) { var slash = obj.ApiVersion.IndexOf('/'); return slash < 0 ? string.Empty : obj.ApiVersion.Substring(0, slash); } return null; } /// <summary>Extracts the Kubernetes API version (excluding the group) from the <see cref="IKubernetesObject.ApiVersion"/>.</summary> /// <param name="obj">the kubernetes client <see cref="IKubernetesObject"/></param> /// <returns>api group version from server</returns> public static string ApiGroupVersion(this IKubernetesObject obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (obj.ApiVersion != null) { var slash = obj.ApiVersion.IndexOf('/'); return slash < 0 ? obj.ApiVersion : obj.ApiVersion.Substring(slash + 1); } return null; } /// <summary>Splits the Kubernetes API version into the group and version.</summary> /// <param name="obj">the kubernetes client <see cref="IKubernetesObject"/></param> /// <returns>api group and version from server</returns> public static (string, string) ApiGroupAndVersion(this IKubernetesObject obj) { string group, version; GetApiGroupAndVersion(obj, out group, out version); return (group, version); } /// <summary>Splits the Kubernetes API version into the group and version.</summary> /// <param name="obj">the kubernetes client <see cref="IKubernetesObject"/></param> /// <param name="group">api group output var</param> /// <param name="version">api group version output var</param> public static void GetApiGroupAndVersion(this IKubernetesObject obj, out string group, out string version) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (obj.ApiVersion == null) { group = version = null; } else { var slash = obj.ApiVersion.IndexOf('/'); if (slash < 0) { (group, version) = (string.Empty, obj.ApiVersion); } else { (group, version) = (obj.ApiVersion.Substring(0, slash), obj.ApiVersion.Substring(slash + 1)); } } } /// <summary> /// Gets the continuation token version of a Kubernetes list. /// </summary> /// <param name="list">Kubernetes list</param> /// <returns>continuation token </returns> public static string Continue(this IMetadata<V1ListMeta> list) => list?.Metadata?.ContinueProperty; /// <summary>Ensures that the <see cref="V1ListMeta"/> metadata field is set, and returns it.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the metadata <see cref="V1ListMeta"/> </returns> public static V1ListMeta EnsureMetadata(this IMetadata<V1ListMeta> obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (obj.Metadata == null) { obj.Metadata = new V1ListMeta(); } return obj.Metadata; } /// <summary>Gets the resource version of a Kubernetes list.</summary> /// <param name="list">the object meta list<see cref="V1ListMeta"/></param> /// <returns>resource version</returns> public static string ResourceVersion(this IMetadata<V1ListMeta> list) => list?.Metadata?.ResourceVersion; /// <summary>Adds an owner reference to the object. No attempt is made to ensure the reference is correct or fits with the /// other references. /// </summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="ownerRef">the owner reference to the object</param> public static void AddOwnerReference(this IMetadata<V1ObjectMeta> obj, V1OwnerReference ownerRef) { if (ownerRef == null) { throw new ArgumentNullException(nameof(ownerRef)); } if (EnsureMetadata(obj).OwnerReferences == null) { obj.Metadata.OwnerReferences = new List<V1OwnerReference>(); } obj.Metadata.OwnerReferences.Add(ownerRef); } /// <summary>Gets the annotations of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>a dictionary of the annotations</returns> public static IDictionary<string, string> Annotations(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.Annotations; /// <summary>Gets the creation time of a Kubernetes object, or null if it hasn't been created yet.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>creation time of a Kubernetes object, null if it hasn't been created yet.</returns> public static DateTime? CreationTimestamp(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.CreationTimestamp; /// <summary>Gets the deletion time of a Kubernetes object, or null if it hasn't been scheduled for deletion.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the deletion time of a Kubernetes object, or null if it hasn't been scheduled for deletion.</returns> public static DateTime? DeletionTimestamp(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.DeletionTimestamp; /// <summary>Ensures that the <see cref="V1ObjectMeta"/> metadata field is set, and returns it.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the metadata field <see cref="V1ObjectMeta"/></returns> public static V1ObjectMeta EnsureMetadata(this IMetadata<V1ObjectMeta> obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (obj.Metadata == null) { obj.Metadata = new V1ObjectMeta(); } return obj.Metadata; } /// <summary>Gets the <see cref="V1ObjectMeta.Finalizers"/> of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>Metadata.Finalizers of <see cref="V1ObjectMeta"/></returns> public static IList<string> Finalizers(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.Finalizers; /// <summary>Gets the index of the <see cref="V1OwnerReference"/> that matches the given object, or -1 if no such /// reference could be found. /// </summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="owner">the owner of the object<see cref="V1ObjectMeta"/></param> /// <returns>the index of the <see cref="V1OwnerReference"/> that matches the given object, or -1 if no such /// reference could be found.</returns> public static int FindOwnerReference(this IMetadata<V1ObjectMeta> obj, IKubernetesObject<V1ObjectMeta> owner) => FindOwnerReference(obj, r => r.Matches(owner)); /// <summary>Gets the index of the <see cref="V1OwnerReference"/> that matches the given predicate, or -1 if no such /// reference could be found. /// </summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="predicate">a <see cref="Predicate"/> to test owner reference</param> /// <returns>the index of the <see cref="V1OwnerReference"/> that matches the given object, or -1 if no such /// reference could be found.</returns> public static int FindOwnerReference(this IMetadata<V1ObjectMeta> obj, Predicate<V1OwnerReference> predicate) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } var ownerRefs = obj.OwnerReferences(); if (ownerRefs != null) { for (var i = 0; i < ownerRefs.Count; i++) { if (predicate(ownerRefs[i])) { return i; } } } return -1; } /// <summary>Gets the generation a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the Metadata.Generation of object meta<see cref="V1ObjectMeta"/></returns> public static long? Generation(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.Generation; /// <summary>Returns the given annotation from a Kubernetes object or null if the annotation was not found.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="key">the key of the annotation</param> /// <returns>the content of the annotation</returns> public static string GetAnnotation(this IMetadata<V1ObjectMeta> obj, string key) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } var annotations = obj.Annotations(); return annotations != null && annotations.TryGetValue(key, out var value) ? value : null; } /// <summary>Gets the <see cref="V1OwnerReference"/> for the controller of this object, or null if it couldn't be found.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the <see cref="V1OwnerReference"/> for the controller of this object, or null if it couldn't be found.</returns> public static V1OwnerReference GetController(this IMetadata<V1ObjectMeta> obj) => obj.OwnerReferences()?.FirstOrDefault(r => r.Controller.GetValueOrDefault()); /// <summary>Returns the given label from a Kubernetes object or null if the label was not found.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="key">the key of the label</param> /// <returns>content of the label</returns> public static string GetLabel(this IMetadata<V1ObjectMeta> obj, string key) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } var labels = obj.Labels(); return labels != null && labels.TryGetValue(key, out var value) ? value : null; } /// <summary>Gets <see cref="V1OwnerReference"/> that matches the given object, or null if no matching reference exists.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="owner">the owner of the object<see cref="V1ObjectMeta"/></param> /// <returns>the <see cref="V1OwnerReference"/> that matches the given object, or null if no matching reference exists.</returns> public static V1OwnerReference GetOwnerReference( this IMetadata<V1ObjectMeta> obj, IKubernetesObject<V1ObjectMeta> owner) => GetOwnerReference(obj, r => r.Matches(owner)); /// <summary>Gets the <see cref="V1OwnerReference"/> that matches the given predicate, or null if no matching reference exists.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="predicate">a <see cref="Predicate"/> to test owner reference</param> /// <returns>the <see cref="V1OwnerReference"/> that matches the given object, or null if no matching reference exists.</returns> public static V1OwnerReference GetOwnerReference( this IMetadata<V1ObjectMeta> obj, Predicate<V1OwnerReference> predicate) { var index = FindOwnerReference(obj, predicate); return index >= 0 ? obj.Metadata.OwnerReferences[index] : null; } /// <summary>Determines whether the Kubernetes object has the given finalizer.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="finalizer">the finalizer</param> /// <returns>true if object has the finalizer</returns> public static bool HasFinalizer(this IMetadata<V1ObjectMeta> obj, string finalizer) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (string.IsNullOrEmpty(finalizer)) { throw new ArgumentNullException(nameof(finalizer)); } return obj.Finalizers() != null && obj.Metadata.Finalizers.Contains(finalizer); } /// <summary>Determines whether one object is owned by another.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="owner">the owner of the object<see cref="V1ObjectMeta"/></param> /// <returns>true if owned by obj</returns> public static bool IsOwnedBy(this IMetadata<V1ObjectMeta> obj, IKubernetesObject<V1ObjectMeta> owner) => FindOwnerReference(obj, owner) >= 0; /// <summary>Gets the labels of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>labels of the object in a Dictionary</returns> public static IDictionary<string, string> Labels(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.Labels; /// <summary>Gets the name of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the name of the Kubernetes object</returns> public static string Name(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.Name; /// <summary>Gets the namespace of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the namespace of the Kubernetes object</returns> public static string Namespace(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.NamespaceProperty; /// <summary>Gets the owner references of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>all owner reference in a list of the Kubernetes object</returns> public static IList<V1OwnerReference> OwnerReferences(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.OwnerReferences; /// <summary>Removes the given finalizer from a Kubernetes object if it exists.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="finalizer">the finalizer</param> /// <returns>Returns true if the finalizer was removed and false if it didn't exist.</returns> public static bool RemoveFinalizer(this IMetadata<V1ObjectMeta> obj, string finalizer) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (string.IsNullOrEmpty(finalizer)) { throw new ArgumentNullException(nameof(finalizer)); } return obj.Finalizers() != null && obj.Metadata.Finalizers.Remove(finalizer); } /// <summary>Removes the first <see cref="V1OwnerReference"/> that matches the given object and returns it, or returns null if no /// matching reference could be found. /// </summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="owner">the owner of the object<see cref="V1ObjectMeta"/></param> /// <returns>the first <see cref="V1OwnerReference"/> that matches the given object</returns> public static V1OwnerReference RemoveOwnerReference( this IMetadata<V1ObjectMeta> obj, IKubernetesObject<V1ObjectMeta> owner) { var index = FindOwnerReference(obj, owner); var ownerRef = index >= 0 ? obj?.Metadata.OwnerReferences[index] : null; if (index >= 0) { obj?.Metadata.OwnerReferences.RemoveAt(index); } return ownerRef; } /// <summary>Removes all <see cref="V1OwnerReference">owner references</see> that match the given predicate, and returns true if /// any were removed. /// </summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="predicate">a <see cref="Predicate"/> to test owner reference</param> /// <returns>true if any were removed</returns> public static bool RemoveOwnerReferences( this IMetadata<V1ObjectMeta> obj, Predicate<V1OwnerReference> predicate) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } var removed = false; var refs = obj.Metadata?.OwnerReferences; if (refs != null) { for (var i = refs.Count - 1; i >= 0; i--) { if (predicate(refs[i])) { refs.RemoveAt(i); removed = true; } } } return removed; } /// <summary>Removes all <see cref="V1OwnerReference">owner references</see> that match the given object, and returns true if /// any were removed. /// </summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="owner">the owner of the object<see cref="V1ObjectMeta"/></param> /// <returns>true if any were removed</returns> public static bool RemoveOwnerReferences( this IMetadata<V1ObjectMeta> obj, IKubernetesObject<V1ObjectMeta> owner) => RemoveOwnerReferences(obj, r => r.Matches(owner)); /// <summary>Gets the resource version of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the resource version of a Kubernetes object</returns> public static string ResourceVersion(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.ResourceVersion; /// <summary>Sets or removes an annotation on a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="key">the key of the annotation<see cref="V1ObjectMeta"/></param> /// <param name="value">the value of the annotation, null to remove it<see cref="V1ObjectMeta"/></param> public static void SetAnnotation(this IMetadata<V1ObjectMeta> obj, string key, string value) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value != null) { obj.EnsureMetadata().EnsureAnnotations()[key] = value; } else { obj.Metadata?.Annotations?.Remove(key); } } /// <summary>Sets or removes a label on a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="key">the key of the label<see cref="V1ObjectMeta"/></param> /// <param name="value">the value of the label, null to remove it<see cref="V1ObjectMeta"/></param> public static void SetLabel(this IMetadata<V1ObjectMeta> obj, string key, string value) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value != null) { obj.EnsureMetadata().EnsureLabels()[key] = value; } else { obj.Metadata?.Labels?.Remove(key); } } /// <summary>Gets the unique ID of a Kubernetes object.</summary> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns> the unique ID of a Kubernetes object</returns> public static string Uid(this IMetadata<V1ObjectMeta> obj) => obj?.Metadata?.Uid; /// <summary>Ensures that the <see cref="V1ObjectMeta.Annotations"/> field is not null, and returns it.</summary> /// <param name="meta">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the annotations in a Dictionary</returns> public static IDictionary<string, string> EnsureAnnotations(this V1ObjectMeta meta) { if (meta == null) { throw new ArgumentNullException(nameof(meta)); } if (meta.Annotations == null) { meta.Annotations = new Dictionary<string, string>(); } return meta.Annotations; } /// <summary>Ensures that the <see cref="V1ObjectMeta.Finalizers"/> field is not null, and returns it.</summary> /// <param name="meta">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the list of finalizers</returns> public static IList<string> EnsureFinalizers(this V1ObjectMeta meta) { if (meta == null) { throw new ArgumentNullException(nameof(meta)); } if (meta.Finalizers == null) { meta.Finalizers = new List<string>(); } return meta.Finalizers; } /// <summary>Ensures that the <see cref="V1ObjectMeta.Labels"/> field is not null, and returns it.</summary> /// <param name="meta">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the dictionary of labels</returns> public static IDictionary<string, string> EnsureLabels(this V1ObjectMeta meta) { if (meta == null) { throw new ArgumentNullException(nameof(meta)); } if (meta.Labels == null) { meta.Labels = new Dictionary<string, string>(); } return meta.Labels; } /// <summary>Gets the namespace from Kubernetes metadata.</summary> /// <param name="meta">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>the namespace from Kubernetes metadata</returns> public static string Namespace(this V1ObjectMeta meta) => meta?.NamespaceProperty; /// <summary>Sets the namespace from Kubernetes metadata.</summary> /// <param name="meta">the object meta<see cref="V1ObjectMeta"/></param> /// <param name="ns">the namespace</param> public static void SetNamespace(this V1ObjectMeta meta, string ns) { if (meta == null) { throw new ArgumentNullException(nameof(meta)); } meta.NamespaceProperty = ns; } /// <summary>Determines whether an object reference references the given object.</summary> /// <param name="objref">the object reference<see cref="V1ObjectReference"/></param> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>true if the object reference references the given object.</returns> public static bool Matches(this V1ObjectReference objref, IKubernetesObject<V1ObjectMeta> obj) { if (objref == null) { throw new ArgumentNullException(nameof(objref)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } return objref.ApiVersion == obj.ApiVersion && objref.Kind == obj.Kind && objref.Name == obj.Name() && objref.Uid == obj.Uid() && objref.NamespaceProperty == obj.Namespace(); } /// <summary>Determines whether an owner reference references the given object.</summary> /// <param name="owner">the object reference<see cref="V1ObjectReference"/></param> /// <param name="obj">the object meta<see cref="V1ObjectMeta"/></param> /// <returns>true if the owner reference references the given object</returns> public static bool Matches(this V1OwnerReference owner, IKubernetesObject<V1ObjectMeta> obj) { if (owner == null) { throw new ArgumentNullException(nameof(owner)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } return owner.ApiVersion == obj.ApiVersion && owner.Kind == obj.Kind && owner.Name == obj.Name() && owner.Uid == obj.Uid(); } } }
/* * 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.Examples.Sql { using System; using System.Linq; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.ExamplesDll.Binary; using Apache.Ignite.Linq; /// <summary> /// This example populates cache with sample data and runs several LINQ queries over this data. /// <para /> /// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build). /// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties -> /// Application -> Startup object); /// 3) Start example (F5 or Ctrl+F5). /// <para /> /// This example can be run with standalone Apache Ignite.NET node: /// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe: /// Apache.Ignite.exe -configFileName=platforms\dotnet\examples\apache.ignite.examples\app.config /// 2) Start example. /// </summary> public class LinqExample { /// <summary>Organization cache name.</summary> private const string OrganizationCacheName = "dotnet_cache_query_organization"; /// <summary>Employee cache name.</summary> private const string EmployeeCacheName = "dotnet_cache_query_employee"; /// <summary>Colocated employee cache name.</summary> private const string EmployeeCacheNameColocated = "dotnet_cache_query_employee_colocated"; [STAThread] public static void Main() { using (var ignite = Ignition.StartFromApplicationConfiguration()) { Console.WriteLine(); Console.WriteLine(">>> Cache LINQ example started."); var employeeCache = ignite.GetOrCreateCache<int, Employee>( new CacheConfiguration(EmployeeCacheName, new QueryEntity(typeof(int), typeof(Employee)))); var employeeCacheColocated = ignite.GetOrCreateCache<AffinityKey, Employee>( new CacheConfiguration(EmployeeCacheNameColocated, new QueryEntity(typeof(AffinityKey), typeof(Employee)))); var organizationCache = ignite.GetOrCreateCache<int, Organization>( new CacheConfiguration(OrganizationCacheName, new QueryEntity(typeof(int), typeof(Organization)))); // Populate cache with sample data entries. PopulateCache(employeeCache); PopulateCache(employeeCacheColocated); PopulateCache(organizationCache); // Run SQL query example. QueryExample(employeeCache); // Run compiled SQL query example. CompiledQueryExample(employeeCache); // Run SQL query with join example. JoinQueryExample(employeeCacheColocated, organizationCache); // Run SQL query with distributed join example. DistributedJoinQueryExample(employeeCache, organizationCache); // Run SQL fields query example. FieldsQueryExample(employeeCache); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(">>> Example finished, press any key to exit ..."); Console.ReadKey(); } /// <summary> /// Queries employees that have provided ZIP code in address. /// </summary> /// <param name="cache">Cache.</param> private static void QueryExample(ICache<int, Employee> cache) { const int zip = 94109; IQueryable<ICacheEntry<int, Employee>> qry = cache.AsCacheQueryable().Where(emp => emp.Value.Address.Zip == zip); Console.WriteLine(); Console.WriteLine(">>> Employees with zipcode " + zip + ":"); foreach (ICacheEntry<int, Employee> entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that have provided ZIP code in address with a compiled query. /// </summary> /// <param name="cache">Cache.</param> private static void CompiledQueryExample(ICache<int, Employee> cache) { const int zip = 94109; var cache0 = cache.AsCacheQueryable(); // Compile cache query to eliminate LINQ overhead on multiple runs. Func<int, IQueryCursor<ICacheEntry<int, Employee>>> qry = CompiledQuery.Compile((int z) => cache0.Where(emp => emp.Value.Address.Zip == z)); Console.WriteLine(); Console.WriteLine(">>> Employees with zipcode {0} using compiled query:", zip); foreach (ICacheEntry<int, Employee> entry in qry(zip)) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that work for organization with provided name. /// </summary> /// <param name="employeeCache">Employee cache.</param> /// <param name="organizationCache">Organization cache.</param> private static void JoinQueryExample(ICache<AffinityKey, Employee> employeeCache, ICache<int, Organization> organizationCache) { const string orgName = "Apache"; IQueryable<ICacheEntry<AffinityKey, Employee>> employees = employeeCache.AsCacheQueryable(); IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(); IQueryable<ICacheEntry<AffinityKey, Employee>> qry = from employee in employees from organization in organizations where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName select employee; Console.WriteLine(); Console.WriteLine(">>> Employees working for " + orgName + ":"); foreach (ICacheEntry<AffinityKey, Employee> entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries employees that work for organization with provided name. /// </summary> /// <param name="employeeCache">Employee cache.</param> /// <param name="organizationCache">Organization cache.</param> private static void DistributedJoinQueryExample(ICache<int, Employee> employeeCache, ICache<int, Organization> organizationCache) { const string orgName = "Apache"; var queryOptions = new QueryOptions { EnableDistributedJoins = true, Timeout = new TimeSpan(0, 1, 0) }; IQueryable<ICacheEntry<int, Employee>> employees = employeeCache.AsCacheQueryable(queryOptions); IQueryable<ICacheEntry<int, Organization>> organizations = organizationCache.AsCacheQueryable(queryOptions); IQueryable<ICacheEntry<int, Employee>> qry = from employee in employees from organization in organizations where employee.Value.OrganizationId == organization.Key && organization.Value.Name == orgName select employee; Console.WriteLine(); Console.WriteLine(">>> Employees working for " + orgName + ":"); foreach (ICacheEntry<int, Employee> entry in qry) Console.WriteLine(">>> " + entry.Value); } /// <summary> /// Queries names and salaries for all employees. /// </summary> /// <param name="cache">Cache.</param> private static void FieldsQueryExample(ICache<int, Employee> cache) { var qry = cache.AsCacheQueryable().Select(entry => new {entry.Value.Name, entry.Value.Salary}); Console.WriteLine(); Console.WriteLine(">>> Employee names and their salaries:"); foreach (var row in qry) Console.WriteLine(">>> [Name=" + row.Name + ", salary=" + row.Salary + ']'); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, Organization> cache) { cache.Put(1, new Organization( "Apache", new Address("1065 East Hillsdale Blvd, Foster City, CA", 94404), OrganizationType.Private, DateTime.Now)); cache.Put(2, new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now)); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<AffinityKey, Employee> cache) { cache.Put(new AffinityKey(1, 1), new Employee( "James Wilson", 12500, new Address("1096 Eddy Street, San Francisco, CA", 94109), new[] {"Human Resources", "Customer Service"}, 1)); cache.Put(new AffinityKey(2, 1), new Employee( "Daniel Adams", 11000, new Address("184 Fidler Drive, San Antonio, TX", 78130), new[] {"Development", "QA"}, 1)); cache.Put(new AffinityKey(3, 1), new Employee( "Cristian Moss", 12500, new Address("667 Jerry Dove Drive, Florence, SC", 29501), new[] {"Logistics"}, 1)); cache.Put(new AffinityKey(4, 2), new Employee( "Allison Mathis", 25300, new Address("2702 Freedom Lane, San Francisco, CA", 94109), new[] {"Development"}, 2)); cache.Put(new AffinityKey(5, 2), new Employee( "Breana Robbin", 6500, new Address("3960 Sundown Lane, Austin, TX", 78130), new[] {"Sales"}, 2)); cache.Put(new AffinityKey(6, 2), new Employee( "Philip Horsley", 19800, new Address("2803 Elsie Drive, Sioux Falls, SD", 57104), new[] {"Sales"}, 2)); cache.Put(new AffinityKey(7, 2), new Employee( "Brian Peters", 10600, new Address("1407 Pearlman Avenue, Boston, MA", 12110), new[] {"Development", "QA"}, 2)); } /// <summary> /// Populate cache with data for this example. /// </summary> /// <param name="cache">Cache.</param> private static void PopulateCache(ICache<int, Employee> cache) { cache.Put(1, new Employee( "James Wilson", 12500, new Address("1096 Eddy Street, San Francisco, CA", 94109), new[] {"Human Resources", "Customer Service"}, 1)); cache.Put(2, new Employee( "Daniel Adams", 11000, new Address("184 Fidler Drive, San Antonio, TX", 78130), new[] {"Development", "QA"}, 1)); cache.Put(3, new Employee( "Cristian Moss", 12500, new Address("667 Jerry Dove Drive, Florence, SC", 29501), new[] {"Logistics"}, 1)); cache.Put(4, new Employee( "Allison Mathis", 25300, new Address("2702 Freedom Lane, San Francisco, CA", 94109), new[] {"Development"}, 2)); cache.Put(5, new Employee( "Breana Robbin", 6500, new Address("3960 Sundown Lane, Austin, TX", 78130), new[] {"Sales"}, 2)); cache.Put(6, new Employee( "Philip Horsley", 19800, new Address("2803 Elsie Drive, Sioux Falls, SD", 57104), new[] {"Sales"}, 2)); cache.Put(7, new Employee( "Brian Peters", 10600, new Address("1407 Pearlman Avenue, Boston, MA", 12110), new[] {"Development", "QA"}, 2)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void SumAbsoluteDifferencesUInt16() { var test = new SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, Byte[] inArray2, UInt16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Byte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Byte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Byte> _fld1; public Vector128<Byte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16 testClass) { var result = Sse2.SumAbsoluteDifferences(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16 testClass) { fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.SumAbsoluteDifferences( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector128<Byte> _clsVar1; private static Vector128<Byte> _clsVar2; private Vector128<Byte> _fld1; private Vector128<Byte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetByte(); } _dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.SumAbsoluteDifferences( Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.SumAbsoluteDifferences( Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.SumAbsoluteDifferences( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SumAbsoluteDifferences), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SumAbsoluteDifferences), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.SumAbsoluteDifferences), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.SumAbsoluteDifferences( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Byte>* pClsVar1 = &_clsVar1) fixed (Vector128<Byte>* pClsVar2 = &_clsVar2) { var result = Sse2.SumAbsoluteDifferences( Sse2.LoadVector128((Byte*)(pClsVar1)), Sse2.LoadVector128((Byte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr); var result = Sse2.SumAbsoluteDifferences(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.SumAbsoluteDifferences(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr)); var result = Sse2.SumAbsoluteDifferences(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16(); var result = Sse2.SumAbsoluteDifferences(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__SumAbsoluteDifferencesUInt16(); fixed (Vector128<Byte>* pFld1 = &test._fld1) fixed (Vector128<Byte>* pFld2 = &test._fld2) { var result = Sse2.SumAbsoluteDifferences( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.SumAbsoluteDifferences(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Byte>* pFld1 = &_fld1) fixed (Vector128<Byte>* pFld2 = &_fld2) { var result = Sse2.SumAbsoluteDifferences( Sse2.LoadVector128((Byte*)(pFld1)), Sse2.LoadVector128((Byte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.SumAbsoluteDifferences(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.SumAbsoluteDifferences( Sse2.LoadVector128((Byte*)(&test._fld1)), Sse2.LoadVector128((Byte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> op1, Vector128<Byte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, Byte[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != Math.Abs(left[0] - right[0]) + Math.Abs(left[1] - right[1]) + Math.Abs(left[2] - right[2]) + Math.Abs(left[3] - right[3]) + Math.Abs(left[4] - right[4]) + Math.Abs(left[5] - right[5]) + Math.Abs(left[6] - right[6]) + Math.Abs(left[7] - right[7])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i != 4 ? 0 : Math.Abs(left[8] - right[8]) + Math.Abs(left[9] - right[9]) + Math.Abs(left[10] - right[10]) + Math.Abs(left[11] - right[11]) + Math.Abs(left[12] - right[12]) + Math.Abs(left[13] - right[13]) + Math.Abs(left[14] - right[14]) + Math.Abs(left[15] - right[15]))) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.SumAbsoluteDifferences)}<UInt16>(Vector128<Byte>, Vector128<Byte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; namespace OTFontFile { public class Table_maxp : OTTable { /************************ * constructors */ public Table_maxp(OTTag tag, MBOBuffer buf) : base(tag, buf) { } /************************ * field offset values */ public enum FieldOffsets { TableVersionNumber = 0, // TableVersionNumber available in version 0x00010000 AND 0x00005000 NumGlyphs = 4, // numglyphs available in version 0x00010000 AND 0x00005000 maxPoints = 6, // fields from here down only in version 0x00010000 maxContours = 8, maxCompositePoints = 10, maxCompositeContours = 12, maxZones = 14, maxTwilightPoints = 16, maxStorage = 18, maxFunctionDefs = 20, maxInstructionDefs = 22, maxStackElements = 24, maxSizeOfInstructions = 26, maxComponentElements = 28, maxComponentDepth = 30 } /************************ * accessors */ public OTFixed TableVersionNumber { get {return m_bufTable.GetFixed((uint)FieldOffsets.TableVersionNumber);} } public ushort NumGlyphs { get {return m_bufTable.GetUshort((uint)FieldOffsets.NumGlyphs);} } public ushort maxPoints { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxPoints); } } public ushort maxContours { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxContours); } } public ushort maxCompositePoints { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxCompositePoints); } } public ushort maxCompositeContours { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxCompositeContours); } } public ushort maxZones { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxZones); } } public ushort maxTwilightPoints { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxTwilightPoints); } } public ushort maxStorage { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxStorage); } } public ushort maxFunctionDefs { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxFunctionDefs); } } public ushort maxInstructionDefs { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxInstructionDefs); } } public ushort maxStackElements { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxStackElements); } } public ushort maxSizeOfInstructions { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxSizeOfInstructions); } } public ushort maxComponentElements { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxComponentElements); } } public ushort maxComponentDepth { get { if (TableVersionNumber.GetUint() != 0x00010000) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort((uint)FieldOffsets.maxComponentDepth); } } /************************ * DataCache class */ public override DataCache GetCache() { if (m_cache == null) { m_cache = new maxp_cache(this); } return m_cache; } public class maxp_cache : DataCache { // the cached data protected OTFixed m_TableVersionNumber; protected ushort m_NumGlyphs; protected ushort m_maxPoints; protected ushort m_maxContours; protected ushort m_maxCompositePoints; protected ushort m_maxCompositeContours; protected ushort m_maxZones; protected ushort m_maxTwilightPoints; protected ushort m_maxStorage; protected ushort m_maxFunctionDefs; protected ushort m_maxInstructionDefs; protected ushort m_maxStackElements; protected ushort m_maxSizeOfInstructions; protected ushort m_maxComponentElements; protected ushort m_maxComponentDepth; // constructor public maxp_cache(Table_maxp OwnerTable) { // copy the data from the owner table's MBOBuffer // and store it in the cache variables m_TableVersionNumber = OwnerTable.TableVersionNumber; m_NumGlyphs = OwnerTable.NumGlyphs; if( m_TableVersionNumber.GetUint() == 0x00010000 ) { m_maxPoints = OwnerTable.maxPoints; m_maxContours = OwnerTable.maxContours; m_maxCompositePoints = OwnerTable.maxCompositePoints; m_maxCompositeContours = OwnerTable.maxCompositeContours; m_maxZones = OwnerTable.maxZones; m_maxTwilightPoints = OwnerTable.maxTwilightPoints; m_maxStorage = OwnerTable.maxStorage; m_maxFunctionDefs = OwnerTable.maxFunctionDefs; m_maxInstructionDefs = OwnerTable.maxInstructionDefs; m_maxStackElements = OwnerTable.maxStackElements; m_maxSizeOfInstructions = OwnerTable.maxSizeOfInstructions; m_maxComponentElements = OwnerTable.maxComponentElements; m_maxComponentDepth = OwnerTable.maxComponentDepth; } } // accessors for the cached data public OTFixed TableVersionNumber { get {return m_TableVersionNumber;} set { m_TableVersionNumber = value; m_bDirty = true; } } public ushort NumGlyphs { get {return m_NumGlyphs;} set { m_NumGlyphs = value; m_bDirty = true; } } public ushort maxPoints { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxPoints; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxPoints = value; m_bDirty = true; } } public ushort maxContours { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxContours; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxContours = value; m_bDirty = true; } } public ushort maxCompositePoints { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxCompositePoints; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxCompositePoints = value; m_bDirty = true; } } public ushort maxCompositeContours { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxCompositeContours; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxCompositeContours = value; m_bDirty = true; } } public ushort maxZones { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxZones; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxZones = value; m_bDirty = true; } } public ushort maxTwilightPoints { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxTwilightPoints; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxTwilightPoints = value; m_bDirty = true; } } public ushort maxStorage { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxStorage; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxStorage = value; m_bDirty = true; } } public ushort maxFunctionDefs { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxFunctionDefs; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxFunctionDefs = value; m_bDirty = true; } } public ushort maxInstructionDefs { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxInstructionDefs; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxInstructionDefs = value; m_bDirty = true; } } public ushort maxStackElements { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxStackElements; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxStackElements = value; m_bDirty = true; } } public ushort maxSizeOfInstructions { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxSizeOfInstructions; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxSizeOfInstructions = value; m_bDirty = true; } } public ushort maxComponentElements { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxComponentElements; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxComponentElements = value; m_bDirty = true; } } public ushort maxComponentDepth { get { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } return m_maxComponentDepth; } set { if( m_TableVersionNumber.GetUint() != 0x00010000 ) { throw new System.InvalidOperationException(); } m_maxComponentDepth = value; m_bDirty = true; } } // generate a new table from the cached data public override OTTable GenerateTable() { // create a Motorola Byte Order buffer for the new table MBOBuffer newbuf; if( m_TableVersionNumber.GetUint() == 0x00000000 ) { newbuf = new MBOBuffer(6); newbuf.SetFixed (m_TableVersionNumber, (uint)Table_maxp.FieldOffsets.TableVersionNumber); newbuf.SetUshort (m_NumGlyphs, (uint)Table_maxp.FieldOffsets.NumGlyphs); } else { newbuf = new MBOBuffer(32); newbuf.SetFixed (m_TableVersionNumber, (uint)Table_maxp.FieldOffsets.TableVersionNumber); newbuf.SetUshort (m_NumGlyphs, (uint)Table_maxp.FieldOffsets.NumGlyphs); newbuf.SetUshort (m_maxPoints, (uint)Table_maxp.FieldOffsets.maxPoints); newbuf.SetUshort (m_maxContours, (uint)Table_maxp.FieldOffsets.maxContours); newbuf.SetUshort (m_maxCompositePoints, (uint)Table_maxp.FieldOffsets.maxCompositePoints); newbuf.SetUshort (m_maxCompositeContours, (uint)Table_maxp.FieldOffsets.maxCompositeContours); newbuf.SetUshort (m_maxZones, (uint)Table_maxp.FieldOffsets.maxZones); newbuf.SetUshort (m_maxTwilightPoints, (uint)Table_maxp.FieldOffsets.maxTwilightPoints); newbuf.SetUshort (m_maxStorage, (uint)Table_maxp.FieldOffsets.maxStorage); newbuf.SetUshort (m_maxFunctionDefs, (uint)Table_maxp.FieldOffsets.maxFunctionDefs); newbuf.SetUshort (m_maxInstructionDefs, (uint)Table_maxp.FieldOffsets.maxInstructionDefs); newbuf.SetUshort (m_maxStackElements, (uint)Table_maxp.FieldOffsets.maxStackElements); newbuf.SetUshort (m_maxSizeOfInstructions, (uint)Table_maxp.FieldOffsets.maxSizeOfInstructions); newbuf.SetUshort (m_maxComponentElements, (uint)Table_maxp.FieldOffsets.maxComponentElements); newbuf.SetUshort (m_maxComponentDepth, (uint)Table_maxp.FieldOffsets.maxComponentDepth); } // put the buffer into a Table_maxp object and return it Table_maxp maxpTable = new Table_maxp("maxp", newbuf); return maxpTable; } } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_BUFFER_GPU_ADDRESS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public const int BUFFER_GPU_ADDRESS_NV = 0x8F1D; /// <summary> /// [GL] Value of GL_GPU_ADDRESS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public const int GPU_ADDRESS_NV = 0x8F34; /// <summary> /// [GL] Value of GL_MAX_SHADER_BUFFER_ADDRESS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public const int MAX_SHADER_BUFFER_ADDRESS_NV = 0x8F35; /// <summary> /// [GL] glMakeBufferResidentNV: Binding for glMakeBufferResidentNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> /// <param name="access"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void MakeBufferResidentNV(int target, int access) { Debug.Assert(Delegates.pglMakeBufferResidentNV != null, "pglMakeBufferResidentNV not implemented"); Delegates.pglMakeBufferResidentNV(target, access); LogCommand("glMakeBufferResidentNV", null, target, access ); DebugCheckErrors(null); } /// <summary> /// [GL] glMakeBufferNonResidentNV: Binding for glMakeBufferNonResidentNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void MakeBufferNonResidentNV(int target) { Debug.Assert(Delegates.pglMakeBufferNonResidentNV != null, "pglMakeBufferNonResidentNV not implemented"); Delegates.pglMakeBufferNonResidentNV(target); LogCommand("glMakeBufferNonResidentNV", null, target ); DebugCheckErrors(null); } /// <summary> /// [GL] glIsBufferResidentNV: Binding for glIsBufferResidentNV. /// </summary> /// <param name="target"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static bool IsBufferResidentNV(int target) { bool retValue; Debug.Assert(Delegates.pglIsBufferResidentNV != null, "pglIsBufferResidentNV not implemented"); retValue = Delegates.pglIsBufferResidentNV(target); LogCommand("glIsBufferResidentNV", retValue, target ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glMakeNamedBufferResidentNV: Binding for glMakeNamedBufferResidentNV. /// </summary> /// <param name="buffer"> /// A <see cref="T:uint"/>. /// </param> /// <param name="access"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void MakeNamedBufferResidentNV(uint buffer, int access) { Debug.Assert(Delegates.pglMakeNamedBufferResidentNV != null, "pglMakeNamedBufferResidentNV not implemented"); Delegates.pglMakeNamedBufferResidentNV(buffer, access); LogCommand("glMakeNamedBufferResidentNV", null, buffer, access ); DebugCheckErrors(null); } /// <summary> /// [GL] glMakeNamedBufferNonResidentNV: Binding for glMakeNamedBufferNonResidentNV. /// </summary> /// <param name="buffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void MakeNamedBufferNonResidentNV(uint buffer) { Debug.Assert(Delegates.pglMakeNamedBufferNonResidentNV != null, "pglMakeNamedBufferNonResidentNV not implemented"); Delegates.pglMakeNamedBufferNonResidentNV(buffer); LogCommand("glMakeNamedBufferNonResidentNV", null, buffer ); DebugCheckErrors(null); } /// <summary> /// [GL] glIsNamedBufferResidentNV: Binding for glIsNamedBufferResidentNV. /// </summary> /// <param name="buffer"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static bool IsNamedBufferResidentNV(uint buffer) { bool retValue; Debug.Assert(Delegates.pglIsNamedBufferResidentNV != null, "pglIsNamedBufferResidentNV not implemented"); retValue = Delegates.pglIsNamedBufferResidentNV(buffer); LogCommand("glIsNamedBufferResidentNV", retValue, buffer ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glGetBufferParameterui64vNV: Binding for glGetBufferParameterui64vNV. /// </summary> /// <param name="target"> /// A <see cref="T:BufferTarget"/>. /// </param> /// <param name="pname"> /// A <see cref="T:int"/>. /// </param> /// <param name="params"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void GetBufferParameterNV(BufferTarget target, int pname, [Out] ulong[] @params) { unsafe { fixed (ulong* p_params = @params) { Debug.Assert(Delegates.pglGetBufferParameterui64vNV != null, "pglGetBufferParameterui64vNV not implemented"); Delegates.pglGetBufferParameterui64vNV((int)target, pname, p_params); LogCommand("glGetBufferParameterui64vNV", null, target, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetNamedBufferParameterui64vNV: Binding for glGetNamedBufferParameterui64vNV. /// </summary> /// <param name="buffer"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:VertexBufferObjectParameter"/>. /// </param> /// <param name="params"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void GetNamedBufferParameterNV(uint buffer, VertexBufferObjectParameter pname, [Out] ulong[] @params) { unsafe { fixed (ulong* p_params = @params) { Debug.Assert(Delegates.pglGetNamedBufferParameterui64vNV != null, "pglGetNamedBufferParameterui64vNV not implemented"); Delegates.pglGetNamedBufferParameterui64vNV(buffer, (int)pname, p_params); LogCommand("glGetNamedBufferParameterui64vNV", null, buffer, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetIntegerui64vNV: Binding for glGetIntegerui64vNV. /// </summary> /// <param name="value"> /// A <see cref="T:GetPName"/>. /// </param> /// <param name="result"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void GetIntegerNV(GetPName value, [Out] ulong[] result) { unsafe { fixed (ulong* p_result = result) { Debug.Assert(Delegates.pglGetIntegerui64vNV != null, "pglGetIntegerui64vNV not implemented"); Delegates.pglGetIntegerui64vNV((int)value, p_result); LogCommand("glGetIntegerui64vNV", null, value, result ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glUniformui64NV: Binding for glUniformui64NV. /// </summary> /// <param name="location"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:ulong"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void UniformNV(int location, ulong value) { Debug.Assert(Delegates.pglUniformui64NV != null, "pglUniformui64NV not implemented"); Delegates.pglUniformui64NV(location, value); LogCommand("glUniformui64NV", null, location, value ); DebugCheckErrors(null); } /// <summary> /// [GL] glUniformui64vNV: Binding for glUniformui64vNV. /// </summary> /// <param name="location"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void UniformNV(int location, ulong[] value) { unsafe { fixed (ulong* p_value = value) { Debug.Assert(Delegates.pglUniformui64vNV != null, "pglUniformui64vNV not implemented"); Delegates.pglUniformui64vNV(location, value.Length, p_value); LogCommand("glUniformui64vNV", null, location, value.Length, value ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetUniformui64vNV: Binding for glGetUniformui64vNV. /// </summary> /// <param name="program"> /// A <see cref="T:uint"/>. /// </param> /// <param name="location"> /// A <see cref="T:int"/>. /// </param> /// <param name="params"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_AMD_gpu_shader_int64")] [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void GetUniformNV(uint program, int location, [Out] ulong[] @params) { unsafe { fixed (ulong* p_params = @params) { Debug.Assert(Delegates.pglGetUniformui64vNV != null, "pglGetUniformui64vNV not implemented"); Delegates.pglGetUniformui64vNV(program, location, p_params); LogCommand("glGetUniformui64vNV", null, program, location, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramUniformui64NV: Binding for glProgramUniformui64NV. /// </summary> /// <param name="program"> /// A <see cref="T:uint"/>. /// </param> /// <param name="location"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:ulong"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void ProgramUniformNV(uint program, int location, ulong value) { Debug.Assert(Delegates.pglProgramUniformui64NV != null, "pglProgramUniformui64NV not implemented"); Delegates.pglProgramUniformui64NV(program, location, value); LogCommand("glProgramUniformui64NV", null, program, location, value ); DebugCheckErrors(null); } /// <summary> /// [GL] glProgramUniformui64vNV: Binding for glProgramUniformui64vNV. /// </summary> /// <param name="program"> /// A <see cref="T:uint"/>. /// </param> /// <param name="location"> /// A <see cref="T:int"/>. /// </param> /// <param name="value"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] public static void ProgramUniformNV(uint program, int location, ulong[] value) { unsafe { fixed (ulong* p_value = value) { Debug.Assert(Delegates.pglProgramUniformui64vNV != null, "pglProgramUniformui64vNV not implemented"); Delegates.pglProgramUniformui64vNV(program, location, value.Length, p_value); LogCommand("glProgramUniformui64vNV", null, program, location, value.Length, value ); } } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glMakeBufferResidentNV(int target, int access); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glMakeBufferResidentNV pglMakeBufferResidentNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glMakeBufferNonResidentNV(int target); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glMakeBufferNonResidentNV pglMakeBufferNonResidentNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glIsBufferResidentNV(int target); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glIsBufferResidentNV pglIsBufferResidentNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glMakeNamedBufferResidentNV(uint buffer, int access); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glMakeNamedBufferResidentNV pglMakeNamedBufferResidentNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glMakeNamedBufferNonResidentNV(uint buffer); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glMakeNamedBufferNonResidentNV pglMakeNamedBufferNonResidentNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glIsNamedBufferResidentNV(uint buffer); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glIsNamedBufferResidentNV pglIsNamedBufferResidentNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetBufferParameterui64vNV(int target, int pname, ulong* @params); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glGetBufferParameterui64vNV pglGetBufferParameterui64vNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetNamedBufferParameterui64vNV(uint buffer, int pname, ulong* @params); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glGetNamedBufferParameterui64vNV pglGetNamedBufferParameterui64vNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetIntegerui64vNV(int value, ulong* result); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glGetIntegerui64vNV pglGetIntegerui64vNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformui64NV(int location, ulong value); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glUniformui64NV pglUniformui64NV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glUniformui64vNV(int location, int count, ulong* value); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glUniformui64vNV pglUniformui64vNV; [RequiredByFeature("GL_AMD_gpu_shader_int64")] [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetUniformui64vNV(uint program, int location, ulong* @params); [RequiredByFeature("GL_AMD_gpu_shader_int64")] [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glGetUniformui64vNV pglGetUniformui64vNV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramUniformui64NV(uint program, int location, ulong value); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glProgramUniformui64NV pglProgramUniformui64NV; [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramUniformui64vNV(uint program, int location, int count, ulong* value); [RequiredByFeature("GL_NV_shader_buffer_load", Api = "gl|glcore")] [ThreadStatic] internal static glProgramUniformui64vNV pglProgramUniformui64vNV; } } }
////////////////////////////////////////////////////////////////////////////////////////////////// // // file: computeDeformations.cs // // alternative solution or GPU skinning and blendshapes // // Author Sergey Solokhin (Neill3d) // // GitHub page - https://github.com/Neill3d/MoPlugs // Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE // /////////////////////////////////////////////////////////////////////////////////////////////////// #version 430 layout (local_size_x = 1024, local_size_y = 1) in; uniform int numberOfBlendshapes; uniform int numberOfVertices; uniform int numberOfClusters; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // TYPES AND DATA BUFFERS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct BlendShapeVertex { vec4 pos; vec4 nor; }; /* // INPUT from mobu mesh data layout (std430, binding = 0) readonly buffer NormalBuffer { vec4 normals[]; } normalBuffer; */ // stores x-blendshape index offset, w-blendshape weight layout (std430, binding = 0) buffer WeightsBuffer { vec4 weights[]; } weightsBuffer; // stores all blendshape normals and tangents (static shapes) layout (std430, binding = 1) buffer BlendShapeBuffer { BlendShapeVertex vertices[]; } blendshapeBuffer; // output layout (std140, binding = 2) buffer OutputNormals { vec4 normals[]; } outputNormals; layout (std140, binding = 3) buffer OutputPositions { vec4 positions[]; } outputPositions; // for each vertex data, limit 4 bones per vertex // almost constant data ! struct ClusterVertex { vec4 links; vec4 weights; }; layout (std140, binding = 4) buffer ClusterInfo { ClusterVertex vertices[]; } clusterInfo; // update each frame for the binded skeleton layout (std430, binding = 5) buffer JointsInfo { mat4 tm[]; // computed transform of each link (cluster) } jointsInfo; //////////////////////////////////////////////////////// // uint get_invocation() { //uint work_group = gl_WorkGroupID.x * gl_NumWorkGroups.y * gl_NumWorkGroups.z + gl_WorkGroupID.y * gl_NumWorkGroups.z + gl_WorkGroupID.z; //return work_group * gl_WorkGroupSize.x * gl_WorkGroupSize.y * gl_WorkGroupSize.z + gl_LocalInvocationIndex; // uint work_group = gl_WorkGroupID.y * gl_NumWorkGroups.x * gl_WorkGroupSize.x + gl_WorkGroupID.x * gl_WorkGroupSize.x + gl_LocalInvocationIndex; uint work_group = gl_GlobalInvocationID.y * (gl_NumWorkGroups.x * gl_WorkGroupSize.x) + gl_GlobalInvocationID.x; return work_group; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MAIN ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void main() { // particle id in the array uint flattened_id = get_invocation(); // ?! skip unused part of the array if (flattened_id >= numberOfVertices) return; // Read source normal vec4 nor = blendshapeBuffer.vertices[flattened_id].nor; vec4 pos = blendshapeBuffer.vertices[flattened_id].pos; //vec4 tan = tangentBuffer.tangents[flattened_id]; // default deform order: blendshapes, then clusters // blend with active blendshapes for (int i=0; i<numberOfBlendshapes; ++i) { float weight = weightsBuffer.weights[i].x; int index = (i+1) * numberOfVertices + int(flattened_id); vec4 blendshapeNormal = blendshapeBuffer.vertices[index].nor; vec4 blendshapePos = blendshapeBuffer.vertices[index].pos; //vec4 blendshapeTangent = blendshapeBuffer.tangents[index]; nor = mix(nor, blendshapeNormal, weight); pos = mix(pos, blendshapePos, weight); //nor = blendshapeNormal; //tan = mix(tan, blendshapeTangent, weights.w); } // deform with clusters if (numberOfClusters > 0) { vec4 weights = clusterInfo.vertices[flattened_id].weights; vec4 links = clusterInfo.vertices[flattened_id].links; pos.w = 1.0; /* float weight1 = weights.x; //mat4 tm = mat4(1.0); pos.w = 1.0; outPos = vec4(0.0, 0.0, 0.0, 0.0); float weight2 = weights.y; mat4 influence = jointsInfo.tm[int(links.x)]; pos1 = influence * pos; //outPos += pos1; */ int id1 = int(links.x); //if (clamp(links.x, 0.0, 1.0) > 0.0) id1 = 1; int id2 = int(links.y); //if (clamp(links.y, 0.0, 1.0) > 0.0) id2 = 1; float w1 = clamp(weights.x, 0.0, 1.0); float w2 = clamp(weights.y, 0.0, 1.0); //w2 = 1.0 - w1; float sum = w1 + w2; if (sum == 1.0) { mat4 inf1 = jointsInfo.tm[id1]; vec4 pos1 = inf1 * pos; mat4 inf2 = jointsInfo.tm[id2]; vec4 pos2 = inf2 * pos; pos = pos1 * w1 + pos2 * w2; pos.w = 1.0; /* vec4 nor1 = transpose(inverse(inf1)) * nor; vec4 nor2 = transpose(inverse(inf2)) * nor; nor1 = normalize(nor1); nor1.w = 0.0; nor2 = normalize(nor2); nor2.w = 0.0; nor = nor1 * w1 + nor2 * w2; */ } /* //outPos += weights.y * pos2; if (weight1 > weight2) pos = pos1; else pos = pos2;*/ //pos = pos2; //pos = pos1 + pos2; /* if (weights.x >= 0.0) { int id = 0; if (links.x > 0.0) id = 1; //int id = int(links.x); mat4 influence = jointsInfo.tm[id]; pos1 = influence * pos; //tm = influence * weights.x; //pos = tm * vec4(pos.x, pos.y, pos.z, 1.0); outPos = pos1; } if (weights.y >= 0.0) { int id = 0; if (links.y > 0.0) id = 1; //int id = int(links.y); mat4 influence = jointsInfo.tm[id]; pos2 = influence * pos; //tm += influence * weights.y; //pos = pos2; outPos = pos2; } pos = outPos; */ //pos = mix(pos1, pos2, weights.x); // pos1 * weights.x + pos2 * weights.y; //pos = tm * vec4(pos.x, pos.y, pos.z, 1.0); //nor = tm * vec4(nor.x, nor.y, nor.z, 1.0); //nor = normalize(nor); } outputNormals.normals[flattened_id] = nor; outputPositions.positions[flattened_id] = pos; }
// <copyright file="RemoteSessionSettings.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium { /// <summary> /// Base class for managing options specific to a browser driver. /// </summary> public class RemoteSessionSettings : ICapabilities { private const string FirstMatchCapabilityName = "firstMatch"; private const string AlwaysMatchCapabilityName = "alwaysMatch"; private readonly List<string> reservedSettingNames = new List<string>() { FirstMatchCapabilityName, AlwaysMatchCapabilityName }; private DriverOptions mustMatchDriverOptions; private List<DriverOptions> firstMatchOptions = new List<DriverOptions>(); private Dictionary<string, object> remoteMetadataSettings = new Dictionary<string, object>(); /// <summary> /// Creates a new instance of the <see cref="RemoteSessionSettings"/> class. /// </summary> public RemoteSessionSettings() { } /// <summary> /// Creates a new instance of the <see cref="RemoteSessionSettings"/> class, /// containing the specified <see cref="DriverOptions"/> to use in the remote /// session. /// </summary> /// <param name="mustMatchDriverOptions"> /// A <see cref="DriverOptions"/> object that contains values that must be matched /// by the remote end to create the remote session. /// </param> /// <param name="firstMatchDriverOptions"> /// A list of <see cref="DriverOptions"/> objects that contain values that may be matched /// by the remote end to create the remote session. /// </param> public RemoteSessionSettings(DriverOptions mustMatchDriverOptions, params DriverOptions[] firstMatchDriverOptions) { this.mustMatchDriverOptions = mustMatchDriverOptions; foreach (DriverOptions firstMatchOption in firstMatchDriverOptions) { this.AddFirstMatchDriverOption(firstMatchOption); } } /// <summary> /// Gets a value indicating the options that must be matched by the remote end to create a session. /// </summary> internal DriverOptions MustMatchDriverOptions { get { return this.mustMatchDriverOptions; } } /// <summary> /// Gets a value indicating the number of options that may be matched by the remote end to create a session. /// </summary> internal int FirstMatchOptionsCount { get { return this.firstMatchOptions.Count; } } /// <summary> /// Gets the capability value with the specified name. /// </summary> /// <param name="capabilityName">The name of the capability to get.</param> /// <returns>The value of the capability.</returns> /// <exception cref="ArgumentException"> /// The specified capability name is not in the set of capabilities. /// </exception> public object this[string capabilityName] { get { if (capabilityName == AlwaysMatchCapabilityName) { return this.GetAlwaysMatchOptionsAsSerializableDictionary(); } if (capabilityName == FirstMatchCapabilityName) { return this.GetFirstMatchOptionsAsSerializableList(); } if (!this.remoteMetadataSettings.ContainsKey(capabilityName)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The capability {0} is not present in this set of capabilities", capabilityName)); } return this.remoteMetadataSettings[capabilityName]; } } /// <summary> /// Add a metadata setting to this set of remote session settings. /// </summary> /// <param name="settingName">The name of the setting to set.</param> /// <param name="settingValue">The value of the setting.</param> /// <remarks> /// The value to be set must be serializable to JSON for transmission /// across the wire to the remote end. To be JSON-serializable, the value /// must be a string, a numeric value, a boolean value, an object that /// implmeents <see cref="IEnumerable"/> that contains JSON-serializable /// objects, or a <see cref="Dictionary{TKey, TValue}"/> where the keys /// are strings and the values are JSON-serializable. /// </remarks> /// <exception cref="ArgumentException"> /// Thrown if the setting name is null, the empty string, or one of the /// reserved names of metadata settings; or if the setting value is not /// JSON serializable. /// </exception> public void AddMetadataSetting(string settingName, object settingValue) { if (string.IsNullOrEmpty(settingName)) { throw new ArgumentException("Metadata setting name cannot be null or empty", "settingName"); } if (this.reservedSettingNames.Contains(settingName)) { throw new ArgumentException(string.Format("'{0}' is a reserved name for a metadata setting, and cannot be used as a name.", settingName), "settingName"); } if (!this.IsJsonSerializable(settingValue)) { throw new ArgumentException("Metadata setting value must be JSON serializable.", "settingValue"); } this.remoteMetadataSettings[settingName] = settingValue; } /// <summary> /// Adds a <see cref="DriverOptions"/> object to the list of options containing values to be /// "first matched" by the remote end. /// </summary> /// <param name="options">The <see cref="DriverOptions"/> to add to the list of "first matched" options.</param> public void AddFirstMatchDriverOption(DriverOptions options) { if (mustMatchDriverOptions != null) { DriverOptionsMergeResult mergeResult = mustMatchDriverOptions.GetMergeResult(options); if (mergeResult.IsMergeConflict) { string msg = string.Format(CultureInfo.InvariantCulture, "You cannot request the same capability in both must-match and first-match capabilities. You are attempting to add a first-match driver options object that defines a capability, '{0}', that is already defined in the must-match driver options.", mergeResult.MergeConflictOptionName); throw new ArgumentException(msg, "options"); } } firstMatchOptions.Add(options); } /// <summary> /// Adds a <see cref="DriverOptions"/> object containing values that must be matched /// by the remote end to successfully create a session. /// </summary> /// <param name="options">The <see cref="DriverOptions"/> that must be matched by /// the remote end to successfully create a session.</param> public void SetMustMatchDriverOptions(DriverOptions options) { if (this.firstMatchOptions.Count > 0) { int driverOptionIndex = 0; foreach (DriverOptions firstMatchOption in this.firstMatchOptions) { DriverOptionsMergeResult mergeResult = firstMatchOption.GetMergeResult(options); if (mergeResult.IsMergeConflict) { string msg = string.Format(CultureInfo.InvariantCulture, "You cannot request the same capability in both must-match and first-match capabilities. You are attempting to add a must-match driver options object that defines a capability, '{0}', that is already defined in the first-match driver options with index {1}.", mergeResult.MergeConflictOptionName, driverOptionIndex); throw new ArgumentException(msg, "options"); } driverOptionIndex++; } } this.mustMatchDriverOptions = options; } /// <summary> /// Gets a value indicating whether the browser has a given capability. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>Returns <see langword="true"/> if this set of capabilities has the capability; /// otherwise, <see langword="false"/>.</returns> public bool HasCapability(string capability) { if (capability == AlwaysMatchCapabilityName || capability == FirstMatchCapabilityName) { return true; } return this.remoteMetadataSettings.ContainsKey(capability); } /// <summary> /// Gets a capability of the browser. /// </summary> /// <param name="capability">The capability to get.</param> /// <returns>An object associated with the capability, or <see langword="null"/> /// if the capability is not set in this set of capabilities.</returns> public object GetCapability(string capability) { if (capability == AlwaysMatchCapabilityName) { return this.GetAlwaysMatchOptionsAsSerializableDictionary(); } if (capability == FirstMatchCapabilityName) { return this.GetFirstMatchOptionsAsSerializableList(); } if (this.remoteMetadataSettings.ContainsKey(capability)) { return this.remoteMetadataSettings[capability]; } return null; } /// <summary> /// Return a dictionary representation of this <see cref="RemoteSessionSettings"/>. /// </summary> /// <returns>A <see cref="Dictionary{TKey, TValue}"/> representation of this <see cref="RemoteSessionSettings"/>.</returns> public Dictionary<string, object> ToDictionary() { Dictionary<string, object> capabilitiesDictionary = new Dictionary<string, object>(); foreach (KeyValuePair<string, object> remoteMetadataSetting in this.remoteMetadataSettings) { capabilitiesDictionary[remoteMetadataSetting.Key] = remoteMetadataSetting.Value; } if (this.mustMatchDriverOptions != null) { capabilitiesDictionary["alwaysMatch"] = GetAlwaysMatchOptionsAsSerializableDictionary(); } if (this.firstMatchOptions.Count > 0) { List<object> optionsMatches = GetFirstMatchOptionsAsSerializableList(); capabilitiesDictionary["firstMatch"] = optionsMatches; } return capabilitiesDictionary; } /// <summary> /// Return a string representation of the remote session settings to be sent. /// </summary> /// <returns>String representation of the remote session settings to be sent.</returns> public override string ToString() { return JsonConvert.SerializeObject(this.ToDictionary(), Formatting.Indented); } internal DriverOptions GetFirstMatchDriverOptions(int firstMatchIndex) { if (firstMatchIndex < 0 || firstMatchIndex >= this.firstMatchOptions.Count) { throw new ArgumentException("Requested index must be greater than zero and less than the count of firstMatch options added."); } return this.firstMatchOptions[firstMatchIndex]; } private Dictionary<string, object> GetAlwaysMatchOptionsAsSerializableDictionary() { return this.mustMatchDriverOptions.ToDictionary(); } private List<object> GetFirstMatchOptionsAsSerializableList() { List<object> optionsMatches = new List<object>(); foreach (DriverOptions options in this.firstMatchOptions) { optionsMatches.Add(options.ToDictionary()); } return optionsMatches; } private bool IsJsonSerializable(object arg) { IEnumerable argAsEnumerable = arg as IEnumerable; IDictionary argAsDictionary = arg as IDictionary; if (arg is string || arg is float || arg is double || arg is int || arg is long || arg is bool || arg == null) { return true; } else if (argAsDictionary != null) { foreach (object key in argAsDictionary.Keys) { if (!(key is string)) { return false; } } foreach (object value in argAsDictionary.Values) { if (!IsJsonSerializable(value)) { return false; } } } else if (argAsEnumerable != null) { foreach (object item in argAsEnumerable) { if (!IsJsonSerializable(item)) { return false; } } } else { return false; } return true; } } }
using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using Swetugg.Web.Models; namespace Swetugg.Web.Areas.Admin.Controllers { public class SessionAdminController : ConferenceAdminControllerBase { public SessionAdminController(ApplicationDbContext dbContext) : base(dbContext) { } [Route("{conferenceSlug}/sessions")] public async Task<ActionResult> Index() { var conferenceId = ConferenceId; var sessions = from s in dbContext.Sessions where s.ConferenceId == conferenceId orderby s.Name select s; var sessionsList = await sessions.ToListAsync(); return View(sessionsList); } [Route("{conferenceSlug}/sessions/{id:int}")] #pragma warning disable 0108 public async Task<ActionResult> Session(int id) #pragma warning restore 0108 { var conferenceId = ConferenceId; var session = await dbContext.Sessions .Include(m => m.Speakers.Select(s => s.Speaker)) .Include(s => s.Tags) .Include(s => s.SessionType) .SingleAsync(s => s.Id == id); var speakers = await dbContext.Speakers.Where(m => m.ConferenceId == conferenceId).OrderBy(s => s.Name).ToListAsync(); var tags = await dbContext.Tags.Where(m => m.ConferenceId == conferenceId && m.Type == TagType.Session).OrderBy(s => s.Name).ToListAsync(); ViewBag.Speakers = speakers.Where(s => session.Speakers.All(se => se.SpeakerId != s.Id)).ToList(); ViewBag.Tags = tags.Where(t => session.Tags.All(st => st.Id != t.Id)).ToList(); return View(session); } [Route("{conferenceSlug}/sessions/edit/{id:int}", Order = 1)] public async Task<ActionResult> Edit(int id) { var conferenceId = ConferenceId; var session = await dbContext.Sessions .Include(s => s.SessionType) .SingleAsync(s => s.Id == id); ViewBag.SessionTypes = dbContext.SessionTypes.Where(m => m.ConferenceId == conferenceId).OrderBy(s => s.Priority).ToList(); return View(session); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/edit/{id:int}", Order = 1)] public async Task<ActionResult> Edit(int id, Session session) { var conferenceId = ConferenceId; if (ModelState.IsValid) { try { session.ConferenceId = conferenceId; dbContext.Entry(session).State = EntityState.Modified; await dbContext.SaveChangesAsync(); return RedirectToAction("Session", new { session.Id }); } catch (Exception ex) { ModelState.AddModelError("Updating", ex); } ViewBag.SessionTypes = dbContext.SessionTypes.Where(m => m.ConferenceId == conferenceId).OrderBy(s => s.Priority).ToList(); } return View(session); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/addspeaker/{id:int}")] public async Task<ActionResult> AddSpeaker(int id, int speakerId) { var session = await dbContext.Sessions.Include(m => m.Speakers).SingleAsync(s => s.Id == id); session.Speakers.Add(new SessionSpeaker() { SpeakerId = speakerId }); await dbContext.SaveChangesAsync(); return RedirectToAction("Session", new { id }); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/removespeaker/{id:int}")] public async Task<ActionResult> RemoveSpeaker(int id, int speakerId) { var session = await dbContext.Sessions.Include(m => m.Speakers).Where(s => s.Id == id).SingleAsync(); var sessionSpeaker = session.Speakers.Single(s => s.SpeakerId == speakerId); dbContext.Entry(sessionSpeaker).State = EntityState.Deleted; await dbContext.SaveChangesAsync(); return RedirectToAction("Session", new { id }); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/addtag/{id:int}")] public async Task<ActionResult> AddTag(int id, int tagId) { var session = await dbContext.Sessions.Include(m => m.Tags).SingleAsync(s => s.Id == id); var tag = await dbContext.Tags.FirstAsync(t => t.Id == tagId); session.Tags.Add(tag); await dbContext.SaveChangesAsync(); return RedirectToAction("Session", new { id }); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/removetag/{id:int}")] public async Task<ActionResult> RemoveTag(int id, int tagId) { var session = await dbContext.Sessions.Include(m => m.Tags).Where(s => s.Id == id).SingleAsync(); foreach (var tag in session.Tags) { if (tag.Id == tagId) { session.Tags.Remove(tag); break; } } await dbContext.SaveChangesAsync(); return RedirectToAction("Session", new { id }); } [Route("{conferenceSlug}/sessions/new", Order = 2)] public async Task<ActionResult> Edit() { var conferenceId = ConferenceId; ViewBag.SessionTypes = await dbContext.SessionTypes.Where(m => m.ConferenceId == conferenceId).OrderBy(s => s.Priority).ToListAsync(); return View(); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/new", Order = 2)] public async Task<ActionResult> Edit(Session session) { var conferenceId = ConferenceId; if (ModelState.IsValid) { try { session.ConferenceId = conferenceId; dbContext.Sessions.Add(session); await dbContext.SaveChangesAsync(); return RedirectToAction("Session", new { session.Id }); } catch (Exception ex) { ModelState.AddModelError("Updating", ex); } ViewBag.SessionTypes = await dbContext.SessionTypes.Where(m => m.ConferenceId == conferenceId).OrderBy(s => s.Priority).ToListAsync(); } return View(session); } [ValidateAntiForgeryToken] [HttpPost] [Route("{conferenceSlug}/sessions/delete/{id:int}", Order = 1)] public async Task<ActionResult> Delete(int id) { var session = await dbContext.Sessions.Include(s => s.Speakers).Include(s => s.RoomSlots).Include(s => s.CfpSessions).SingleAsync(s => s.Id == id); foreach (var speaker in session.Speakers.ToArray()) { dbContext.Entry(speaker).State = EntityState.Deleted; } foreach (var roomSlot in session.RoomSlots.ToArray()) { dbContext.Entry(roomSlot).State = EntityState.Deleted; } session.CfpSessions.Clear(); dbContext.Entry(session).State = EntityState.Deleted; await dbContext.SaveChangesAsync(); return RedirectToAction("Index"); } } }
/* * CP858.cs - Western European (DOS with Euro) code page. * * Copyright (c) 2002 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "ibm-858.ucm". namespace I18N.Rare { using System; using I18N.Common; public class CP858 : ByteEncoding { public CP858() : base(858, ToChars, "Western European (DOS with Euro)", "IBM00858", "IBM00858", "IBM00858", false, false, false, false, 1252) {} private static readonly char[] ToChars = { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001C', '\u001B', '\u007F', '\u001D', '\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023', '\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029', '\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F', '\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035', '\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B', '\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041', '\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047', '\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D', '\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053', '\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059', '\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F', '\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065', '\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B', '\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071', '\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077', '\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D', '\u007E', '\u001A', '\u00C7', '\u00FC', '\u00E9', '\u00E2', '\u00E4', '\u00E0', '\u00E5', '\u00E7', '\u00EA', '\u00EB', '\u00E8', '\u00EF', '\u00EE', '\u00EC', '\u00C4', '\u00C5', '\u00C9', '\u00E6', '\u00C6', '\u00F4', '\u00F6', '\u00F2', '\u00FB', '\u00F9', '\u00FF', '\u00D6', '\u00DC', '\u00F8', '\u00A3', '\u00D8', '\u00D7', '\u0192', '\u00E1', '\u00ED', '\u00F3', '\u00FA', '\u00F1', '\u00D1', '\u00AA', '\u00BA', '\u00BF', '\u00AE', '\u00AC', '\u00BD', '\u00BC', '\u00A1', '\u00AB', '\u00BB', '\u2591', '\u2592', '\u2593', '\u2502', '\u2524', '\u00C1', '\u00C2', '\u00C0', '\u00A9', '\u2563', '\u2551', '\u2557', '\u255D', '\u00A2', '\u00A5', '\u2510', '\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C', '\u00E3', '\u00C3', '\u255A', '\u2554', '\u2569', '\u2566', '\u2560', '\u2550', '\u256C', '\u00A4', '\u00F0', '\u00D0', '\u00CA', '\u00CB', '\u00C8', '\u20AC', '\u00CD', '\u00CE', '\u00CF', '\u2518', '\u250C', '\u2588', '\u2584', '\u00A6', '\u00CC', '\u2580', '\u00D3', '\u00DF', '\u00D4', '\u00D2', '\u00F5', '\u00D5', '\u00B5', '\u00FE', '\u00DE', '\u00DA', '\u00DB', '\u00D9', '\u00FD', '\u00DD', '\u00AF', '\u00B4', '\u00AD', '\u00B1', '\u2017', '\u00BE', '\u00B6', '\u00A7', '\u00F7', '\u00B8', '\u00B0', '\u00A8', '\u00B7', '\u00B9', '\u00B3', '\u00B2', '\u25A0', '\u00A0', }; protected override void ToBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(chars[charIndex++]); if(ch >= 26) switch(ch) { case 0x001B: case 0x001D: case 0x001E: case 0x001F: case 0x0020: case 0x0021: case 0x0022: case 0x0023: case 0x0024: case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002C: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003B: case 0x003C: case 0x003D: case 0x003E: case 0x003F: case 0x0040: case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x0060: case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: case 0x007B: case 0x007C: case 0x007D: case 0x007E: break; case 0x001A: ch = 0x7F; break; case 0x001C: ch = 0x1A; break; case 0x007F: ch = 0x1C; break; case 0x00A0: ch = 0xFF; break; case 0x00A1: ch = 0xAD; break; case 0x00A2: ch = 0xBD; break; case 0x00A3: ch = 0x9C; break; case 0x00A4: ch = 0xCF; break; case 0x00A5: ch = 0xBE; break; case 0x00A6: ch = 0xDD; break; case 0x00A7: ch = 0xF5; break; case 0x00A8: ch = 0xF9; break; case 0x00A9: ch = 0xB8; break; case 0x00AA: ch = 0xA6; break; case 0x00AB: ch = 0xAE; break; case 0x00AC: ch = 0xAA; break; case 0x00AD: ch = 0xF0; break; case 0x00AE: ch = 0xA9; break; case 0x00AF: ch = 0xEE; break; case 0x00B0: ch = 0xF8; break; case 0x00B1: ch = 0xF1; break; case 0x00B2: ch = 0xFD; break; case 0x00B3: ch = 0xFC; break; case 0x00B4: ch = 0xEF; break; case 0x00B5: ch = 0xE6; break; case 0x00B6: ch = 0xF4; break; case 0x00B7: ch = 0xFA; break; case 0x00B8: ch = 0xF7; break; case 0x00B9: ch = 0xFB; break; case 0x00BA: ch = 0xA7; break; case 0x00BB: ch = 0xAF; break; case 0x00BC: ch = 0xAC; break; case 0x00BD: ch = 0xAB; break; case 0x00BE: ch = 0xF3; break; case 0x00BF: ch = 0xA8; break; case 0x00C0: ch = 0xB7; break; case 0x00C1: ch = 0xB5; break; case 0x00C2: ch = 0xB6; break; case 0x00C3: ch = 0xC7; break; case 0x00C4: ch = 0x8E; break; case 0x00C5: ch = 0x8F; break; case 0x00C6: ch = 0x92; break; case 0x00C7: ch = 0x80; break; case 0x00C8: ch = 0xD4; break; case 0x00C9: ch = 0x90; break; case 0x00CA: ch = 0xD2; break; case 0x00CB: ch = 0xD3; break; case 0x00CC: ch = 0xDE; break; case 0x00CD: ch = 0xD6; break; case 0x00CE: ch = 0xD7; break; case 0x00CF: ch = 0xD8; break; case 0x00D0: ch = 0xD1; break; case 0x00D1: ch = 0xA5; break; case 0x00D2: ch = 0xE3; break; case 0x00D3: ch = 0xE0; break; case 0x00D4: ch = 0xE2; break; case 0x00D5: ch = 0xE5; break; case 0x00D6: ch = 0x99; break; case 0x00D7: ch = 0x9E; break; case 0x00D8: ch = 0x9D; break; case 0x00D9: ch = 0xEB; break; case 0x00DA: ch = 0xE9; break; case 0x00DB: ch = 0xEA; break; case 0x00DC: ch = 0x9A; break; case 0x00DD: ch = 0xED; break; case 0x00DE: ch = 0xE8; break; case 0x00DF: ch = 0xE1; break; case 0x00E0: ch = 0x85; break; case 0x00E1: ch = 0xA0; break; case 0x00E2: ch = 0x83; break; case 0x00E3: ch = 0xC6; break; case 0x00E4: ch = 0x84; break; case 0x00E5: ch = 0x86; break; case 0x00E6: ch = 0x91; break; case 0x00E7: ch = 0x87; break; case 0x00E8: ch = 0x8A; break; case 0x00E9: ch = 0x82; break; case 0x00EA: ch = 0x88; break; case 0x00EB: ch = 0x89; break; case 0x00EC: ch = 0x8D; break; case 0x00ED: ch = 0xA1; break; case 0x00EE: ch = 0x8C; break; case 0x00EF: ch = 0x8B; break; case 0x00F0: ch = 0xD0; break; case 0x00F1: ch = 0xA4; break; case 0x00F2: ch = 0x95; break; case 0x00F3: ch = 0xA2; break; case 0x00F4: ch = 0x93; break; case 0x00F5: ch = 0xE4; break; case 0x00F6: ch = 0x94; break; case 0x00F7: ch = 0xF6; break; case 0x00F8: ch = 0x9B; break; case 0x00F9: ch = 0x97; break; case 0x00FA: ch = 0xA3; break; case 0x00FB: ch = 0x96; break; case 0x00FC: ch = 0x81; break; case 0x00FD: ch = 0xEC; break; case 0x00FE: ch = 0xE7; break; case 0x00FF: ch = 0x98; break; case 0x0192: ch = 0x9F; break; case 0x2017: ch = 0xF2; break; case 0x2022: ch = 0x07; break; case 0x203C: ch = 0x13; break; case 0x203E: ch = 0xEE; break; case 0x20AC: ch = 0xD5; break; case 0x2190: ch = 0x1B; break; case 0x2191: ch = 0x18; break; case 0x2192: ch = 0x1A; break; case 0x2193: ch = 0x19; break; case 0x2194: ch = 0x1D; break; case 0x2195: ch = 0x12; break; case 0x21A8: ch = 0x17; break; case 0x221F: ch = 0x1C; break; case 0x2302: ch = 0x7F; break; case 0x2500: ch = 0xC4; break; case 0x2502: ch = 0xB3; break; case 0x250C: ch = 0xDA; break; case 0x2510: ch = 0xBF; break; case 0x2514: ch = 0xC0; break; case 0x2518: ch = 0xD9; break; case 0x251C: ch = 0xC3; break; case 0x2524: ch = 0xB4; break; case 0x252C: ch = 0xC2; break; case 0x2534: ch = 0xC1; break; case 0x253C: ch = 0xC5; break; case 0x2550: ch = 0xCD; break; case 0x2551: ch = 0xBA; break; case 0x2554: ch = 0xC9; break; case 0x2557: ch = 0xBB; break; case 0x255A: ch = 0xC8; break; case 0x255D: ch = 0xBC; break; case 0x2560: ch = 0xCC; break; case 0x2563: ch = 0xB9; break; case 0x2566: ch = 0xCB; break; case 0x2569: ch = 0xCA; break; case 0x256C: ch = 0xCE; break; case 0x2580: ch = 0xDF; break; case 0x2584: ch = 0xDC; break; case 0x2588: ch = 0xDB; break; case 0x2591: ch = 0xB0; break; case 0x2592: ch = 0xB1; break; case 0x2593: ch = 0xB2; break; case 0x25A0: ch = 0xFE; break; case 0x25AC: ch = 0x16; break; case 0x25B2: ch = 0x1E; break; case 0x25BA: ch = 0x10; break; case 0x25BC: ch = 0x1F; break; case 0x25C4: ch = 0x11; break; case 0x25CB: ch = 0x09; break; case 0x25D8: ch = 0x08; break; case 0x25D9: ch = 0x0A; break; case 0x263A: ch = 0x01; break; case 0x263B: ch = 0x02; break; case 0x263C: ch = 0x0F; break; case 0x2640: ch = 0x0C; break; case 0x2642: ch = 0x0B; break; case 0x2660: ch = 0x06; break; case 0x2663: ch = 0x05; break; case 0x2665: ch = 0x03; break; case 0x2666: ch = 0x04; break; case 0x266A: ch = 0x0D; break; case 0x266C: ch = 0x0E; break; case 0xFFE8: ch = 0xB3; break; case 0xFFE9: ch = 0x1B; break; case 0xFFEA: ch = 0x18; break; case 0xFFEB: ch = 0x1A; break; case 0xFFEC: ch = 0x19; break; case 0xFFED: ch = 0xFE; break; case 0xFFEE: ch = 0x09; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } protected override void ToBytes(String s, int charIndex, int charCount, byte[] bytes, int byteIndex) { int ch; while(charCount > 0) { ch = (int)(s[charIndex++]); if(ch >= 26) switch(ch) { case 0x001B: case 0x001D: case 0x001E: case 0x001F: case 0x0020: case 0x0021: case 0x0022: case 0x0023: case 0x0024: case 0x0025: case 0x0026: case 0x0027: case 0x0028: case 0x0029: case 0x002A: case 0x002B: case 0x002C: case 0x002D: case 0x002E: case 0x002F: case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: case 0x003A: case 0x003B: case 0x003C: case 0x003D: case 0x003E: case 0x003F: case 0x0040: case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: case 0x0046: case 0x0047: case 0x0048: case 0x0049: case 0x004A: case 0x004B: case 0x004C: case 0x004D: case 0x004E: case 0x004F: case 0x0050: case 0x0051: case 0x0052: case 0x0053: case 0x0054: case 0x0055: case 0x0056: case 0x0057: case 0x0058: case 0x0059: case 0x005A: case 0x005B: case 0x005C: case 0x005D: case 0x005E: case 0x005F: case 0x0060: case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: case 0x0066: case 0x0067: case 0x0068: case 0x0069: case 0x006A: case 0x006B: case 0x006C: case 0x006D: case 0x006E: case 0x006F: case 0x0070: case 0x0071: case 0x0072: case 0x0073: case 0x0074: case 0x0075: case 0x0076: case 0x0077: case 0x0078: case 0x0079: case 0x007A: case 0x007B: case 0x007C: case 0x007D: case 0x007E: break; case 0x001A: ch = 0x7F; break; case 0x001C: ch = 0x1A; break; case 0x007F: ch = 0x1C; break; case 0x00A0: ch = 0xFF; break; case 0x00A1: ch = 0xAD; break; case 0x00A2: ch = 0xBD; break; case 0x00A3: ch = 0x9C; break; case 0x00A4: ch = 0xCF; break; case 0x00A5: ch = 0xBE; break; case 0x00A6: ch = 0xDD; break; case 0x00A7: ch = 0xF5; break; case 0x00A8: ch = 0xF9; break; case 0x00A9: ch = 0xB8; break; case 0x00AA: ch = 0xA6; break; case 0x00AB: ch = 0xAE; break; case 0x00AC: ch = 0xAA; break; case 0x00AD: ch = 0xF0; break; case 0x00AE: ch = 0xA9; break; case 0x00AF: ch = 0xEE; break; case 0x00B0: ch = 0xF8; break; case 0x00B1: ch = 0xF1; break; case 0x00B2: ch = 0xFD; break; case 0x00B3: ch = 0xFC; break; case 0x00B4: ch = 0xEF; break; case 0x00B5: ch = 0xE6; break; case 0x00B6: ch = 0xF4; break; case 0x00B7: ch = 0xFA; break; case 0x00B8: ch = 0xF7; break; case 0x00B9: ch = 0xFB; break; case 0x00BA: ch = 0xA7; break; case 0x00BB: ch = 0xAF; break; case 0x00BC: ch = 0xAC; break; case 0x00BD: ch = 0xAB; break; case 0x00BE: ch = 0xF3; break; case 0x00BF: ch = 0xA8; break; case 0x00C0: ch = 0xB7; break; case 0x00C1: ch = 0xB5; break; case 0x00C2: ch = 0xB6; break; case 0x00C3: ch = 0xC7; break; case 0x00C4: ch = 0x8E; break; case 0x00C5: ch = 0x8F; break; case 0x00C6: ch = 0x92; break; case 0x00C7: ch = 0x80; break; case 0x00C8: ch = 0xD4; break; case 0x00C9: ch = 0x90; break; case 0x00CA: ch = 0xD2; break; case 0x00CB: ch = 0xD3; break; case 0x00CC: ch = 0xDE; break; case 0x00CD: ch = 0xD6; break; case 0x00CE: ch = 0xD7; break; case 0x00CF: ch = 0xD8; break; case 0x00D0: ch = 0xD1; break; case 0x00D1: ch = 0xA5; break; case 0x00D2: ch = 0xE3; break; case 0x00D3: ch = 0xE0; break; case 0x00D4: ch = 0xE2; break; case 0x00D5: ch = 0xE5; break; case 0x00D6: ch = 0x99; break; case 0x00D7: ch = 0x9E; break; case 0x00D8: ch = 0x9D; break; case 0x00D9: ch = 0xEB; break; case 0x00DA: ch = 0xE9; break; case 0x00DB: ch = 0xEA; break; case 0x00DC: ch = 0x9A; break; case 0x00DD: ch = 0xED; break; case 0x00DE: ch = 0xE8; break; case 0x00DF: ch = 0xE1; break; case 0x00E0: ch = 0x85; break; case 0x00E1: ch = 0xA0; break; case 0x00E2: ch = 0x83; break; case 0x00E3: ch = 0xC6; break; case 0x00E4: ch = 0x84; break; case 0x00E5: ch = 0x86; break; case 0x00E6: ch = 0x91; break; case 0x00E7: ch = 0x87; break; case 0x00E8: ch = 0x8A; break; case 0x00E9: ch = 0x82; break; case 0x00EA: ch = 0x88; break; case 0x00EB: ch = 0x89; break; case 0x00EC: ch = 0x8D; break; case 0x00ED: ch = 0xA1; break; case 0x00EE: ch = 0x8C; break; case 0x00EF: ch = 0x8B; break; case 0x00F0: ch = 0xD0; break; case 0x00F1: ch = 0xA4; break; case 0x00F2: ch = 0x95; break; case 0x00F3: ch = 0xA2; break; case 0x00F4: ch = 0x93; break; case 0x00F5: ch = 0xE4; break; case 0x00F6: ch = 0x94; break; case 0x00F7: ch = 0xF6; break; case 0x00F8: ch = 0x9B; break; case 0x00F9: ch = 0x97; break; case 0x00FA: ch = 0xA3; break; case 0x00FB: ch = 0x96; break; case 0x00FC: ch = 0x81; break; case 0x00FD: ch = 0xEC; break; case 0x00FE: ch = 0xE7; break; case 0x00FF: ch = 0x98; break; case 0x0192: ch = 0x9F; break; case 0x2017: ch = 0xF2; break; case 0x2022: ch = 0x07; break; case 0x203C: ch = 0x13; break; case 0x203E: ch = 0xEE; break; case 0x20AC: ch = 0xD5; break; case 0x2190: ch = 0x1B; break; case 0x2191: ch = 0x18; break; case 0x2192: ch = 0x1A; break; case 0x2193: ch = 0x19; break; case 0x2194: ch = 0x1D; break; case 0x2195: ch = 0x12; break; case 0x21A8: ch = 0x17; break; case 0x221F: ch = 0x1C; break; case 0x2302: ch = 0x7F; break; case 0x2500: ch = 0xC4; break; case 0x2502: ch = 0xB3; break; case 0x250C: ch = 0xDA; break; case 0x2510: ch = 0xBF; break; case 0x2514: ch = 0xC0; break; case 0x2518: ch = 0xD9; break; case 0x251C: ch = 0xC3; break; case 0x2524: ch = 0xB4; break; case 0x252C: ch = 0xC2; break; case 0x2534: ch = 0xC1; break; case 0x253C: ch = 0xC5; break; case 0x2550: ch = 0xCD; break; case 0x2551: ch = 0xBA; break; case 0x2554: ch = 0xC9; break; case 0x2557: ch = 0xBB; break; case 0x255A: ch = 0xC8; break; case 0x255D: ch = 0xBC; break; case 0x2560: ch = 0xCC; break; case 0x2563: ch = 0xB9; break; case 0x2566: ch = 0xCB; break; case 0x2569: ch = 0xCA; break; case 0x256C: ch = 0xCE; break; case 0x2580: ch = 0xDF; break; case 0x2584: ch = 0xDC; break; case 0x2588: ch = 0xDB; break; case 0x2591: ch = 0xB0; break; case 0x2592: ch = 0xB1; break; case 0x2593: ch = 0xB2; break; case 0x25A0: ch = 0xFE; break; case 0x25AC: ch = 0x16; break; case 0x25B2: ch = 0x1E; break; case 0x25BA: ch = 0x10; break; case 0x25BC: ch = 0x1F; break; case 0x25C4: ch = 0x11; break; case 0x25CB: ch = 0x09; break; case 0x25D8: ch = 0x08; break; case 0x25D9: ch = 0x0A; break; case 0x263A: ch = 0x01; break; case 0x263B: ch = 0x02; break; case 0x263C: ch = 0x0F; break; case 0x2640: ch = 0x0C; break; case 0x2642: ch = 0x0B; break; case 0x2660: ch = 0x06; break; case 0x2663: ch = 0x05; break; case 0x2665: ch = 0x03; break; case 0x2666: ch = 0x04; break; case 0x266A: ch = 0x0D; break; case 0x266C: ch = 0x0E; break; case 0xFFE8: ch = 0xB3; break; case 0xFFE9: ch = 0x1B; break; case 0xFFEA: ch = 0x18; break; case 0xFFEB: ch = 0x1A; break; case 0xFFEC: ch = 0x19; break; case 0xFFED: ch = 0xFE; break; case 0xFFEE: ch = 0x09; break; default: { if(ch >= 0xFF01 && ch <= 0xFF5E) ch -= 0xFEE0; else ch = 0x3F; } break; } bytes[byteIndex++] = (byte)ch; --charCount; } } }; // class CP858 public class ENCibm00858 : CP858 { public ENCibm00858() : base() {} }; // class ENCibm00858 }; // namespace I18N.Rare
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Build.Construction; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using MSBuild = Microsoft.Build.Evaluation; namespace Microsoft.VisualStudioTools.Project { /// <summary> /// Creates projects within the solution /// </summary> public abstract class ProjectFactory : FlavoredProjectFactoryBase, #if DEV11_OR_LATER IVsAsynchronousProjectCreate, IVsProjectUpgradeViaFactory4, #endif IVsProjectUpgradeViaFactory { #region fields private System.IServiceProvider site; /// <summary> /// The msbuild engine that we are going to use. /// </summary> private MSBuild.ProjectCollection buildEngine; /// <summary> /// The msbuild project for the project file. /// </summary> private MSBuild.Project buildProject; #if DEV11_OR_LATER private readonly Lazy<IVsTaskSchedulerService> taskSchedulerService; #endif // (See GetSccInfo below.) // When we upgrade a project, we need to cache the SCC info in case // somebody calls to ask for it via GetSccInfo. // We only need to know about the most recently upgraded project, and // can fail for other projects. private string _cachedSccProject; private string _cachedSccProjectName, _cachedSccAuxPath, _cachedSccLocalPath, _cachedSccProvider; #endregion #region properties [Obsolete("Use Site instead")] protected Microsoft.VisualStudio.Shell.Package Package { get { return (Microsoft.VisualStudio.Shell.Package)this.site; } } protected internal System.IServiceProvider Site { get { return this.site; } internal set { this.site = value; } } #endregion #region ctor [Obsolete("Provide an IServiceProvider instead of a package")] protected ProjectFactory(Microsoft.VisualStudio.Shell.Package package) : this((IServiceProvider)package) { } protected ProjectFactory(IServiceProvider serviceProvider) : base(serviceProvider) { this.site = serviceProvider; this.buildEngine = MSBuild.ProjectCollection.GlobalProjectCollection; #if DEV11_OR_LATER this.taskSchedulerService = new Lazy<IVsTaskSchedulerService>(() => Site.GetService(typeof(SVsTaskSchedulerService)) as IVsTaskSchedulerService); #endif } #endregion #region abstract methods internal abstract ProjectNode CreateProject(); #endregion #region overriden methods /// <summary> /// Rather than directly creating the project, ask VS to initate the process of /// creating an aggregated project in case we are flavored. We will be called /// on the IVsAggregatableProjectFactory to do the real project creation. /// </summary> /// <param name="fileName">Project file</param> /// <param name="location">Path of the project</param> /// <param name="name">Project Name</param> /// <param name="flags">Creation flags</param> /// <param name="projectGuid">Guid of the project</param> /// <param name="project">Project that end up being created by this method</param> /// <param name="canceled">Was the project creation canceled</param> protected override void CreateProject(string fileName, string location, string name, uint flags, ref Guid projectGuid, out IntPtr project, out int canceled) { using (new DebugTimer("CreateProject")) { project = IntPtr.Zero; canceled = 0; // Get the list of GUIDs from the project/template string guidsList = this.ProjectTypeGuids(fileName); // Launch the aggregate creation process (we should be called back on our IVsAggregatableProjectFactoryCorrected implementation) IVsCreateAggregateProject aggregateProjectFactory = (IVsCreateAggregateProject)this.Site.GetService(typeof(SVsCreateAggregateProject)); int hr = aggregateProjectFactory.CreateAggregateProject(guidsList, fileName, location, name, flags, ref projectGuid, out project); if (hr == VSConstants.E_ABORT) canceled = 1; ErrorHandler.ThrowOnFailure(hr); this.buildProject = null; } } /// <summary> /// Instantiate the project class, but do not proceed with the /// initialization just yet. /// Delegate to CreateProject implemented by the derived class. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The global property handles is instantiated here and used in the project node that will Dispose it")] protected override object PreCreateForOuter(IntPtr outerProjectIUnknown) { Utilities.CheckNotNull(this.buildProject, "The build project should have been initialized before calling PreCreateForOuter."); // Please be very carefull what is initialized here on the ProjectNode. Normally this should only instantiate and return a project node. // The reason why one should very carefully add state to the project node here is that at this point the aggregation has not yet been created and anything that would cause a CCW for the project to be created would cause the aggregation to fail // Our reasoning is that there is no other place where state on the project node can be set that is known by the Factory and has to execute before the Load method. ProjectNode node = this.CreateProject(); Utilities.CheckNotNull(node, "The project failed to be created"); node.BuildEngine = this.buildEngine; node.BuildProject = this.buildProject; return node; } /// <summary> /// Retrives the list of project guids from the project file. /// If you don't want your project to be flavorable, override /// to only return your project factory Guid: /// return this.GetType().GUID.ToString("B"); /// </summary> /// <param name="file">Project file to look into to find the Guid list</param> /// <returns>List of semi-colon separated GUIDs</returns> protected override string ProjectTypeGuids(string file) { // Load the project so we can extract the list of GUIDs this.buildProject = Utilities.ReinitializeMsBuildProject(this.buildEngine, file, this.buildProject); // Retrieve the list of GUIDs, if it is not specify, make it our GUID string guids = buildProject.GetPropertyValue(ProjectFileConstants.ProjectTypeGuids); if (String.IsNullOrEmpty(guids)) guids = this.GetType().GUID.ToString("B"); return guids; } #endregion #if DEV11_OR_LATER public virtual bool CanCreateProjectAsynchronously(ref Guid rguidProjectID, string filename, uint flags) { return true; } public void OnBeforeCreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { } public IVsTask CreateProjectAsync(ref Guid rguidProjectID, string filename, string location, string pszName, uint flags) { Guid iid = typeof(IVsHierarchy).GUID; return VsTaskLibraryHelper.CreateAndStartTask(taskSchedulerService.Value, VsTaskRunContext.UIThreadBackgroundPriority, VsTaskLibraryHelper.CreateTaskBody(() => { IntPtr project; int cancelled; CreateProject(filename, location, pszName, flags, ref iid, out project, out cancelled); if (cancelled != 0) { throw new OperationCanceledException(); } return Marshal.GetObjectForIUnknown(project); })); } #endif #region Project Upgrades /// <summary> /// Override this method to upgrade project files. /// </summary> /// <param name="projectXml"> /// The XML of the project file being upgraded. This may be modified /// directly or replaced with a new element. /// </param> /// <param name="userProjectXml"> /// The XML of the user file being upgraded. This may be modified /// directly or replaced with a new element. /// /// If there is no user file before upgrading, this may be null. If it /// is non-null on return, the file is created. /// </param> /// <param name="log"> /// Callback to log messages. These messages will be added to the /// migration log that is displayed after upgrading completes. /// </param> protected virtual void UpgradeProject( ref ProjectRootElement projectXml, ref ProjectRootElement userProjectXml, Action<__VSUL_ERRORLEVEL, string> log ) { } /// <summary> /// Determines whether a project needs to be upgraded. /// </summary> /// <param name="projectXml"> /// The XML of the project file being upgraded. /// </param> /// <param name="userProjectXml"> /// The XML of the user file being upgraded, or null if no user file /// exists. /// </param> /// <param name="log"> /// Callback to log messages. These messages will be added to the /// migration log that is displayed after upgrading completes. /// </param> /// <param name="projectFactory"> /// The project factory that will be used. This may be replaced with /// another Guid if a new project factory should be used to upgrade the /// project. /// </param> /// <param name="backupSupport"> /// The level of backup support requested for the project. By default, /// the project file (and user file, if any) will be copied alongside /// the originals with ".old" added to the filenames. /// </param> /// <returns> /// The form of upgrade required. /// </returns> protected virtual ProjectUpgradeState UpgradeProjectCheck( ProjectRootElement projectXml, ProjectRootElement userProjectXml, Action<__VSUL_ERRORLEVEL, string> log, ref Guid projectFactory, ref __VSPPROJECTUPGRADEVIAFACTORYFLAGS backupSupport ) { return ProjectUpgradeState.NotNeeded; } class UpgradeLogger { private readonly string _projectFile; private readonly string _projectName; private readonly IVsUpgradeLogger _logger; public UpgradeLogger(string projectFile, IVsUpgradeLogger logger) { _projectFile = projectFile; _projectName = Path.GetFileNameWithoutExtension(projectFile); _logger = logger; } public void Log(__VSUL_ERRORLEVEL level, string text) { if (_logger != null) { ErrorHandler.ThrowOnFailure(_logger.LogMessage((uint)level, _projectName, _projectFile, text)); } } } int IVsProjectUpgradeViaFactory.GetSccInfo( string bstrProjectFileName, out string pbstrSccProjectName, out string pbstrSccAuxPath, out string pbstrSccLocalPath, out string pbstrProvider ) { if (string.Equals(_cachedSccProject, bstrProjectFileName, StringComparison.OrdinalIgnoreCase)) { pbstrSccProjectName = _cachedSccProjectName; pbstrSccAuxPath = _cachedSccAuxPath; pbstrSccLocalPath = _cachedSccLocalPath; pbstrProvider = _cachedSccProvider; return VSConstants.S_OK; } pbstrSccProjectName = null; pbstrSccAuxPath = null; pbstrSccLocalPath = null; pbstrProvider = null; return VSConstants.E_FAIL; } int IVsProjectUpgradeViaFactory.UpgradeProject( string bstrFileName, uint fUpgradeFlag, string bstrCopyLocation, out string pbstrUpgradedFullyQualifiedFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory ) { pbstrUpgradedFullyQualifiedFileName = null; // We first run (or re-run) the upgrade check and bail out early if // there is actually no need to upgrade. uint dummy; var hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly( bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out dummy ); if (!ErrorHandler.Succeeded(hr)) { return hr; } var logger = new UpgradeLogger(bstrFileName, pLogger); var backup = (__VSPPROJECTUPGRADEVIAFACTORYFLAGS)fUpgradeFlag; bool anyBackup, sxsBackup, copyBackup; anyBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED); if (anyBackup) { sxsBackup = backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP); copyBackup = !sxsBackup && backup.HasFlag(__VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP); } else { sxsBackup = copyBackup = false; } if (copyBackup) { throw new NotSupportedException("PUVFF_COPYBACKUP is not supported"); } pbstrUpgradedFullyQualifiedFileName = bstrFileName; if (pUpgradeRequired == 0 && !copyBackup) { // No upgrade required, and no backup required. logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired)); return VSConstants.S_OK; } try { UpgradeLogger logger2 = null; var userFileName = bstrFileName + ".user"; if (File.Exists(userFileName)) { logger2 = new UpgradeLogger(userFileName, pLogger); } else { userFileName = null; } if (sxsBackup) { // For SxS backups we want to put the old project file alongside // the current one. bstrCopyLocation = Path.GetDirectoryName(bstrFileName); } if (anyBackup) { var namePart = Path.GetFileNameWithoutExtension(bstrFileName); var extPart = Path.GetExtension(bstrFileName) + (sxsBackup ? ".old" : ""); var projectFileBackup = Path.Combine(bstrCopyLocation, namePart + extPart); for (int i = 1; File.Exists(projectFileBackup); ++i) { projectFileBackup = Path.Combine( bstrCopyLocation, string.Format("{0}{1}{2}", namePart, i, extPart) ); } File.Copy(bstrFileName, projectFileBackup); // Back up the .user file if there is one if (userFileName != null) { if (sxsBackup) { File.Copy( userFileName, Path.ChangeExtension(projectFileBackup, ".user.old") ); } else { File.Copy(userFileName, projectFileBackup + ".old"); } } // TODO: Implement support for backing up all files //if (copyBackup) { // - Open the project // - Inspect all Items // - Copy those items that are referenced relative to the // project file into bstrCopyLocation //} } var queryEdit = site.GetService(typeof(SVsQueryEditQuerySave)) as IVsQueryEditQuerySave2; if (queryEdit != null) { uint editVerdict; uint queryEditMoreInfo; var tagVSQueryEditFlags_QEF_AllowUnopenedProjects = (tagVSQueryEditFlags)0x80; ErrorHandler.ThrowOnFailure(queryEdit.QueryEditFiles( (uint)(tagVSQueryEditFlags.QEF_ForceEdit_NoPrompting | tagVSQueryEditFlags.QEF_DisallowInMemoryEdits | tagVSQueryEditFlags_QEF_AllowUnopenedProjects), 1, new[] { bstrFileName }, null, null, out editVerdict, out queryEditMoreInfo )); if (editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UpgradeCannotCheckOutProject)); return VSConstants.E_FAIL; } // File may have been updated during checkout, so check // again whether we need to upgrade. if ((queryEditMoreInfo & (uint)tagVSQueryEditResultFlags.QER_MaybeChanged) != 0) { hr = ((IVsProjectUpgradeViaFactory)this).UpgradeProject_CheckOnly( bstrFileName, pLogger, out pUpgradeRequired, out pguidNewProjectFactory, out dummy ); if (!ErrorHandler.Succeeded(hr)) { return hr; } if (pUpgradeRequired == 0) { logger.Log(__VSUL_ERRORLEVEL.VSUL_INFORMATIONAL, SR.GetString(SR.UpgradeNotRequired)); return VSConstants.S_OK; } } } // Load the project file and user file into MSBuild as plain // XML to make it easier for subclasses. var projectXml = ProjectRootElement.Open(bstrFileName); if (projectXml == null) { throw new Exception(SR.GetString(SR.UpgradeCannotLoadProject)); } var userXml = userFileName != null ? ProjectRootElement.Open(userFileName) : null; // Invoke our virtual UpgradeProject function. If it fails, it // will throw and we will log the exception. UpgradeProject(ref projectXml, ref userXml, logger.Log); // Get the SCC info from the project file. if (projectXml != null) { _cachedSccProject = bstrFileName; _cachedSccProjectName = string.Empty; _cachedSccAuxPath = string.Empty; _cachedSccLocalPath = string.Empty; _cachedSccProvider = string.Empty; foreach (var property in projectXml.Properties) { switch (property.Name) { case ProjectFileConstants.SccProjectName: _cachedSccProjectName = property.Value; break; case ProjectFileConstants.SccAuxPath: _cachedSccAuxPath = property.Value; break; case ProjectFileConstants.SccLocalPath: _cachedSccLocalPath = property.Value; break; case ProjectFileConstants.SccProvider: _cachedSccProvider = property.Value; break; default: break; } } } // Save the updated files. if (projectXml != null) { projectXml.Save(); } if (userXml != null) { userXml.Save(); } // Need to add "Converted" (unlocalized) to the report because // the XSLT refers to it. logger.Log(__VSUL_ERRORLEVEL.VSUL_STATUSMSG, "Converted"); return VSConstants.S_OK; } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); try { ActivityLog.LogError(GetType().FullName, ex.ToString()); } catch (InvalidOperationException) { // Cannot log to ActivityLog. This may occur if we are // outside of VS right now (for example, unit tests). System.Diagnostics.Trace.TraceError(ex.ToString()); } return VSConstants.E_FAIL; } } int IVsProjectUpgradeViaFactory.UpgradeProject_CheckOnly( string bstrFileName, IVsUpgradeLogger pLogger, out int pUpgradeRequired, out Guid pguidNewProjectFactory, out uint pUpgradeProjectCapabilityFlags ) { pUpgradeRequired = 0; pguidNewProjectFactory = Guid.Empty; if (!File.Exists(bstrFileName)) { pUpgradeProjectCapabilityFlags = 0; return VSConstants.E_INVALIDARG; } var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; var logger = new UpgradeLogger(bstrFileName, pLogger); try { var projectXml = ProjectRootElement.Open(bstrFileName); var userProjectName = bstrFileName + ".user"; var userProjectXml = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null; var upgradeRequired = UpgradeProjectCheck( projectXml, userProjectXml, logger.Log, ref pguidNewProjectFactory, ref backupSupport ); if (upgradeRequired != ProjectUpgradeState.NotNeeded) { pUpgradeRequired = 1; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } // Log the error and don't attempt to upgrade the project. logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); try { ActivityLog.LogError(GetType().FullName, ex.ToString()); } catch (InvalidOperationException) { // Cannot log to ActivityLog. This may occur if we are // outside of VS right now (for example, unit tests). System.Diagnostics.Trace.TraceError(ex.ToString()); } pUpgradeRequired = 0; } pUpgradeProjectCapabilityFlags = (uint)backupSupport; // If the upgrade checker set the factory GUID to ourselves, we need // to clear it if (pguidNewProjectFactory == GetType().GUID) { pguidNewProjectFactory = Guid.Empty; } return VSConstants.S_OK; } #if DEV11_OR_LATER void IVsProjectUpgradeViaFactory4.UpgradeProject_CheckOnly( string bstrFileName, IVsUpgradeLogger pLogger, out uint pUpgradeRequired, out Guid pguidNewProjectFactory, out uint pUpgradeProjectCapabilityFlags ) { pguidNewProjectFactory = Guid.Empty; if (!File.Exists(bstrFileName)) { pUpgradeRequired = 0; pUpgradeProjectCapabilityFlags = 0; return; } var backupSupport = __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_BACKUPSUPPORTED | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_COPYBACKUP | __VSPPROJECTUPGRADEVIAFACTORYFLAGS.PUVFF_SXSBACKUP; var logger = new UpgradeLogger(bstrFileName, pLogger); try { var projectXml = ProjectRootElement.Open(bstrFileName); var userProjectName = bstrFileName + ".user"; var userProjectXml = File.Exists(userProjectName) ? ProjectRootElement.Open(userProjectName) : null; var upgradeRequired = UpgradeProjectCheck( projectXml, userProjectXml, logger.Log, ref pguidNewProjectFactory, ref backupSupport ); switch (upgradeRequired) { case ProjectUpgradeState.SafeRepair: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_SAFEREPAIR; break; case ProjectUpgradeState.UnsafeRepair: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_UNSAFEREPAIR; break; case ProjectUpgradeState.OneWayUpgrade: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_ONEWAYUPGRADE; break; case ProjectUpgradeState.Incompatible: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_INCOMPATIBLE; break; case ProjectUpgradeState.Deprecated: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_DEPRECATED; break; default: case ProjectUpgradeState.NotNeeded: pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; break; } } catch (Exception ex) { if (ex.IsCriticalException()) { throw; } // Log the error and don't attempt to upgrade the project. logger.Log(__VSUL_ERRORLEVEL.VSUL_ERROR, SR.GetString(SR.UnexpectedUpgradeError, ex.Message)); try { ActivityLog.LogError(GetType().FullName, ex.ToString()); } catch (InvalidOperationException) { // Cannot log to ActivityLog. This may occur if we are // outside of VS right now (for example, unit tests). System.Diagnostics.Trace.TraceError(ex.ToString()); } pUpgradeRequired = (uint)__VSPPROJECTUPGRADEVIAFACTORYREPAIRFLAGS.VSPUVF_PROJECT_NOREPAIR; } pUpgradeProjectCapabilityFlags = (uint)backupSupport; // If the upgrade checker set the factory GUID to ourselves, we need // to clear it if (pguidNewProjectFactory == GetType().GUID) { pguidNewProjectFactory = Guid.Empty; } } #endif #endregion } /// <summary> /// Status indicating whether a project upgrade should occur and how the /// project will be affected. /// </summary> public enum ProjectUpgradeState { /// <summary> /// No action will be taken. /// </summary> NotNeeded, /// <summary> /// The project will be upgraded without asking the user. /// </summary> SafeRepair, /// <summary> /// The project will be upgraded with the user's permission. /// </summary> UnsafeRepair, /// <summary> /// The project will be upgraded with the user's permission and they /// will be informed that the project will no longer work with earlier /// versions of Visual Studio. /// </summary> OneWayUpgrade, /// <summary> /// The project will be marked as incompatible. /// </summary> Incompatible, /// <summary> /// The project will be marked as deprecated. /// </summary> Deprecated } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System; [CustomEditor(typeof(PrefabAssembler))] [CanEditMultipleObjects] [InitializeOnLoad] public class PrefabAssemblerEditor : Editor { static PrefabAssemblerEditor () { EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyWindowItemGUI; EditorApplication.projectWindowItemOnGUI += OnProjectWindowItemGUI; var assembleCallbackField = typeof(PrefabAssembler).GetField("EDITOR_AssembleCallback", BindingFlags.Static | BindingFlags.NonPublic); var assembleCallbackDelegate = Delegate.CreateDelegate(typeof(Action<PrefabAssembler>), typeof(PrefabAssemblerUtility), "Assemble"); assembleCallbackField.SetValue(null, assembleCallbackDelegate); } static void OnProjectWindowItemGUI (string guid, Rect selectionRect) { if(Event.current.type == EventType.MouseDown && Event.current.button == 0 && Event.current.clickCount == 2 && selectionRect.Contains(Event.current.mousePosition)) { var path = AssetDatabase.GUIDToAssetPath(guid); var file = new FileInfo(path); if(file.Extension != ".prefab") { return; } var go = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)); var labels = AssetDatabase.GetLabels(go); for(int i = 0; i < labels.Length; i++) { var l = labels[i]; if(l.StartsWith("Stage: ")) { if(EditorApplication.SaveCurrentSceneIfUserWantsTo()) { EditorApplication.OpenScene("Assets/" + l.Replace("Stage: ", "")); } break; } } } } static void OnHierarchyWindowItemGUI (int instanceID, Rect selectionRect) { var go = EditorUtility.InstanceIDToObject(instanceID) as GameObject; if(!go) return; var assembler = go.GetComponent<PrefabAssembler>(); if(!assembler) return; var size = GUI.skin.label.CalcSize(new GUIContent(go.name)); selectionRect.x += size.x; var label = new GUIContent("[P]"); var color = new Color(0.15f, 0.15f, 0.15f, 1f); if(!assembler.prefab) { label = new GUIContent("[X]"); color = new Color(1f, 0.25f, 0.25f, 1f); } size = GUI.skin.label.CalcSize(label); selectionRect.width = size.x; EditorGUIUtility.AddCursorRect(selectionRect, MouseCursor.Link); GUI.color = color; GUI.Label(selectionRect, label); GUI.color = Color.white; if(selectionRect.Contains(Event.current.mousePosition)) { if(Event.current.type == EventType.MouseDown && Event.current.button == 0) { if(assembler.prefab) { EditorGUIUtility.PingObject(assembler.prefab); } else { BrowsePrefabPath(assembler); } } if((Event.current.type == EventType.MouseDown && Event.current.button == 2) || (Event.current.type == EventType.MouseDown && Event.current.button == 0 && Event.current.command)) { if(assembler.prefab) { PrefabAssemblerUtility.Assemble(new PrefabAssembler[]{assembler}); } else { BrowsePrefabPath(assembler); } } } } static void BrowsePrefabPath (PrefabAssembler assembler) { var curPath = assembler.prefab ? AssetDatabase.GetAssetPath(assembler.prefab) : !string.IsNullOrEmpty(EditorApplication.currentScene) ? EditorApplication.currentScene : "Assets/"; var newPath = EditorUtility.SaveFilePanelInProject("Pick Prefab Path", assembler.name, "prefab", "Pick a location to save the prefab.", curPath); if(newPath != null && newPath != "" && newPath != curPath) { PrefabAssemblerUtility.SetAssemblerTarget(assembler, newPath); } } void OnEnable () { while(UnityEditorInternal.ComponentUtility.MoveComponentUp((Component)target)); } public override void OnInspectorGUI () { EditorGUIUtility.fieldWidth = 100; EditorGUIUtility.labelWidth = 60; serializedObject.Update(); var assemblers = new PrefabAssembler[targets.Length]; for(int i = 0; i < assemblers.Length; i++) { assemblers[i] = (PrefabAssembler)targets[i]; } GUILayout.Space(5); if(assemblers.Length == 1) { var assembler = assemblers[0]; EditorGUILayout.BeginHorizontal(); GUILayout.Space(14); DrawPrefabField(assembler); if(GUILayout.Button("Browse", GUILayout.Width(60))) { BrowsePrefabPath(assembler); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Space(12); EditorGUILayout.BeginVertical(); AdvancedSettings(); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } else { for(int i = 0; i < assemblers.Length; i++) { var assembler = assemblers[i]; EditorGUILayout.BeginHorizontal(); GUILayout.Space(14); DrawPrefabField(assembler); EditorGUILayout.EndHorizontal(); } } serializedObject.ApplyModifiedProperties(); } void DrawPrefabField (PrefabAssembler assembler) { if(!assembler.prefab) { EditorGUILayout.LabelField("Target:", "None Assigned"); } else { EditorGUILayout.ObjectField("Target:", assembler.prefab, typeof(GameObject), false); } } void AdvancedSettings () { var priority = serializedObject.FindProperty("priority"); EditorGUILayout.BeginHorizontal(); { priority.intValue = EditorGUILayout.IntField("Priority:", priority.intValue); if(GUILayout.Button("-", GUILayout.Width(23))) { priority.intValue--; } if(GUILayout.Button("+", GUILayout.Width(23))) { priority.intValue++; } } EditorGUILayout.EndHorizontal(); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: client/conf_test_primitive.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 UF.Config { /// <summary>Holder for reflection information generated from client/conf_test_primitive.proto</summary> public static partial class ConfTestPrimitiveReflection { #region Descriptor /// <summary>File descriptor for client/conf_test_primitive.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ConfTestPrimitiveReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiBjbGllbnQvY29uZl90ZXN0X3ByaW1pdGl2ZS5wcm90bxIGY2xpZW50Io0B", "ChFDb25mVGVzdFByaW1pdGl2ZRIMCgRtSW50GAEgASgFEg4KBm1GbG9hdBgC", "IAEoAhIPCgdtRG91YmxlGAMgASgBEg0KBW1Cb29sGAQgASgIEg0KBW1CeXRl", "GAUgASgFEg4KBm1TaG9ydBgGIAEoBRINCgVtTG9uZxgHIAEoAxIMCgRtU3Ry", "GAggASgJQgyqAglVRi5Db25maWdiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::UF.Config.ConfTestPrimitive), global::UF.Config.ConfTestPrimitive.Parser, new[]{ "MInt", "MFloat", "MDouble", "MBool", "MByte", "MShort", "MLong", "MStr" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ConfTestPrimitive : pb::IMessage<ConfTestPrimitive> { private static readonly pb::MessageParser<ConfTestPrimitive> _parser = new pb::MessageParser<ConfTestPrimitive>(() => new ConfTestPrimitive()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConfTestPrimitive> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::UF.Config.ConfTestPrimitiveReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConfTestPrimitive() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConfTestPrimitive(ConfTestPrimitive other) : this() { mInt_ = other.mInt_; mFloat_ = other.mFloat_; mDouble_ = other.mDouble_; mBool_ = other.mBool_; mByte_ = other.mByte_; mShort_ = other.mShort_; mLong_ = other.mLong_; mStr_ = other.mStr_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConfTestPrimitive Clone() { return new ConfTestPrimitive(this); } /// <summary>Field number for the "mInt" field.</summary> public const int MIntFieldNumber = 1; private int mInt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MInt { get { return mInt_; } set { mInt_ = value; } } /// <summary>Field number for the "mFloat" field.</summary> public const int MFloatFieldNumber = 2; private float mFloat_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public float MFloat { get { return mFloat_; } set { mFloat_ = value; } } /// <summary>Field number for the "mDouble" field.</summary> public const int MDoubleFieldNumber = 3; private double mDouble_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double MDouble { get { return mDouble_; } set { mDouble_ = value; } } /// <summary>Field number for the "mBool" field.</summary> public const int MBoolFieldNumber = 4; private bool mBool_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool MBool { get { return mBool_; } set { mBool_ = value; } } /// <summary>Field number for the "mByte" field.</summary> public const int MByteFieldNumber = 5; private int mByte_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MByte { get { return mByte_; } set { mByte_ = value; } } /// <summary>Field number for the "mShort" field.</summary> public const int MShortFieldNumber = 6; private int mShort_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MShort { get { return mShort_; } set { mShort_ = value; } } /// <summary>Field number for the "mLong" field.</summary> public const int MLongFieldNumber = 7; private long mLong_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long MLong { get { return mLong_; } set { mLong_ = value; } } /// <summary>Field number for the "mStr" field.</summary> public const int MStrFieldNumber = 8; private string mStr_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MStr { get { return mStr_; } set { mStr_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConfTestPrimitive); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConfTestPrimitive other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MInt != other.MInt) return false; if (MFloat != other.MFloat) return false; if (MDouble != other.MDouble) return false; if (MBool != other.MBool) return false; if (MByte != other.MByte) return false; if (MShort != other.MShort) return false; if (MLong != other.MLong) return false; if (MStr != other.MStr) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (MInt != 0) hash ^= MInt.GetHashCode(); if (MFloat != 0F) hash ^= MFloat.GetHashCode(); if (MDouble != 0D) hash ^= MDouble.GetHashCode(); if (MBool != false) hash ^= MBool.GetHashCode(); if (MByte != 0) hash ^= MByte.GetHashCode(); if (MShort != 0) hash ^= MShort.GetHashCode(); if (MLong != 0L) hash ^= MLong.GetHashCode(); if (MStr.Length != 0) hash ^= MStr.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 (MInt != 0) { output.WriteRawTag(8); output.WriteInt32(MInt); } if (MFloat != 0F) { output.WriteRawTag(21); output.WriteFloat(MFloat); } if (MDouble != 0D) { output.WriteRawTag(25); output.WriteDouble(MDouble); } if (MBool != false) { output.WriteRawTag(32); output.WriteBool(MBool); } if (MByte != 0) { output.WriteRawTag(40); output.WriteInt32(MByte); } if (MShort != 0) { output.WriteRawTag(48); output.WriteInt32(MShort); } if (MLong != 0L) { output.WriteRawTag(56); output.WriteInt64(MLong); } if (MStr.Length != 0) { output.WriteRawTag(66); output.WriteString(MStr); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (MInt != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MInt); } if (MFloat != 0F) { size += 1 + 4; } if (MDouble != 0D) { size += 1 + 8; } if (MBool != false) { size += 1 + 1; } if (MByte != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MByte); } if (MShort != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MShort); } if (MLong != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(MLong); } if (MStr.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MStr); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConfTestPrimitive other) { if (other == null) { return; } if (other.MInt != 0) { MInt = other.MInt; } if (other.MFloat != 0F) { MFloat = other.MFloat; } if (other.MDouble != 0D) { MDouble = other.MDouble; } if (other.MBool != false) { MBool = other.MBool; } if (other.MByte != 0) { MByte = other.MByte; } if (other.MShort != 0) { MShort = other.MShort; } if (other.MLong != 0L) { MLong = other.MLong; } if (other.MStr.Length != 0) { MStr = other.MStr; } } [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: { MInt = input.ReadInt32(); break; } case 21: { MFloat = input.ReadFloat(); break; } case 25: { MDouble = input.ReadDouble(); break; } case 32: { MBool = input.ReadBool(); break; } case 40: { MByte = input.ReadInt32(); break; } case 48: { MShort = input.ReadInt32(); break; } case 56: { MLong = input.ReadInt64(); break; } case 66: { MStr = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using Google.Apis.Bigquery.v2.Data; using System; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.BigQuery.V2 { public abstract partial class BigQueryClient { #region GetDataset (autogenerated - do not edit manually) /// <summary> /// Retrieves the specified dataset within this client's project. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetDataset(DatasetReference, GetDatasetOptions)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The requested dataset.</returns> public virtual BigQueryDataset GetDataset(string datasetId, GetDatasetOptions options = null) => GetDataset(GetDatasetReference(datasetId), options); /// <summary> /// Retrieves the specified dataset. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetDataset(DatasetReference, GetDatasetOptions)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The requested dataset.</returns> public virtual BigQueryDataset GetDataset(string projectId, string datasetId, GetDatasetOptions options = null) => GetDataset(GetDatasetReference(projectId, datasetId), options); /// <summary> /// Retrieves the specified dataset. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The requested dataset.</returns> public virtual BigQueryDataset GetDataset(DatasetReference datasetReference, GetDatasetOptions options = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously retrieves the specified dataset within this client's project. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetDatasetAsync(DatasetReference, GetDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the requested dataset.</returns> public virtual Task<BigQueryDataset> GetDatasetAsync(string datasetId, GetDatasetOptions options = null, CancellationToken cancellationToken = default) => GetDatasetAsync(GetDatasetReference(datasetId), options, cancellationToken); /// <summary> /// Asynchronously retrieves the specified dataset. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetDatasetAsync(DatasetReference, GetDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the requested dataset.</returns> public virtual Task<BigQueryDataset> GetDatasetAsync(string projectId, string datasetId, GetDatasetOptions options = null, CancellationToken cancellationToken = default) => GetDatasetAsync(GetDatasetReference(projectId, datasetId), options, cancellationToken); /// <summary> /// Asynchronously retrieves the specified dataset. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the requested dataset.</returns> public virtual Task<BigQueryDataset> GetDatasetAsync(DatasetReference datasetReference, GetDatasetOptions options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion #region ListDatasets /// <summary> /// Lists the datasets within this client's project. /// This method just creates a <see cref="ProjectReference"/> and delegates to <see cref="ListDatasets(ProjectReference, ListDatasetsOptions)"/>. /// </summary> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>A sequence of datasets within this project.</returns> public virtual PagedEnumerable<DatasetList, BigQueryDataset> ListDatasets(ListDatasetsOptions options = null) => ListDatasets(GetProjectReference(ProjectId), options); /// <summary> /// Lists the datasets within the specified project. /// This method just creates a <see cref="ProjectReference"/> and delegates to <see cref="ListDatasets(ProjectReference, ListDatasetsOptions)"/>. /// </summary> /// <param name="projectId">The project to list the datasets from. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>A sequence of datasets within the specified project.</returns> public virtual PagedEnumerable<DatasetList, BigQueryDataset> ListDatasets(string projectId, ListDatasetsOptions options = null) => ListDatasets(GetProjectReference(projectId), options); /// <summary> /// Lists the datasets within the specified project. /// </summary> /// <param name="projectReference">A fully-qualified identifier for the project. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>A sequence of datasets within the specified project.</returns> public virtual PagedEnumerable<DatasetList, BigQueryDataset> ListDatasets(ProjectReference projectReference, ListDatasetsOptions options = null) { throw new NotImplementedException(); } /// <summary> /// Asynchronously lists the datasets within this client's project. /// This method just creates a <see cref="ProjectReference"/> and delegates to <see cref="ListDatasetsAsync(ProjectReference, ListDatasetsOptions)"/>. /// </summary> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>An asynchronous sequence of datasets within this project.</returns> public virtual PagedAsyncEnumerable<DatasetList, BigQueryDataset> ListDatasetsAsync(ListDatasetsOptions options = null) => ListDatasetsAsync(GetProjectReference(ProjectId), options); /// <summary> /// Asynchronously lists the datasets within the specified project. /// This method just creates a <see cref="ProjectReference"/> and delegates to <see cref="ListDatasetsAsync(ProjectReference, ListDatasetsOptions)"/>. /// </summary> /// <param name="projectId">The project to list the datasets from. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>An asynchronous sequence of datasets within the specified project.</returns> public virtual PagedAsyncEnumerable<DatasetList, BigQueryDataset> ListDatasetsAsync(string projectId, ListDatasetsOptions options = null) => ListDatasetsAsync(GetProjectReference(projectId), options); /// <summary> /// Asynchronously lists the datasets within the specified project. /// </summary> /// <param name="projectReference">A fully-qualified identifier for the project. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>An asynchronous sequence of datasets within the specified project.</returns> public virtual PagedAsyncEnumerable<DatasetList, BigQueryDataset> ListDatasetsAsync(ProjectReference projectReference, ListDatasetsOptions options = null) { throw new NotImplementedException(); } #endregion #region CreateDataset (autogenerated - do not edit manually) /// <summary> /// Creates the specified dataset within this client's project. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="CreateDataset(DatasetReference, CreateDatasetOptions)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The created dataset.</returns> public virtual BigQueryDataset CreateDataset(string datasetId, CreateDatasetOptions options = null) => CreateDataset(GetDatasetReference(datasetId), options); /// <summary> /// Creates the specified dataset. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="CreateDataset(DatasetReference, CreateDatasetOptions)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The created dataset.</returns> public virtual BigQueryDataset CreateDataset(string projectId, string datasetId, CreateDatasetOptions options = null) => CreateDataset(GetDatasetReference(projectId, datasetId), options); /// <summary> /// Creates the specified dataset. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The created dataset.</returns> public virtual BigQueryDataset CreateDataset(DatasetReference datasetReference, CreateDatasetOptions options = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously creates the specified dataset within this client's project. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="CreateDatasetAsync(DatasetReference, CreateDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the created dataset.</returns> public virtual Task<BigQueryDataset> CreateDatasetAsync(string datasetId, CreateDatasetOptions options = null, CancellationToken cancellationToken = default) => CreateDatasetAsync(GetDatasetReference(datasetId), options, cancellationToken); /// <summary> /// Asynchronously creates the specified dataset. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="CreateDatasetAsync(DatasetReference, CreateDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the created dataset.</returns> public virtual Task<BigQueryDataset> CreateDatasetAsync(string projectId, string datasetId, CreateDatasetOptions options = null, CancellationToken cancellationToken = default) => CreateDatasetAsync(GetDatasetReference(projectId, datasetId), options, cancellationToken); /// <summary> /// Asynchronously creates the specified dataset. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the created dataset.</returns> public virtual Task<BigQueryDataset> CreateDatasetAsync(DatasetReference datasetReference, CreateDatasetOptions options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion #region GetOrCreateDataset (autogenerated - do not edit manually) /// <summary> /// Attempts to fetch the specified dataset within this client's project, creating it if it doesn't exist. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetOrCreateDataset(DatasetReference, GetDatasetOptions, CreateDatasetOptions)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="getOptions">The options for the "get" operation. May be null, in which case defaults will be supplied.</param> /// <param name="createOptions">The options for the "create" operation. May be null, in which case defaults will be supplied.</param> /// <returns>The existing or new dataset.</returns> public virtual BigQueryDataset GetOrCreateDataset(string datasetId, GetDatasetOptions getOptions = null, CreateDatasetOptions createOptions = null) => GetOrCreateDataset(GetDatasetReference(datasetId), getOptions, createOptions); /// <summary> /// Attempts to fetch the specified dataset, creating it if it doesn't exist. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetOrCreateDataset(DatasetReference, GetDatasetOptions, CreateDatasetOptions)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="getOptions">The options for the "get" operation. May be null, in which case defaults will be supplied.</param> /// <param name="createOptions">The options for the "create" operation. May be null, in which case defaults will be supplied.</param> /// <returns>The existing or new dataset.</returns> public virtual BigQueryDataset GetOrCreateDataset(string projectId, string datasetId, GetDatasetOptions getOptions = null, CreateDatasetOptions createOptions = null) => GetOrCreateDataset(GetDatasetReference(projectId, datasetId), getOptions, createOptions); /// <summary> /// Attempts to fetch the specified dataset, creating it if it doesn't exist. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="getOptions">The options for the "get" operation. May be null, in which case defaults will be supplied.</param> /// <param name="createOptions">The options for the "create" operation. May be null, in which case defaults will be supplied.</param> /// <returns>The existing or new dataset.</returns> public virtual BigQueryDataset GetOrCreateDataset(DatasetReference datasetReference, GetDatasetOptions getOptions = null, CreateDatasetOptions createOptions = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously attempts to fetch the specified dataset within this client's project, creating it if it doesn't exist. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetOrCreateDatasetAsync(DatasetReference, GetDatasetOptions, CreateDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="getOptions">The options for the "get" operation. May be null, in which case defaults will be supplied.</param> /// <param name="createOptions">The options for the "create" operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the existing or new dataset.</returns> public virtual Task<BigQueryDataset> GetOrCreateDatasetAsync(string datasetId, GetDatasetOptions getOptions = null, CreateDatasetOptions createOptions = null, CancellationToken cancellationToken = default) => GetOrCreateDatasetAsync(GetDatasetReference(datasetId), getOptions, createOptions, cancellationToken); /// <summary> /// Asynchronously attempts to fetch the specified dataset, creating it if it doesn't exist. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="GetOrCreateDatasetAsync(DatasetReference, GetDatasetOptions, CreateDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="getOptions">The options for the "get" operation. May be null, in which case defaults will be supplied.</param> /// <param name="createOptions">The options for the "create" operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the existing or new dataset.</returns> public virtual Task<BigQueryDataset> GetOrCreateDatasetAsync(string projectId, string datasetId, GetDatasetOptions getOptions = null, CreateDatasetOptions createOptions = null, CancellationToken cancellationToken = default) => GetOrCreateDatasetAsync(GetDatasetReference(projectId, datasetId), getOptions, createOptions, cancellationToken); /// <summary> /// Asynchronously attempts to fetch the specified dataset, creating it if it doesn't exist. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="getOptions">The options for the "get" operation. May be null, in which case defaults will be supplied.</param> /// <param name="createOptions">The options for the "create" operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the existing or new dataset.</returns> public virtual Task<BigQueryDataset> GetOrCreateDatasetAsync(DatasetReference datasetReference, GetDatasetOptions getOptions = null, CreateDatasetOptions createOptions = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion #region DeleteDataset (autogenerated - do not edit manually) /// <summary> /// Deletes the specified dataset within this client's project. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="DeleteDataset(DatasetReference, DeleteDatasetOptions)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> public virtual void DeleteDataset(string datasetId, DeleteDatasetOptions options = null) => DeleteDataset(GetDatasetReference(datasetId), options); /// <summary> /// Deletes the specified dataset. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="DeleteDataset(DatasetReference, DeleteDatasetOptions)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> public virtual void DeleteDataset(string projectId, string datasetId, DeleteDatasetOptions options = null) => DeleteDataset(GetDatasetReference(projectId, datasetId), options); /// <summary> /// Deletes the specified dataset. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> public virtual void DeleteDataset(DatasetReference datasetReference, DeleteDatasetOptions options = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously deletes the specified dataset within this client's project. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="DeleteDatasetAsync(DatasetReference, DeleteDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation.</returns> public virtual Task DeleteDatasetAsync(string datasetId, DeleteDatasetOptions options = null, CancellationToken cancellationToken = default) => DeleteDatasetAsync(GetDatasetReference(datasetId), options, cancellationToken); /// <summary> /// Asynchronously deletes the specified dataset. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="DeleteDatasetAsync(DatasetReference, DeleteDatasetOptions, CancellationToken)"/>. /// </summary> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation.</returns> public virtual Task DeleteDatasetAsync(string projectId, string datasetId, DeleteDatasetOptions options = null, CancellationToken cancellationToken = default) => DeleteDatasetAsync(GetDatasetReference(projectId, datasetId), options, cancellationToken); /// <summary> /// Asynchronously deletes the specified dataset. /// </summary> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation.</returns> public virtual Task DeleteDatasetAsync(DatasetReference datasetReference, DeleteDatasetOptions options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion #region UpdateDataset (autogenerated - do not edit manually) /// <summary> /// Updates the specified dataset within this client's project to match the specified resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="UpdateDataset(DatasetReference, Dataset, UpdateDatasetOptions)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the update. All updatable fields will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The updated dataset.</returns> public virtual BigQueryDataset UpdateDataset(string datasetId, Dataset resource, UpdateDatasetOptions options = null) => UpdateDataset(GetDatasetReference(datasetId), resource, options); /// <summary> /// Updates the specified dataset to match the specified resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="UpdateDataset(DatasetReference, Dataset, UpdateDatasetOptions)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the update. All updatable fields will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The updated dataset.</returns> public virtual BigQueryDataset UpdateDataset(string projectId, string datasetId, Dataset resource, UpdateDatasetOptions options = null) => UpdateDataset(GetDatasetReference(projectId, datasetId), resource, options); /// <summary> /// Updates the specified dataset to match the specified resource. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the update. All updatable fields will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The updated dataset.</returns> public virtual BigQueryDataset UpdateDataset(DatasetReference datasetReference, Dataset resource, UpdateDatasetOptions options = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously updates the specified dataset within this client's project to match the specified resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="UpdateDatasetAsync(DatasetReference, Dataset, UpdateDatasetOptions, CancellationToken)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the update. All updatable fields will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the updated dataset.</returns> public virtual Task<BigQueryDataset> UpdateDatasetAsync(string datasetId, Dataset resource, UpdateDatasetOptions options = null, CancellationToken cancellationToken = default) => UpdateDatasetAsync(GetDatasetReference(datasetId), resource, options, cancellationToken); /// <summary> /// Asynchronously updates the specified dataset to match the specified resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="UpdateDatasetAsync(DatasetReference, Dataset, UpdateDatasetOptions, CancellationToken)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the update. All updatable fields will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the updated dataset.</returns> public virtual Task<BigQueryDataset> UpdateDatasetAsync(string projectId, string datasetId, Dataset resource, UpdateDatasetOptions options = null, CancellationToken cancellationToken = default) => UpdateDatasetAsync(GetDatasetReference(projectId, datasetId), resource, options, cancellationToken); /// <summary> /// Asynchronously updates the specified dataset to match the specified resource. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the update. All updatable fields will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the updated dataset.</returns> public virtual Task<BigQueryDataset> UpdateDatasetAsync(DatasetReference datasetReference, Dataset resource, UpdateDatasetOptions options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion #region PatchDataset (autogenerated - do not edit manually) /// <summary> /// Patches the specified dataset within this client's project with fields in the given resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="PatchDataset(DatasetReference, Dataset, PatchDatasetOptions)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the patch. Only fields present in the resource will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The updated dataset.</returns> public virtual BigQueryDataset PatchDataset(string datasetId, Dataset resource, PatchDatasetOptions options = null) => PatchDataset(GetDatasetReference(datasetId), resource, options); /// <summary> /// Patches the specified dataset with fields in the given resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="PatchDataset(DatasetReference, Dataset, PatchDatasetOptions)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the patch. Only fields present in the resource will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The updated dataset.</returns> public virtual BigQueryDataset PatchDataset(string projectId, string datasetId, Dataset resource, PatchDatasetOptions options = null) => PatchDataset(GetDatasetReference(projectId, datasetId), resource, options); /// <summary> /// Patches the specified dataset with fields in the given resource. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the patch. Only fields present in the resource will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <returns>The updated dataset.</returns> public virtual BigQueryDataset PatchDataset(DatasetReference datasetReference, Dataset resource, PatchDatasetOptions options = null) => throw new NotImplementedException(); /// <summary> /// Asynchronously patches the specified dataset within this client's project with fields in the given resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="PatchDatasetAsync(DatasetReference, Dataset, PatchDatasetOptions, CancellationToken)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the patch. Only fields present in the resource will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the updated dataset.</returns> public virtual Task<BigQueryDataset> PatchDatasetAsync(string datasetId, Dataset resource, PatchDatasetOptions options = null, CancellationToken cancellationToken = default) => PatchDatasetAsync(GetDatasetReference(datasetId), resource, options, cancellationToken); /// <summary> /// Asynchronously patches the specified dataset with fields in the given resource. /// This method just creates a <see cref="DatasetReference"/> and delegates to <see cref="PatchDatasetAsync(DatasetReference, Dataset, PatchDatasetOptions, CancellationToken)"/>. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="projectId">The project ID. Must not be null.</param> /// <param name="datasetId">The dataset ID. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the patch. Only fields present in the resource will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the updated dataset.</returns> public virtual Task<BigQueryDataset> PatchDatasetAsync(string projectId, string datasetId, Dataset resource, PatchDatasetOptions options = null, CancellationToken cancellationToken = default) => PatchDatasetAsync(GetDatasetReference(projectId, datasetId), resource, options, cancellationToken); /// <summary> /// Asynchronously patches the specified dataset with fields in the given resource. /// </summary> /// <remarks> /// If the resource contains an ETag, it is used for optimistic concurrency validation. /// </remarks> /// <param name="datasetReference">A fully-qualified identifier for the dataset. Must not be null.</param> /// <param name="resource">The dataset resource representation to use for the patch. Only fields present in the resource will be updated.</param> /// <param name="options">The options for the operation. May be null, in which case defaults will be supplied.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task representing the asynchronous operation. When complete, the result is /// the updated dataset.</returns> public virtual Task<BigQueryDataset> PatchDatasetAsync(DatasetReference datasetReference, Dataset resource, PatchDatasetOptions options = null, CancellationToken cancellationToken = default) => throw new NotImplementedException(); #endregion } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com) 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. * 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. */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Xml; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using System.IO; namespace Prebuild.Core.Nodes { /// <summary> /// /// </summary> [DataNode("Files")] public class FilesNode : DataNode { #region Fields private readonly List<string> m_Files = new List<string>(); private readonly Dictionary<string,BuildAction> m_BuildActions = new Dictionary<string, BuildAction>(); private readonly Dictionary<string, SubType> m_SubTypes = new Dictionary<string, SubType>(); private readonly Dictionary<string, string> m_ResourceNames = new Dictionary<string, string>(); private readonly Dictionary<string, CopyToOutput> m_CopyToOutputs = new Dictionary<string, CopyToOutput>(); private readonly Dictionary<string, bool> m_Links = new Dictionary<string, bool>(); private readonly Dictionary<string, string> m_LinkPaths = new Dictionary<string, string>(); private readonly Dictionary<string, bool> m_PreservePaths = new Dictionary<string, bool>(); private readonly Dictionary<string, string> m_DestinationPath = new Dictionary<string, string>(); private readonly NameValueCollection m_CopyFiles = new NameValueCollection(); #endregion #region Properties public int Count { get { return m_Files.Count; } } public string[] Destinations { get { return m_CopyFiles.AllKeys; } } public int CopyFiles { get { return m_CopyFiles.Count; } } #endregion #region Public Methods public BuildAction GetBuildAction(string file) { if(!m_BuildActions.ContainsKey(file)) { return BuildAction.Compile; } return m_BuildActions[file]; } public string GetDestinationPath(string file) { if( !m_DestinationPath.ContainsKey(file)) { return null; } return m_DestinationPath[file]; } public string[] SourceFiles(string dest) { return m_CopyFiles.GetValues(dest); } public CopyToOutput GetCopyToOutput(string file) { if (!m_CopyToOutputs.ContainsKey(file)) { return CopyToOutput.Never; } return m_CopyToOutputs[file]; } public bool GetIsLink(string file) { if (!m_Links.ContainsKey(file)) { return false; } return m_Links[file]; } public bool Contains(string file) { return m_Files.Contains(file); } public string GetLinkPath( string file ) { if ( !m_LinkPaths.ContainsKey( file ) ) { return string.Empty; } return m_LinkPaths[ file ]; } public SubType GetSubType(string file) { if(!m_SubTypes.ContainsKey(file)) { return SubType.Code; } return m_SubTypes[file]; } public string GetResourceName(string file) { if(!m_ResourceNames.ContainsKey(file)) { return string.Empty; } return m_ResourceNames[file]; } public bool GetPreservePath( string file ) { if ( !m_PreservePaths.ContainsKey( file ) ) { return false; } return m_PreservePaths[ file ]; } public override void Parse(XmlNode node) { if( node == null ) { throw new ArgumentNullException("node"); } foreach(XmlNode child in node.ChildNodes) { IDataNode dataNode = Kernel.Instance.ParseNode(child, this); if(dataNode is FileNode) { FileNode fileNode = (FileNode)dataNode; if(fileNode.IsValid) { if (!m_Files.Contains(fileNode.Path)) { m_Files.Add(fileNode.Path); m_BuildActions[fileNode.Path] = fileNode.BuildAction; m_SubTypes[fileNode.Path] = fileNode.SubType; m_ResourceNames[fileNode.Path] = fileNode.ResourceName; m_PreservePaths[ fileNode.Path ] = fileNode.PreservePath; m_Links[ fileNode.Path ] = fileNode.IsLink; m_LinkPaths[ fileNode.Path ] = fileNode.LinkPath; m_CopyToOutputs[ fileNode.Path ] = fileNode.CopyToOutput; } } } else if(dataNode is MatchNode) { foreach(string file in ((MatchNode)dataNode).Files) { MatchNode matchNode = (MatchNode)dataNode; if (!m_Files.Contains(file)) { m_Files.Add(file); if (matchNode.BuildAction == null) m_BuildActions[file] = GetBuildActionByFileName(file); else m_BuildActions[file] = matchNode.BuildAction.Value; if (matchNode.BuildAction == BuildAction.Copy) { m_CopyFiles.Add(matchNode.DestinationPath, file); m_DestinationPath[file] = matchNode.DestinationPath; } m_SubTypes[file] = matchNode.SubType == null ? GetSubTypeByFileName(file) : matchNode.SubType.Value; m_ResourceNames[ file ] = matchNode.ResourceName; m_PreservePaths[ file ] = matchNode.PreservePath; m_Links[ file ] = matchNode.IsLink; m_LinkPaths[ file ] = matchNode.LinkPath; m_CopyToOutputs[ file ] = matchNode.CopyToOutput; } } } } } // TODO: Check in to why StringCollection's enumerator doesn't implement // IEnumerator? public IEnumerator<string> GetEnumerator() { return m_Files.GetEnumerator(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace MongoInClustorWithFailover.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System.Threading.Tasks; using CSharpGuidelinesAnalyzer.Rules.Naming; using CSharpGuidelinesAnalyzer.Test.TestDataBuilders; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace CSharpGuidelinesAnalyzer.Test.Specs.Naming { public sealed class SuffixAsyncMethodCorrectlySpecs : CSharpGuidelinesAnalysisTestFixture { protected override string DiagnosticId => SuffixAsyncMethodCorrectlyAnalyzer.DiagnosticId; [Fact] internal void When_async_method_name_ends_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" async Task SomeAsync() { throw new NotImplementedException(); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_async_method_name_ends_with_TaskAsync_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" async Task SomeTaskAsync() { throw new NotImplementedException(); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_async_method_name_does_not_end_with_Async_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(Task).Namespace) .InGlobalScope(@" class C { async Task [|Some|]() { throw new NotImplementedException(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Name of async method 'C.Some()' should end with Async or TaskAsync"); } [Fact] internal void When_regular_method_name_does_not_end_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" Task Some() { throw new NotImplementedException(); } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_async_local_function_name_ends_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" void M() { async Task SomeAsync() { throw new NotImplementedException(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_async_local_function_name_ends_with_TaskAsync_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" void M() { async Task SomeTaskAsync() { throw new NotImplementedException(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_async_local_function_name_does_not_end_with_Async_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" void M() { async Task [|Some|]() { throw new NotImplementedException(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Name of async local function 'Some()' should end with Async or TaskAsync"); } [Fact] internal void When_regular_local_function_name_does_not_end_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(Task).Namespace) .InDefaultClass(@" void M() { Task Some() { throw new NotImplementedException(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_async_entry_point_method_name_does_not_end_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(Task).Namespace) .WithOutputKind(OutputKind.WindowsApplication) .InGlobalScope(@" class Program { static async Task Main(string[] args) { throw new NotImplementedException(); } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_test_method_name_does_not_end_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(Task).Namespace) .InGlobalScope(@" namespace Xunit { public class FactAttribute : Attribute { } } namespace App { using Xunit; class UnitTests { [Fact] public async Task When_some_condition_it_must_work() { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_parameterized_test_method_name_does_not_end_with_Async_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .Using(typeof(Task).Namespace) .InGlobalScope(@" namespace Xunit { public class TheoryAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class InlineDataAttribute : Attribute { public InlineDataAttribute(params object[] data) { } } } namespace App { using Xunit; class UnitTests { [InlineData(""A"")] [InlineData(""B"")] [Theory] public async Task When_some_condition_it_must_work(string value) { _ = value; } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } protected override DiagnosticAnalyzer CreateAnalyzer() { return new SuffixAsyncMethodCorrectlyAnalyzer(); } } }
using System; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; [CustomEditor(typeof(CreatePalette))] public class CreatePaletteEditor : Editor { private const int ColorSquares = 16; private const int MaxColors = 256; private CreatePalette script; public override void OnInspectorGUI() { base.OnInspectorGUI(); script = (CreatePalette)target; if (GUILayout.Button("Create color palette from .PNG")) CreatePalette(); } /// <summary> /// Creates and saves a palette image from the unique colors in another image. /// /// The palette image structure: /// /// | | | | | | | | row of 16 16x16 squares with the third mix color /// |__|__|__|__|__|__|__|__ /// | | | | | | | | row of 16 16x16 squares with the second mix color /// |__|__|__|__|__|__|__|__ /// | | | | | | | | row of 16 16x16 squares with the first mix color /// |__|__|__|__|__|__|__|__ /// /// Each horizontal square has a fixed Red component: 0/15 to 15/15. /// The blue component increases from 0 to 1 horizontally over a square. /// The green component increases from 0 to 1 vertically over a square. /// /// The palette image is used in the shaders to convert a truecolor to several dithered colors. /// The truecolor RGB components points to N colors in the palette, one color per row of squares. /// The N colors are mixed together in a dithering pattern to produce a close approximation of the original truecolor. /// /// The steps to create the palette image: /// /// 1. Load the color image to a Texture2D /// 2. Create a list of all the unique colors in the color image /// 3. Create the palette image /// 4. a) Loop through each pixel in the palette image and determine the truecolor for that pixel /// b) Device a mixing plan to achieve the truecolor /// c) Save the N colors in the square column /// 5. Save the palette image /// </summary> private void CreatePalette() { if (script.MixedColorCount < 1) return; // Load the color image to a Texture2D Texture2D colorTexture = LoadTexture(); if (colorTexture == null) return; // Create a list of all the unique colors in the color image List<Color> paletteColors = new List<Color>(); bool proceed = false; for (int x = 0; x < colorTexture.width; x++) for (int y = 0; y < colorTexture.height; y++) if (!paletteColors.Contains(colorTexture.GetPixel(x, y))) { paletteColors.Add(colorTexture.GetPixel(x, y)); if (paletteColors.Count > MaxColors && !proceed) { proceed = EditorUtility.DisplayDialog("Error", "Source image contains more than " + MaxColors + " colors. Continuing may lock up Unity for a long time", "Continue", "Stop"); if (!proceed) return; } } uint[] palette = new uint[paletteColors.Count]; for (int i = 0; i < paletteColors.Count; i++) palette[i] = ColorToInt(paletteColors[i]); MixingPlanner mixingPlanner = new MixingPlanner(palette); // Create the palette image int height = (int)Math.Pow(2, Math.Ceiling(Math.Log(ColorSquares * script.MixedColorCount - 1) / Math.Log(2))); Texture2D paletteTexture = new Texture2D(ColorSquares * ColorSquares, height, TextureFormat.RGB24, false); paletteTexture.name = colorTexture.name + "_pal_" + script.MixedColorCount; // Loop through each pixel in the palette image and determine the target color for that pixel for (int x = 0; x < ColorSquares * ColorSquares; x++) for (int y = 0; y < ColorSquares; y++) { byte r = (byte)((float)(x / ColorSquares) / (ColorSquares - 1) * 255); byte g = (byte)((float)y / (ColorSquares - 1) * 255); byte b = (byte)(((float)x % ColorSquares) / (ColorSquares - 1) * 255); uint targetColor = (uint)((r << 16) + (g << 8) + b); // Device a mixing plan to achieve the truecolor uint[] mixingPlan = mixingPlanner.DeviseBestMixingPlan(targetColor, (uint)script.MixedColorCount); // Save the N colors in the square column for (int c = 0; c < script.MixedColorCount; c++) paletteTexture.SetPixel(x, y + (script.MixedColorCount - c - 1) * ColorSquares, paletteColors[(int)mixingPlan[c]]); } // Save the palette image SaveTexture(paletteTexture); } /// <summary> /// Opens a file dialog and loads a .png image to a Texture2D. /// </summary> private Texture2D LoadTexture() { string path = EditorUtility.OpenFilePanel("Select your .PNG color image", "", "png"); if (path.Length == 0) return null; Texture2D texture = new Texture2D(4, 4, TextureFormat.ARGB32, false); texture.name = Path.GetFileNameWithoutExtension(path); new WWW("file://" + path).LoadImageIntoTexture(texture); return texture; } /// <summary> /// Opens a file dialog and saves a Texture2D to a .png image. /// </summary> private void SaveTexture(Texture2D texture) { string path = EditorUtility.SaveFilePanel("Save your new .PNG palette image", "", texture.name + ".png", "png"); if (path.Length == 0) return; byte[] bytes = texture.EncodeToPNG(); File.WriteAllBytes(path, bytes); } private static uint ColorToInt(Color color) { return ((uint)(color.r * 255) << 16) + ((uint)(color.g * 255) << 8) + (uint)(color.b * 255); } /// <summary> /// The mixing planner is based on algorithms and code by Joel Yliluoma. /// http://bisqwit.iki.fi/story/howto/dither/jy/ /// </summary> private class MixingPlanner { private const double Gamma = 2.2; private uint[] palette; private uint[] luminance; private double[,] gammaCorrect; private double GammaCorrect(double v) { return Math.Pow(v, Gamma); } private double GammaUncorrect(double v) { return Math.Pow(v, 1.0 / Gamma); } public MixingPlanner(uint[] palette) { this.palette = palette; luminance = new uint[palette.Length]; gammaCorrect = new double[palette.Length, 3]; for (int i = 0; i < palette.Length; i++) { byte r = (byte)((palette[i] >> 16) & 0xff); byte g = (byte)((palette[i] >> 8) & 0xff); byte b = (byte)(palette[i] & 0xff); luminance[i] = (uint)(r * 299 + g * 587 + b * 114); gammaCorrect[i, 0] = GammaCorrect(r / 255.0); gammaCorrect[i, 1] = GammaCorrect(g / 255.0); gammaCorrect[i, 2] = GammaCorrect(b / 255.0); } } private double ColorCompare(byte r1, byte g1, byte b1, byte r2, byte g2, byte b2) { double luma1 = (r1 * 299 + g1 * 587 + b1 * 114) / (255.0 * 1000); double luma2 = (r2 * 299 + g2 * 587 + b2 * 114) / (255.0 * 1000); double lumadiff = luma1 - luma2; double diffR = (r1 - r2) / 255.0, diffG = (g1 - g2) / 255.0, diffB = (b1 - b2) / 255.0; return (diffR * diffR * 0.299 + diffG * diffG * 0.587 + diffB * diffB * 0.114) * 0.75 + lumadiff * lumadiff; } public uint[] DeviseBestMixingPlan(uint targetColor, uint colorCount) { byte[] inputRgb = new byte[] { (byte)((targetColor >> 16) & 0xff), (byte)((targetColor >> 8) & 0xff), (byte)(targetColor & 0xff) }; uint[] mixingPlan = new uint[colorCount]; if (palette.Length == 2) { // Use an alternative planning algorithm if the palette only has 2 colors uint[] soFar = new uint[] { 0, 0, 0 }; uint proportionTotal = 0; while (proportionTotal < colorCount) { uint chosenAmount = 1; uint chosen = 0; uint maxTestCount = Math.Max(1, proportionTotal); double leastPenalty = -1; for (uint i = 0; i < palette.Length; ++i) { uint color = palette[i]; uint[] sum = new uint[] { soFar[0], soFar[1], soFar[2] }; uint[] add = new uint[] { color >> 16, (color >> 8) & 0xff, color & 0xff }; for (uint p = 1; p <= maxTestCount; p *= 2) { for (uint c = 0; c < 3; ++c) sum[c] += add[c]; for (uint c = 0; c < 3; ++c) add[c] += add[c]; uint t = proportionTotal + p; uint[] test = new uint[] { sum[0] / t, sum[1] / t, sum[2] / t }; double penalty = ColorCompare((byte)inputRgb[0], (byte)inputRgb[1], (byte)inputRgb[2], (byte)test[0], (byte)test[1], (byte)test[2]); if (penalty < leastPenalty || leastPenalty < 0) { leastPenalty = penalty; chosen = i; chosenAmount = p; } } } for (uint p = 0; p < chosenAmount; ++p) { if (proportionTotal >= colorCount) break; mixingPlan[proportionTotal++] = chosen; } uint newColor = palette[chosen]; uint[] palcolor = new uint[] { newColor >> 16, (newColor >> 8) & 0xff, newColor & 0xff }; for (uint c = 0; c < 3; ++c) soFar[c] += palcolor[c] * chosenAmount; } } else { // Use the gamma corrected planning algorithm if the palette has more than 2 colors Dictionary<uint, uint> solution = new Dictionary<uint, uint>(); double currentPenalty = -1; uint chosenIndex = 0; for (uint i = 0; i < palette.Length; ++i) { byte r = (byte)((palette[i] >> 16) & 0xff); byte g = (byte)((palette[i] >> 8) & 0xff); byte b = (byte)(palette[i] & 0xff); double penalty = ColorCompare(inputRgb[0], inputRgb[1], inputRgb[2], r, g, b); if (penalty < currentPenalty || currentPenalty < 0) { currentPenalty = penalty; chosenIndex = i; } } solution[chosenIndex] = colorCount; double dblLimit = 1.0 / colorCount; while (currentPenalty != 0.0) { double bestPenalty = currentPenalty; uint bestSplitFrom = 0; uint[] bestSplitTo = new uint[] { 0, 0 }; foreach (KeyValuePair<uint, uint> i in solution) { uint splitColor = i.Key; uint splitCount = i.Value; double[] sum = new double[] { 0, 0, 0 }; foreach (KeyValuePair<uint, uint> j in solution) { if (j.Key == splitColor) continue; sum[0] += gammaCorrect[j.Key, 0] * j.Value * dblLimit; sum[1] += gammaCorrect[j.Key, 1] * j.Value * dblLimit; sum[2] += gammaCorrect[j.Key, 2] * j.Value * dblLimit; } double portion1 = (splitCount / 2) * dblLimit; double portion2 = (splitCount - splitCount / 2) * dblLimit; for (uint a = 0; a < palette.Length; ++a) { uint firstb = 0; if (portion1 == portion2) firstb = a + 1; for (uint b = firstb; b < palette.Length; ++b) { if (a == b) continue; int lumadiff = (int)(luminance[a]) - (int)(luminance[b]); if (lumadiff < 0) lumadiff = -lumadiff; if (lumadiff > 80000) continue; double[] test = new double[] { GammaUncorrect(sum[0] + gammaCorrect[a, 0] * portion1 + gammaCorrect[b, 0] * portion2), GammaUncorrect(sum[1] + gammaCorrect[a, 1] * portion1 + gammaCorrect[b, 1] * portion2), GammaUncorrect(sum[2] + gammaCorrect[a, 2] * portion1 + gammaCorrect[b, 2] * portion2) }; double penalty = ColorCompare(inputRgb[0], inputRgb[1], inputRgb[2], (byte)(test[0] * 255), (byte)(test[1] * 255), (byte)(test[2] * 255)); if (penalty < bestPenalty) { bestPenalty = penalty; bestSplitFrom = splitColor; bestSplitTo[0] = a; bestSplitTo[1] = b; } if (portion2 == 0) break; } } } if (bestPenalty == currentPenalty) break; uint splitC = solution[bestSplitFrom]; uint split1 = splitC / 2; uint split2 = splitC - split1; solution.Remove(bestSplitFrom); if (split1 > 0) solution[bestSplitTo[0]] = (solution.ContainsKey(bestSplitTo[0]) ? solution[bestSplitTo[0]] : 0) + split1; if (split2 > 0) solution[bestSplitTo[1]] = (solution.ContainsKey(bestSplitTo[1]) ? solution[bestSplitTo[1]] : 0) + split2; currentPenalty = bestPenalty; } uint n = 0; foreach (KeyValuePair<uint, uint> i in solution) for (uint c = 0; c < i.Value; c++) mixingPlan[n++] = i.Key; } // Sort the colors by luminance and return the mixing plan Array.Sort(mixingPlan, delegate(uint index1, uint index2) { return luminance[index1].CompareTo(luminance[index2]); }); return mixingPlan; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Contoso.Core.OneDriveCustomizerWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleMultiConnection.SampleMultiConnectionPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleMultiConnection { using System; using System.ComponentModel; using System.IO; using System.Windows; using Ecng.Common; using Ecng.Configuration; using Ecng.Serialization; using Ecng.Xaml; using StockSharp.Algo; using StockSharp.Algo.Storages; using StockSharp.Algo.Storages.Csv; using StockSharp.BusinessEntities; using StockSharp.Logging; using StockSharp.Configuration; using StockSharp.Localization; public partial class MainWindow { private bool _isConnected; public readonly Connector Connector; private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly StopOrderWindow _stopOrdersWindow = new StopOrderWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly TradesWindow _tradesWindow = new TradesWindow(); private const string _settingsFile = "connection.xml"; public MainWindow() { InitializeComponent(); Instance = this; Title = Title.Put("Multi connection"); _ordersWindow.MakeHideable(); _myTradesWindow.MakeHideable(); _tradesWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); var logManager = new LogManager(); logManager.Listeners.Add(new FileLogListener("sample.log")); var entityRegistry = new CsvEntityRegistry("Data"); ConfigManager.RegisterService<IEntityRegistry>(entityRegistry); // ecng.serialization invoke in several places IStorage obj ConfigManager.RegisterService(entityRegistry.Storage); var storageRegistry = ConfigManager.GetService<IStorageRegistry>(); SerializationContext.DelayAction = entityRegistry.DelayAction = new DelayAction(entityRegistry.Storage, ex => ex.LogError()); Connector = new Connector(entityRegistry, storageRegistry); logManager.Sources.Add(Connector); InitConnector(entityRegistry); } private void InitConnector(CsvEntityRegistry entityRegistry) { // subscribe on connection successfully event Connector.Connected += () => { this.GuiAsync(() => ChangeConnectStatus(true)); }; // subscribe on connection error event Connector.ConnectionError += error => this.GuiAsync(() => { ChangeConnectStatus(false); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Connector.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false)); // subscribe on error event Connector.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Connector.MarketDataSubscriptionFailed += (security, msg, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security))); Connector.NewSecurity += security => _securitiesWindow.SecurityPicker.Securities.Add(security); Connector.NewTrade += trade => _tradesWindow.TradeGrid.Trades.Add(trade); Connector.NewOrder += order => _ordersWindow.OrderGrid.Orders.Add(order); Connector.NewStopOrder += order => _stopOrdersWindow.OrderGrid.Orders.Add(order); Connector.NewMyTrade += trade => _myTradesWindow.TradeGrid.Trades.Add(trade); Connector.NewPortfolio += portfolio => _portfoliosWindow.PortfolioGrid.Portfolios.Add(portfolio); Connector.NewPosition += position => _portfoliosWindow.PortfolioGrid.Positions.Add(position); // subscribe on error of order registration event Connector.OrderRegisterFailed += _ordersWindow.OrderGrid.AddRegistrationFail; // subscribe on error of order cancelling event Connector.OrderCancelFailed += OrderFailed; // subscribe on error of stop-order registration event Connector.OrderRegisterFailed += _stopOrdersWindow.OrderGrid.AddRegistrationFail; // subscribe on error of stop-order cancelling event Connector.StopOrderCancelFailed += OrderFailed; // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Connector; try { if (File.Exists(_settingsFile)) Connector.Load(new XmlSerializer<SettingsStorage>().Deserialize(_settingsFile)); } catch { } if (Connector.StorageAdapter == null) return; try { entityRegistry.Init(); } catch (Exception ex) { MessageBox.Show(this, ex.ToString()); } Connector.StorageAdapter.DaysLoad = TimeSpan.FromDays(3); Connector.StorageAdapter.Load(); ConfigManager.RegisterService<IExchangeInfoProvider>(new StorageExchangeInfoProvider(entityRegistry)); } protected override void OnClosing(CancelEventArgs e) { _ordersWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _tradesWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _securitiesWindow.Close(); _tradesWindow.Close(); _myTradesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); Connector.Dispose(); ConfigManager.GetService<IEntityRegistry>().DelayAction.WaitFlush(); base.OnClosing(e); } public static MainWindow Instance { get; private set; } private void SettingsClick(object sender, RoutedEventArgs e) { if (Connector.Configure(this)) new XmlSerializer<SettingsStorage>().Serialize(Connector.Save(), _settingsFile); } private void ConnectClick(object sender, RoutedEventArgs e) { if (!_isConnected) { Connector.Connect(); } else { Connector.Disconnect(); } } private void OrderFailed(OrderFail fail) { this.GuiAsync(() => { MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153); }); } private void ChangeConnectStatus(bool isConnected) { _isConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } private void ShowTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_tradesWindow); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } } }
namespace Gu.Wpf.UiAutomation { using System; using System.Windows.Automation; using System.Xml; using System.Xml.XPath; /// <summary> /// Custom implementation of a <see cref="XPathNavigator" /> which allows /// selecting items by xpath by using the <see cref="TreeWalker" />. /// </summary> public class AutomationElementXPathNavigator : XPathNavigator { private const int NoAttributeValue = -1; private readonly UiElement rootElement; private readonly TreeWalker treeWalker; private AutomationElement currentElement; private int attributeIndex = NoAttributeValue; public AutomationElementXPathNavigator(UiElement rootElement) { this.treeWalker = TreeWalker.ControlViewWalker; this.rootElement = rootElement ?? throw new ArgumentNullException(nameof(rootElement)); this.currentElement = rootElement.AutomationElement; } private enum ElementAttributes { AutomationId, Name, ClassName, HelpText, } /// <inheritdoc/> public override bool HasAttributes => !this.IsInAttribute; /// <inheritdoc/> public override string? Value => this.IsInAttribute ? this.GetAttributeValue(this.attributeIndex) : this.currentElement.ToString(); /// <inheritdoc/> public override object UnderlyingObject => new UiElement(this.currentElement); /// <inheritdoc/> public override XPathNodeType NodeType { get { if (this.IsInAttribute) { return XPathNodeType.Attribute; } if (Equals(this.currentElement, this.rootElement.AutomationElement)) { return XPathNodeType.Root; } return XPathNodeType.Element; } } /// <inheritdoc/> public override string LocalName => this.IsInAttribute ? GetAttributeName(this.attributeIndex) : this.currentElement.ControlType().ProgrammaticName.TrimStart("ControlType."); /// <inheritdoc/> public override string Name => this.LocalName; /// <inheritdoc/> public override XmlNameTable NameTable => throw new NotSupportedException(); /// <inheritdoc/> public override string NamespaceURI => string.Empty; /// <inheritdoc/> public override string Prefix => string.Empty; /// <inheritdoc/> public override string BaseURI => string.Empty; /// <inheritdoc/> public override bool IsEmptyElement => false; private bool IsInAttribute => this.attributeIndex != NoAttributeValue; /// <inheritdoc/> public override XPathNavigator Clone() { var clonedObject = new AutomationElementXPathNavigator(this.rootElement) { currentElement = this.currentElement, attributeIndex = this.attributeIndex, }; return clonedObject; } /// <inheritdoc/> public override bool MoveToFirstAttribute() { if (this.IsInAttribute) { return false; } this.attributeIndex = 0; return true; } /// <inheritdoc/> public override bool MoveToNextAttribute() { if (this.attributeIndex >= Enum.GetNames(typeof(ElementAttributes)).Length - 1) { // No more attributes return false; } if (!this.IsInAttribute) { return false; } this.attributeIndex++; return true; } /// <inheritdoc/> public override string GetAttribute(string localName, string namespaceUri) { if (this.IsInAttribute) { return string.Empty; } var index = GetAttributeIndexFromName(localName); if (index != NoAttributeValue) { return this.GetAttributeValue(index); } return string.Empty; } /// <inheritdoc/> public override bool MoveToAttribute(string localName, string namespaceUri) { if (this.IsInAttribute) { return false; } var index = GetAttributeIndexFromName(localName); if (index != NoAttributeValue) { this.attributeIndex = index; return true; } return false; } /// <inheritdoc/> public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) { throw new NotSupportedException(); } /// <inheritdoc/> public override bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { throw new NotSupportedException(); } /// <inheritdoc/> public override void MoveToRoot() { this.attributeIndex = NoAttributeValue; this.currentElement = this.rootElement.AutomationElement; } /// <inheritdoc/> public override bool MoveToNext() { if (this.IsInAttribute) { return false; } var nextElement = this.treeWalker.GetNextSibling(this.currentElement); if (nextElement is null) { return false; } this.currentElement = nextElement; return true; } /// <inheritdoc/> public override bool MoveToPrevious() { if (this.IsInAttribute) { return false; } var previousElement = this.treeWalker.GetPreviousSibling(this.currentElement); if (previousElement is null) { return false; } this.currentElement = previousElement; return true; } /// <inheritdoc/> public override bool MoveToFirstChild() { if (this.IsInAttribute) { return false; } var childElement = this.treeWalker.GetFirstChild(this.currentElement); if (childElement is null) { return false; } this.currentElement = childElement; return true; } /// <inheritdoc/> public override bool MoveToParent() { if (this.IsInAttribute) { this.attributeIndex = NoAttributeValue; return true; } if (Equals(this.currentElement, this.rootElement.AutomationElement)) { return false; } this.currentElement = this.treeWalker.GetParent(this.currentElement); return true; } /// <inheritdoc/> public override bool MoveTo(XPathNavigator other) { if (other is AutomationElementXPathNavigator navigator && Equals(this.rootElement.AutomationElement, navigator.rootElement.AutomationElement)) { this.currentElement = navigator.currentElement; this.attributeIndex = navigator.attributeIndex; return true; } return false; } /// <inheritdoc/> public override bool MoveToId(string id) { return false; } /// <inheritdoc/> public override bool IsSamePosition(XPathNavigator other) { return other is AutomationElementXPathNavigator navigator && this.rootElement.Equals(navigator.rootElement) && this.currentElement.Equals(navigator.currentElement) && this.attributeIndex == navigator.attributeIndex; } private static string GetAttributeName(int index) { return ((ElementAttributes)index) switch { ElementAttributes.AutomationId => nameof(ElementAttributes.AutomationId), ElementAttributes.Name => nameof(ElementAttributes.Name), ElementAttributes.ClassName => nameof(ElementAttributes.ClassName), ElementAttributes.HelpText => nameof(ElementAttributes.HelpText), _ => throw new ArgumentOutOfRangeException(nameof(index)), }; } private static int GetAttributeIndexFromName(string attributeName) { if (Enum.TryParse<ElementAttributes>(attributeName, out var parsedValue)) { return (int)parsedValue; } return NoAttributeValue; } private string GetAttributeValue(int index) { return ((ElementAttributes)index) switch { ElementAttributes.AutomationId => this.currentElement.AutomationId(), ElementAttributes.Name => this.currentElement.Name(), ElementAttributes.ClassName => this.currentElement.ClassName(), ElementAttributes.HelpText => this.currentElement.HelpText(), _ => throw new ArgumentOutOfRangeException(nameof(index)), }; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Text; using ServiceStack.Common.Extensions; using ServiceStack.Text; namespace ServiceStack.OrmLite { public static class WriteExtensions { /// <summary> /// Use an expression visitor to select which fields to update and construct the where expression, E.g: /// /// dbCmd.UpdateOnly(new Person { FirstName = "JJ" }, ev => ev.Update(p => p.FirstName).Where(x => x.FirstName == "Jimi")); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// /// What's not in the update expression doesn't get updated. No where expression updates all rows. E.g: /// /// dbCmd.UpdateOnly(new Person { FirstName = "JJ", LastName = "Hendo" }, ev => ev.Update(p => p.FirstName)); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static int UpdateOnly<T>(this IDbCommand dbCmd, T model, Func<SqlExpressionVisitor<T>, SqlExpressionVisitor<T>> onlyFields) { return dbCmd.UpdateOnly(model, onlyFields(OrmLiteConfig.DialectProvider.ExpressionVisitor<T>())); } /// <summary> /// Use an expression visitor to select which fields to update and construct the where expression, E.g: /// /// var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor&gt;Person&lt;()); /// dbCmd.UpdateOnly(new Person { FirstName = "JJ" }, ev.Update(p => p.FirstName).Where(x => x.FirstName == "Jimi")); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// /// What's not in the update expression doesn't get updated. No where expression updates all rows. E.g: /// /// dbCmd.UpdateOnly(new Person { FirstName = "JJ", LastName = "Hendo" }, ev.Update(p => p.FirstName)); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static int UpdateOnly<T>(this IDbCommand dbCmd, T model, SqlExpressionVisitor<T> onlyFields) { var fieldsToUpdate = onlyFields.UpdateFields.Count == 0 ? onlyFields.GetAllFields() : onlyFields.UpdateFields; var sql = OrmLiteConfig.DialectProvider.ToUpdateRowStatement(model, fieldsToUpdate); if (!onlyFields.WhereExpression.IsNullOrEmpty()) sql += " " + onlyFields.WhereExpression; return dbCmd.ExecuteSql(sql); } /// <summary> /// Update record, updating only fields specified in updateOnly that matches the where condition (if any), E.g: /// /// dbCmd.UpdateOnly(new Person { FirstName = "JJ" }, p => p.FirstName, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// /// dbCmd.UpdateOnly(new Person { FirstName = "JJ" }, p => p.FirstName); /// UPDATE "Person" SET "FirstName" = 'JJ' /// </summary> public static int UpdateOnly<T, TKey>(this IDbCommand dbCmd, T obj, Expression<Func<T, TKey>> onlyFields = null, Expression<Func<T, bool>> where = null) { if (onlyFields == null) throw new ArgumentNullException("onlyFields"); var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>(); ev.Update(onlyFields); ev.Where(where); return dbCmd.UpdateOnly(obj, ev); } /// <summary> /// Updates all non-default values set on item matching the where condition (if any). E.g /// /// dbCmd.UpdateNonDefault(new Person { FirstName = "JJ" }, p => p.FirstName == "Jimi"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// </summary> public static int UpdateNonDefaults<T>(this IDbCommand dbCmd, T item, Expression<Func<T, bool>> where) { var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>(); ev.Where(where); var sql = ev.ToUpdateStatement(item, excludeDefaults: true); return dbCmd.ExecuteSql(sql); } /// <summary> /// Updates all values set on item matching the where condition (if any). E.g /// /// dbCmd.UpdateNonDefault(new Person { FirstName = "JJ" }, p => p.FirstName == "Jimi"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("FirstName" = 'Jimi') /// /// dbCmd.Update(new Person { Id = 1, FirstName = "JJ" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "Id" = 1,"FirstName" = 'JJ',"LastName" = NULL,"Age" = 0 WHERE ("LastName" = 'Hendrix') /// </summary> public static int Update<T>(this IDbCommand dbCmd, T item, Expression<Func<T, bool>> where) { var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>(); ev.Where(where); var sql = ev.ToUpdateStatement(item); return dbCmd.ExecuteSql(sql); } /// <summary> /// Updates all matching fields populated on anonymousType that matches where condition (if any). E.g: /// /// dbCmd.Update&lt;Person&gt;(new { FirstName = "JJ" }, p => p.LastName == "Hendrix"); /// UPDATE "Person" SET "FirstName" = 'JJ' WHERE ("LastName" = 'Hendrix') /// </summary> public static int Update<T>(this IDbCommand dbCmd, object updateOnly, Expression<Func<T, bool>> where = null) { var dialectProvider = OrmLiteConfig.DialectProvider; var ev = dialectProvider.ExpressionVisitor<T>(); var whereSql = ev.Where(where).WhereExpression; var sql = new StringBuilder(); var modelDef = typeof(T).GetModelDefinition(); var fields = modelDef.FieldDefinitionsArray; foreach (var setField in updateOnly.GetType().GetPublicProperties()) { var fieldDef = fields.FirstOrDefault(x => string.Equals(x.Name, setField.Name, StringComparison.InvariantCultureIgnoreCase)); if (fieldDef == null) continue; if (sql.Length > 0) sql.Append(","); sql.AppendFormat("{0} = {1}", dialectProvider.GetQuotedColumnName(fieldDef.FieldName), dialectProvider.GetQuotedValue(setField.GetPropertyGetterFn()(updateOnly), fieldDef.FieldType)); } var updateSql = string.Format("UPDATE {0} SET {1} {2}", dialectProvider.GetQuotedTableName(modelDef), sql, whereSql); return dbCmd.ExecuteSql(updateSql); } /// <summary> /// Flexible Update method to succinctly execute a free-text update statement using optional params. E.g: /// /// dbCmd.Update&lt;Person&gt;(set:"FirstName = {0}".Params("JJ"), where:"LastName = {0}".Params("Hendrix")); /// UPDATE "Person" SET FirstName = 'JJ' WHERE LastName = 'Hendrix' /// </summary> public static int Update<T>(this IDbCommand dbCmd, string set = null, string where = null) { return dbCmd.Update(typeof(T).GetModelDefinition().ModelName, set, where); } /// <summary> /// Flexible Update method to succinctly execute a free-text update statement using optional params. E.g. /// /// dbCmd.Update(table:"Person", set: "FirstName = {0}".Params("JJ"), where: "LastName = {0}".Params("Hendrix")); /// UPDATE "Person" SET FirstName = 'JJ' WHERE LastName = 'Hendrix' /// </summary> public static int Update(this IDbCommand dbCmd, string table = null, string set = null, string where = null) { if (table == null) throw new ArgumentNullException("table"); if (set == null) throw new ArgumentNullException("set"); var sql = new StringBuilder("UPDATE "); sql.Append(OrmLiteConfig.DialectProvider.GetQuotedTableName(table)); sql.Append(" SET "); sql.Append(set); if (!string.IsNullOrEmpty(where)) { sql.Append(" WHERE "); sql.Append(where); } return dbCmd.ExecuteSql(sql.ToString()); } /// <summary> /// Using an Expression Visitor to only Insert the fields specified, e.g: /// /// dbCmd.InsertOnly(new Person { FirstName = "Amy" }, ev => ev.Insert(p => new { p.FirstName })); /// INSERT INTO "Person" ("FirstName") VALUES ('Amy'); /// </summary> public static void InsertOnly<T>(this IDbCommand dbCmd, T obj, Func<SqlExpressionVisitor<T>, SqlExpressionVisitor<T>> onlyFields) { dbCmd.InsertOnly(obj, onlyFields(OrmLiteConfig.DialectProvider.ExpressionVisitor<T>())); } /// <summary> /// Using an Expression Visitor to only Insert the fields specified, e.g: /// /// var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor&gt;Person&lt;()); /// dbCmd.InsertOnly(new Person { FirstName = "Amy" }, ev.Insert(p => new { p.FirstName })); /// INSERT INTO "Person" ("FirstName") VALUES ('Amy'); /// </summary> public static void InsertOnly<T>(this IDbCommand dbCmd, T obj, SqlExpressionVisitor<T> onlyFields) { var sql = OrmLiteConfig.DialectProvider.ToInsertRowStatement(obj, onlyFields.InsertFields, dbCmd); dbCmd.ExecuteSql(sql); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// dbCmd.Delete&lt;Person&gt;(p => p.Age == 27); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static int Delete<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> where) { var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<T>(); ev.Where(where); return dbCmd.Delete(ev); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// dbCmd.Delete&lt;Person&gt;(ev => ev.Where(p => p.Age == 27)); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static int Delete<T>(this IDbCommand dbCmd, Func<SqlExpressionVisitor<T>, SqlExpressionVisitor<T>> where) { return dbCmd.Delete(where(OrmLiteConfig.DialectProvider.ExpressionVisitor<T>())); } /// <summary> /// Delete the rows that matches the where expression, e.g: /// /// var ev = OrmLiteConfig.DialectProvider.ExpressionVisitor&gt;Person&lt;()); /// dbCmd.Delete&lt;Person&gt;(ev.Where(p => p.Age == 27)); /// DELETE FROM "Person" WHERE ("Age" = 27) /// </summary> public static int Delete<T>(this IDbCommand dbCmd, SqlExpressionVisitor<T> where) { var sql = where.ToDeleteRowStatement(); return dbCmd.ExecuteSql(sql); } /// <summary> /// Flexible Delete method to succinctly execute a delete statement using free-text where expression. E.g. /// /// dbCmd.Delete&lt;Person&gt;(where:"Age = {0}".Params(27)); /// DELETE FROM "Person" WHERE Age = 27 /// </summary> public static int Delete<T>(this IDbCommand dbCmd, string where = null) { return dbCmd.Delete(typeof(T).GetModelDefinition().ModelName, where); } /// <summary> /// Flexible Delete method to succinctly execute a delete statement using free-text where expression. E.g. /// /// dbCmd.Delete(table:"Person", where: "Age = {0}".Params(27)); /// DELETE FROM "Person" WHERE Age = 27 /// </summary> public static int Delete(this IDbCommand dbCmd, string table = null, string where = null) { if (table == null) throw new ArgumentNullException("table"); if (where == null) throw new ArgumentNullException("where"); var sql = new StringBuilder(); sql.AppendFormat("DELETE FROM {0} WHERE {1}", OrmLiteConfig.DialectProvider.GetQuotedTableName(table), where); return dbCmd.ExecuteSql(sql.ToString()); } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:Stefan.Lange@pdfsharp.com) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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.Diagnostics; using System.Globalization; using System.IO; //#if GDI //using System.Drawing; //using System.Drawing.Drawing2D; //using System.Drawing.Imaging; //#endif #if WPF using System.Windows; using System.Windows.Controls; using System.Windows.Media; #endif using PdfSharp.Internal; using PdfSharp.Pdf; using PdfSharp.Drawing.Pdf; using PdfSharp.Fonts; using PdfSharp.Fonts.OpenType; using PdfSharp.Pdf.Advanced; namespace PdfSharp.Drawing { #if WPF /// <summary> /// The Get WPF Value flags. /// </summary> enum GWV { GetCellAscent, GetCellDescent, GetEmHeight, GetLineSpacing, //IsStyleAvailable } /// <summary> /// Helper class for fonts. /// </summary> static class FontHelper { //private const string testFontName = "Times New Roman"; //const string testFontName = "Segoe Condensed"; //const string testFontName = "Frutiger LT 45 Light"; //static FontHelper() //{ // FontFamily fontFamily = new FontFamily(testFontName); // s_typefaces = new List<Typeface>(fontFamily.GetTypefaces()); //} //private static List<Typeface> s_typefaces; /// <summary> /// Creates a typeface. /// </summary> public static Typeface CreateTypeface(FontFamily family, XFontStyle style) { // BUG: does not work with fonts that have others than the four default styles FontStyle fontStyle = FontStyleFromStyle(style); FontWeight fontWeight = FontWeightFromStyle(style); Typeface typeface = new Typeface(family, fontStyle, fontWeight, FontStretches.Normal); //List<Typeface> typefaces = new List<Typeface>(fontFamily.GetTypefaces()); //typefaces.GetType(); //Typeface typeface = typefaces[3]; return typeface; } #if !SILVERLIGHT /// <summary> /// Creates the formatted text. /// </summary> public static FormattedText CreateFormattedText(string text, Typeface typeface, double emSize, Brush brush) { //FontFamily fontFamily = new FontFamily(testFontName); //typeface = new Typeface(fontFamily, FontStyles.Normal, FontWeights.Bold, FontStretches.Condensed); //List<Typeface> typefaces = new List<Typeface>(fontFamily.GetTypefaces()); //typefaces.GetType(); //typeface = s_typefaces[0]; // BUG: does not work with fonts that have others than the four default styles FormattedText formattedText = new FormattedText(text, new CultureInfo("en-us"), FlowDirection.LeftToRight, typeface, emSize, brush); //formattedText.SetFontWeight(FontWeights.Bold); //formattedText.SetFontStyle(FontStyles.Oblique); //formattedText.SetFontStretch(FontStretches.Condensed); return formattedText; } #endif #if SILVERLIGHT /// <summary> /// Creates the TextBlock. /// </summary> public static TextBlock CreateTextBlock(string text, Typeface typeface, double emSize, Brush brush) { TextBlock textBlock = new TextBlock(); textBlock.FontFamily = new FontFamily("Verdana"); textBlock.FontSize = emSize; textBlock.Foreground = brush; textBlock.Text = text; return textBlock; } #endif /// <summary> /// Simple hack to make it work... /// </summary> public static FontStyle FontStyleFromStyle(XFontStyle style) { switch (style & XFontStyle.BoldItalic) // mask out Underline and Strikeout { case XFontStyle.Regular: return FontStyles.Normal; case XFontStyle.Bold: return FontStyles.Normal; case XFontStyle.Italic: return FontStyles.Italic; case XFontStyle.BoldItalic: return FontStyles.Italic; } return FontStyles.Normal; } /// <summary> /// Simple hack to make it work... /// </summary> public static FontWeight FontWeightFromStyle(XFontStyle style) { switch (style) { case XFontStyle.Regular: return FontWeights.Normal; case XFontStyle.Bold: return FontWeights.Bold; case XFontStyle.Italic: return FontWeights.Normal; case XFontStyle.BoldItalic: return FontWeights.Bold; } return FontWeights.Normal; } public static int GetWpfValue(XFontFamily family, XFontStyle style, GWV value) { FontDescriptor descriptor = FontDescriptorStock.Global.CreateDescriptor(family, style); XFontMetrics metrics = descriptor.FontMetrics; switch (value) { case GWV.GetCellAscent: return metrics.Ascent; case GWV.GetCellDescent: return Math.Abs(metrics.Descent); case GWV.GetEmHeight: //return (int)metrics.CapHeight; return metrics.UnitsPerEm; case GWV.GetLineSpacing: return metrics.Ascent + Math.Abs(metrics.Descent) + metrics.Leading; default: throw new InvalidOperationException("Unknown GWV value."); // DELETE //case GWV.IsStyleAvailable: // style &= XFontStyle.Regular | XFontStyle.Bold | XFontStyle.Italic | XFontStyle.BoldItalic; // same as XFontStyle.BoldItalic // List<Typeface> s_typefaces = new List<Typeface>(family.wpfFamily.GetTypefaces()); // foreach (Typeface typeface in s_typefaces) // { // } // Debugger.Break(); ////typeface.Style = FontStyles. } } /// <summary> /// Determines whether the style is available as a glyph type face in the specified font family, i.e. the specified style is not simulated. /// </summary> public static bool IsStyleAvailable(XFontFamily family, XFontStyle style) { #if !SILVERLIGHT // TODOWPF: check for correctness FontDescriptor descriptor = FontDescriptorStock.Global.CreateDescriptor(family, style); XFontMetrics metrics = descriptor.FontMetrics; style &= XFontStyle.Regular | XFontStyle.Bold | XFontStyle.Italic | XFontStyle.BoldItalic; // same as XFontStyle.BoldItalic List<Typeface> typefaces = new List<Typeface>(family.wpfFamily.GetTypefaces()); foreach (Typeface typeface in typefaces) { bool available = false; GlyphTypeface glyphTypeface; if (typeface.TryGetGlyphTypeface(out glyphTypeface)) { #if DEBUG glyphTypeface.GetType(); #endif available = true; } #if DEBUG_ // int weightClass = typeface.Weight.ToOpenTypeWeight(); switch (style) { case XFontStyle.Regular: //if (typeface.TryGetGlyphTypeface(.Style == FontStyles.Normal && typeface.Weight== FontWeights.Normal.) break; case XFontStyle.Bold: break; case XFontStyle.Italic: break; case XFontStyle.BoldItalic: break; } #endif if (available) return true; } return false; #else return true; // AGHACK #endif } } #endif }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// RecordingResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Api.V2010.Account { public class RecordingResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum InProgress = new StatusEnum("in-progress"); public static readonly StatusEnum Paused = new StatusEnum("paused"); public static readonly StatusEnum Stopped = new StatusEnum("stopped"); public static readonly StatusEnum Processing = new StatusEnum("processing"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Absent = new StatusEnum("absent"); } public sealed class SourceEnum : StringEnum { private SourceEnum(string value) : base(value) {} public SourceEnum() {} public static implicit operator SourceEnum(string value) { return new SourceEnum(value); } public static readonly SourceEnum Dialverb = new SourceEnum("DialVerb"); public static readonly SourceEnum Conference = new SourceEnum("Conference"); public static readonly SourceEnum Outboundapi = new SourceEnum("OutboundAPI"); public static readonly SourceEnum Trunking = new SourceEnum("Trunking"); public static readonly SourceEnum Recordverb = new SourceEnum("RecordVerb"); public static readonly SourceEnum Startcallrecordingapi = new SourceEnum("StartCallRecordingAPI"); public static readonly SourceEnum Startconferencerecordingapi = new SourceEnum("StartConferenceRecordingAPI"); } private static Request BuildFetchRequest(FetchRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Recordings/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch an instance of a recording /// </summary> /// <param name="options"> Fetch Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Fetch(FetchRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch an instance of a recording /// </summary> /// <param name="options"> Fetch Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> FetchAsync(FetchRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch an instance of a recording /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static RecordingResource Fetch(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchRecordingOptions(pathSid){PathAccountSid = pathAccountSid}; return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch an instance of a recording /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<RecordingResource> FetchAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new FetchRecordingOptions(pathSid){PathAccountSid = pathAccountSid}; return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Recordings/" + options.PathSid + ".json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a recording from your account /// </summary> /// <param name="options"> Delete Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static bool Delete(DeleteRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a recording from your account /// </summary> /// <param name="options"> Delete Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a recording from your account /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static bool Delete(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteRecordingOptions(pathSid){PathAccountSid = pathAccountSid}; return Delete(options, client); } #if !NET35 /// <summary> /// Delete a recording from your account /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="pathAccountSid"> The SID of the Account that created the resources to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null) { var options = new DeleteRecordingOptions(pathSid){PathAccountSid = pathAccountSid}; return await DeleteAsync(options, client); } #endif private static Request BuildReadRequest(ReadRecordingOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Api, "/2010-04-01/Accounts/" + (options.PathAccountSid ?? client.AccountSid) + "/Recordings.json", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of recordings belonging to the account used to make the request /// </summary> /// <param name="options"> Read Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static ResourceSet<RecordingResource> Read(ReadRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<RecordingResource>.FromJson("recordings", response.Content); return new ResourceSet<RecordingResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of recordings belonging to the account used to make the request /// </summary> /// <param name="options"> Read Recording parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<ResourceSet<RecordingResource>> ReadAsync(ReadRecordingOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<RecordingResource>.FromJson("recordings", response.Content); return new ResourceSet<RecordingResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of recordings belonging to the account used to make the request /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="dateCreatedBefore"> Only include recordings that were created on this date </param> /// <param name="dateCreated"> Only include recordings that were created on this date </param> /// <param name="dateCreatedAfter"> Only include recordings that were created on this date </param> /// <param name="callSid"> The Call SID of the resources to read </param> /// <param name="conferenceSid"> Read by unique Conference SID for the recording </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Recording </returns> public static ResourceSet<RecordingResource> Read(string pathAccountSid = null, DateTime? dateCreatedBefore = null, DateTime? dateCreated = null, DateTime? dateCreatedAfter = null, string callSid = null, string conferenceSid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRecordingOptions(){PathAccountSid = pathAccountSid, DateCreatedBefore = dateCreatedBefore, DateCreated = dateCreated, DateCreatedAfter = dateCreatedAfter, CallSid = callSid, ConferenceSid = conferenceSid, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of recordings belonging to the account used to make the request /// </summary> /// <param name="pathAccountSid"> The SID of the Account that created the resources to read </param> /// <param name="dateCreatedBefore"> Only include recordings that were created on this date </param> /// <param name="dateCreated"> Only include recordings that were created on this date </param> /// <param name="dateCreatedAfter"> Only include recordings that were created on this date </param> /// <param name="callSid"> The Call SID of the resources to read </param> /// <param name="conferenceSid"> Read by unique Conference SID for the recording </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Recording </returns> public static async System.Threading.Tasks.Task<ResourceSet<RecordingResource>> ReadAsync(string pathAccountSid = null, DateTime? dateCreatedBefore = null, DateTime? dateCreated = null, DateTime? dateCreatedAfter = null, string callSid = null, string conferenceSid = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadRecordingOptions(){PathAccountSid = pathAccountSid, DateCreatedBefore = dateCreatedBefore, DateCreated = dateCreated, DateCreatedAfter = dateCreatedAfter, CallSid = callSid, ConferenceSid = conferenceSid, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<RecordingResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<RecordingResource> NextPage(Page<RecordingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<RecordingResource> PreviousPage(Page<RecordingResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Api) ); var response = client.Request(request); return Page<RecordingResource>.FromJson("recordings", response.Content); } /// <summary> /// Converts a JSON string into a RecordingResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> RecordingResource object represented by the provided JSON </returns> public static RecordingResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<RecordingResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The API version used during the recording. /// </summary> [JsonProperty("api_version")] public string ApiVersion { get; private set; } /// <summary> /// The SID of the Call the resource is associated with /// </summary> [JsonProperty("call_sid")] public string CallSid { get; private set; } /// <summary> /// The unique ID for the conference associated with the recording. /// </summary> [JsonProperty("conference_sid")] public string ConferenceSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT that the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The start time of the recording, given in RFC 2822 format /// </summary> [JsonProperty("start_time")] public DateTime? StartTime { get; private set; } /// <summary> /// The length of the recording in seconds. /// </summary> [JsonProperty("duration")] public string Duration { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The one-time cost of creating the recording. /// </summary> [JsonProperty("price")] public string Price { get; private set; } /// <summary> /// The currency used in the price property. /// </summary> [JsonProperty("price_unit")] public string PriceUnit { get; private set; } /// <summary> /// The status of the recording. /// </summary> [JsonProperty("status")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.StatusEnum Status { get; private set; } /// <summary> /// The number of channels in the final recording file as an integer. /// </summary> [JsonProperty("channels")] public int? Channels { get; private set; } /// <summary> /// How the recording was created /// </summary> [JsonProperty("source")] [JsonConverter(typeof(StringEnumConverter))] public RecordingResource.SourceEnum Source { get; private set; } /// <summary> /// More information about why the recording is missing, if status is `absent`. /// </summary> [JsonProperty("error_code")] public int? ErrorCode { get; private set; } /// <summary> /// The URI of the resource, relative to `https://api.twilio.com` /// </summary> [JsonProperty("uri")] public string Uri { get; private set; } /// <summary> /// How to decrypt the recording. /// </summary> [JsonProperty("encryption_details")] public object EncryptionDetails { get; private set; } /// <summary> /// A list of related resources identified by their relative URIs /// </summary> [JsonProperty("subresource_uris")] public Dictionary<string, string> SubresourceUris { get; private set; } private RecordingResource() { } } }
/* * 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.Impl.Binary { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Metadata; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.Messaging; /// <summary> /// Marshaller implementation. /// </summary> internal class Marshaller { /** Binary configuration. */ private readonly BinaryConfiguration _cfg; /** Type to descriptor map. */ private readonly IDictionary<Type, IBinaryTypeDescriptor> _typeToDesc = new Dictionary<Type, IBinaryTypeDescriptor>(); /** Type name to descriptor map. */ private readonly IDictionary<string, IBinaryTypeDescriptor> _typeNameToDesc = new Dictionary<string, IBinaryTypeDescriptor>(); /** ID to descriptor map. */ private readonly CopyOnWriteConcurrentDictionary<long, IBinaryTypeDescriptor> _idToDesc = new CopyOnWriteConcurrentDictionary<long, IBinaryTypeDescriptor>(); /** Cached metadatas. */ private volatile IDictionary<int, BinaryTypeHolder> _metas = new Dictionary<int, BinaryTypeHolder>(); /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configurtaion.</param> public Marshaller(BinaryConfiguration cfg) { // Validation. if (cfg == null) cfg = new BinaryConfiguration(); CompactFooter = cfg.CompactFooter; if (cfg.TypeConfigurations == null) cfg.TypeConfigurations = new List<BinaryTypeConfiguration>(); foreach (BinaryTypeConfiguration typeCfg in cfg.TypeConfigurations) { if (string.IsNullOrEmpty(typeCfg.TypeName)) throw new BinaryObjectException("Type name cannot be null or empty: " + typeCfg); } // Define system types. They use internal reflective stuff, so configuration doesn't affect them. AddSystemTypes(); // 2. Define user types. var typeResolver = new TypeResolver(); ICollection<BinaryTypeConfiguration> typeCfgs = cfg.TypeConfigurations; if (typeCfgs != null) foreach (BinaryTypeConfiguration typeCfg in typeCfgs) AddUserType(cfg, typeCfg, typeResolver); var typeNames = cfg.Types; if (typeNames != null) foreach (string typeName in typeNames) AddUserType(cfg, new BinaryTypeConfiguration(typeName), typeResolver); _cfg = cfg; } /// <summary> /// Gets or sets the backing grid. /// </summary> public Ignite Ignite { get; set; } /// <summary> /// Gets the compact footer flag. /// </summary> public bool CompactFooter { get; set; } /// <summary> /// Marshal object. /// </summary> /// <param name="val">Value.</param> /// <returns>Serialized data as byte array.</returns> public byte[] Marshal<T>(T val) { using (var stream = new BinaryHeapStream(128)) { Marshal(val, stream); return stream.GetArrayCopy(); } } /// <summary> /// Marshal object. /// </summary> /// <param name="val">Value.</param> /// <param name="stream">Output stream.</param> /// <returns>Collection of metadatas (if any).</returns> private void Marshal<T>(T val, IBinaryStream stream) { BinaryWriter writer = StartMarshal(stream); writer.Write(val); FinishMarshal(writer); } /// <summary> /// Start marshal session. /// </summary> /// <param name="stream">Stream.</param> /// <returns>Writer.</returns> public BinaryWriter StartMarshal(IBinaryStream stream) { return new BinaryWriter(this, stream); } /// <summary> /// Finish marshal session. /// </summary> /// <param name="writer">Writer.</param> /// <returns>Dictionary with metadata.</returns> public void FinishMarshal(BinaryWriter writer) { var metas = writer.GetBinaryTypes(); var ignite = Ignite; if (ignite != null && metas != null && metas.Count > 0) { ignite.BinaryProcessor.PutBinaryTypes(metas); } } /// <summary> /// Unmarshal object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data">Data array.</param> /// <param name="keepBinary">Whether to keep binarizable as binary.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(byte[] data, bool keepBinary) { using (var stream = new BinaryHeapStream(data)) { return Unmarshal<T>(stream, keepBinary); } } /// <summary> /// Unmarshal object. /// </summary> /// <param name="data">Data array.</param> /// <param name="mode">The mode.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(byte[] data, BinaryMode mode = BinaryMode.Deserialize) { using (var stream = new BinaryHeapStream(data)) { return Unmarshal<T>(stream, mode); } } /// <summary> /// Unmarshal object. /// </summary> /// <param name="stream">Stream over underlying byte array with correct position.</param> /// <param name="keepBinary">Whether to keep binary objects in binary form.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(IBinaryStream stream, bool keepBinary) { return Unmarshal<T>(stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null); } /// <summary> /// Unmarshal object. /// </summary> /// <param name="stream">Stream over underlying byte array with correct position.</param> /// <param name="mode">The mode.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize) { return Unmarshal<T>(stream, mode, null); } /// <summary> /// Unmarshal object. /// </summary> /// <param name="stream">Stream over underlying byte array with correct position.</param> /// <param name="mode">The mode.</param> /// <param name="builder">Builder.</param> /// <returns> /// Object. /// </returns> public T Unmarshal<T>(IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder) { return new BinaryReader(this, stream, mode, builder).Deserialize<T>(); } /// <summary> /// Start unmarshal session. /// </summary> /// <param name="stream">Stream.</param> /// <param name="keepBinary">Whether to keep binarizable as binary.</param> /// <returns> /// Reader. /// </returns> public BinaryReader StartUnmarshal(IBinaryStream stream, bool keepBinary) { return new BinaryReader(this, stream, keepBinary ? BinaryMode.KeepBinary : BinaryMode.Deserialize, null); } /// <summary> /// Start unmarshal session. /// </summary> /// <param name="stream">Stream.</param> /// <param name="mode">The mode.</param> /// <returns>Reader.</returns> public BinaryReader StartUnmarshal(IBinaryStream stream, BinaryMode mode = BinaryMode.Deserialize) { return new BinaryReader(this, stream, mode, null); } /// <summary> /// Gets metadata for the given type ID. /// </summary> /// <param name="typeId">Type ID.</param> /// <returns>Metadata or null.</returns> public IBinaryType GetBinaryType(int typeId) { if (Ignite != null) { IBinaryType meta = Ignite.BinaryProcessor.GetBinaryType(typeId); if (meta != null) return meta; } return BinaryType.Empty; } /// <summary> /// Puts the binary type metadata to Ignite. /// </summary> /// <param name="desc">Descriptor.</param> public void PutBinaryType(IBinaryTypeDescriptor desc) { Debug.Assert(desc != null); GetBinaryTypeHandler(desc); // ensure that handler exists if (Ignite != null) { ICollection<BinaryType> metas = new[] {new BinaryType(desc)}; Ignite.BinaryProcessor.PutBinaryTypes(metas); } } /// <summary> /// Gets binary type handler for the given type ID. /// </summary> /// <param name="desc">Type descriptor.</param> /// <returns>Binary type handler.</returns> public IBinaryTypeHandler GetBinaryTypeHandler(IBinaryTypeDescriptor desc) { BinaryTypeHolder holder; if (!_metas.TryGetValue(desc.TypeId, out holder)) { lock (this) { if (!_metas.TryGetValue(desc.TypeId, out holder)) { IDictionary<int, BinaryTypeHolder> metas0 = new Dictionary<int, BinaryTypeHolder>(_metas); holder = new BinaryTypeHolder(desc.TypeId, desc.TypeName, desc.AffinityKeyFieldName, desc.IsEnum); metas0[desc.TypeId] = holder; _metas = metas0; } } } if (holder != null) { ICollection<int> ids = holder.GetFieldIds(); bool newType = ids.Count == 0 && !holder.Saved(); return new BinaryTypeHashsetHandler(ids, newType); } return null; } /// <summary> /// Callback invoked when metadata has been sent to the server and acknowledged by it. /// </summary> /// <param name="newMetas">Binary types.</param> public void OnBinaryTypesSent(IEnumerable<BinaryType> newMetas) { foreach (var meta in newMetas) { var mergeInfo = new Dictionary<int, Tuple<string, int>>(meta.GetFieldsMap().Count); foreach (KeyValuePair<string, int> fieldMeta in meta.GetFieldsMap()) { int fieldId = BinaryUtils.FieldId(meta.TypeId, fieldMeta.Key, null, null); mergeInfo[fieldId] = new Tuple<string, int>(fieldMeta.Key, fieldMeta.Value); } _metas[meta.TypeId].Merge(mergeInfo); } } /// <summary> /// Gets descriptor for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Descriptor.</returns> public IBinaryTypeDescriptor GetDescriptor(Type type) { IBinaryTypeDescriptor desc; _typeToDesc.TryGetValue(type, out desc); return desc; } /// <summary> /// Gets descriptor for type name. /// </summary> /// <param name="typeName">Type name.</param> /// <returns>Descriptor.</returns> public IBinaryTypeDescriptor GetDescriptor(string typeName) { IBinaryTypeDescriptor desc; return _typeNameToDesc.TryGetValue(typeName, out desc) ? desc : new BinarySurrogateTypeDescriptor(_cfg, typeName); } /// <summary> /// Gets descriptor for a type id. /// </summary> /// <param name="userType">User type flag.</param> /// <param name="typeId">Type id.</param> /// <returns>Descriptor.</returns> public IBinaryTypeDescriptor GetDescriptor(bool userType, int typeId) { IBinaryTypeDescriptor desc; var typeKey = BinaryUtils.TypeKey(userType, typeId); if (_idToDesc.TryGetValue(typeKey, out desc)) return desc; if (!userType) return null; var meta = GetBinaryType(typeId); if (meta != BinaryType.Empty) { desc = new BinaryFullTypeDescriptor(null, meta.TypeId, meta.TypeName, true, null, null, null, false, meta.AffinityKeyFieldName, meta.IsEnum); _idToDesc.GetOrAdd(typeKey, _ => desc); return desc; } return new BinarySurrogateTypeDescriptor(_cfg, typeId); } /// <summary> /// Add user type. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="typeCfg">Type configuration.</param> /// <param name="typeResolver">The type resolver.</param> private void AddUserType(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg, TypeResolver typeResolver) { // Get converter/mapper/serializer. IBinaryNameMapper nameMapper = typeCfg.NameMapper ?? cfg.DefaultNameMapper; IBinaryIdMapper idMapper = typeCfg.IdMapper ?? cfg.DefaultIdMapper; bool keepDeserialized = typeCfg.KeepDeserialized ?? cfg.DefaultKeepDeserialized; // Try resolving type. Type type = typeResolver.ResolveType(typeCfg.TypeName); if (type != null) { if (typeCfg.IsEnum != type.IsEnum) throw new BinaryObjectException( string.Format( "Invalid IsEnum flag in binary type configuration. " + "Configuration value: IsEnum={0}, actual type: IsEnum={1}", typeCfg.IsEnum, type.IsEnum)); // Type is found. var typeName = BinaryUtils.GetTypeName(type); int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper); var affKeyFld = typeCfg.AffinityKeyFieldName ?? GetAffinityKeyFieldNameFromAttribute(type); var serializer = GetSerializer(cfg, typeCfg, type, typeId, nameMapper, idMapper); AddType(type, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, serializer, affKeyFld, type.IsEnum); } else { // Type is not found. string typeName = BinaryUtils.SimpleTypeName(typeCfg.TypeName); int typeId = BinaryUtils.TypeId(typeName, nameMapper, idMapper); AddType(null, typeId, typeName, true, keepDeserialized, nameMapper, idMapper, null, typeCfg.AffinityKeyFieldName, typeCfg.IsEnum); } } /// <summary> /// Gets the serializer. /// </summary> private static IBinarySerializerInternal GetSerializer(BinaryConfiguration cfg, BinaryTypeConfiguration typeCfg, Type type, int typeId, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper) { var serializer = typeCfg.Serializer ?? cfg.DefaultSerializer; if (serializer == null) { if (type.GetInterfaces().Contains(typeof(IBinarizable))) return BinarizableSerializer.Instance; serializer = new BinaryReflectiveSerializer(); } var refSerializer = serializer as BinaryReflectiveSerializer; return refSerializer != null ? refSerializer.Register(type, typeId, nameMapper, idMapper) : new UserSerializerProxy(serializer); } /// <summary> /// Gets the affinity key field name from attribute. /// </summary> private static string GetAffinityKeyFieldNameFromAttribute(Type type) { var res = type.GetMembers() .Where(x => x.GetCustomAttributes(false).OfType<AffinityKeyMappedAttribute>().Any()) .Select(x => x.Name).ToArray(); if (res.Length > 1) { throw new BinaryObjectException(string.Format("Multiple '{0}' attributes found on type '{1}'. " + "There can be only one affinity field.", typeof (AffinityKeyMappedAttribute).Name, type)); } return res.SingleOrDefault(); } /// <summary> /// Add type. /// </summary> /// <param name="type">Type.</param> /// <param name="typeId">Type ID.</param> /// <param name="typeName">Type name.</param> /// <param name="userType">User type flag.</param> /// <param name="keepDeserialized">Whether to cache deserialized value in IBinaryObject</param> /// <param name="nameMapper">Name mapper.</param> /// <param name="idMapper">ID mapper.</param> /// <param name="serializer">Serializer.</param> /// <param name="affKeyFieldName">Affinity key field name.</param> /// <param name="isEnum">Enum flag.</param> private void AddType(Type type, int typeId, string typeName, bool userType, bool keepDeserialized, IBinaryNameMapper nameMapper, IBinaryIdMapper idMapper, IBinarySerializerInternal serializer, string affKeyFieldName, bool isEnum) { long typeKey = BinaryUtils.TypeKey(userType, typeId); IBinaryTypeDescriptor conflictingType; if (_idToDesc.TryGetValue(typeKey, out conflictingType)) { var type1 = conflictingType.Type != null ? conflictingType.Type.AssemblyQualifiedName : conflictingType.TypeName; var type2 = type != null ? type.AssemblyQualifiedName : typeName; throw new BinaryObjectException(string.Format("Conflicting type IDs [type1='{0}', " + "type2='{1}', typeId={2}]", type1, type2, typeId)); } if (userType && _typeNameToDesc.ContainsKey(typeName)) throw new BinaryObjectException("Conflicting type name: " + typeName); var descriptor = new BinaryFullTypeDescriptor(type, typeId, typeName, userType, nameMapper, idMapper, serializer, keepDeserialized, affKeyFieldName, isEnum); if (type != null) _typeToDesc[type] = descriptor; if (userType) _typeNameToDesc[typeName] = descriptor; _idToDesc.GetOrAdd(typeKey, _ => descriptor); } /// <summary> /// Adds a predefined system type. /// </summary> private void AddSystemType<T>(int typeId, Func<BinaryReader, T> ctor, string affKeyFldName = null, IBinarySerializerInternal serializer = null) where T : IBinaryWriteAware { var type = typeof(T); serializer = serializer ?? new BinarySystemTypeSerializer<T>(ctor); if (typeId == 0) typeId = BinaryUtils.TypeId(type.Name, null, null); AddType(type, typeId, BinaryUtils.GetTypeName(type), false, false, null, null, serializer, affKeyFldName, false); } /// <summary> /// Adds predefined system types. /// </summary> private void AddSystemTypes() { AddSystemType(BinaryUtils.TypeNativeJobHolder, r => new ComputeJobHolder(r)); AddSystemType(BinaryUtils.TypeComputeJobWrapper, r => new ComputeJobWrapper(r)); AddSystemType(BinaryUtils.TypeIgniteProxy, r => new IgniteProxy()); AddSystemType(BinaryUtils.TypeComputeOutFuncJob, r => new ComputeOutFuncJob(r)); AddSystemType(BinaryUtils.TypeComputeOutFuncWrapper, r => new ComputeOutFuncWrapper(r)); AddSystemType(BinaryUtils.TypeComputeFuncWrapper, r => new ComputeFuncWrapper(r)); AddSystemType(BinaryUtils.TypeComputeFuncJob, r => new ComputeFuncJob(r)); AddSystemType(BinaryUtils.TypeComputeActionJob, r => new ComputeActionJob(r)); AddSystemType(BinaryUtils.TypeContinuousQueryRemoteFilterHolder, r => new ContinuousQueryFilterHolder(r)); AddSystemType(BinaryUtils.TypeSerializableHolder, r => new SerializableObjectHolder(r), serializer: new SerializableSerializer()); AddSystemType(BinaryUtils.TypeDateTimeHolder, r => new DateTimeHolder(r), serializer: new DateTimeSerializer()); AddSystemType(BinaryUtils.TypeCacheEntryProcessorHolder, r => new CacheEntryProcessorHolder(r)); AddSystemType(BinaryUtils.TypeCacheEntryPredicateHolder, r => new CacheEntryFilterHolder(r)); AddSystemType(BinaryUtils.TypeMessageListenerHolder, r => new MessageListenerHolder(r)); AddSystemType(BinaryUtils.TypeStreamReceiverHolder, r => new StreamReceiverHolder(r)); AddSystemType(0, r => new AffinityKey(r), "affKey"); AddSystemType(BinaryUtils.TypePlatformJavaObjectFactoryProxy, r => new PlatformJavaObjectFactoryProxy()); AddSystemType(0, r => new ObjectInfoHolder(r)); } } }
using System; namespace BizHawk.Emulation.Common.Components.LR35902 { public partial class LR35902 { private ulong totalExecutedCycles; public ulong TotalExecutedCycles { get { return totalExecutedCycles; } set { totalExecutedCycles = value; } } private int EI_pending; private bool interrupts_enabled; // variables for executing instructions public int instr_pntr = 0; public ushort[] cur_instr; public int opcode; public bool CB_prefix; public bool halted; public bool stopped; public bool jammed; public int LY; public void FetchInstruction(byte opcode) { if (!CB_prefix) { switch (opcode) { case 0x00: NOP_(); break; // NOP case 0x01: LD_IND_16(C, B, PCl, PCh); break; // LD BC, nn case 0x02: LD_8_IND(C, B, A); break; // LD (BC), A case 0x03: INC_16(C, B); break; // INC BC case 0x04: INT_OP(INC8, B); break; // INC B case 0x05: INT_OP(DEC8, B); break; // DEC B case 0x06: LD_IND_8_INC(B, PCl, PCh); break; // LD B, n case 0x07: INT_OP(RLC, Aim); break; // RLCA case 0x08: LD_R_IM(SPl, SPh, PCl, PCh); break; // LD (imm), SP case 0x09: ADD_16(L, H, C, B); break; // ADD HL, BC case 0x0A: REG_OP_IND(TR, A, C, B); break; // LD A, (BC) case 0x0B: DEC_16(C, B); break; // DEC BC case 0x0C: INT_OP(INC8, C); break; // INC C case 0x0D: INT_OP(DEC8, C); break; // DEC C case 0x0E: LD_IND_8_INC(C, PCl, PCh); break; // LD C, n case 0x0F: INT_OP(RRC, Aim); break; // RRCA case 0x10: STOP_(); break; // STOP case 0x11: LD_IND_16(E, D, PCl, PCh); break; // LD DE, nn case 0x12: LD_8_IND(E, D, A); break; // LD (DE), A case 0x13: INC_16(E, D); break; // INC DE case 0x14: INT_OP(INC8, D); break; // INC D case 0x15: INT_OP(DEC8, D); break; // DEC D case 0x16: LD_IND_8_INC(D, PCl, PCh); break; // LD D, n case 0x17: INT_OP(RL, Aim); break; // RLA case 0x18: JR_COND(true); break; // JR, r8 case 0x19: ADD_16(L, H, E, D); break; // ADD HL, DE case 0x1A: REG_OP_IND(TR, A, E, D); break; // LD A, (DE) case 0x1B: DEC_16(E, D); break; // DEC DE case 0x1C: INT_OP(INC8, E); break; // INC E case 0x1D: INT_OP(DEC8, E); break; // DEC E case 0x1E: LD_IND_8_INC(E, PCl, PCh); break; // LD E, n case 0x1F: INT_OP(RR, Aim); break; // RRA case 0x20: JR_COND(!FlagZ); break; // JR NZ, r8 case 0x21: LD_IND_16(L, H, PCl, PCh); break; // LD HL, nn case 0x22: LD_8_IND_INC(L, H, A); break; // LD (HL+), A case 0x23: INC_16(L, H); break; // INC HL case 0x24: INT_OP(INC8, H); break; // INC H case 0x25: INT_OP(DEC8, H); break; // DEC H case 0x26: LD_IND_8_INC(H, PCl, PCh); break; // LD H, n case 0x27: INT_OP(DA, A); break; // DAA case 0x28: JR_COND(FlagZ); break; // JR Z, r8 case 0x29: ADD_16(L, H, L, H); break; // ADD HL, HL case 0x2A: LD_IND_8_INC_HL(A, L, H); break; // LD A, (HL+) case 0x2B: DEC_16(L, H); break; // DEC HL case 0x2C: INT_OP(INC8, L); break; // INC L case 0x2D: INT_OP(DEC8, L); break; // DEC L case 0x2E: LD_IND_8_INC(L, PCl, PCh); break; // LD L, n case 0x2F: INT_OP(CPL, A); break; // CPL case 0x30: JR_COND(!FlagC); break; // JR NC, r8 case 0x31: LD_IND_16(SPl, SPh, PCl, PCh); break; // LD SP, nn case 0x32: LD_8_IND_DEC(L, H, A); break; // LD (HL-), A case 0x33: INC_16(SPl, SPh); break; // INC SP case 0x34: INC_8_IND(L, H); break; // INC (HL) case 0x35: DEC_8_IND(L, H); break; // DEC (HL) case 0x36: LD_8_IND_IND(L, H, PCl, PCh); break; // LD (HL), n case 0x37: INT_OP(SCF, A); break; // SCF case 0x38: JR_COND(FlagC); break; // JR C, r8 case 0x39: ADD_16(L, H, SPl, SPh); break; // ADD HL, SP case 0x3A: LD_IND_8_DEC_HL(A, L, H); break; // LD A, (HL-) case 0x3B: DEC_16(SPl, SPh); break; // DEC SP case 0x3C: INT_OP(INC8, A); break; // INC A case 0x3D: INT_OP(DEC8, A); break; // DEC A case 0x3E: LD_IND_8_INC(A, PCl, PCh); break; // LD A, n case 0x3F: INT_OP(CCF, A); break; // CCF case 0x40: REG_OP(TR, B, B); break; // LD B, B case 0x41: REG_OP(TR, B, C); break; // LD B, C case 0x42: REG_OP(TR, B, D); break; // LD B, D case 0x43: REG_OP(TR, B, E); break; // LD B, E case 0x44: REG_OP(TR, B, H); break; // LD B, H case 0x45: REG_OP(TR, B, L); break; // LD B, L case 0x46: REG_OP_IND(TR, B, L, H); break; // LD B, (HL) case 0x47: REG_OP(TR, B, A); break; // LD B, A case 0x48: REG_OP(TR, C, B); break; // LD C, B case 0x49: REG_OP(TR, C, C); break; // LD C, C case 0x4A: REG_OP(TR, C, D); break; // LD C, D case 0x4B: REG_OP(TR, C, E); break; // LD C, E case 0x4C: REG_OP(TR, C, H); break; // LD C, H case 0x4D: REG_OP(TR, C, L); break; // LD C, L case 0x4E: REG_OP_IND(TR, C, L, H); break; // LD C, (HL) case 0x4F: REG_OP(TR, C, A); break; // LD C, A case 0x50: REG_OP(TR, D, B); break; // LD D, B case 0x51: REG_OP(TR, D, C); break; // LD D, C case 0x52: REG_OP(TR, D, D); break; // LD D, D case 0x53: REG_OP(TR, D, E); break; // LD D, E case 0x54: REG_OP(TR, D, H); break; // LD D, H case 0x55: REG_OP(TR, D, L); break; // LD D, L case 0x56: REG_OP_IND(TR, D, L, H); break; // LD D, (HL) case 0x57: REG_OP(TR, D, A); break; // LD D, A case 0x58: REG_OP(TR, E, B); break; // LD E, B case 0x59: REG_OP(TR, E, C); break; // LD E, C case 0x5A: REG_OP(TR, E, D); break; // LD E, D case 0x5B: REG_OP(TR, E, E); break; // LD E, E case 0x5C: REG_OP(TR, E, H); break; // LD E, H case 0x5D: REG_OP(TR, E, L); break; // LD E, L case 0x5E: REG_OP_IND(TR, E, L, H); break; // LD E, (HL) case 0x5F: REG_OP(TR, E, A); break; // LD E, A case 0x60: REG_OP(TR, H, B); break; // LD H, B case 0x61: REG_OP(TR, H, C); break; // LD H, C case 0x62: REG_OP(TR, H, D); break; // LD H, D case 0x63: REG_OP(TR, H, E); break; // LD H, E case 0x64: REG_OP(TR, H, H); break; // LD H, H case 0x65: REG_OP(TR, H, L); break; // LD H, L case 0x66: REG_OP_IND(TR, H, L, H); break; // LD H, (HL) case 0x67: REG_OP(TR, H, A); break; // LD H, A case 0x68: REG_OP(TR, L, B); break; // LD L, B case 0x69: REG_OP(TR, L, C); break; // LD L, C case 0x6A: REG_OP(TR, L, D); break; // LD L, D case 0x6B: REG_OP(TR, L, E); break; // LD L, E case 0x6C: REG_OP(TR, L, H); break; // LD L, H case 0x6D: REG_OP(TR, L, L); break; // LD L, L case 0x6E: REG_OP_IND(TR, L, L, H); break; // LD L, (HL) case 0x6F: REG_OP(TR, L, A); break; // LD L, A case 0x70: LD_8_IND(L, H, B); break; // LD (HL), B case 0x71: LD_8_IND(L, H, C); break; // LD (HL), C case 0x72: LD_8_IND(L, H, D); break; // LD (HL), D case 0x73: LD_8_IND(L, H, E); break; // LD (HL), E case 0x74: LD_8_IND(L, H, H); break; // LD (HL), H case 0x75: LD_8_IND(L, H, L); break; // LD (HL), L case 0x76: HALT_(); break; // HALT case 0x77: LD_8_IND(L, H, A); break; // LD (HL), A case 0x78: REG_OP(TR, A, B); break; // LD A, B case 0x79: REG_OP(TR, A, C); break; // LD A, C case 0x7A: REG_OP(TR, A, D); break; // LD A, D case 0x7B: REG_OP(TR, A, E); break; // LD A, E case 0x7C: REG_OP(TR, A, H); break; // LD A, H case 0x7D: REG_OP(TR, A, L); break; // LD A, L case 0x7E: REG_OP_IND(TR, A, L, H); break; // LD A, (HL) case 0x7F: REG_OP(TR, A, A); break; // LD A, A case 0x80: REG_OP(ADD8, A, B); break; // ADD A, B case 0x81: REG_OP(ADD8, A, C); break; // ADD A, C case 0x82: REG_OP(ADD8, A, D); break; // ADD A, D case 0x83: REG_OP(ADD8, A, E); break; // ADD A, E case 0x84: REG_OP(ADD8, A, H); break; // ADD A, H case 0x85: REG_OP(ADD8, A, L); break; // ADD A, L case 0x86: REG_OP_IND(ADD8, A, L, H); break; // ADD A, (HL) case 0x87: REG_OP(ADD8, A, A); break; // ADD A, A case 0x88: REG_OP(ADC8, A, B); break; // ADC A, B case 0x89: REG_OP(ADC8, A, C); break; // ADC A, C case 0x8A: REG_OP(ADC8, A, D); break; // ADC A, D case 0x8B: REG_OP(ADC8, A, E); break; // ADC A, E case 0x8C: REG_OP(ADC8, A, H); break; // ADC A, H case 0x8D: REG_OP(ADC8, A, L); break; // ADC A, L case 0x8E: REG_OP_IND(ADC8, A, L, H); break; // ADC A, (HL) case 0x8F: REG_OP(ADC8, A, A); break; // ADC A, A case 0x90: REG_OP(SUB8, A, B); break; // SUB A, B case 0x91: REG_OP(SUB8, A, C); break; // SUB A, C case 0x92: REG_OP(SUB8, A, D); break; // SUB A, D case 0x93: REG_OP(SUB8, A, E); break; // SUB A, E case 0x94: REG_OP(SUB8, A, H); break; // SUB A, H case 0x95: REG_OP(SUB8, A, L); break; // SUB A, L case 0x96: REG_OP_IND(SUB8, A, L, H); break; // SUB A, (HL) case 0x97: REG_OP(SUB8, A, A); break; // SUB A, A case 0x98: REG_OP(SBC8, A, B); break; // SBC A, B case 0x99: REG_OP(SBC8, A, C); break; // SBC A, C case 0x9A: REG_OP(SBC8, A, D); break; // SBC A, D case 0x9B: REG_OP(SBC8, A, E); break; // SBC A, E case 0x9C: REG_OP(SBC8, A, H); break; // SBC A, H case 0x9D: REG_OP(SBC8, A, L); break; // SBC A, L case 0x9E: REG_OP_IND(SBC8, A, L, H); break; // SBC A, (HL) case 0x9F: REG_OP(SBC8, A, A); break; // SBC A, A case 0xA0: REG_OP(AND8, A, B); break; // AND A, B case 0xA1: REG_OP(AND8, A, C); break; // AND A, C case 0xA2: REG_OP(AND8, A, D); break; // AND A, D case 0xA3: REG_OP(AND8, A, E); break; // AND A, E case 0xA4: REG_OP(AND8, A, H); break; // AND A, H case 0xA5: REG_OP(AND8, A, L); break; // AND A, L case 0xA6: REG_OP_IND(AND8, A, L, H); break; // AND A, (HL) case 0xA7: REG_OP(AND8, A, A); break; // AND A, A case 0xA8: REG_OP(XOR8, A, B); break; // XOR A, B case 0xA9: REG_OP(XOR8, A, C); break; // XOR A, C case 0xAA: REG_OP(XOR8, A, D); break; // XOR A, D case 0xAB: REG_OP(XOR8, A, E); break; // XOR A, E case 0xAC: REG_OP(XOR8, A, H); break; // XOR A, H case 0xAD: REG_OP(XOR8, A, L); break; // XOR A, L case 0xAE: REG_OP_IND(XOR8, A, L, H); break; // XOR A, (HL) case 0xAF: REG_OP(XOR8, A, A); break; // XOR A, A case 0xB0: REG_OP(OR8, A, B); break; // OR A, B case 0xB1: REG_OP(OR8, A, C); break; // OR A, C case 0xB2: REG_OP(OR8, A, D); break; // OR A, D case 0xB3: REG_OP(OR8, A, E); break; // OR A, E case 0xB4: REG_OP(OR8, A, H); break; // OR A, H case 0xB5: REG_OP(OR8, A, L); break; // OR A, L case 0xB6: REG_OP_IND(OR8, A, L, H); break; // OR A, (HL) case 0xB7: REG_OP(OR8, A, A); break; // OR A, A case 0xB8: REG_OP(CP8, A, B); break; // CP A, B case 0xB9: REG_OP(CP8, A, C); break; // CP A, C case 0xBA: REG_OP(CP8, A, D); break; // CP A, D case 0xBB: REG_OP(CP8, A, E); break; // CP A, E case 0xBC: REG_OP(CP8, A, H); break; // CP A, H case 0xBD: REG_OP(CP8, A, L); break; // CP A, L case 0xBE: REG_OP_IND(CP8, A, L, H); break; // CP A, (HL) case 0xBF: REG_OP(CP8, A, A); break; // CP A, A case 0xC0: RET_COND(!FlagZ); break; // Ret NZ case 0xC1: POP_(C, B); break; // POP BC case 0xC2: JP_COND(!FlagZ); break; // JP NZ case 0xC3: JP_COND(true); break; // JP case 0xC4: CALL_COND(!FlagZ); break; // CALL NZ case 0xC5: PUSH_(C, B); break; // PUSH BC case 0xC6: REG_OP_IND_INC(ADD8, A, PCl, PCh); break; // ADD A, n case 0xC7: RST_(0); break; // RST 0 case 0xC8: RET_COND(FlagZ); break; // RET Z case 0xC9: RET_(); break; // RET case 0xCA: JP_COND(FlagZ); break; // JP Z case 0xCB: PREFIX_(); break; // PREFIX case 0xCC: CALL_COND(FlagZ); break; // CALL Z case 0xCD: CALL_COND(true); break; // CALL case 0xCE: REG_OP_IND_INC(ADC8, A, PCl, PCh); break; // ADC A, n case 0xCF: RST_(0x08); break; // RST 0x08 case 0xD0: RET_COND(!FlagC); break; // Ret NC case 0xD1: POP_(E, D); break; // POP DE case 0xD2: JP_COND(!FlagC); break; // JP NC case 0xD3: JAM_(); break; // JAM case 0xD4: CALL_COND(!FlagC); break; // CALL NC case 0xD5: PUSH_(E, D); break; // PUSH DE case 0xD6: REG_OP_IND_INC(SUB8, A, PCl, PCh); break; // SUB A, n case 0xD7: RST_(0x10); break; // RST 0x10 case 0xD8: RET_COND(FlagC); break; // RET C case 0xD9: RETI_(); break; // RETI case 0xDA: JP_COND(FlagC); break; // JP C case 0xDB: JAM_(); break; // JAM case 0xDC: CALL_COND(FlagC); break; // CALL C case 0xDD: JAM_(); break; // JAM case 0xDE: REG_OP_IND_INC(SBC8, A, PCl, PCh); break; // SBC A, n case 0xDF: RST_(0x18); break; // RST 0x18 case 0xE0: LD_FF_IND_8(PCl, PCh, A); break; // LD(n), A case 0xE1: POP_(L, H); break; // POP HL case 0xE2: LD_FFC_IND_8(PCl, PCh, A); break; // LD(C), A case 0xE3: JAM_(); break; // JAM case 0xE4: JAM_(); break; // JAM case 0xE5: PUSH_(L, H); break; // PUSH HL case 0xE6: REG_OP_IND_INC(AND8, A, PCl, PCh); break; // AND A, n case 0xE7: RST_(0x20); break; // RST 0x20 case 0xE8: ADD_SP(); break; // ADD SP,n case 0xE9: JP_HL(); break; // JP (HL) case 0xEA: LD_FF_IND_16(PCl, PCh, A); break; // LD(nn), A case 0xEB: JAM_(); break; // JAM case 0xEC: JAM_(); break; // JAM case 0xED: JAM_(); break; // JAM case 0xEE: REG_OP_IND_INC(XOR8, A, PCl, PCh); break; // XOR A, n case 0xEF: RST_(0x28); break; // RST 0x28 case 0xF0: LD_8_IND_FF(A, PCl, PCh); break; // A, LD(n) case 0xF1: POP_(F, A); break; // POP AF case 0xF2: LD_8_IND_FFC(A, PCl, PCh); break; // A, LD(C) case 0xF3: DI_(); break; // DI case 0xF4: JAM_(); break; // JAM case 0xF5: PUSH_(F, A); break; // PUSH AF case 0xF6: REG_OP_IND_INC(OR8, A, PCl, PCh); break; // OR A, n case 0xF7: RST_(0x30); break; // RST 0x30 case 0xF8: LD_HL_SPn(); break; // LD HL, SP+n case 0xF9: LD_SP_HL(); break; // LD, SP, HL case 0xFA: LD_16_IND_FF(A, PCl, PCh); break; // A, LD(nn) case 0xFB: EI_(); break; // EI case 0xFC: JAM_(); break; // JAM case 0xFD: JAM_(); break; // JAM case 0xFE: REG_OP_IND_INC(CP8, A, PCl, PCh); break; // XOR A, n case 0xFF: RST_(0x38); break; // RST 0x38 } } else { CB_prefix = false; switch (opcode) { case 0x00: INT_OP(RLC, B); break; // RLC B case 0x01: INT_OP(RLC, C); break; // RLC C case 0x02: INT_OP(RLC, D); break; // RLC D case 0x03: INT_OP(RLC, E); break; // RLC E case 0x04: INT_OP(RLC, H); break; // RLC H case 0x05: INT_OP(RLC, L); break; // RLC L case 0x06: INT_OP_IND(RLC, L, H); break; // RLC (HL) case 0x07: INT_OP(RLC, A); break; // RLC A case 0x08: INT_OP(RRC, B); break; // RRC B case 0x09: INT_OP(RRC, C); break; // RRC C case 0x0A: INT_OP(RRC, D); break; // RRC D case 0x0B: INT_OP(RRC, E); break; // RRC E case 0x0C: INT_OP(RRC, H); break; // RRC H case 0x0D: INT_OP(RRC, L); break; // RRC L case 0x0E: INT_OP_IND(RRC, L, H); break; // RRC (HL) case 0x0F: INT_OP(RRC, A); break; // RRC A case 0x10: INT_OP(RL, B); break; // RL B case 0x11: INT_OP(RL, C); break; // RL C case 0x12: INT_OP(RL, D); break; // RL D case 0x13: INT_OP(RL, E); break; // RL E case 0x14: INT_OP(RL, H); break; // RL H case 0x15: INT_OP(RL, L); break; // RL L case 0x16: INT_OP_IND(RL, L, H); break; // RL (HL) case 0x17: INT_OP(RL, A); break; // RL A case 0x18: INT_OP(RR, B); break; // RR B case 0x19: INT_OP(RR, C); break; // RR C case 0x1A: INT_OP(RR, D); break; // RR D case 0x1B: INT_OP(RR, E); break; // RR E case 0x1C: INT_OP(RR, H); break; // RR H case 0x1D: INT_OP(RR, L); break; // RR L case 0x1E: INT_OP_IND(RR, L, H); break; // RR (HL) case 0x1F: INT_OP(RR, A); break; // RR A case 0x20: INT_OP(SLA, B); break; // SLA B case 0x21: INT_OP(SLA, C); break; // SLA C case 0x22: INT_OP(SLA, D); break; // SLA D case 0x23: INT_OP(SLA, E); break; // SLA E case 0x24: INT_OP(SLA, H); break; // SLA H case 0x25: INT_OP(SLA, L); break; // SLA L case 0x26: INT_OP_IND(SLA, L, H); break; // SLA (HL) case 0x27: INT_OP(SLA, A); break; // SLA A case 0x28: INT_OP(SRA, B); break; // SRA B case 0x29: INT_OP(SRA, C); break; // SRA C case 0x2A: INT_OP(SRA, D); break; // SRA D case 0x2B: INT_OP(SRA, E); break; // SRA E case 0x2C: INT_OP(SRA, H); break; // SRA H case 0x2D: INT_OP(SRA, L); break; // SRA L case 0x2E: INT_OP_IND(SRA, L, H); break; // SRA (HL) case 0x2F: INT_OP(SRA, A); break; // SRA A case 0x30: INT_OP(SWAP, B); break; // SWAP B case 0x31: INT_OP(SWAP, C); break; // SWAP C case 0x32: INT_OP(SWAP, D); break; // SWAP D case 0x33: INT_OP(SWAP, E); break; // SWAP E case 0x34: INT_OP(SWAP, H); break; // SWAP H case 0x35: INT_OP(SWAP, L); break; // SWAP L case 0x36: INT_OP_IND(SWAP, L, H); break; // SWAP (HL) case 0x37: INT_OP(SWAP, A); break; // SWAP A case 0x38: INT_OP(SRL, B); break; // SRL B case 0x39: INT_OP(SRL, C); break; // SRL C case 0x3A: INT_OP(SRL, D); break; // SRL D case 0x3B: INT_OP(SRL, E); break; // SRL E case 0x3C: INT_OP(SRL, H); break; // SRL H case 0x3D: INT_OP(SRL, L); break; // SRL L case 0x3E: INT_OP_IND(SRL, L, H); break; // SRL (HL) case 0x3F: INT_OP(SRL, A); break; // SRL A case 0x40: BIT_OP(BIT, 0, B); break; // BIT 0, B case 0x41: BIT_OP(BIT, 0, C); break; // BIT 0, C case 0x42: BIT_OP(BIT, 0, D); break; // BIT 0, D case 0x43: BIT_OP(BIT, 0, E); break; // BIT 0, E case 0x44: BIT_OP(BIT, 0, H); break; // BIT 0, H case 0x45: BIT_OP(BIT, 0, L); break; // BIT 0, L case 0x46: BIT_TE_IND(BIT, 0, L, H); break; // BIT 0, (HL) case 0x47: BIT_OP(BIT, 0, A); break; // BIT 0, A case 0x48: BIT_OP(BIT, 1, B); break; // BIT 1, B case 0x49: BIT_OP(BIT, 1, C); break; // BIT 1, C case 0x4A: BIT_OP(BIT, 1, D); break; // BIT 1, D case 0x4B: BIT_OP(BIT, 1, E); break; // BIT 1, E case 0x4C: BIT_OP(BIT, 1, H); break; // BIT 1, H case 0x4D: BIT_OP(BIT, 1, L); break; // BIT 1, L case 0x4E: BIT_TE_IND(BIT, 1, L, H); break; // BIT 1, (HL) case 0x4F: BIT_OP(BIT, 1, A); break; // BIT 1, A case 0x50: BIT_OP(BIT, 2, B); break; // BIT 2, B case 0x51: BIT_OP(BIT, 2, C); break; // BIT 2, C case 0x52: BIT_OP(BIT, 2, D); break; // BIT 2, D case 0x53: BIT_OP(BIT, 2, E); break; // BIT 2, E case 0x54: BIT_OP(BIT, 2, H); break; // BIT 2, H case 0x55: BIT_OP(BIT, 2, L); break; // BIT 2, L case 0x56: BIT_TE_IND(BIT, 2, L, H); break; // BIT 2, (HL) case 0x57: BIT_OP(BIT, 2, A); break; // BIT 2, A case 0x58: BIT_OP(BIT, 3, B); break; // BIT 3, B case 0x59: BIT_OP(BIT, 3, C); break; // BIT 3, C case 0x5A: BIT_OP(BIT, 3, D); break; // BIT 3, D case 0x5B: BIT_OP(BIT, 3, E); break; // BIT 3, E case 0x5C: BIT_OP(BIT, 3, H); break; // BIT 3, H case 0x5D: BIT_OP(BIT, 3, L); break; // BIT 3, L case 0x5E: BIT_TE_IND(BIT, 3, L, H); break; // BIT 3, (HL) case 0x5F: BIT_OP(BIT, 3, A); break; // BIT 3, A case 0x60: BIT_OP(BIT, 4, B); break; // BIT 4, B case 0x61: BIT_OP(BIT, 4, C); break; // BIT 4, C case 0x62: BIT_OP(BIT, 4, D); break; // BIT 4, D case 0x63: BIT_OP(BIT, 4, E); break; // BIT 4, E case 0x64: BIT_OP(BIT, 4, H); break; // BIT 4, H case 0x65: BIT_OP(BIT, 4, L); break; // BIT 4, L case 0x66: BIT_TE_IND(BIT, 4, L, H); break; // BIT 4, (HL) case 0x67: BIT_OP(BIT, 4, A); break; // BIT 4, A case 0x68: BIT_OP(BIT, 5, B); break; // BIT 5, B case 0x69: BIT_OP(BIT, 5, C); break; // BIT 5, C case 0x6A: BIT_OP(BIT, 5, D); break; // BIT 5, D case 0x6B: BIT_OP(BIT, 5, E); break; // BIT 5, E case 0x6C: BIT_OP(BIT, 5, H); break; // BIT 5, H case 0x6D: BIT_OP(BIT, 5, L); break; // BIT 5, L case 0x6E: BIT_TE_IND(BIT, 5, L, H); break; // BIT 5, (HL) case 0x6F: BIT_OP(BIT, 5, A); break; // BIT 5, A case 0x70: BIT_OP(BIT, 6, B); break; // BIT 6, B case 0x71: BIT_OP(BIT, 6, C); break; // BIT 6, C case 0x72: BIT_OP(BIT, 6, D); break; // BIT 6, D case 0x73: BIT_OP(BIT, 6, E); break; // BIT 6, E case 0x74: BIT_OP(BIT, 6, H); break; // BIT 6, H case 0x75: BIT_OP(BIT, 6, L); break; // BIT 6, L case 0x76: BIT_TE_IND(BIT, 6, L, H); break; // BIT 6, (HL) case 0x77: BIT_OP(BIT, 6, A); break; // BIT 6, A case 0x78: BIT_OP(BIT, 7, B); break; // BIT 7, B case 0x79: BIT_OP(BIT, 7, C); break; // BIT 7, C case 0x7A: BIT_OP(BIT, 7, D); break; // BIT 7, D case 0x7B: BIT_OP(BIT, 7, E); break; // BIT 7, E case 0x7C: BIT_OP(BIT, 7, H); break; // BIT 7, H case 0x7D: BIT_OP(BIT, 7, L); break; // BIT 7, L case 0x7E: BIT_TE_IND(BIT, 7, L, H); break; // BIT 7, (HL) case 0x7F: BIT_OP(BIT, 7, A); break; // BIT 7, A case 0x80: BIT_OP(RES, 0, B); break; // RES 0, B case 0x81: BIT_OP(RES, 0, C); break; // RES 0, C case 0x82: BIT_OP(RES, 0, D); break; // RES 0, D case 0x83: BIT_OP(RES, 0, E); break; // RES 0, E case 0x84: BIT_OP(RES, 0, H); break; // RES 0, H case 0x85: BIT_OP(RES, 0, L); break; // RES 0, L case 0x86: BIT_OP_IND(RES, 0, L, H); break; // RES 0, (HL) case 0x87: BIT_OP(RES, 0, A); break; // RES 0, A case 0x88: BIT_OP(RES, 1, B); break; // RES 1, B case 0x89: BIT_OP(RES, 1, C); break; // RES 1, C case 0x8A: BIT_OP(RES, 1, D); break; // RES 1, D case 0x8B: BIT_OP(RES, 1, E); break; // RES 1, E case 0x8C: BIT_OP(RES, 1, H); break; // RES 1, H case 0x8D: BIT_OP(RES, 1, L); break; // RES 1, L case 0x8E: BIT_OP_IND(RES, 1, L, H); break; // RES 1, (HL) case 0x8F: BIT_OP(RES, 1, A); break; // RES 1, A case 0x90: BIT_OP(RES, 2, B); break; // RES 2, B case 0x91: BIT_OP(RES, 2, C); break; // RES 2, C case 0x92: BIT_OP(RES, 2, D); break; // RES 2, D case 0x93: BIT_OP(RES, 2, E); break; // RES 2, E case 0x94: BIT_OP(RES, 2, H); break; // RES 2, H case 0x95: BIT_OP(RES, 2, L); break; // RES 2, L case 0x96: BIT_OP_IND(RES, 2, L, H); break; // RES 2, (HL) case 0x97: BIT_OP(RES, 2, A); break; // RES 2, A case 0x98: BIT_OP(RES, 3, B); break; // RES 3, B case 0x99: BIT_OP(RES, 3, C); break; // RES 3, C case 0x9A: BIT_OP(RES, 3, D); break; // RES 3, D case 0x9B: BIT_OP(RES, 3, E); break; // RES 3, E case 0x9C: BIT_OP(RES, 3, H); break; // RES 3, H case 0x9D: BIT_OP(RES, 3, L); break; // RES 3, L case 0x9E: BIT_OP_IND(RES, 3, L, H); break; // RES 3, (HL) case 0x9F: BIT_OP(RES, 3, A); break; // RES 3, A case 0xA0: BIT_OP(RES, 4, B); break; // RES 4, B case 0xA1: BIT_OP(RES, 4, C); break; // RES 4, C case 0xA2: BIT_OP(RES, 4, D); break; // RES 4, D case 0xA3: BIT_OP(RES, 4, E); break; // RES 4, E case 0xA4: BIT_OP(RES, 4, H); break; // RES 4, H case 0xA5: BIT_OP(RES, 4, L); break; // RES 4, L case 0xA6: BIT_OP_IND(RES, 4, L, H); break; // RES 4, (HL) case 0xA7: BIT_OP(RES, 4, A); break; // RES 4, A case 0xA8: BIT_OP(RES, 5, B); break; // RES 5, B case 0xA9: BIT_OP(RES, 5, C); break; // RES 5, C case 0xAA: BIT_OP(RES, 5, D); break; // RES 5, D case 0xAB: BIT_OP(RES, 5, E); break; // RES 5, E case 0xAC: BIT_OP(RES, 5, H); break; // RES 5, H case 0xAD: BIT_OP(RES, 5, L); break; // RES 5, L case 0xAE: BIT_OP_IND(RES, 5, L, H); break; // RES 5, (HL) case 0xAF: BIT_OP(RES, 5, A); break; // RES 5, A case 0xB0: BIT_OP(RES, 6, B); break; // RES 6, B case 0xB1: BIT_OP(RES, 6, C); break; // RES 6, C case 0xB2: BIT_OP(RES, 6, D); break; // RES 6, D case 0xB3: BIT_OP(RES, 6, E); break; // RES 6, E case 0xB4: BIT_OP(RES, 6, H); break; // RES 6, H case 0xB5: BIT_OP(RES, 6, L); break; // RES 6, L case 0xB6: BIT_OP_IND(RES, 6, L, H); break; // RES 6, (HL) case 0xB7: BIT_OP(RES, 6, A); break; // RES 6, A case 0xB8: BIT_OP(RES, 7, B); break; // RES 7, B case 0xB9: BIT_OP(RES, 7, C); break; // RES 7, C case 0xBA: BIT_OP(RES, 7, D); break; // RES 7, D case 0xBB: BIT_OP(RES, 7, E); break; // RES 7, E case 0xBC: BIT_OP(RES, 7, H); break; // RES 7, H case 0xBD: BIT_OP(RES, 7, L); break; // RES 7, L case 0xBE: BIT_OP_IND(RES, 7, L, H); break; // RES 7, (HL) case 0xBF: BIT_OP(RES, 7, A); break; // RES 7, A case 0xC0: BIT_OP(SET, 0, B); break; // SET 0, B case 0xC1: BIT_OP(SET, 0, C); break; // SET 0, C case 0xC2: BIT_OP(SET, 0, D); break; // SET 0, D case 0xC3: BIT_OP(SET, 0, E); break; // SET 0, E case 0xC4: BIT_OP(SET, 0, H); break; // SET 0, H case 0xC5: BIT_OP(SET, 0, L); break; // SET 0, L case 0xC6: BIT_OP_IND(SET, 0, L, H); break; // SET 0, (HL) case 0xC7: BIT_OP(SET, 0, A); break; // SET 0, A case 0xC8: BIT_OP(SET, 1, B); break; // SET 1, B case 0xC9: BIT_OP(SET, 1, C); break; // SET 1, C case 0xCA: BIT_OP(SET, 1, D); break; // SET 1, D case 0xCB: BIT_OP(SET, 1, E); break; // SET 1, E case 0xCC: BIT_OP(SET, 1, H); break; // SET 1, H case 0xCD: BIT_OP(SET, 1, L); break; // SET 1, L case 0xCE: BIT_OP_IND(SET, 1, L, H); break; // SET 1, (HL) case 0xCF: BIT_OP(SET, 1, A); break; // SET 1, A case 0xD0: BIT_OP(SET, 2, B); break; // SET 2, B case 0xD1: BIT_OP(SET, 2, C); break; // SET 2, C case 0xD2: BIT_OP(SET, 2, D); break; // SET 2, D case 0xD3: BIT_OP(SET, 2, E); break; // SET 2, E case 0xD4: BIT_OP(SET, 2, H); break; // SET 2, H case 0xD5: BIT_OP(SET, 2, L); break; // SET 2, L case 0xD6: BIT_OP_IND(SET, 2, L, H); break; // SET 2, (HL) case 0xD7: BIT_OP(SET, 2, A); break; // SET 2, A case 0xD8: BIT_OP(SET, 3, B); break; // SET 3, B case 0xD9: BIT_OP(SET, 3, C); break; // SET 3, C case 0xDA: BIT_OP(SET, 3, D); break; // SET 3, D case 0xDB: BIT_OP(SET, 3, E); break; // SET 3, E case 0xDC: BIT_OP(SET, 3, H); break; // SET 3, H case 0xDD: BIT_OP(SET, 3, L); break; // SET 3, L case 0xDE: BIT_OP_IND(SET, 3, L, H); break; // SET 3, (HL) case 0xDF: BIT_OP(SET, 3, A); break; // SET 3, A case 0xE0: BIT_OP(SET, 4, B); break; // SET 4, B case 0xE1: BIT_OP(SET, 4, C); break; // SET 4, C case 0xE2: BIT_OP(SET, 4, D); break; // SET 4, D case 0xE3: BIT_OP(SET, 4, E); break; // SET 4, E case 0xE4: BIT_OP(SET, 4, H); break; // SET 4, H case 0xE5: BIT_OP(SET, 4, L); break; // SET 4, L case 0xE6: BIT_OP_IND(SET, 4, L, H); break; // SET 4, (HL) case 0xE7: BIT_OP(SET, 4, A); break; // SET 4, A case 0xE8: BIT_OP(SET, 5, B); break; // SET 5, B case 0xE9: BIT_OP(SET, 5, C); break; // SET 5, C case 0xEA: BIT_OP(SET, 5, D); break; // SET 5, D case 0xEB: BIT_OP(SET, 5, E); break; // SET 5, E case 0xEC: BIT_OP(SET, 5, H); break; // SET 5, H case 0xED: BIT_OP(SET, 5, L); break; // SET 5, L case 0xEE: BIT_OP_IND(SET, 5, L, H); break; // SET 5, (HL) case 0xEF: BIT_OP(SET, 5, A); break; // SET 5, A case 0xF0: BIT_OP(SET, 6, B); break; // SET 6, B case 0xF1: BIT_OP(SET, 6, C); break; // SET 6, C case 0xF2: BIT_OP(SET, 6, D); break; // SET 6, D case 0xF3: BIT_OP(SET, 6, E); break; // SET 6, E case 0xF4: BIT_OP(SET, 6, H); break; // SET 6, H case 0xF5: BIT_OP(SET, 6, L); break; // SET 6, L case 0xF6: BIT_OP_IND(SET, 6, L, H); break; // SET 6, (HL) case 0xF7: BIT_OP(SET, 6, A); break; // SET 6, A case 0xF8: BIT_OP(SET, 7, B); break; // SET 7, B case 0xF9: BIT_OP(SET, 7, C); break; // SET 7, C case 0xFA: BIT_OP(SET, 7, D); break; // SET 7, D case 0xFB: BIT_OP(SET, 7, E); break; // SET 7, E case 0xFC: BIT_OP(SET, 7, H); break; // SET 7, H case 0xFD: BIT_OP(SET, 7, L); break; // SET 7, L case 0xFE: BIT_OP_IND(SET, 7, L, H); break; // SET 7, (HL) case 0xFF: BIT_OP(SET, 7, A); break; // SET 7, A } } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Rdio.Android.Sdk; using Rdio.Android.Sdk.Services; using Log = Android.Util.Log; namespace Similardio { [Activity (Label = "Similardio", MainLauncher = true, Theme = "@android:style/Theme.Holo.Light.NoActionBar")] public class MainActivity : Activity, IRdioListener { bool hasTokens; ArtistAdapter adapter; LoadingFragment loadingFragment; ListFragment list; LastFmApi lastFmApi; RdioAPI rdioApi; TaskCompletionSource<bool> rdioReady = new TaskCompletionSource<bool> (); protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); DensityExtensions.Initialize (this); SetContentView (Resource.Layout.Main); loadingFragment = new LoadingFragment (); var t = FragmentManager.BeginTransaction (); t.Add (Resource.Id.mainContainer, loadingFragment, "loading"); t.Commit (); RetrieveArtist (); } void ShowList () { adapter = new ArtistAdapter (this); list = new RdioListFragment (); var t = FragmentManager.BeginTransaction (); t.SetTransition (FragmentTransit.FragmentClose); t.Replace (Resource.Id.mainContainer, list, "artist-list"); t.Commit (); } async void RetrieveArtist () { var artists = await Task.Run (() => DoRetrieve (new UIProgress (this)).Result); ShowList (); foreach (var artist in artists) adapter.Data.Add (artist); list.ListAdapter = adapter; } async Task<ArtistData[]> DoRetrieve (IProgress<Action> uiProgress) { lastFmApi = new LastFmApi (); var prefs = GetPreferences (FileCreationMode.Private); hasTokens = prefs.GetString ("accessToken", null) != null; if (!hasTokens) uiProgress.Report (() => loadingFragment.SetExtraExplanation ("(will need more time to login)")); rdioApi = new RdioAPI (Keys.RdioKey, Keys.RdioSecret, prefs.GetString ("accessToken", null), prefs.GetString ("accessSecret", null), this, this); await rdioReady.Task.ConfigureAwait (false); var args = new object[] { new Org.Apache.Http.Message.BasicNameValuePair ("sort", "playCount"), new Org.Apache.Http.Message.BasicNameValuePair ("count", "30") }; var artistsCompletion = new TaskCompletionSource<RdioArtist[]> (); var callback = new LambdaRdioCallback (success: json => { var array = json.GetJSONArray ("result"); var result = Enumerable.Range (0, array.Length ()).Select (i => { var o = array.GetJSONObject (i); return new RdioArtist { Key = o.GetString ("key"), Name = o.GetString ("name") }; }).ToArray (); artistsCompletion.SetResult (result); }); rdioApi.ApiCall ("getArtistsInCollection", args, callback); var rdioArtists = await artistsCompletion.Task.ConfigureAwait (false); uiProgress.Report (() => loadingFragment.ChangeLoading (Resource.Drawable.lastfm_logo, "Scouting Lastfm")); var artists = new Dictionary<ArtistData, List<SimilarityLink>> (); int rdioArtistIndex = rdioArtists.Length; var counter = 0; var existingArtists = new HashSet<string> (rdioArtists.Select (ra => ra.Name)); foreach (var rdioArtist in rdioArtists) { var arts = await lastFmApi.GetSimilarArtistsAsync (rdioArtist.Name).ConfigureAwait (false); var newExplanation = "(" + (++counter) + " out of " + rdioArtists.Length + ")"; uiProgress.Report (() => loadingFragment.SetExtraExplanation (newExplanation)); foreach (var a in arts.Where (a => !existingArtists.Contains (a.Name))) { List<SimilarityLink> links; if (!artists.TryGetValue (a, out links)) artists[a] = links = new List<SimilarityLink> (); links.Add (new SimilarityLink { Strength = a.Match, RdioArtistIndex = rdioArtistIndex, RdioArtistName = rdioArtist.Name }); } rdioArtistIndex--; } return SynthetizeLinks (artists, rdioArtists.Length); } ArtistData[] SynthetizeLinks (Dictionary<ArtistData, List<SimilarityLink>> links, int maxRdioIndex) { return links.Select (node => { var ad = node.Key; ad.SimilarArtists = node.Value.Select (v => v.RdioArtistName).ToArray (); // Final AD match is the mean of all links calculated power. // A link power is a value composed for 60% of the original link strength // and 40% for the Rdio artist position it links to ad.Match = node.Value .Select (link => Math.Min (1, .6 * link.Strength + .4 * (((double)link.RdioArtistIndex) / maxRdioIndex))) .Average (); return ad; }).OrderByDescending (ad => ad.Match).ToArray (); } public void OnRdioAuthorised (string accessToken, string accessSecret) { var prefs = GetPreferences (FileCreationMode.Private); using (var editor = prefs.Edit ()) { editor.PutString ("accessToken", accessToken); editor.PutString ("accessSecret", accessSecret); editor.Commit (); } rdioReady.TrySetResult (true); } public void OnRdioReady () { if (hasTokens) rdioReady.TrySetResult (true); } public void OnRdioUserAppApprovalNeeded (Intent authIntent) { try { StartActivityForResult (authIntent, 100); } catch (ActivityNotFoundException) { Log.Error ("Auth", "Rdio App not found"); } } public void OnRdioUserPlayingElsewhere () { } protected override void OnActivityResult (int requestCode, Result resultCode, Intent data) { if ((int)resultCode == RdioAPI.ResultAuthorisationRejected) { Finish (); return; } else if (data != null && (int)resultCode == RdioAPI.ResultAuthorisationAccepted) { rdioApi.SetTokenAndSecret (data); } } } class LambdaRdioCallback : Java.Lang.Object, IRdioApiCallback { Action<Org.Json.JSONObject> success; Action<string, Exception> failure; public LambdaRdioCallback (Action<Org.Json.JSONObject> success = null, Action<string, Exception> failure = null) { this.success = success; this.failure = failure; } public void OnApiFailure (string p0, Java.Lang.Exception p1) { if (failure != null) failure (p0, p1); } public void OnApiSuccess (Org.Json.JSONObject p0) { if (success != null) success (p0); } } class UIProgress : IProgress<Action> { Activity activity; public UIProgress (Activity activity) { this.activity = activity; } public void Report (Action action) { activity.RunOnUiThread (action); } } struct RdioArtist { public string Name { get; set; } public string Key { get; set; } } struct SimilarityLink { public double Strength; public int RdioArtistIndex; public string RdioArtistName; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DEBUG_DUMP_ALL_PHASES_AFTER_TYPE_SYSTEM_REDUCTION //#define DEBUG_DUMP_ALL_PHASES #define DEBUG_DUMP_XML //#define REPORT_OPERATORS_AT_EACH_PHASE //#define CLONE_STATE //#define USE_IMOTE_PLATFORM namespace Microsoft.Zelig.CodeGeneration.UnitTest { using System; using System.Collections.Generic; using System.Text; using System.IO; using Microsoft.Zelig.MetaData; using Importer = Microsoft.Zelig.MetaData.Importer; using Normalized = Microsoft.Zelig.MetaData.Normalized; using IR = Microsoft.Zelig.CodeGeneration.IR; using TS = Microsoft.Zelig.Runtime.TypeSystem; using ARM = Microsoft.Zelig.Emulation.ArmProcessor; class CodeGenerationTester : BaseTester, Microsoft.Zelig.MetaData.IMetaDataResolverHelper, Microsoft.Zelig.MetaData.ISymbolResolverHelper { // // State // private string m_filePrefix; private bool m_fDumpIRToFile; private int m_dumpCount; // // Constructor Methods // private CodeGenerationTester() { m_symbolHelper = this; m_metaDataResolverHelper = this; Initialize(); } public static void Run( string[] args ) { string[] files = { #if USE_IMOTE_PLATFORM BuildRoot + @"\Target\bin\" + BuildFlavor + @"\Microsoft.iMote2.dll", BuildRoot + @"\Target\bin\" + BuildFlavor + @"\Microsoft.DeviceModels.ModelForPXA27x.dll", BuildRoot + @"\Target\bin\" + BuildFlavor + @"\QuickTest.exe", #else BuildRoot + @"\Target\bin\" + BuildFlavor + @"\mscorlib_unittest.exe", BuildRoot + @"\Target\bin\" + BuildFlavor + @"\Microsoft.VoxSoloFormFactor.dll", #endif }; CodeGenerationTester pThis = new CodeGenerationTester(); pThis.Run( files, true, true ); Console.WriteLine( "Execution time: {0}", pThis.GetTime() ); } private void Run( string[] files , bool fDumpIRToFile , bool fSerialize ) { string root = Expand( @"%DEPOTROOT%\ZeligUnitTestResults\" ); string file2 = Path.GetFileNameWithoutExtension( files[0] ); string filePrefix = root + file2; m_filePrefix = filePrefix; m_fDumpIRToFile = fDumpIRToFile; foreach(string file in files) { LoadAndResolve( file ); } ConvertToIR(); #if CLONE_STATE Console.WriteLine( "{0}: Cloning State", GetTime() ); byte[] buf; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".serializer.txt" )) { buf = IR.TypeSystemSerializer.Serialize( m_typeSystem ); } TypeSystemForUnitTest typeSystem2; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".deserializer.txt" )) { typeSystem2 = (TypeSystemForUnitTest)IR.TypeSystemSerializer.Deserialize( new System.IO.MemoryStream( buf ), CreateInstanceForType ); } TypeSystemForUnitTest typeSystem3 = m_typeSystem; m_typeSystem = typeSystem2; Console.WriteLine( "{0}: Done", GetTime() ); #endif Console.WriteLine( "{0}: ExecuteSteps", GetTime() ); ExecuteSteps(); Console.WriteLine( "{0}: Done", GetTime() ); //--// if(fSerialize) { Console.WriteLine( "{0}: Type System Serialization Test...", GetTime() ); System.IO.MemoryStream stream = new System.IO.MemoryStream(); using(RedirectOutput ro = new RedirectOutput( filePrefix + ".serializer.txt" )) { IR.TypeSystemSerializer.Serialize( stream, m_typeSystem ); } stream.Seek( 0, SeekOrigin.Begin ); TypeSystemForUnitTest deserializedTypeSystem; using(RedirectOutput ro = new RedirectOutput( filePrefix + ".deserializer.txt" )) { deserializedTypeSystem = (TypeSystemForUnitTest)IR.TypeSystemSerializer.Deserialize( stream, CreateInstanceForType, null, 0 ); } System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); using(RedirectOutput ro = new RedirectOutput( filePrefix + ".reserializer.txt" )) { IR.TypeSystemSerializer.Serialize( stream2, deserializedTypeSystem ); } if(ArrayUtility.ArrayEquals( stream.ToArray(), stream2.ToArray() )) { Console.WriteLine( "{0}: Type System Serialization PASS", GetTime() ); } else { Console.WriteLine( "{0}: Type System Serialization FAIL", GetTime() ); } } } //--// Importer.PdbInfo.PdbFile ISymbolResolverHelper.ResolveAssemblySymbols( string file ) { return InnerResolveAssemblySymbols( file ); } Importer.MetaData IMetaDataResolverHelper.ResolveAssemblyReference( string name , MetaDataVersion ver ) { // // Force use of our version of mscorlib. // if(name == "mscorlib" || name == "system") { return CheckAndLoad( BuildRoot + @"\Target\bin\" + BuildFlavor, name ); } return InnerResolveAssemblyReference( name, ver ); } //--// private object CreateInstanceForType( Type t ) { if(t == typeof(IR.TypeSystemForCodeTransformation)) { return new TypeSystemForUnitTest( this, null ); } return null; } private void DumpPerformanceCounters( string filePrefix ) { if(PerformanceCounters.ContextualTiming.IsEnabled()) { Console.WriteLine( "{0}: Dumping Performance Counters", GetTime() ); using(System.IO.StreamWriter output = new System.IO.StreamWriter( filePrefix + "_timing.type.txt", false, System.Text.Encoding.ASCII )) { PerformanceCounters.ContextualTiming.DumpAllByType( output ); } using(System.IO.StreamWriter output = new System.IO.StreamWriter( filePrefix + "_timing.reason.txt", false, System.Text.Encoding.ASCII )) { PerformanceCounters.ContextualTiming.DumpAllByReason( output ); } Console.WriteLine( "{0}: Done", GetTime() ); } } //--// protected override void NotifyCompilationPhase( IR.CompilationSteps.PhaseDriver phase ) { if(!m_fDumpIRToFile) return; bool fDumpIR = false; bool fDumpTXT = false; #if DEBUG_DUMP_XML bool fDumpXML = true; #else bool fDumpXML = false; #endif bool fDumpOps = false; bool fDumpASM = false; bool fDumpIMG = false; ++m_dumpCount; Console.WriteLine( "{0}: Phase: {1}", GetTime(), phase ); #if REPORT_OPERATORS_AT_EACH_PHASE fDumpOps = true; #endif //// if(phase >= IR.CompilationSteps.Phase.ConvertToSSA) //// { //// fDumpTXT = true; //// } if(phase is IR.CompilationSteps.Phases.GenerateImage) { DumpPerformanceCounters( m_filePrefix ); fDumpTXT = true; } else if(phase is IR.CompilationSteps.Phases.Done) { fDumpIMG = true; fDumpASM = true; fDumpTXT = true; fDumpIR = true; m_typeSystem.DropCompileTimeObjects(); // Get the smallest dump. } //--// #if DEBUG_DUMP_ALL_PHASES fDumpTXT = true; #endif #if DEBUG_DUMP_ALL_PHASES_AFTER_TYPE_SYSTEM_REDUCTION if(IR.CompilationSteps.PhaseDriver.CompareOrder( phase, typeof(IR.CompilationSteps.Phases.ReduceTypeSystem) ) > 0) { fDumpTXT = true; } #endif //--// //// if(phase is IR.CompilationSteps.Phases.LayoutTypes) //// { //// fDumpOps = true; //// } //// else if(phase is IR.CompilationSteps.Phases.GenerateImage || //// phase is IR.CompilationSteps.Phases.Done ) //// { //// fDumpOps = true; //// } if(fDumpOps) { ReportOperators( phase ); } if(fDumpIR || fDumpTXT || fDumpXML) { string file = string.Format( "{0}.{1:X2}.{2}.{3}.", m_filePrefix, m_dumpCount, phase.PhaseIndex, phase ); Console.WriteLine( "{0}: Dump {1}", GetTime(), file ); if(fDumpIR ) SaveIrToDisk( file + "ZeligImage", m_typeSystem ); if(fDumpTXT) DumpIRAsText( file + "ZeligIR" ); if(fDumpXML) DumpIRAsXML ( file + "xml" , GetAllMethods() ); if(fDumpASM) { m_typeSystem.DisassembleImage( file + "asmdir" ); } if(fDumpIMG) { using(FileStream stream = new FileStream( file + "hex", FileMode.Create )) { foreach(var section in m_typeSystem.Image) { ARM.SRecordParser.Encode( stream, section.Payload, section.Address ); } } } Console.WriteLine( "{0}: Done", GetTime() ); } } private void ReportOperators( IR.CompilationSteps.PhaseDriver phase ) { GrowOnlySet< Type > types = SetFactory.NewWithReferenceEquality< Type >(); m_typeSystem.EnumerateFlowGraphs( delegate( IR.ControlFlowGraphStateForCodeTransformation cfg ) { foreach(IR.Operator op in cfg.DataFlow_SpanningTree_Operators) { types.Insert( op.GetType() ); } } ); Console.WriteLine( "Operators at phase {0}", phase ); foreach(Type t in types) { Console.WriteLine( " {0}", t.Name ); } } //--// private List< TS.MethodRepresentation > GetAllMethods() { List< TS.MethodRepresentation > lst = new List< TS.MethodRepresentation >(); m_typeSystem.EnumerateMethods( delegate( TS.MethodRepresentation md ) { lst.Add( md ); } ); return lst; } private List< TS.MethodRepresentation > GetAllReferencedMethods() { List< TS.MethodRepresentation > lst = new List< TS.MethodRepresentation >(); foreach(TS.MethodRepresentation md in m_controller.EntitiesReferencedByMethods.Keys) { lst.Add( md ); } return lst; } } }
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 Quilt4.Service.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Composition.Hosting; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OmniSharp.Extensions.LanguageServer; using OmniSharp.Extensions.LanguageServer.Models; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.LanguageServerProtocol.Eventing; using OmniSharp.LanguageServerProtocol.Handlers; using OmniSharp.Mef; using OmniSharp.Models.Diagnostics; using OmniSharp.Services; using OmniSharp.Utilities; namespace OmniSharp.LanguageServerProtocol { internal class LanguageServerHost : IDisposable { private readonly ServiceCollection _services; private readonly LanguageServer _server; private CompositionHost _compositionHost; private readonly LanguageServerLoggerFactory _loggerFactory; private readonly CommandLineApplication _application; private readonly CancellationTokenSource _cancellationTokenSource; private IServiceProvider _serviceProvider; private RequestHandlers _handlers; private OmniSharpEnvironment _environment; private ILogger<LanguageServerHost> _logger; public LanguageServerHost( Stream input, Stream output, CommandLineApplication application, CancellationTokenSource cancellationTokenSource) { _services = new ServiceCollection(); _loggerFactory = new LanguageServerLoggerFactory(); _services.AddSingleton<ILoggerFactory>(_loggerFactory); _server = new LanguageServer(input, output, _loggerFactory); _server.OnInitialize(Initialize); _application = application; _cancellationTokenSource = cancellationTokenSource; } public void Dispose() { _compositionHost?.Dispose(); _loggerFactory?.Dispose(); _cancellationTokenSource?.Dispose(); } private static LogLevel GetLogLevel(InitializeTrace initializeTrace) { switch (initializeTrace) { case InitializeTrace.verbose: return LogLevel.Trace; case InitializeTrace.off: return LogLevel.Warning; case InitializeTrace.messages: default: return LogLevel.Information; } } private void CreateCompositionHost(InitializeParams initializeParams) { _environment = new OmniSharpEnvironment( Helpers.FromUri(initializeParams.RootUri), Convert.ToInt32(initializeParams.ProcessId ?? -1L), GetLogLevel(initializeParams.Trace), _application.OtherArgs.ToArray()); // TODO: Make this work with logger factory differently // Maybe create a child logger factory? _loggerFactory.AddProvider(_server, _environment); _logger = _loggerFactory.CreateLogger<LanguageServerHost>(); var configurationRoot = new ConfigurationBuilder(_environment).Build(); var eventEmitter = new LanguageServerEventEmitter(_server); _serviceProvider = CompositionHostBuilder.CreateDefaultServiceProvider(_environment, configurationRoot, eventEmitter, _services); var plugins = _application.CreatePluginAssemblies(); var assemblyLoader = _serviceProvider.GetRequiredService<IAssemblyLoader>(); var compositionHostBuilder = new CompositionHostBuilder(_serviceProvider) .WithOmniSharpAssemblies() .WithAssemblies(typeof(LanguageServerHost).Assembly) .WithAssemblies(assemblyLoader.LoadByAssemblyNameOrPath(plugins.AssemblyNames).ToArray()); _compositionHost = compositionHostBuilder.Build(); var projectSystems = _compositionHost.GetExports<IProjectSystem>(); var documentSelectors = projectSystems .GroupBy(x => x.Language) .Select(x => ( language: x.Key, selector: new DocumentSelector(x .SelectMany(z => z.Extensions) .Distinct() .Select(z => new DocumentFilter() { Pattern = $"**/*{z}" })) )); _logger.LogTrace( "Configured Document Selectors {@DocumentSelectors}", documentSelectors.Select(x => new { x.language, x.selector }) ); // TODO: Get these with metadata so we can attach languages // This will thne let us build up a better document filter, and add handles foreach type of handler // This will mean that we will have a strategy to create handlers from the interface type _handlers = new RequestHandlers( _compositionHost.GetExports<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>>(), documentSelectors ); _logger.LogTrace("--- Handler Definitions ---"); foreach (var handlerCollection in _handlers) { foreach (var handler in handlerCollection) { _logger.LogTrace( "Handler: {Language}:{DocumentSelector}:{Handler}", handlerCollection.Language, handlerCollection.DocumentSelector.ToString(), handler.GetType().FullName ); } } _logger.LogTrace("--- Handler Definitions ---"); } private Task Initialize(InitializeParams initializeParams) { CreateCompositionHost(initializeParams); // TODO: Make it easier to resolve handlers from MEF (without having to add more attributes to the services if we can help it) var workspace = _compositionHost.GetExport<OmniSharpWorkspace>(); _server.AddHandlers(TextDocumentSyncHandler.Enumerate(_handlers, workspace)); _server.AddHandlers(DefinitionHandler.Enumerate(_handlers)); _server.AddHandlers(HoverHandler.Enumerate(_handlers)); _server.AddHandlers(CompletionHandler.Enumerate(_handlers)); _server.AddHandlers(SignatureHelpHandler.Enumerate(_handlers)); _server.AddHandlers(RenameHandler.Enumerate(_handlers)); _server.AddHandlers(DocumentSymbolHandler.Enumerate(_handlers)); _server.LogMessage(new LogMessageParams() { Message = "Added handlers... waiting for initialize...", Type = MessageType.Log }); return Task.CompletedTask; } public async Task Start() { _server.LogMessage(new LogMessageParams() { Message = "Starting server...", Type = MessageType.Log }); await _server.Initialize(); _server.LogMessage(new LogMessageParams() { Message = "initialized...", Type = MessageType.Log }); var logger = _loggerFactory.CreateLogger(typeof(LanguageServerHost)); WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost); // Kick on diagnostics var diagnosticHandler = _handlers.GetAll() .OfType<IRequestHandler<DiagnosticsRequest, DiagnosticsResponse>>(); foreach (var handler in diagnosticHandler) await handler.Handle(new DiagnosticsRequest()); logger.LogInformation($"Omnisharp server running using Lsp at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}."); Console.CancelKeyPress += (sender, e) => { _cancellationTokenSource.Cancel(); e.Cancel = true; }; if (_environment.HostProcessId != -1) { try { var hostProcess = Process.GetProcessById(_environment.HostProcessId); hostProcess.EnableRaisingEvents = true; hostProcess.OnExit(() => _cancellationTokenSource.Cancel()); } catch { // If the process dies before we get here then request shutdown // immediately _cancellationTokenSource.Cancel(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using FlatRedBall.IO; using System.IO; //using System.IO.Compression; namespace FlatRedBall.Performance.Measurement { public class Section : IDisposable { #region Fields double mTimeStarted; bool mStarted; static Section mContext; #endregion #region Properties [XmlIgnore] public Section Parent { get; private set; } [XmlIgnore] public Section TopParent { get { if (Parent == null) { return this; } else { return Parent.TopParent; } } } [XmlElement("C")] public List<Section> Children { get; set; } [XmlAttribute("T")] public float Time { get; set; } [XmlAttribute("N")] public string Name { get; set; } [XmlIgnore] public bool IsCurrentContext { get { return this == mContext; } } public static Section Context { get { return mContext; } } public static int ContextDepth { get { int toReturn = 0; Section context = Context; while (context != null) { toReturn++; context = context.Parent; } return toReturn; } } #endregion public Section() { Children = new List<Section>(); if (mContext != null) { mContext.Children.Add(this); this.Parent = mContext; } } //public static Section GetAndStartContext(string name) //{ // Section section = new Section(); // section.Name = name; // section.StartContext(); // return section; //} //public static Section GetAndStartTime(string name) //{ // Section section = new Section(); // section.Name = name; // section.StartTime(); // return section; //} public static Section GetAndStartContextAndTime(string name) { Section section = new Section(); section.Name = name; section.StartContext(); section.StartTime(); return section; } public static Section GetAndStartMergedContextAndTime(string name) { Section section = null; if (mContext != null) { section = mContext.Children.FirstOrDefault(item => item.Name == name); if (section != null) { section.mTimeStarted = TimeManager.SystemCurrentTime - section.Time; section.mStarted = true; section.StartContext(); // no need to do this, we do it above by manually setting the time started and whether it's started //section.StartTime(); } else //(section == null) { section = GetAndStartContextAndTime(name); } } return section; } public static Section EndContextAndTime() { // Store this off because ending context could set a new mContext Section toReturn = mContext; mContext.EndTimeAndContext(); return toReturn; } public void StartContext() { mContext = this; } public void StartTime() { mTimeStarted = TimeManager.SystemCurrentTime; mStarted = true; } public void EndContext() { if (mContext == this) { mContext = this.Parent; } else { string message = "This Section is not the context, so it can't end it."; if(mContext == null) { message += "Current context is null"; } else { message += "Current context is " + mContext.Name; } throw new Exception(message); } } public void EndTime() { if (!mStarted) { throw new Exception("Could not end time because it hasn't been started, or it has already been ended"); } Time = (float)(TimeManager.SystemCurrentTime - mTimeStarted); mStarted = false; } public void EndTimeAndContext() { EndTime(); EndContext(); } public void Save(string fileName) { #if XBOX360 || WINDOWS_8 FileManager.XmlSerialize(this, fileName); #else // This doesn't use FileManager.XmlSerialize because FileManager.XmlSerialize // requires files to be saved to the user's folder on platforms like Android. Sections // are saved for diagnostic reasons so their save location should not be restricted. string outputText; FlatRedBall.IO.FileManager.XmlSerialize(typeof(FlatRedBall.Performance.Measurement.Section), this, out outputText); System.IO.File.WriteAllText(fileName, outputText); #endif } public override string ToString() { return "Name: " + Name + " Time: " + Time; } public string ToStringVerbose() { return ToStringVerbose (int.MaxValue); } public string ToStringVerbose(int depth) { StringBuilder stringBuilder = new StringBuilder (); ToStringVerbose (stringBuilder, 0, depth); return stringBuilder.ToString (); } internal void ToStringVerbose(StringBuilder stringBuilder, int spaces, int depth) { if (depth > 0) { if (Children.Count == 0 || depth == 1) { stringBuilder.AppendLine (new string (' ', spaces) + "<" + ToString () + ">"); } else { stringBuilder.AppendLine (new string (' ', spaces) + "<" + ToString ()); foreach (var item in Children) { item.ToStringVerbose (stringBuilder, spaces + 2, depth-1); } stringBuilder.AppendLine (new string (' ', spaces) + ">"); } } } public string GetAsXml() { string body; FileManager.XmlSerialize(this, out body); return body; } public void SendToEmail(string address) { string body; FileManager.XmlSerialize(this, out body); string compressed = Compress(body); #if WINDOWS_PHONE Microsoft.Phone.Tasks.EmailComposeTask task = new Microsoft.Phone.Tasks.EmailComposeTask { Body = compressed, Cc = "", Subject = "Performance measurements", To = address }; task.Show(); #else FileManager.SaveText(compressed, "Compressed.txt"); #endif } private static string Compress(string body) { //MemoryStream memoryStream = new MemoryStream(); //GZipStream zipStream = new GZipStream(memoryStream, CompressionMode.Compress); //zipStream.Write(UTF8Encoding.UTF8.GetBytes(body), 0, body.Length); //string compressed = Convert.ToBase64String(memoryStream.ToArray()); //return compressed; return body; } public static Section FromBase64GzipFile(string fileName) { string text = FileManager.FromFileText(fileName); string decompressedString = Decompress(text); return FileManager.XmlDeserializeFromString<Section>(decompressedString); } private static string Decompress(string text) { //byte[] encodedDataAsBytes = Convert.FromBase64String(text); //MemoryStream memoryStream = new MemoryStream(encodedDataAsBytes); //GZipStream zipStream = new GZipStream(memoryStream, CompressionMode.Decompress); //MemoryStream decompressedStream = new MemoryStream(); //var buffer = new byte[4096]; //int read; //while ((read = zipStream.Read(buffer, 0, buffer.Length)) > 0) //{ // decompressedStream.Write(buffer, 0, read); //} //string decompressedString = UTF8Encoding.UTF8.GetString(decompressedStream.ToArray()); //return decompressedString; return text; } public void SetParentRelationships() { foreach (var child in Children) { child.Parent = this; child.SetParentRelationships(); } } public void Dispose() { EndTimeAndContext(); } } }
//--------------------------------------------------------------------- // <copyright file="Span.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Objects { using System.Collections.Generic; using System.Data.Common.Internal; using System.Diagnostics; using System.Text; /// <summary> /// A collection of paths to determine which entities are spanned into a query. /// </summary> internal sealed class Span { private List<SpanPath> _spanList; private string _cacheKey; internal Span() { _spanList = new List<SpanPath>(); } /// <summary> /// The list of paths that should be spanned into the query /// </summary> internal List<SpanPath> SpanList { get { return _spanList; } } /// <summary> /// Checks whether relationship span needs to be performed. Currently this is only when the query is /// not using MergeOption.NoTracking. /// </summary> /// <param name="mergeOption"></param> /// <returns>True if the query needs a relationship span rewrite</returns> internal static bool RequiresRelationshipSpan(MergeOption mergeOption) { return (mergeOption != MergeOption.NoTracking); } /// <summary> /// Includes the specified span path in the specified span instance and returns the updated span instance. /// If <paramref name="spanToIncludeIn"/> is null, a new span instance is constructed and returned that contains /// the specified include path. /// </summary> /// <param name="spanToIncludeIn">The span instance to which the include path should be added. May be null</param> /// <param name="pathToInclude">The include path to add</param> /// <returns>A non-null span instance that contains the specified include path in addition to any paths ut already contained</returns> internal static Span IncludeIn(Span spanToIncludeIn, string pathToInclude) { if (null == spanToIncludeIn) { spanToIncludeIn = new Span(); } spanToIncludeIn.Include(pathToInclude); return spanToIncludeIn; } /// <summary> /// Returns a span instance that is the union of the two specified span instances. /// If <paramref name="span1"/> and <paramref name="span2"/> are both <c>null</c>, /// then <c>null</c> is returned. /// If <paramref name="span1"/> or <paramref name="span2"/> is null, but the remaining argument is non-null, /// then the non-null argument is returned. /// If neither <paramref name="span1"/> nor <paramref name="span2"/> are null, a new span instance is returned /// that contains the merged span paths from both. /// </summary> /// <param name="span1">The first span instance from which to include span paths; may be <c>null</c></param> /// <param name="span2">The second span instance from which to include span paths; may be <c>null</c></param> /// <returns>A span instance representing the union of the two arguments; may be <c>null</c> if both arguments are null</returns> internal static Span CopyUnion(Span span1, Span span2) { if (null == span1) { return span2; } if (null == span2) { return span1; } Span retSpan = span1.Clone(); foreach (SpanPath path in span2.SpanList) { retSpan.AddSpanPath(path); } return retSpan; } internal string GetCacheKey() { if (null == _cacheKey) { if (_spanList.Count > 0) { // If there is only a single Include path with a single property, // then simply use the property name as the cache key rather than // creating any new strings. if (_spanList.Count == 1 && _spanList[0].Navigations.Count == 1) { _cacheKey = _spanList[0].Navigations[0]; } else { StringBuilder keyBuilder = new StringBuilder(); for (int pathIdx = 0; pathIdx < _spanList.Count; pathIdx++) { if (pathIdx > 0) { keyBuilder.Append(";"); } SpanPath thisPath = _spanList[pathIdx]; keyBuilder.Append(thisPath.Navigations[0]); for (int propIdx = 1; propIdx < thisPath.Navigations.Count; propIdx++) { keyBuilder.Append("."); keyBuilder.Append(thisPath.Navigations[propIdx]); } } _cacheKey = keyBuilder.ToString(); } } } return _cacheKey; } /// <summary> /// Adds a path to span into the query. /// </summary> /// <param name="path">The path to span</param> public void Include(string path) { EntityUtil.CheckStringArgument(path, "path"); if (path.Trim().Length == 0) { throw new ArgumentException(System.Data.Entity.Strings.ObjectQuery_Span_WhiteSpacePath, "path"); } SpanPath spanPath = new SpanPath(ParsePath(path)); AddSpanPath(spanPath); _cacheKey = null; } /// <summary> /// Creates a new Span with the same SpanPaths as this Span /// </summary> /// <returns></returns> internal Span Clone() { Span newSpan = new Span(); newSpan.SpanList.AddRange(_spanList); newSpan._cacheKey = this._cacheKey; return newSpan; } /// <summary> /// Adds the path if it does not already exist /// </summary> /// <param name="spanPath"></param> internal void AddSpanPath(SpanPath spanPath) { if (ValidateSpanPath(spanPath)) { RemoveExistingSubPaths(spanPath); _spanList.Add(spanPath); } } /// <summary> /// Returns true if the path can be added /// </summary> /// <param name="spanPath"></param> private bool ValidateSpanPath(SpanPath spanPath) { // Check for dupliacte entries for (int i = 0; i < _spanList.Count; i++) { // make sure spanPath is not a sub-path of anything already in the list if (spanPath.IsSubPath(_spanList[i])) { return false; } } return true; } private void RemoveExistingSubPaths(SpanPath spanPath) { List<SpanPath> toDelete = new List<SpanPath>(); for (int i = 0; i < _spanList.Count; i++) { // make sure spanPath is not a sub-path of anything already in the list if (_spanList[i].IsSubPath(spanPath)) { toDelete.Add(_spanList[i]); } } foreach (SpanPath path in toDelete) { _spanList.Remove(path); } } /// <summary> /// Storage for a span path /// Currently this includes the list of navigation properties /// </summary> internal class SpanPath { public readonly List<string> Navigations; public SpanPath(List<string> navigations) { Navigations = navigations; } public bool IsSubPath(SpanPath rhs) { // this is a subpath of rhs if it has fewer paths, and all the path element values are equal if (Navigations.Count > rhs.Navigations.Count) { return false; } for (int i = 0; i < Navigations.Count; i++) { if (!Navigations[i].Equals(rhs.Navigations[i], StringComparison.OrdinalIgnoreCase)) { return false; } } return true; } } private static List<string> ParsePath(string path) { List<string> navigations = MultipartIdentifier.ParseMultipartIdentifier(path, "[", "]", '.'); for (int i = navigations.Count - 1; i >= 0; i--) { if (navigations[i] == null) { navigations.RemoveAt(i); } else if (navigations[i].Length == 0) { throw EntityUtil.SpanPathSyntaxError(); } } Debug.Assert(navigations.Count > 0, "Empty path found"); return navigations; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Subscriptions; using Microsoft.Azure.Subscriptions.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Subscriptions { /// <summary> /// Operations for managing tenants. /// </summary> internal partial class TenantOperations : IServiceOperations<SubscriptionClient>, ITenantOperations { /// <summary> /// Initializes a new instance of the TenantOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TenantOperations(SubscriptionClient client) { this._client = client; } private SubscriptionClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Subscriptions.SubscriptionClient. /// </summary> public SubscriptionClient Client { get { return this._client; } } /// <summary> /// Gets a list of the tenantIds. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Tenant Ids information. /// </returns> public async Task<TenantListResult> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/tenants?"; url = url + "api-version=2014-04-01-preview"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result TenantListResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TenantListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { TenantIdDescription tenantIdDescriptionInstance = new TenantIdDescription(); result.TenantIds.Add(tenantIdDescriptionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); tenantIdDescriptionInstance.Id = idInstance; } JToken tenantIdValue = valueValue["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { string tenantIdInstance = ((string)tenantIdValue); tenantIdDescriptionInstance.TenantId = tenantIdInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// // RangeCollectionTests.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-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. // #if ENABLE_TESTS using System; using System.Collections.Generic; using NUnit.Framework; using Hyena.Collections; namespace Hyena.Collections.Tests { [TestFixture] public class RangeCollectionTests { [Test] public void SingleRanges () { _TestRanges (new RangeCollection (), new int [] { 1, 11, 5, 7, 15, 32, 3, 9, 34 }); } [Test] public void MergedRanges () { RangeCollection range = new RangeCollection (); int [] indexes = new int [] { 0, 7, 5, 9, 1, 6, 8, 2, 10, 12 }; _TestRanges (range, indexes); Assert.AreEqual (3, range.RangeCount); int i= 0; foreach (RangeCollection.Range r in range.Ranges) { switch (i++) { case 0: Assert.AreEqual (0, r.Start); Assert.AreEqual (2, r.End); break; case 1: Assert.AreEqual (5, r.Start); Assert.AreEqual (10, r.End); break; case 2: Assert.AreEqual (12, r.Start); Assert.AreEqual (12, r.End); break; default: Assert.Fail ("This should not be reached!"); break; } } } [Test] public void LargeSequentialContains () { RangeCollection range = new RangeCollection (); int i, n = 1000000; for (i = 0; i < n; i++) { range.Add (i); } for (i = 0; i < n; i++) { Assert.AreEqual (true, range.Contains (i)); } } [Test] public void LargeSequential () { RangeCollection range = new RangeCollection (); int i, n = 1000000; for (i = 0; i < n; i++) { range.Add (i); Assert.AreEqual (1, range.RangeCount); } Assert.AreEqual (n, range.Count); i = 0; foreach (int j in range) { Assert.AreEqual (i++, j); } Assert.AreEqual (n, i); } [Test] public void LargeNonAdjacent () { RangeCollection range = new RangeCollection (); int i, n = 1000000; for (i = 0; i < n; i += 2) { range.Add (i); } Assert.AreEqual (n / 2, range.Count); i = 0; foreach (int j in range) { Assert.AreEqual (i, j); i += 2; } Assert.AreEqual (n, i); } private static void _TestRanges (RangeCollection range, int [] indexes) { foreach (int index in indexes) { range.Add (index); } Assert.AreEqual (indexes.Length, range.Count); Array.Sort (indexes); int i = 0; foreach (int index in range) { Assert.AreEqual (indexes[i++], index); } } [Test] public void RemoveSingles () { RangeCollection range = new RangeCollection (); int [] indexes = new int [] { 0, 2, 4, 6, 8, 10, 12, 14 }; foreach (int index in indexes) { range.Add (index); } foreach (int index in indexes) { Assert.AreEqual (true, range.Remove (index)); } } [Test] public void RemoveStarts () { RangeCollection range = _SetupTestRemoveMerges (); Assert.AreEqual (true, range.Contains (0)); range.Remove (0); Assert.AreEqual (false, range.Contains (0)); Assert.AreEqual (4, range.RangeCount); Assert.AreEqual (true, range.Contains (2)); range.Remove (2); Assert.AreEqual (false, range.Contains (2)); Assert.AreEqual (4, range.RangeCount); Assert.AreEqual (3, range.Ranges[0].Start); Assert.AreEqual (5, range.Ranges[0].End); Assert.AreEqual (true, range.Contains (14)); range.Remove (14); Assert.AreEqual (false, range.Contains (14)); Assert.AreEqual (4, range.RangeCount); Assert.AreEqual (15, range.Ranges[2].Start); Assert.AreEqual (15, range.Ranges[2].End); } [Test] public void RemoveEnds () { RangeCollection range = _SetupTestRemoveMerges (); Assert.AreEqual (true, range.Contains (5)); range.Remove (5); Assert.AreEqual (false, range.Contains (5)); Assert.AreEqual (5, range.RangeCount); Assert.AreEqual (2, range.Ranges[1].Start); Assert.AreEqual (4, range.Ranges[1].End); Assert.AreEqual (true, range.Contains (15)); range.Remove (15); Assert.AreEqual (false, range.Contains (15)); Assert.AreEqual (5, range.RangeCount); Assert.AreEqual (14, range.Ranges[3].Start); Assert.AreEqual (14, range.Ranges[3].End); } [Test] public void RemoveMids () { RangeCollection range = _SetupTestRemoveMerges (); Assert.AreEqual (5, range.RangeCount); Assert.AreEqual (14, range.Ranges[3].Start); Assert.AreEqual (15, range.Ranges[3].End); Assert.AreEqual (true, range.Contains (9)); range.Remove (9); Assert.AreEqual (false, range.Contains (9)); Assert.AreEqual (6, range.RangeCount); Assert.AreEqual (7, range.Ranges[2].Start); Assert.AreEqual (8, range.Ranges[2].End); Assert.AreEqual (10, range.Ranges[3].Start); Assert.AreEqual (11, range.Ranges[3].End); Assert.AreEqual (14, range.Ranges[4].Start); Assert.AreEqual (15, range.Ranges[4].End); } private static RangeCollection _SetupTestRemoveMerges () { RangeCollection range = new RangeCollection (); int [] indexes = new int [] { 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19 }; foreach (int index in indexes) { range.Add (index); } int i = 0; foreach (RangeCollection.Range r in range.Ranges) { switch (i++) { case 0: Assert.AreEqual (0, r.Start); Assert.AreEqual (0, r.End); break; case 1: Assert.AreEqual (2, r.Start); Assert.AreEqual (5, r.End); break; case 2: Assert.AreEqual (7, r.Start); Assert.AreEqual (11, r.End); break; case 3: Assert.AreEqual (14, r.Start); Assert.AreEqual (15, r.End); break; case 4: Assert.AreEqual (17, r.Start); Assert.AreEqual (19, r.End); break; default: Assert.Fail ("Should never reach here"); break; } } return range; } [Test] public void IndexOf () { RangeCollection range = new RangeCollection (); range.Add (0); range.Add (2); range.Add (3); range.Add (5); range.Add (6); range.Add (7); range.Add (8); range.Add (11); range.Add (12); range.Add (13); Assert.AreEqual (0, range.IndexOf (0)); Assert.AreEqual (1, range.IndexOf (2)); Assert.AreEqual (2, range.IndexOf (3)); Assert.AreEqual (3, range.IndexOf (5)); Assert.AreEqual (4, range.IndexOf (6)); Assert.AreEqual (5, range.IndexOf (7)); Assert.AreEqual (6, range.IndexOf (8)); Assert.AreEqual (7, range.IndexOf (11)); Assert.AreEqual (8, range.IndexOf (12)); Assert.AreEqual (9, range.IndexOf (13)); Assert.AreEqual (-1, range.IndexOf (99)); } [Test] public void IndexerForGoodIndexes () { RangeCollection range = new RangeCollection (); /* Range Idx Value 0-2 0 -> 0 1 -> 1 2 -> 2 7-9 3 -> 7 4 -> 8 5 -> 9 11-13 6 -> 11 7 -> 12 8 -> 13 */ range.Add (0); range.Add (1); range.Add (2); range.Add (7); range.Add (8); range.Add (9); range.Add (11); range.Add (12); range.Add (13); Assert.AreEqual (0, range[0]); Assert.AreEqual (1, range[1]); Assert.AreEqual (2, range[2]); Assert.AreEqual (7, range[3]); Assert.AreEqual (8, range[4]); Assert.AreEqual (9, range[5]); Assert.AreEqual (11, range[6]); Assert.AreEqual (12, range[7]); Assert.AreEqual (13, range[8]); } [Test] public void StressForGoodIndexes () { Random random = new Random (0xbeef); RangeCollection ranges = new RangeCollection (); List<int> indexes = new List<int> (); for (int i = 0, n = 75000; i < n; i++) { int value = random.Next (n); if (ranges.Add (value)) { CollectionExtensions.SortedInsert (indexes, value); } } Assert.AreEqual (indexes.Count, ranges.Count); for (int i = 0; i < indexes.Count; i++) { Assert.AreEqual (indexes[i], ranges[i]); } } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void IndexerForNegativeBadIndex () { RangeCollection range = new RangeCollection (); Assert.AreEqual (0, range[1]); } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void IndexerForZeroBadIndex () { RangeCollection range = new RangeCollection (); Assert.AreEqual (0, range[0]); } [Test] [ExpectedException (typeof (IndexOutOfRangeException))] public void IndexerForPositiveBadIndex () { RangeCollection range = new RangeCollection (); range.Add (1); Assert.AreEqual (0, range[1]); } [Test] public void ExplicitInterface () { ICollection<int> range = new RangeCollection (); range.Add (1); range.Add (2); range.Add (5); range.Add (6); Assert.AreEqual (4, range.Count); } [Test] public void NegativeIndices () { RangeCollection c = new RangeCollection (); c.Add (-10); c.Add (-5); c.Add (5); c.Add (-8); c.Add (10); c.Add (-9); c.Add (-11); Assert.IsTrue (c.Contains(-10), "#1"); Assert.IsTrue (c.Contains(-5), "#2"); Assert.IsTrue (c.Contains(5), "#3"); Assert.IsTrue (c.Contains(-8), "#4"); Assert.AreEqual (4, c.RangeCount, "#5"); Assert.AreEqual (new RangeCollection.Range (-11, -8), c.Ranges[0], "#6"); Assert.AreEqual (new RangeCollection.Range (-5, -5), c.Ranges[1], "#7"); Assert.AreEqual (new RangeCollection.Range (5, 5), c.Ranges[2], "#8"); Assert.AreEqual (new RangeCollection.Range (10, 10), c.Ranges[3], "#9"); Assert.AreEqual (0, c.FindRangeIndexForValue (-9), "#10"); Assert.IsTrue (c.FindRangeIndexForValue (-7) < 0, "#11"); } [Test] public void IPAddressRanges () { RangeCollection ranges = new RangeCollection (); int start = GetAddress ("127.0.0.1"); int end = GetAddress ("127.0.0.50"); for (int i = start; i <= end; i++) { ranges.Add (i); } Assert.IsTrue (ranges.Contains (GetAddress ("127.0.0.15"))); Assert.IsFalse (ranges.Contains (GetAddress ("127.0.0.0"))); Assert.IsFalse (ranges.Contains (GetAddress ("127.0.0.51"))); } private static int GetAddress (string addressStr) { System.Net.IPAddress address = System.Net.IPAddress.Parse (addressStr); return (int)(System.Net.IPAddress.NetworkToHostOrder ( BitConverter.ToInt32 (address.GetAddressBytes (), 0)) >> 32); } } } #endif
using System; using System.Collections.Generic; using UnityEngine; using UnityEditor; using Cat.PostProcessing; using Cat.CommonEditor; namespace Cat.PostProcessingEditor { [CatPostProcessingEditorAttribute(typeof(CatColorGrading))] //[CanEditMultipleObjects] public class CatColorGradingEditor : CatPostProcessingEditorBase { private ColorMapperChannel colorMapperChannel; public override void OnInspectorGUI(IEnumerable<AttributedProperty> properties) { serializedObject.Update(); // // Tonemapping: // var propertyIterator = properties.GetEnumerator(); DrawPropertyField(propertyIterator); var tonemapper = (int)(propertyIterator.Current.rawValue as TonemapperProperty).rawValue; if (tonemapper == 2) { DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); } else { SkipPropertyField(propertyIterator); SkipPropertyField(propertyIterator); } if (tonemapper >= 2) { EditorGUILayout.Space(); DrawToneMappingFunction(128, 96, tonemapper-2); EditorGUILayout.Space(); } // // Color Grading: // DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); // // Color Correction: // DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); // // Color Mixer: // DrawPropertyField(propertyIterator); var colorMapper = (int)(propertyIterator.Current.rawValue as ColorMixerProperty).rawValue; if (colorMapper == 4) { EditorGUI.BeginChangeCheck(); { EditorGUILayout.BeginHorizontal(); { //GUILayout.Label("Channel", EditorStyles.label); EditorGUILayout.PrefixLabel("Channel"); colorMapperChannel = GUILayout.Toggle(colorMapperChannel == ColorMapperChannel.Red, "Red", EditorStyles.miniButtonLeft) ? ColorMapperChannel.Red : colorMapperChannel; colorMapperChannel = GUILayout.Toggle(colorMapperChannel == ColorMapperChannel.Green, "Green", EditorStyles.miniButtonMid) ? ColorMapperChannel.Green : colorMapperChannel; colorMapperChannel = GUILayout.Toggle(colorMapperChannel == ColorMapperChannel.Blue, "Blue", EditorStyles.miniButtonRight) ? ColorMapperChannel.Blue : colorMapperChannel; } EditorGUILayout.EndHorizontal(); } if (EditorGUI.EndChangeCheck()) { GUI.FocusControl(null); } for (int i = 0; i <= (int)colorMapperChannel; i++) { SkipPropertyField(propertyIterator); } var c = (propertyIterator.Current.rawValue as ColorProperty).rawValue; c.r = EditorGUILayout.Slider("Red", c.r, -1, 1); c.g = EditorGUILayout.Slider("Green", c.g, -1, 1); c.b = EditorGUILayout.Slider("Blue", c.b, -1, 1); (propertyIterator.Current.rawValue as ColorProperty).rawValue = c; for (int i = (int)colorMapperChannel+1; i <= 2; i++) { SkipPropertyField(propertyIterator); } DrawPropertyField(propertyIterator); } else { SkipPropertyField(propertyIterator); SkipPropertyField(propertyIterator); SkipPropertyField(propertyIterator); SkipPropertyField(propertyIterator); } // // Curves: // DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); DrawPropertyField(propertyIterator); serializedObject.ApplyModifiedProperties(); // // Tonemapping: // EditorGUILayout.Space(); DrawResponseFunction(128, 96); EditorGUILayout.Space(); } bool DrawPropertyField(IEnumerator<AttributedProperty> enumerator) { var hasNext = enumerator.MoveNext(); if (hasNext) { PropertyField(enumerator.Current); } return hasNext; } bool SkipPropertyField(IEnumerator<AttributedProperty> enumerator) { var hasNext = enumerator.MoveNext(); return hasNext; } void DrawToneMappingFunction(float width, float height, int tonemappingFuncionIndex) { var settings = target as CatColorGrading; var response = Mathf.Pow(2, settings.response); var gain = Mathf.Pow(2, settings.gain); var range = new Rect( 0f, 0f, 2, 1f ); var rect = GUILayoutUtility.GetRect(width, height); var graph = new Graph(rect, range); // Background graph.DrawRect(graph.m_Range, 0.1f, 0.4f); // Grid graph.DrawGrid(new Vector2(4, 4), 0.4f, 2); graph.DrawGrid(new Vector2(2, 2), 0.4f, 3); // Graph graph.DrawFunction( x => NeutralTonemap(x, 1, 1), 0.90f ); if (tonemappingFuncionIndex == 0) { graph.DrawFunction( x => NeutralTonemap(x, response, gain), Color.red * 0.75f ); } else if (tonemappingFuncionIndex == 1) { graph.DrawFunction( x => Uncharted2Tonemap(x, response, gain), Color.blue * 0.75f ); } } float NeutralTonemap(float x, float response, float gain) { const float k = 1.235f; var amplitude = x; var y = gain * k * x / ((k - x / (0.1f + x) * 0.3f) / response * gain + amplitude); return y; } float Uncharted2Tonemap(float x, float response, float gain) { //const float k = 1.235f; const float a = 0.15f; const float b = 0.50f; const float c = 0.10f; const float d = 0.20f; const float e = 0.02f; const float f = 0.30f; const float W = 11.21f; const float exposureBias = 2.00f; // Tonemap float whiteScale = 1f / NeutralCurve(W, a, b, c, d, e, f); var y = NeutralCurve(x * exposureBias, a, b, c, d, e, f); y *= whiteScale; //var y = ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f; return y; } float NeutralCurve(float x, float a, float b, float c, float d, float e, float f) { return ((x * (a * x + c * b) + d * e) / (x * (a * x + b) + d * f)) - e / f; } float NeutralTonemap(float x, float a, float b, float c, float d, float e, float f, float whiteLevel, float whiteClip) { x = Mathf.Max(0f, x); // Tonemap float whiteScale = 1f / NeutralCurve(whiteLevel, a, b, c, d, e, f); x = NeutralCurve(x * whiteScale, a, b, c, d, e, f); x *= whiteScale; // Post-curve white point adjustment x /= whiteClip; return x; } void DrawResponseFunction(float width, float height) { var settings = target as CatColorGrading; var blackPoint = settings.blackPoint; var grayPoint = settings.midPoint; var whitePoint = settings.whitePoint; var black = 0.0f + blackPoint * 0.25f; var gray = 0.5f + grayPoint * 0.125f; var white = 1.0f + whitePoint * 0.25f; var minX = Mathf.Min(0f, black); var maxX = Mathf.Max(1f, white); var range = new Rect( minX, 0f, maxX - minX, 1f ); var rect = GUILayoutUtility.GetRect(width, height); var graph = new Graph(rect, range); // Background graph.DrawRect(graph.m_Range, 0.1f, 0.4f); // Grid graph.DrawGrid(new Vector2(4, 4), 0.4f, 2); graph.DrawGrid(new Vector2(2, 2), 0.4f, 3); // Label //Handles.Label( // PointInRect(0, m_RangeY) + Vector3.right, // "Brightness Response (linear)", EditorStyles.miniLabel //); // Threshold Range var thresholdRect = new Rect(black, graph.m_Range.y, white - black, graph.m_Range.height); graph.DrawRect(thresholdRect, 0.25f, -1f); // Threshold line graph.DrawLine(new Vector2(black, graph.m_Range.yMin), new Vector2(black, graph.m_Range.yMax), 0.85f); graph.DrawLine(new Vector2(white, graph.m_Range.yMin), new Vector2(white, graph.m_Range.yMax), 0.85f); var grayLerp = Mathf.Lerp(black, white, gray); graph.DrawLine(new Vector2(grayLerp, graph.m_Range.yMin), new Vector2(grayLerp, graph.m_Range.yMax), 0.85f); // Graph //graph.DrawFunction(x => x * Mathf.Pow(Mathf.Max(0, x - minLuminance) / (x + 1e-1f), kneeStrength + 1), 0.1f); var curveParams = settings.GetCurveParams(); graph.DrawFunction( x => { x = (x - black) / (white - black); x = Mathf.Clamp01(x); return (curveParams.w + (curveParams.z + (curveParams.y + curveParams.x*x)*x)*x)*x; } , 0.90f ); } enum ColorMapperChannel { Red = 0, Green = 1, Blue = 2 } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Framework.Scenes.Animation { /// <summary> /// Handle all animation duties for a scene presence /// </summary> public class ScenePresenceAnimator { public AnimationSet Animations { get { return m_animations; } } protected AnimationSet m_animations = new AnimationSet(); /// <value> /// The current movement animation /// </value> public string CurrentMovementAnimation { get { return m_movementAnimation; } } protected string m_movementAnimation = "DEFAULT"; private int m_animTickFall; private int m_animTickJump; /// <value> /// The scene presence that this animator applies to /// </value> protected ScenePresence m_scenePresence; public ScenePresenceAnimator(ScenePresence sp) { m_scenePresence = sp; } public void AddAnimation(UUID animID, UUID objectID) { if (m_scenePresence.IsChildAgent) return; if (m_animations.Add(animID, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, objectID)) SendAnimPack(); } // Called from scripts public void AddAnimation(string name, UUID objectID) { if (m_scenePresence.IsChildAgent) return; UUID animID = m_scenePresence.ControllingClient.GetDefaultAnimation(name); if (animID == UUID.Zero) return; AddAnimation(animID, objectID); } public void RemoveAnimation(UUID animID) { if (m_scenePresence.IsChildAgent) return; if (m_animations.Remove(animID)) SendAnimPack(); } // Called from scripts public void RemoveAnimation(string name) { if (m_scenePresence.IsChildAgent) return; UUID animID = m_scenePresence.ControllingClient.GetDefaultAnimation(name); if (animID == UUID.Zero) return; RemoveAnimation(animID); } public void ResetAnimations() { m_animations.Clear(); } /// <summary> /// The movement animation is reserved for "main" animations /// that are mutually exclusive, e.g. flying and sitting. /// </summary> public void TrySetMovementAnimation(string anim) { //m_log.DebugFormat("Updating movement animation to {0}", anim); if (!m_scenePresence.IsChildAgent) { if (m_animations.TrySetDefaultAnimation( anim, m_scenePresence.ControllingClient.NextAnimationSequenceNumber, m_scenePresence.UUID)) { // 16384 is CHANGED_ANIMATION m_scenePresence.SendScriptEventToAttachments("changed", new Object[] { (int)Changed.ANIMATION}); SendAnimPack(); } } } /// <summary> /// This method determines the proper movement related animation /// </summary> public string GetMovementAnimation() { const float FALL_DELAY = 0.33f; const float PREJUMP_DELAY = 0.25f; #region Inputs if (m_scenePresence.SitGround) { return "SIT_GROUND_CONSTRAINED"; } AgentManager.ControlFlags controlFlags = (AgentManager.ControlFlags)m_scenePresence.AgentControlFlags; PhysicsActor actor = m_scenePresence.PhysicsActor; // Create forward and left vectors from the current avatar rotation Matrix4 rotMatrix = Matrix4.CreateFromQuaternion(m_scenePresence.Rotation); Vector3 fwd = Vector3.Transform(Vector3.UnitX, rotMatrix); Vector3 left = Vector3.Transform(Vector3.UnitY, rotMatrix); // Check control flags bool heldForward = (((controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) || ((controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS)); bool heldBack = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG; bool heldLeft = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) == AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS; bool heldRight = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG; //bool heldTurnLeft = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) == AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT; //bool heldTurnRight = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) == AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT; bool heldUp = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) == AgentManager.ControlFlags.AGENT_CONTROL_UP_POS; bool heldDown = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) == AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG; //bool flying = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) == AgentManager.ControlFlags.AGENT_CONTROL_FLY; //bool mouselook = (controlFlags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) == AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK; // Direction in which the avatar is trying to move Vector3 move = Vector3.Zero; if (heldForward) { move.X += fwd.X; move.Y += fwd.Y; } if (heldBack) { move.X -= fwd.X; move.Y -= fwd.Y; } if (heldLeft) { move.X += left.X; move.Y += left.Y; } if (heldRight) { move.X -= left.X; move.Y -= left.Y; } if (heldUp) { move.Z += 1; } if (heldDown) { move.Z -= 1; } // Is the avatar trying to move? // bool moving = (move != Vector3.Zero); bool jumping = m_animTickJump != 0; #endregion Inputs #region Flying if (actor != null && actor.Flying) { m_animTickFall = 0; m_animTickJump = 0; if (move.X != 0f || move.Y != 0f) { return (m_scenePresence.Scene.m_useFlySlow ? "FLYSLOW" : "FLY"); } else if (move.Z > 0f) { return "HOVER_UP"; } else if (move.Z < 0f) { if (actor != null && actor.IsColliding) return "LAND"; else return "HOVER_DOWN"; } else { return "HOVER"; } } #endregion Flying #region Falling/Floating/Landing if (actor == null || !actor.IsColliding) { float fallElapsed = (float)(Environment.TickCount - m_animTickFall) / 1000f; float fallVelocity = (actor != null) ? actor.Velocity.Z : 0.0f; if (m_animTickFall == 0 || (fallElapsed > FALL_DELAY && fallVelocity >= 0.0f)) { // Just started falling m_animTickFall = Environment.TickCount; } else if (!jumping && fallElapsed > FALL_DELAY) { // Falling long enough to trigger the animation return "FALLDOWN"; } return m_movementAnimation; } #endregion Falling/Floating/Landing #region Ground Movement if (m_movementAnimation == "FALLDOWN") { m_animTickFall = Environment.TickCount; // TODO: SOFT_LAND support return "LAND"; } else if (m_movementAnimation == "LAND") { float landElapsed = (float)(Environment.TickCount - m_animTickFall) / 1000f; if ((m_animTickFall != 0) && (landElapsed <= FALL_DELAY)) return "LAND"; } m_animTickFall = 0; if (move.Z > 0f) { // Jumping if (!jumping) { // Begin prejump m_animTickJump = Environment.TickCount; return "PREJUMP"; } else if (Environment.TickCount - m_animTickJump > PREJUMP_DELAY * 1000.0f) { // Start actual jump if (m_animTickJump == -1) { // Already jumping! End the current jump m_animTickJump = 0; return "JUMP"; } m_animTickJump = -1; return "JUMP"; } } else { // Not jumping m_animTickJump = 0; if (move.X != 0f || move.Y != 0f) { // Walking / crouchwalking / running if (move.Z < 0f) return "CROUCHWALK"; else if (m_scenePresence.SetAlwaysRun) return "RUN"; else return "WALK"; } else { // Not walking if (move.Z < 0f) return "CROUCH"; else return "STAND"; } } #endregion Ground Movement return m_movementAnimation; } /// <summary> /// Update the movement animation of this avatar according to its current state /// </summary> public void UpdateMovementAnimations() { m_movementAnimation = GetMovementAnimation(); if (m_movementAnimation == "PREJUMP" && !m_scenePresence.Scene.m_usePreJump) { // This was the previous behavior before PREJUMP TrySetMovementAnimation("JUMP"); } else { TrySetMovementAnimation(m_movementAnimation); } } public UUID[] GetAnimationArray() { UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); return animIDs; } public BinBVHAnimation GenerateRandomAnimation() { int rnditerations = 3; BinBVHAnimation anim = new BinBVHAnimation(); List<string> parts = new List<string>(); parts.Add("mPelvis");parts.Add("mHead");parts.Add("mTorso"); parts.Add("mHipLeft");parts.Add("mHipRight");parts.Add("mHipLeft");parts.Add("mKneeLeft"); parts.Add("mKneeRight");parts.Add("mCollarLeft");parts.Add("mCollarRight");parts.Add("mNeck"); parts.Add("mElbowLeft");parts.Add("mElbowRight");parts.Add("mWristLeft");parts.Add("mWristRight"); parts.Add("mShoulderLeft");parts.Add("mShoulderRight");parts.Add("mAnkleLeft");parts.Add("mAnkleRight"); parts.Add("mEyeRight");parts.Add("mChest");parts.Add("mToeLeft");parts.Add("mToeRight"); parts.Add("mFootLeft");parts.Add("mFootRight");parts.Add("mEyeLeft"); anim.HandPose = 1; anim.InPoint = 0; anim.OutPoint = (rnditerations * .10f); anim.Priority = 7; anim.Loop = false; anim.Length = (rnditerations * .10f); anim.ExpressionName = "afraid"; anim.EaseInTime = 0; anim.EaseOutTime = 0; string[] strjoints = parts.ToArray(); anim.Joints = new binBVHJoint[strjoints.Length]; for (int j = 0; j < strjoints.Length; j++) { anim.Joints[j] = new binBVHJoint(); anim.Joints[j].Name = strjoints[j]; anim.Joints[j].Priority = 7; anim.Joints[j].positionkeys = new binBVHJointKey[rnditerations]; anim.Joints[j].rotationkeys = new binBVHJointKey[rnditerations]; Random rnd = new Random(); for (int i = 0; i < rnditerations; i++) { anim.Joints[j].rotationkeys[i] = new binBVHJointKey(); anim.Joints[j].rotationkeys[i].time = (i*.10f); anim.Joints[j].rotationkeys[i].key_element.X = ((float) rnd.NextDouble()*2 - 1); anim.Joints[j].rotationkeys[i].key_element.Y = ((float) rnd.NextDouble()*2 - 1); anim.Joints[j].rotationkeys[i].key_element.Z = ((float) rnd.NextDouble()*2 - 1); anim.Joints[j].positionkeys[i] = new binBVHJointKey(); anim.Joints[j].positionkeys[i].time = (i*.10f); anim.Joints[j].positionkeys[i].key_element.X = 0; anim.Joints[j].positionkeys[i].key_element.Y = 0; anim.Joints[j].positionkeys[i].key_element.Z = 0; } } AssetBase Animasset = new AssetBase(UUID.Random(), "Random Animation", (sbyte)AssetType.Animation, m_scenePresence.UUID.ToString()); Animasset.Data = anim.ToBytes(); Animasset.Temporary = true; Animasset.Local = true; Animasset.Description = "dance"; //BinBVHAnimation bbvhanim = new BinBVHAnimation(Animasset.Data); m_scenePresence.Scene.AssetService.Store(Animasset); AddAnimation(Animasset.FullID, m_scenePresence.UUID); return anim; } /// <summary> /// /// </summary> /// <param name="animations"></param> /// <param name="seqs"></param> /// <param name="objectIDs"></param> public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs) { if (m_scenePresence.IsChildAgent) return; m_scenePresence.Scene.ForEachClient( delegate(IClientAPI client) { client.SendAnimations(animations, seqs, m_scenePresence.ControllingClient.AgentId, objectIDs); }); } public void SendAnimPackToClient(IClientAPI client) { if (m_scenePresence.IsChildAgent) return; UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); client.SendAnimations(animIDs, sequenceNums, m_scenePresence.ControllingClient.AgentId, objectIDs); } /// <summary> /// Send animation information about this avatar to all clients. /// </summary> public void SendAnimPack() { //m_log.Debug("Sending animation pack to all"); if (m_scenePresence.IsChildAgent) return; UUID[] animIDs; int[] sequenceNums; UUID[] objectIDs; m_animations.GetArrays(out animIDs, out sequenceNums, out objectIDs); SendAnimPack(animIDs, sequenceNums, objectIDs); } public void Close() { m_animations = null; m_scenePresence = null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Buffers { using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Text; using DotNetty.Common.Utilities; /// <summary> /// Description of algorithm for PageRun/PoolSubpage allocation from PoolChunk /// Notation: The following terms are important to understand the code /// > page - a page is the smallest unit of memory chunk that can be allocated /// > chunk - a chunk is a collection of pages /// > in this code chunkSize = 2^{maxOrder} /// pageSize /// To begin we allocate a byte array of size = chunkSize /// Whenever a ByteBuf of given size needs to be created we search for the first position /// in the byte array that has enough empty space to accommodate the requested size and /// return a (long) handle that encodes this offset information, (this memory segment is then /// marked as reserved so it is always used by exactly one ByteBuf and no more) /// For simplicity all sizes are normalized according to PoolArena#normalizeCapacity method /// This ensures that when we request for memory segments of size >= pageSize the normalizedCapacity /// equals the next nearest power of 2 /// To search for the first offset in chunk that has at least requested size available we construct a /// complete balanced binary tree and store it in an array (just like heaps) - memoryMap /// The tree looks like this (the size of each node being mentioned in the parenthesis) /// depth=0 1 node (chunkSize) /// depth=1 2 nodes (chunkSize/2) /// .. /// .. /// depth=d 2^d nodes (chunkSize/2^d) /// .. /// depth=maxOrder 2^maxOrder nodes (chunkSize/2^{maxOrder} = pageSize) /// depth=maxOrder is the last level and the leafs consist of pages /// With this tree available searching in chunkArray translates like this: /// To allocate a memory segment of size chunkSize/2^k we search for the first node (from left) at height k /// which is unused /// Algorithm: /// ---------- /// Encode the tree in memoryMap with the notation /// memoryMap[id] = x => in the subtree rooted at id, the first node that is free to be allocated /// is at depth x (counted from depth=0) i.e., at depths [depth_of_id, x), there is no node that is free /// As we allocate & free nodes, we update values stored in memoryMap so that the property is maintained /// Initialization - /// In the beginning we construct the memoryMap array by storing the depth of a node at each node /// i.e., memoryMap[id] = depth_of_id /// Observations: /// ------------- /// 1) memoryMap[id] = depth_of_id => it is free / unallocated /// 2) memoryMap[id] > depth_of_id => at least one of its child nodes is allocated, so we cannot allocate it, but /// some of its children can still be allocated based on their availability /// 3) memoryMap[id] = maxOrder + 1 => the node is fully allocated & thus none of its children can be allocated, it /// is thus marked as unusable /// Algorithm: [allocateNode(d) => we want to find the first node (from left) at height h that can be allocated] /// ---------- /// 1) start at root (i.e., depth = 0 or id = 1) /// 2) if memoryMap[1] > d => cannot be allocated from this chunk /// 3) if left node value &lt;= h; we can allocate from left subtree so move to left and repeat until found /// 4) else try in right subtree /// Algorithm: [allocateRun(size)] /// ---------- /// 1) Compute d = log_2(chunkSize/size) /// 2) Return allocateNode(d) /// Algorithm: [allocateSubpage(size)] /// ---------- /// 1) use allocateNode(maxOrder) to find an empty (i.e., unused) leaf (i.e., page) /// 2) use this handle to construct the PoolSubpage object or if it already exists just call init(normCapacity) /// note that this PoolSubpage object is added to subpagesPool in the PoolArena when we init() it /// Note: /// ----- /// In the implementation for improving cache coherence, /// we store 2 pieces of information (i.e, 2 byte vals) as a short value in memoryMap /// memoryMap[id]= (depth_of_id, x) /// where as per convention defined above /// the second value (i.e, x) indicates that the first node which is free to be allocated is at depth x (from root) /// </summary> sealed class PoolChunk<T> : IPoolChunkMetric { internal enum PoolChunkOrigin { Pooled, UnpooledHuge, UnpooledNormal } internal readonly PoolArena<T> Arena; internal readonly T Memory; internal readonly PoolChunkOrigin Origin; readonly sbyte[] memoryMap; readonly sbyte[] depthMap; readonly PoolSubpage<T>[] subpages; /** Used to determine if the requested capacity is equal to or greater than pageSize. */ readonly int subpageOverflowMask; readonly int pageSize; readonly int pageShifts; readonly int maxOrder; readonly int chunkSize; readonly int log2ChunkSize; readonly int maxSubpageAllocs; /** Used to mark memory as unusable */ readonly sbyte unusable; int freeBytes; internal PoolChunkList<T> Parent; internal PoolChunk<T> Prev; internal PoolChunk<T> Next; // TODO: Test if adding padding helps under contention //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; internal PoolChunk(PoolArena<T> arena, T memory, int pageSize, int maxOrder, int pageShifts, int chunkSize) { Contract.Requires(maxOrder < 30, "maxOrder should be < 30, but is: " + maxOrder); this.Origin = PoolChunkOrigin.Pooled; this.Arena = arena; this.Memory = memory; this.pageSize = pageSize; this.pageShifts = pageShifts; this.maxOrder = maxOrder; this.chunkSize = chunkSize; this.unusable = (sbyte)(maxOrder + 1); this.log2ChunkSize = IntegerExtensions.Log2(chunkSize); this.subpageOverflowMask = ~(pageSize - 1); this.freeBytes = chunkSize; Contract.Assert(maxOrder < 30, "maxOrder should be < 30, but is: " + maxOrder); this.maxSubpageAllocs = 1 << maxOrder; // Generate the memory map. this.memoryMap = new sbyte[this.maxSubpageAllocs << 1]; this.depthMap = new sbyte[this.memoryMap.Length]; int memoryMapIndex = 1; for (int d = 0; d <= maxOrder; ++d) { // move down the tree one level at a time int depth = 1 << d; for (int p = 0; p < depth; ++p) { // in each level traverse left to right and set value to the depth of subtree this.memoryMap[memoryMapIndex] = (sbyte)d; this.depthMap[memoryMapIndex] = (sbyte)d; memoryMapIndex++; } } this.subpages = this.NewSubpageArray(this.maxSubpageAllocs); } /** Creates a special chunk that is not pooled. */ internal PoolChunk(PoolArena<T> arena, T memory, int size, bool huge) { this.Origin = huge ? PoolChunkOrigin.UnpooledHuge : PoolChunkOrigin.UnpooledNormal; this.Arena = arena; this.Memory = memory; this.memoryMap = null; this.depthMap = null; this.subpages = null; this.subpageOverflowMask = 0; this.pageSize = 0; this.pageShifts = 0; this.maxOrder = 0; this.unusable = (sbyte)(this.maxOrder + 1); this.chunkSize = size; this.log2ChunkSize = IntegerExtensions.Log2(this.chunkSize); this.maxSubpageAllocs = 0; } PoolSubpage<T>[] NewSubpageArray(int size) => new PoolSubpage<T>[size]; internal bool Unpooled => this.Origin != PoolChunkOrigin.Pooled; public int Usage { get { int freeBytes = this.freeBytes; if (freeBytes == 0) { return 100; } int freePercentage = (int)(freeBytes * 100L / this.chunkSize); if (freePercentage == 0) { return 99; } return 100 - freePercentage; } } internal long Allocate(int normCapacity) { if ((normCapacity & this.subpageOverflowMask) != 0) { // >= pageSize return this.AllocateRun(normCapacity); } else { return this.AllocateSubpage(normCapacity); } } /** * Update method used by allocate * This is triggered only when a successor is allocated and all its predecessors * need to update their state * The minimal depth at which subtree rooted at id has some free space * * @param id id */ void UpdateParentsAlloc(int id) { while (id > 1) { int parentId = id.RightUShift(1); sbyte val1 = this.Value(id); sbyte val2 = this.Value(id ^ 1); sbyte val = val1 < val2 ? val1 : val2; this.SetValue(parentId, val); id = parentId; } } /** * Update method used by free * This needs to handle the special case when both children are completely free * in which case parent be directly allocated on request of size = child-size * 2 * * @param id id */ void UpdateParentsFree(int id) { int logChild = this.Depth(id) + 1; while (id > 1) { int parentId = id.RightUShift(1); sbyte val1 = this.Value(id); sbyte val2 = this.Value(id ^ 1); logChild -= 1; // in first iteration equals log, subsequently reduce 1 from logChild as we traverse up if (val1 == logChild && val2 == logChild) { this.SetValue(parentId, (sbyte)(logChild - 1)); } else { sbyte val = val1 < val2 ? val1 : val2; this.SetValue(parentId, val); } id = parentId; } } /** * Algorithm to allocate an index in memoryMap when we query for a free node * at depth d * * @param d depth * @return index in memoryMap */ int AllocateNode(int d) { int id = 1; int initial = -(1 << d); // has last d bits = 0 and rest all = 1 sbyte val = this.Value(id); if (val > d) { // unusable return -1; } while (val < d || (id & initial) == 0) { // id & initial == 1 << d for all ids at depth d, for < d it is 0 id <<= 1; val = this.Value(id); if (val > d) { id ^= 1; val = this.Value(id); } } sbyte value = this.Value(id); Contract.Assert(value == d && (id & initial) == 1 << d, $"val = {value}, id & initial = {id & initial}, d = {d}"); this.SetValue(id, this.unusable); // mark as unusable this.UpdateParentsAlloc(id); return id; } /** * Allocate a run of pages (>=1) * * @param normCapacity normalized capacity * @return index in memoryMap */ long AllocateRun(int normCapacity) { int d = this.maxOrder - (IntegerExtensions.Log2(normCapacity) - this.pageShifts); int id = this.AllocateNode(d); if (id < 0) { return id; } this.freeBytes -= this.RunLength(id); return id; } /** * Create/ initialize a new PoolSubpage of normCapacity * Any PoolSubpage created/ initialized here is added to subpage pool in the PoolArena that owns this PoolChunk * * @param normCapacity normalized capacity * @return index in memoryMap */ long AllocateSubpage(int normCapacity) { int d = this.maxOrder; // subpages are only be allocated from pages i.e., leaves int id = this.AllocateNode(d); if (id < 0) { return id; } PoolSubpage<T>[] subpages = this.subpages; int pageSize = this.pageSize; this.freeBytes -= pageSize; int subpageIdx = this.SubpageIdx(id); PoolSubpage<T> subpage = subpages[subpageIdx]; if (subpage == null) { subpage = new PoolSubpage<T>(this, id, this.RunOffset(id), pageSize, normCapacity); subpages[subpageIdx] = subpage; } else { subpage.Init(normCapacity); } return subpage.Allocate(); } /** * Free a subpage or a run of pages * When a subpage is freed from PoolSubpage, it might be added back to subpage pool of the owning PoolArena * If the subpage pool in PoolArena has at least one other PoolSubpage of given elemSize, we can * completely free the owning Page so it is available for subsequent allocations * * @param handle handle to free */ internal void Free(long handle) { int memoryMapIdx = MemoryMapIdx(handle); int bitmapIdx = BitmapIdx(handle); if (bitmapIdx != 0) { // free a subpage PoolSubpage<T> subpage = this.subpages[this.SubpageIdx(memoryMapIdx)]; Contract.Assert(subpage != null && subpage.DoNotDestroy); // Obtain the head of the PoolSubPage pool that is owned by the PoolArena and synchronize on it. // This is need as we may add it back and so alter the linked-list structure. PoolSubpage<T> head = this.Arena.FindSubpagePoolHead(subpage.ElemSize); lock (head) { if (subpage.Free(bitmapIdx & 0x3FFFFFFF)) { return; } } } this.freeBytes += this.RunLength(memoryMapIdx); this.SetValue(memoryMapIdx, this.Depth(memoryMapIdx)); this.UpdateParentsFree(memoryMapIdx); } internal void InitBuf(PooledByteBuffer<T> buf, long handle, int reqCapacity) { int memoryMapIdx = MemoryMapIdx(handle); int bitmapIdx = BitmapIdx(handle); if (bitmapIdx == 0) { sbyte val = this.Value(memoryMapIdx); Contract.Assert(val == this.unusable, val.ToString()); buf.Init(this, handle, this.RunOffset(memoryMapIdx), reqCapacity, this.RunLength(memoryMapIdx), this.Arena.Parent.ThreadCache<T>()); } else { this.InitBufWithSubpage(buf, handle, bitmapIdx, reqCapacity); } } internal void InitBufWithSubpage(PooledByteBuffer<T> buf, long handle, int reqCapacity) => this.InitBufWithSubpage(buf, handle, BitmapIdx(handle), reqCapacity); void InitBufWithSubpage(PooledByteBuffer<T> buf, long handle, int bitmapIdx, int reqCapacity) { Contract.Assert(bitmapIdx != 0); int memoryMapIdx = MemoryMapIdx(handle); PoolSubpage<T> subpage = this.subpages[this.SubpageIdx(memoryMapIdx)]; Contract.Assert(subpage.DoNotDestroy); Contract.Assert(reqCapacity <= subpage.ElemSize); buf.Init( this, handle, this.RunOffset(memoryMapIdx) + (bitmapIdx & 0x3FFFFFFF) * subpage.ElemSize, reqCapacity, subpage.ElemSize, this.Arena.Parent.ThreadCache<T>()); } sbyte Value(int id) => this.memoryMap[id]; void SetValue(int id, sbyte val) => this.memoryMap[id] = val; sbyte Depth(int id) => this.depthMap[id]; /// represents the size in #bytes supported by node 'id' in the tree int RunLength(int id) => 1 << this.log2ChunkSize - this.Depth(id); int RunOffset(int id) { // represents the 0-based offset in #bytes from start of the byte-array chunk int shift = id ^ 1 << this.Depth(id); return shift * this.RunLength(id); } int SubpageIdx(int memoryMapIdx) => memoryMapIdx ^ this.maxSubpageAllocs; // remove highest set bit, to get offset static int MemoryMapIdx(long handle) => (int)handle; static int BitmapIdx(long handle) => (int)handle.RightUShift(IntegerExtensions.SizeInBits); public int ChunkSize => this.chunkSize; public int FreeBytes => this.freeBytes; public override string ToString() { return new StringBuilder() .Append("Chunk(") .Append(RuntimeHelpers.GetHashCode(this).ToString("X")) .Append(": ") .Append(this.Usage) .Append("%, ") .Append(this.chunkSize - this.freeBytes) .Append('/') .Append(this.chunkSize) .Append(')') .ToString(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace FSIX.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/* XML-RPC.NET library Copyright (c) 2001-2006, Charles Cook <charlescook@cookcomputing.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. */ namespace ActiveForumsTapatalk.XmlRpc { using System; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; public class XmlRpcAsyncResult : IAsyncResult { // IAsyncResult members public object AsyncState { get { return userAsyncState; } } public WaitHandle AsyncWaitHandle { get { bool completed = isCompleted; if (manualResetEvent == null) { lock(this) { if (manualResetEvent == null) manualResetEvent = new ManualResetEvent(completed); } } if (!completed && isCompleted) manualResetEvent.Set(); return manualResetEvent; } } public bool CompletedSynchronously { get { return completedSynchronously; } set { if (completedSynchronously) completedSynchronously = value; } } public bool IsCompleted { get { return isCompleted; } } #if (!COMPACT_FRAMEWORK) public CookieCollection ResponseCookies { get { return _responseCookies; } } #endif #if (!COMPACT_FRAMEWORK) public WebHeaderCollection ResponseHeaders { get { return _responseHeaders; } } #endif public bool UseEmptyParamsTag { get { return _useEmptyParamsTag; } } public bool UseIndentation { get { return _useIndentation; } } public int Indentation { get { return _indentation; } } public bool UseIntTag { get { return _useIntTag; } } public bool UseStringTag { get { return _useStringTag; } } // public members public void Abort() { if (request != null) request.Abort(); } public Exception Exception { get { return exception; } } public XmlRpcClientProtocol ClientProtocol { get { return clientProtocol; } } //internal members internal XmlRpcAsyncResult( XmlRpcClientProtocol ClientProtocol, XmlRpcRequest XmlRpcReq, Encoding XmlEncoding, bool useEmptyParamsTag, bool useIndentation, int indentation, bool UseIntTag, bool UseStringTag, WebRequest Request, AsyncCallback UserCallback, object UserAsyncState, int retryNumber) { xmlRpcRequest = XmlRpcReq; clientProtocol = ClientProtocol; request = Request; userAsyncState = UserAsyncState; userCallback = UserCallback; completedSynchronously = true; xmlEncoding = XmlEncoding; _useEmptyParamsTag = useEmptyParamsTag; _useIndentation = useIndentation; _indentation = indentation; _useIntTag = UseIntTag; _useStringTag = UseStringTag; } internal void Complete( Exception ex) { exception = ex; Complete(); } internal void Complete() { try { if (responseStream != null) { responseStream.Close(); responseStream = null; } if (responseBufferedStream != null) responseBufferedStream.Position = 0; } catch(Exception ex) { if (exception == null) exception = ex; } isCompleted = true; try { if (manualResetEvent != null) manualResetEvent.Set(); } catch(Exception ex) { if (exception == null) exception = ex; } if (userCallback != null) userCallback(this); } internal WebResponse WaitForResponse() { if (!isCompleted) AsyncWaitHandle.WaitOne(); if (exception != null) throw exception; return response; } internal bool EndSendCalled { get { return endSendCalled; } set { endSendCalled = value; } } internal byte[] Buffer { get { return buffer; } set { buffer = value; } } internal WebRequest Request { get { return request; } } internal WebResponse Response { get { return response; } set { response = value; } } internal Stream ResponseStream { get { return responseStream; } set { responseStream = value; } } internal XmlRpcRequest XmlRpcRequest { get { return xmlRpcRequest; } set { xmlRpcRequest = value; } } internal Stream ResponseBufferedStream { get { return responseBufferedStream; } set { responseBufferedStream = value; } } internal Encoding XmlEncoding { get { return xmlEncoding; } } XmlRpcClientProtocol clientProtocol; WebRequest request; AsyncCallback userCallback; object userAsyncState; bool completedSynchronously; bool isCompleted; bool endSendCalled = false; ManualResetEvent manualResetEvent; Exception exception; WebResponse response; Stream responseStream; Stream responseBufferedStream; byte[] buffer; XmlRpcRequest xmlRpcRequest; Encoding xmlEncoding; bool _useEmptyParamsTag; bool _useIndentation; int _indentation; bool _useIntTag; bool _useStringTag; #if (!COMPACT_FRAMEWORK) internal CookieCollection _responseCookies; internal WebHeaderCollection _responseHeaders; #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; #pragma warning disable 0067 namespace System.Reflection.Tests { public delegate void VoidDelegate(); public delegate void IntDelegate(int i); public class EventInfoTests { public static IEnumerable<object[]> AddEventHandler_TestData() { EI_Class tc1 = new EI_Class(); yield return new object[] { typeof(EI_Class).GetEvent("PublicEvent"), tc1, new VoidDelegate(tc1.PublicVoidMethod1), 1 }; yield return new object[] { typeof(EI_Class).GetEvent("PublicStaticEvent"), null, new VoidDelegate(tc1.ProtectedInternalVoidMethod), 2 }; yield return new object[] { typeof(EI_Class).GetEvent("PublicStaticEvent"), tc1, new VoidDelegate(tc1.PublicVoidMethod2), 3 }; } [Theory] [MemberData(nameof(AddEventHandler_TestData))] public void AddEventHandler_RemoveEventHandler(EventInfo eventInfo, EI_Class target, Delegate handler, int expectedStaticVariable) { // Add and make sure we bound the event. eventInfo.AddEventHandler(target, handler); target?.InvokeAllEvents(); EI_Class.InvokeStaticEvent(); Assert.Equal(expectedStaticVariable, EI_Class.AddEventHandler_RemoveEventHandler_Test_TrackingVariable); EI_Class.AddEventHandler_RemoveEventHandler_Test_TrackingVariable = 0; // Reset // Remove and make sure we unbound the event. eventInfo.RemoveEventHandler(target, handler); target?.InvokeAllEvents(); EI_Class.InvokeStaticEvent(); Assert.Equal(0, EI_Class.AddEventHandler_RemoveEventHandler_Test_TrackingVariable); } public static IEnumerable<object[]> AddEventHandler_Invalid_TestData() { // Null target for instance method EI_Class tc1 = new EI_Class(); yield return new object[] { typeof(EI_Class).GetEvent("PublicEvent"), null, new VoidDelegate(tc1.ProtectedInternalVoidMethod), typeof(TargetException) }; // Event not declared on target yield return new object[] { typeof(EI_Class).GetEvent("PublicEvent"), new DummyClass(), new VoidDelegate(tc1.ProtectedInternalVoidMethod), typeof(TargetException) }; // Event does not have a public add accessor yield return new object[] { typeof(EI_Class).GetEvent("PrivateEvent", BindingFlags.NonPublic | BindingFlags.Instance), new DummyClass(), new VoidDelegate(tc1.ProtectedInternalVoidMethod), typeof(InvalidOperationException) }; } [Theory] [MemberData(nameof(AddEventHandler_Invalid_TestData))] public void AddEventHandler_Invalid(EventInfo eventInfo, object target, Delegate handler, Type exceptionType) { Assert.Throws(exceptionType, () => eventInfo.AddEventHandler(target, handler)); Assert.Throws(exceptionType, () => eventInfo.RemoveEventHandler(target, handler)); } [Theory] [InlineData(nameof(EI_Class.PublicEvent))] [InlineData(nameof(EI_Class.Public_Event))] [InlineData("PrivateEvent")] [InlineData("ProtectedEvent")] [InlineData(nameof(EI_Class.ProtectedInternalEvent))] public void Attributes_IsSpecialName(string name) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); Assert.Equal(EventAttributes.None, eventInfo.Attributes); Assert.False(eventInfo.IsSpecialName); } [Theory] [InlineData(nameof(EI_Class.PublicEvent), typeof(VoidDelegate))] [InlineData("PrivateEvent", typeof(VoidDelegate))] [InlineData("ProtectedEvent", typeof(VoidDelegate))] [InlineData(nameof(EI_Class.ProtectedInternalEvent), typeof(VoidDelegate))] public void EventHandlerType(string name, Type expected) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); Assert.Equal(expected, eventInfo.EventHandlerType); } [Theory] [InlineData(nameof(EI_Class.PublicEvent), "Void add_PublicEvent(System.Reflection.Tests.VoidDelegate)", false)] [InlineData("PrivateEvent", "Void add_PrivateEvent(System.Reflection.Tests.VoidDelegate)", true)] [InlineData("ProtectedEvent", "Void add_ProtectedEvent(System.Reflection.Tests.VoidDelegate)", true)] [InlineData(nameof(EI_Class.ProtectedInternalEvent), "Void add_ProtectedInternalEvent(System.Reflection.Tests.VoidDelegate)", true)] public void GetAddMethod(string name, string expectedToString, bool nonPublic) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); MethodInfo method = eventInfo.GetAddMethod(); Assert.Equal(nonPublic, method == null); if (method != null) { Assert.Equal(expectedToString, method.ToString()); } method = eventInfo.GetAddMethod(false); Assert.Equal(nonPublic, method == null); if (method != null) { Assert.Equal(expectedToString, method.ToString()); } method = eventInfo.GetAddMethod(true); Assert.NotNull(method); Assert.Equal(expectedToString, method.ToString()); } [Theory] [InlineData(nameof(EI_Class.PublicEvent))] [InlineData("PrivateEvent")] [InlineData("ProtectedEvent")] [InlineData(nameof(EI_Class.ProtectedInternalEvent))] public void GetRaiseMethod(string name) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); Assert.Null(eventInfo.GetRaiseMethod()); Assert.Null(eventInfo.GetRaiseMethod(false)); Assert.Null(eventInfo.GetRaiseMethod(true)); } [Theory] [InlineData(nameof(EI_Class.PublicEvent), "Void remove_PublicEvent(System.Reflection.Tests.VoidDelegate)", false)] [InlineData("PrivateEvent", "Void remove_PrivateEvent(System.Reflection.Tests.VoidDelegate)", true)] [InlineData("ProtectedEvent", "Void remove_ProtectedEvent(System.Reflection.Tests.VoidDelegate)", true)] [InlineData(nameof(EI_Class.ProtectedInternalEvent), "Void remove_ProtectedInternalEvent(System.Reflection.Tests.VoidDelegate)", true)] public void GetRemoveMethod(string name, string expectedToString, bool nonPublic) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); MethodInfo method = eventInfo.GetRemoveMethod(); Assert.Equal(nonPublic, method == null); if (method != null) { Assert.Equal(expectedToString, method.ToString()); } method = eventInfo.GetRemoveMethod(false); Assert.Equal(nonPublic, method == null); if (method != null) { Assert.Equal(expectedToString, method.ToString()); } method = eventInfo.GetRemoveMethod(true); Assert.NotNull(method); Assert.Equal(expectedToString, method.ToString()); } [Theory] [InlineData("PublicEvent")] [InlineData("ProtectedEvent")] [InlineData("PrivateEvent")] [InlineData("InternalEvent")] public void DeclaringType_Module(string name) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); Assert.Equal(typeof(EI_Class), eventInfo.DeclaringType); Assert.Equal(typeof(EI_Class).GetTypeInfo().Module, eventInfo.Module); } [Theory] [InlineData("PublicEvent")] [InlineData("ProtectedEvent")] [InlineData("PrivateEvent")] [InlineData("InternalEvent")] public void Name(string name) { EventInfo eventInfo = Helpers.GetEvent(typeof(EI_Class), name); Assert.Equal(name, eventInfo.Name); } } public class EI_Class { public static int AddEventHandler_RemoveEventHandler_Test_TrackingVariable = 0; public event VoidDelegate PublicEvent; public event VoidDelegate Public_Event; public static event VoidDelegate PublicStaticEvent; private event VoidDelegate PrivateEvent; private event VoidDelegate Private_Event; internal event VoidDelegate InternalEvent; protected event VoidDelegate ProtectedEvent; protected internal event VoidDelegate ProtectedInternalEvent; public void InvokeAllEvents() { PublicEvent?.Invoke(); PrivateEvent?.Invoke(); InternalEvent?.Invoke(); ProtectedEvent?.Invoke(); ProtectedInternalEvent?.Invoke(); } public static void InvokeStaticEvent() { PublicStaticEvent?.Invoke(); } public void PublicVoidMethod1() => AddEventHandler_RemoveEventHandler_Test_TrackingVariable += 1; protected internal void ProtectedInternalVoidMethod() => AddEventHandler_RemoveEventHandler_Test_TrackingVariable += 2; public void PublicVoidMethod2() => AddEventHandler_RemoveEventHandler_Test_TrackingVariable += 3; } public class DummyClass { } }
/// OSVR-Unity Connection /// /// http://sensics.com/osvr /// /// <copyright> /// Copyright 2014 Sensics, 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. /// </copyright> using System.Collections; using System.Text; //a class for storing information about a device based on it's json descriptor file using Newtonsoft.Json; using System.IO; using System; using System.Diagnostics; public class DeviceDescriptor { //filename private string _fileName = ""; public string FileName { get { return _fileName; } set { _fileName = value; } } //hmd private string _vendor = ""; public string Vendor { get { return _vendor; } set { _vendor = value; } } private string _model = ""; public string Model { get { return _model; } set { _model = value; } } private string _version; public string Version { get { return _version; } set { _version = value; } } private string _note = ""; public string Note { get { return _note; } set { _note = value; } } //field of view private float _monocularHorizontal = 60f; public float MonocularHorizontal { get { return _monocularHorizontal; } set { _monocularHorizontal = value; } } private float _monocularVertical = 60f; public float MonocularVertical { get { return _monocularVertical; } set { _monocularVertical = value; } } private float _overlapPercent = 100f; public float OverlapPercent { get { return _overlapPercent; } set { _overlapPercent = value; } } private float _pitchTilt = 0; public float PitchTilt { get { return _pitchTilt; } set { _pitchTilt = value; } } //resolutions private int _width = 1920; public int Width { get { return _width; } set { _width = value; } } private int _height = 1080; public int Height { get { return _height; } set { _height = value; } } private int _numDisplays = 1; public int NumDisplays { get { return _numDisplays; } set { _numDisplays = value; } } private int _videoInputs = 1; public int VideoInputs { get { return _videoInputs; } set { _videoInputs = value; } } private string _displayMode = "horz_side_by_side"; public string DisplayMode { get { return _displayMode; } set { _displayMode = value; } } //distortion private float _k1Red = 0; public float K1Red { get { return _k1Red; } set { _k1Red = value; } } private float _k1Green = 0; public float K1Green { get { return _k1Green; } set { _k1Green = value; } } private float _k1Blue = 0; public float K1Blue { get { return _k1Blue; } set { _k1Blue = value; } } //rendering private float _leftRoll = 0; public float LeftRoll { get { return _leftRoll; } set { _leftRoll = value; } } private float _rightRoll = 0; public float RightRoll { get { return _rightRoll; } set { _rightRoll = value; } } //eyes private float _centerProjX = 0.5f; public float CenterProjX { get { return _centerProjX; } set { _centerProjX = value; } } private float _centerProjY = 0.5f; public float CenterProjY { get { return _centerProjY; } set { _centerProjY = value; } } private int _rotate180 = 0; public int Rotate180 { get { return _rotate180; } set { _rotate180 = value; } } //constructors public DeviceDescriptor() { } public DeviceDescriptor(string fileName, string vendor, string model, string version, int numDisplays, string note, float monocularHorizontal, float monocularVertical, float overlapPercent, float pitchTilt, int width, int height, int videoInputs, string displayMode, float k1Red, float k1Green, float k1Blue, float leftRoll, float rightRoll, float centerProjX, float centerProjY, int rotate180) { this._fileName = fileName; this._vendor = vendor; this._model = model; this._version = version; this._numDisplays = numDisplays; this._note = note; this._monocularHorizontal = monocularHorizontal; this._monocularVertical = monocularVertical; this._overlapPercent = overlapPercent; this._pitchTilt = pitchTilt; this._width = width; this._height = height; this._videoInputs = videoInputs; this._displayMode = displayMode; this._k1Red = k1Red; this._k1Green = k1Green; this._k1Blue = k1Blue; this._leftRoll = leftRoll; this._rightRoll = rightRoll; this._centerProjX = centerProjX; this._centerProjY = centerProjY; this._rotate180 = rotate180; } public override string ToString() { if (FileName.Equals("")) { return "No json file has been provided."; } //print StringBuilder jsonPrinter = new StringBuilder(64); jsonPrinter.AppendLine("Json File Device Description:") .Append("filename = ").AppendLine(FileName) .Append("HMD\n") .Append("vendor = ").AppendLine(Vendor) .Append("model = ").AppendLine(Model) .Append("version = ").AppendLine(Version) .Append("num_displays = ").AppendLine(NumDisplays.ToString()) .Append("notes = ").AppendLine(Note) .Append("\nFIELD OF VIEW\n") .Append("monocular_horizontal = ").AppendLine(MonocularHorizontal.ToString()) .Append("monocular_vertical = ").AppendLine(MonocularVertical.ToString()) .Append("overlap_percent = ").AppendLine(OverlapPercent.ToString()) .Append("pitch_tilt = ").AppendLine(PitchTilt.ToString()) .Append("\nRESOLUTION\n") .Append("width = ").AppendLine(Width.ToString()) .Append("height = ").AppendLine(Height.ToString()) .Append("video_inputs = ").AppendLine(VideoInputs.ToString()) .Append("display_mode = ").AppendLine(DisplayMode) .Append("\nDISTORTION\n") .Append("k1_red = ").AppendLine(K1Red.ToString()) .Append("k1_green = ").AppendLine(K1Green.ToString()) .Append("k1_blue = ").AppendLine(K1Blue.ToString()) .Append("\nRENDERING\n") .Append("left_roll = ").AppendLine(LeftRoll.ToString()) .Append("right_roll = ").AppendLine(RightRoll.ToString()) .Append("\nEYES\n") .Append("center_proj_x = ").AppendLine(CenterProjX.ToString()) .Append("center_proj_y = ").AppendLine(CenterProjY.ToString()) .Append("rotate_180 = ").AppendLine(Rotate180.ToString()); return jsonPrinter.ToString(); } /// <summary> /// This function will parse the device parameters from a device descriptor json file using Newstonsoft /// /// Returns a DeviceDescriptor object containing stored json values. /// </summary> public static DeviceDescriptor Parse(string deviceDescriptorJson) { if (deviceDescriptorJson == null) { throw new ArgumentNullException("deviceDescriptorJson"); } //create a device descriptor object for storing the parsed json in an object DeviceDescriptor deviceDescriptor; JsonTextReader reader; reader = new JsonTextReader(new StringReader(deviceDescriptorJson)); if (reader != null) { deviceDescriptor = new DeviceDescriptor(); } else { //Debug.LogError("No Device Descriptor detected."); return null; } //parsey while (reader.Read()) { if (reader.Value != null && reader.ValueType == typeof(String)) { string parsedJson = reader.Value.ToString().ToLower(); switch (parsedJson) { case "vendor": deviceDescriptor.Vendor = reader.ReadAsString(); break; case "model": deviceDescriptor.Model = reader.ReadAsString(); break; case "version": deviceDescriptor.Version = reader.ReadAsString(); break; case "num_displays": deviceDescriptor.NumDisplays = int.Parse(reader.ReadAsString()); break; case "note": deviceDescriptor.Note = reader.ReadAsString(); break; case "monocular_horizontal": deviceDescriptor.MonocularHorizontal = float.Parse(reader.ReadAsString()); break; case "monocular_vertical": deviceDescriptor.MonocularVertical = float.Parse(reader.ReadAsString()); break; case "overlap_percent": deviceDescriptor.OverlapPercent = float.Parse(reader.ReadAsString()); break; case "pitch_tilt": deviceDescriptor.PitchTilt = float.Parse(reader.ReadAsString()); break; case "width": deviceDescriptor.Width = int.Parse(reader.ReadAsString()); break; case "height": deviceDescriptor.Height = int.Parse(reader.ReadAsString()); break; case "video_inputs": deviceDescriptor.VideoInputs = int.Parse(reader.ReadAsString()); break; case "display_mode": deviceDescriptor.DisplayMode = reader.ReadAsString(); break; case "k1_red": deviceDescriptor.K1Red = float.Parse(reader.ReadAsString()); break; case "k1_green": deviceDescriptor.K1Green = float.Parse(reader.ReadAsString()); break; case "k1_blue": deviceDescriptor.K1Blue = float.Parse(reader.ReadAsString()); break; case "right_roll": deviceDescriptor.RightRoll = float.Parse(reader.ReadAsString()); break; case "left_roll": deviceDescriptor.LeftRoll = float.Parse(reader.ReadAsString()); break; case "center_proj_x": deviceDescriptor.CenterProjX = float.Parse(reader.ReadAsString()); break; case "center_proj_y": deviceDescriptor.CenterProjY = float.Parse(reader.ReadAsString()); break; case "rotate_180": deviceDescriptor.Rotate180 = int.Parse(reader.ReadAsString()); break; } } } return deviceDescriptor; } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Derivatives.Algo File: BlackScholes.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Derivatives { using System; using Ecng.Common; using StockSharp.Algo.Storages; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// The model for calculating Greeks values by the Black-Scholes formula. /// </summary> public class BlackScholes : IBlackScholes { /// <summary> /// Initialize <see cref="BlackScholes"/>. /// </summary> /// <param name="securityProvider">The provider of information about instruments.</param> /// <param name="dataProvider">The market data provider.</param> /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param> protected BlackScholes(ISecurityProvider securityProvider, IMarketDataProvider dataProvider, IExchangeInfoProvider exchangeInfoProvider) { SecurityProvider = securityProvider ?? throw new ArgumentNullException(nameof(securityProvider)); DataProvider = dataProvider ?? throw new ArgumentNullException(nameof(dataProvider)); ExchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider)); } /// <summary> /// Initializes a new instance of the <see cref="BlackScholes"/>. /// </summary> /// <param name="option">Options contract.</param> /// <param name="securityProvider">The provider of information about instruments.</param> /// <param name="dataProvider">The market data provider.</param> /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param> public BlackScholes(Security option, ISecurityProvider securityProvider, IMarketDataProvider dataProvider, IExchangeInfoProvider exchangeInfoProvider) : this(securityProvider, dataProvider, exchangeInfoProvider) { Option = option ?? throw new ArgumentNullException(nameof(option)); } /// <summary> /// Initializes a new instance of the <see cref="BlackScholes"/>. /// </summary> /// <param name="underlyingAsset">Underlying asset.</param> /// <param name="dataProvider">The market data provider.</param> /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param> protected BlackScholes(Security underlyingAsset, IMarketDataProvider dataProvider, IExchangeInfoProvider exchangeInfoProvider) { _underlyingAsset = underlyingAsset ?? throw new ArgumentNullException(nameof(underlyingAsset)); DataProvider = dataProvider ?? throw new ArgumentNullException(nameof(dataProvider)); ExchangeInfoProvider = exchangeInfoProvider ?? throw new ArgumentNullException(nameof(exchangeInfoProvider)); } /// <summary> /// Initializes a new instance of the <see cref="BlackScholes"/>. /// </summary> /// <param name="option">Options contract.</param> /// <param name="underlyingAsset">Underlying asset.</param> /// <param name="dataProvider">The market data provider.</param> /// <param name="exchangeInfoProvider">Exchanges and trading boards provider.</param> public BlackScholes(Security option, Security underlyingAsset, IMarketDataProvider dataProvider, IExchangeInfoProvider exchangeInfoProvider) : this(underlyingAsset, dataProvider, exchangeInfoProvider) { Option = option ?? throw new ArgumentNullException(nameof(option)); } /// <summary> /// The provider of information about instruments. /// </summary> public ISecurityProvider SecurityProvider { get; } /// <summary> /// The market data provider. /// </summary> public virtual IMarketDataProvider DataProvider { get; } /// <summary> /// Exchanges and trading boards provider. /// </summary> public IExchangeInfoProvider ExchangeInfoProvider { get; } /// <inheritdoc /> public virtual Security Option { get; } /// <inheritdoc /> public decimal RiskFree { get; set; } /// <inheritdoc /> public virtual decimal Dividend { get; set; } private int _roundDecimals = -1; /// <summary> /// The number of decimal places at calculated values. The default is -1, which means no values rounding. /// </summary> public virtual int RoundDecimals { get => _roundDecimals; set { if (value < -1) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str702); _roundDecimals = value; } } private Security _underlyingAsset; /// <summary> /// Underlying asset. /// </summary> public virtual Security UnderlyingAsset { get => _underlyingAsset ?? (_underlyingAsset = Option.GetUnderlyingAsset(SecurityProvider)); set => _underlyingAsset = value; } /// <summary> /// The standard deviation by default. /// </summary> public decimal DefaultDeviation => ((decimal?)DataProvider.GetSecurityValue(Option, Level1Fields.ImpliedVolatility) ?? 0) / 100; /// <summary> /// The time before expiration calculation. /// </summary> /// <param name="currentTime">The current time.</param> /// <returns>The time remaining until expiration. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public virtual double? GetExpirationTimeLine(DateTimeOffset currentTime) { return DerivativesHelper.GetExpirationTimeLine(Option.GetExpirationTime(ExchangeInfoProvider), currentTime); } /// <summary> /// To get the price of the underlying asset. /// </summary> /// <param name="assetPrice">The price of the underlying asset if it is specified.</param> /// <returns>The price of the underlying asset. If the value is equal to <see langword="null" />, then the value calculation currently is impossible.</returns> public decimal? GetAssetPrice(decimal? assetPrice = null) { if (assetPrice != null) return (decimal)assetPrice; return (decimal?)DataProvider.GetSecurityValue(UnderlyingAsset, Level1Fields.LastTradePrice); } /// <summary> /// Option type. /// </summary> protected OptionTypes OptionType { get { var type = Option.OptionType; if (type == null) throw new InvalidOperationException(LocalizedStrings.Str703Params.Put(Option)); return type.Value; } } /// <summary> /// To round to <see cref="BlackScholes.RoundDecimals"/>. /// </summary> /// <param name="value">The initial value.</param> /// <returns>The rounded value.</returns> protected decimal? TryRound(decimal? value) { if (value != null && RoundDecimals >= 0) value = Math.Round(value.Value, RoundDecimals); return value; } /// <inheritdoc /> public virtual decimal? Premium(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { deviation = deviation ?? DefaultDeviation; assetPrice = GetAssetPrice(assetPrice); if (assetPrice == null) return null; var timeToExp = GetExpirationTimeLine(currentTime); if (timeToExp == null) return null; return TryRound(DerivativesHelper.Premium(OptionType, GetStrike(), assetPrice.Value, RiskFree, Dividend, deviation.Value, timeToExp.Value, D1(deviation.Value, assetPrice.Value, timeToExp.Value))); } /// <inheritdoc /> public virtual decimal? Delta(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { assetPrice = GetAssetPrice(assetPrice); if (assetPrice == null) return null; var timeToExp = GetExpirationTimeLine(currentTime); if (timeToExp == null) return null; return TryRound(DerivativesHelper.Delta(OptionType, assetPrice.Value, D1(deviation ?? DefaultDeviation, assetPrice.Value, timeToExp.Value))); } /// <inheritdoc /> public virtual decimal? Gamma(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { deviation = deviation ?? DefaultDeviation; assetPrice = GetAssetPrice(assetPrice); if (assetPrice == null) return null; var timeToExp = GetExpirationTimeLine(currentTime); if (timeToExp == null) return null; return TryRound(DerivativesHelper.Gamma(assetPrice.Value, deviation.Value, timeToExp.Value, D1(deviation.Value, assetPrice.Value, timeToExp.Value))); } /// <inheritdoc /> public virtual decimal? Vega(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { assetPrice = GetAssetPrice(assetPrice); if (assetPrice == null) return null; var timeToExp = GetExpirationTimeLine(currentTime); if (timeToExp == null) return null; return TryRound(DerivativesHelper.Vega(assetPrice.Value, timeToExp.Value, D1(deviation ?? DefaultDeviation, assetPrice.Value, timeToExp.Value))); } /// <inheritdoc /> public virtual decimal? Theta(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { deviation = deviation ?? DefaultDeviation; assetPrice = GetAssetPrice(assetPrice); if (assetPrice == null) return null; var timeToExp = GetExpirationTimeLine(currentTime); if (timeToExp == null) return null; return TryRound(DerivativesHelper.Theta(OptionType, GetStrike(), assetPrice.Value, RiskFree, deviation.Value, timeToExp.Value, D1(deviation.Value, assetPrice.Value, timeToExp.Value))); } /// <inheritdoc /> public virtual decimal? Rho(DateTimeOffset currentTime, decimal? deviation = null, decimal? assetPrice = null) { deviation = deviation ?? DefaultDeviation; assetPrice = GetAssetPrice(assetPrice); if (assetPrice == null) return null; var timeToExp = GetExpirationTimeLine(currentTime); if (timeToExp == null) return null; return TryRound(DerivativesHelper.Rho(OptionType, GetStrike(), assetPrice.Value, RiskFree, deviation.Value, timeToExp.Value, D1(deviation.Value, assetPrice.Value, timeToExp.Value))); } /// <inheritdoc /> public virtual decimal? ImpliedVolatility(DateTimeOffset currentTime, decimal premium) { //var timeToExp = GetExpirationTimeLine(); return TryRound(DerivativesHelper.ImpliedVolatility(premium, diviation => Premium(currentTime, diviation))); } /// <summary> /// To calculate the d1 parameter of the option fulfilment probability estimating. /// </summary> /// <param name="deviation">Standard deviation.</param> /// <param name="assetPrice">Underlying asset price.</param> /// <param name="timeToExp">The option period before the expiration.</param> /// <returns>The d1 parameter.</returns> protected virtual double D1(decimal deviation, decimal assetPrice, double timeToExp) { return DerivativesHelper.D1(assetPrice, GetStrike(), RiskFree, Dividend, deviation, timeToExp); } /// <summary> /// To create the order book of volatility. /// </summary> /// <param name="currentTime">The current time.</param> /// <returns>The order book volatility.</returns> public virtual MarketDepth ImpliedVolatility(DateTimeOffset currentTime) { #pragma warning disable CS0618 // Type or member is obsolete return DataProvider.GetMarketDepth(Option).ImpliedVolatility(this, currentTime); #pragma warning restore CS0618 // Type or member is obsolete } internal decimal GetStrike() { return Option.Strike.Value; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration.Provider; using System.Text; using System.Web.SessionState; using Hydra.Framework; namespace Hydra.SharedCache.Common.Provider.Session { // // ********************************************************************** /// <summary> /// LBSProviderBase inherites from <see cref="SessionStateStoreProviderBase"/> /// </summary> // ********************************************************************** // public abstract class LBSProviderBase : SessionStateStoreProviderBase { // // ********************************************************************** /// <summary> /// Creates a new <see cref="T:System.Web.SessionState.SessionStateStoreData"></see> object to be used for the current request. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="timeout">The session-state <see cref="P:System.Web.SessionState.HttpSessionState.Timeout"></see> value for the new <see cref="T:System.Web.SessionState.SessionStateStoreData"></see>.</param> /// <returns> /// A new <see cref="T:System.Web.SessionState.SessionStateStoreData"></see> for the current request. /// </returns> // ********************************************************************** // public override SessionStateStoreData CreateNewStoreData(System.Web.HttpContext context, int timeout) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Adds a new session-state item to the data store. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The <see cref="P:System.Web.SessionState.HttpSessionState.SessionID"></see> for the current request.</param> /// <param name="timeout">The session <see cref="P:System.Web.SessionState.HttpSessionState.Timeout"></see> for the current request.</param> // ********************************************************************** // public override void CreateUninitializedItem(System.Web.HttpContext context, string id, int timeout) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Releases all resources used by the <see cref="T:System.Web.SessionState.SessionStateStoreProviderBase"></see> implementation. /// </summary> // ********************************************************************** // public override void Dispose() { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Called by the <see cref="T:System.Web.SessionState.SessionStateModule"></see> object at the end of a request. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> // ********************************************************************** // public override void EndRequest(System.Web.HttpContext context) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Returns read-only session-state data from the session data store. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The <see cref="P:System.Web.SessionState.HttpSessionState.SessionID"></see> for the current request.</param> /// <param name="locked">When this method returns, contains a Boolean value that is set to true if the requested session item is locked at the session data store; otherwise, false.</param> /// <param name="lockAge">When this method returns, contains a <see cref="T:System.TimeSpan"></see> object that is set to the amount of time that an item in the session data store has been locked.</param> /// <param name="lockId">When this method returns, contains an object that is set to the lock identifier for the current request. For details on the lock identifier, see "Locking Session-Store Data" in the <see cref="T:System.Web.SessionState.SessionStateStoreProviderBase"></see> class summary.</param> /// <param name="actions">When this method returns, contains one of the <see cref="T:System.Web.SessionState.SessionStateActions"></see> values, indicating whether the current session is an uninitialized, cookieless session.</param> /// <returns> /// A <see cref="T:System.Web.SessionState.SessionStateStoreData"></see> populated with session values and information from the session data store. /// </returns> // ********************************************************************** // public override SessionStateStoreData GetItem(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Returns read-only session-state data from the session data store. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The <see cref="P:System.Web.SessionState.HttpSessionState.SessionID"></see> for the current request.</param> /// <param name="locked">When this method returns, contains a Boolean value that is set to true if a lock is successfully obtained; otherwise, false.</param> /// <param name="lockAge">When this method returns, contains a <see cref="T:System.TimeSpan"></see> object that is set to the amount of time that an item in the session data store has been locked.</param> /// <param name="lockId">When this method returns, contains an object that is set to the lock identifier for the current request. For details on the lock identifier, see "Locking Session-Store Data" in the <see cref="T:System.Web.SessionState.SessionStateStoreProviderBase"></see> class summary.</param> /// <param name="actions">When this method returns, contains one of the <see cref="T:System.Web.SessionState.SessionStateActions"></see> values, indicating whether the current session is an uninitialized, cookieless session.</param> /// <returns> /// A <see cref="T:System.Web.SessionState.SessionStateStoreData"></see> populated with session values and information from the session data store. /// </returns> // ********************************************************************** // public override SessionStateStoreData GetItemExclusive(System.Web.HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Called by the <see cref="T:System.Web.SessionState.SessionStateModule"></see> object for per-request initialization. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> // ********************************************************************** // public override void InitializeRequest(System.Web.HttpContext context) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Releases a lock on an item in the session data store. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The session identifier for the current request.</param> /// <param name="lockId">The lock identifier for the current request.</param> // ********************************************************************** // public override void ReleaseItemExclusive(System.Web.HttpContext context, string id, object lockId) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Deletes item data from the session data store. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The session identifier for the current request.</param> /// <param name="lockId">The lock identifier for the current request.</param> /// <param name="item">The <see cref="T:System.Web.SessionState.SessionStateStoreData"></see> that represents the item to delete from the data store.</param> // ********************************************************************** // public override void RemoveItem(System.Web.HttpContext context, string id, object lockId, SessionStateStoreData item) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Updates the expiration date and time of an item in the session data store. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The session identifier for the current request.</param> // ********************************************************************** // public override void ResetItemTimeout(System.Web.HttpContext context, string id) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Updates the session-item information in the session-state data store with values from the current request, and clears the lock on the data. /// </summary> /// <param name="context">The <see cref="T:System.Web.HttpContext"></see> for the current request.</param> /// <param name="id">The session identifier for the current request.</param> /// <param name="item">The <see cref="T:System.Web.SessionState.SessionStateStoreData"></see> object that contains the current session values to be stored.</param> /// <param name="lockId">The lock identifier for the current request.</param> /// <param name="newItem">true to identify the session item as a new item; false to identify the session item as an existing item.</param> // ********************************************************************** // public override void SetAndReleaseItemExclusive(System.Web.HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { throw new Exception("The method or operation is not implemented."); } // // ********************************************************************** /// <summary> /// Sets a reference to the <see cref="T:System.Web.SessionState.SessionStateItemExpireCallback"></see> delegate for the Session_OnEnd event defined in the Global.asax file. /// </summary> /// <param name="expireCallback">The <see cref="T:System.Web.SessionState.SessionStateItemExpireCallback"></see> delegate for the Session_OnEnd event defined in the Global.asax file.</param> /// <returns> /// true if the session-state store provider supports calling the Session_OnEnd event; otherwise, false. /// </returns> // ********************************************************************** // public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback) { throw new Exception("The method or operation is not implemented."); } } }
#pragma warning disable 1591 using System; using System.Collections.Generic; using System.Text; namespace Braintree { public class WebhookTestingGateway : IWebhookTestingGateway { private readonly BraintreeService service; protected internal WebhookTestingGateway(BraintreeGateway gateway) { gateway.Configuration.AssertHasAccessTokenOrKeys(); service = gateway.Service; } public virtual Dictionary<string, string> SampleNotification(WebhookKind kind, string id, string sourceMerchantId = null) { var response = new Dictionary<string, string>(); string payload = BuildPayload(kind, id, sourceMerchantId); response["bt_payload"] = payload; response["bt_signature"] = BuildSignature(payload); return response; } private string BuildPayload(WebhookKind kind, string id, string sourceMerchantId) { var currentTime = DateTime.Now.ToUniversalTime().ToString("u"); var sourceMerchantIdXml = ""; if (sourceMerchantId != null) { sourceMerchantIdXml = $"<source-merchant-id>{sourceMerchantId}</source-merchant-id>"; } var payload = $"<notification><timestamp type=\"datetime\">{currentTime}</timestamp><kind>{kind}</kind>{sourceMerchantIdXml}<subject>{SubjectSampleXml(kind, id)}</subject></notification>"; return Convert.ToBase64String(Encoding.GetEncoding(0).GetBytes(payload)) + '\n'; } private string BuildSignature(string payload) { return $"{service.PublicKey}|{new Sha1Hasher().HmacHash(service.PrivateKey, payload).Trim().ToLower()}"; } private string SubjectSampleXml(WebhookKind kind, string id) { // NEXT_UNDER_MAJOR_VERSION // Convert to switch statement if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_APPROVED) { return MerchantAccountApprovedSampleXml(id); } else if (kind == WebhookKind.SUB_MERCHANT_ACCOUNT_DECLINED) { return MerchantAccountDeclinedSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_DISBURSED) { return TransactionDisbursedSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_REVIEWED) { return TransactionReviewedSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_SETTLED) { return TransactionSettledSampleXml(id); } else if (kind == WebhookKind.TRANSACTION_SETTLEMENT_DECLINED) { return TransactionSettlementDeclinedSampleXml(id); } else if (kind == WebhookKind.DISBURSEMENT_EXCEPTION) { return DisbursementExceptionSampleXml(id); } else if (kind == WebhookKind.DISBURSEMENT) { return DisbursementSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_CONNECTED) { return PartnerMerchantConnectedSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_DISCONNECTED) { return PartnerMerchantDisconnectedSampleXml(id); } else if (kind == WebhookKind.CONNECTED_MERCHANT_STATUS_TRANSITIONED) { return ConnectedMerchantStatusTransitionedSampleXml(id); } else if (kind == WebhookKind.CONNECTED_MERCHANT_PAYPAL_STATUS_CHANGED) { return ConnectedMerchantPayPalStatusChangedSampleXml(id); } else if (kind == WebhookKind.PARTNER_MERCHANT_DECLINED) { return PartnerMerchantDeclinedSampleXml(id); } else if (kind == WebhookKind.OAUTH_ACCESS_REVOKED) { return OAuthAccessRevokedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_OPENED) { return DisputeOpenedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_LOST) { return DisputeLostSampleXml(id); } else if (kind == WebhookKind.DISPUTE_WON) { return DisputeWonSampleXml(id); } else if (kind == WebhookKind.DISPUTE_ACCEPTED) { return DisputeAcceptedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_DISPUTED) { return DisputeDisputedSampleXml(id); } else if (kind == WebhookKind.DISPUTE_EXPIRED) { return DisputeExpiredSampleXml(id); } else if (kind == WebhookKind.SUBSCRIPTION_CHARGED_SUCCESSFULLY) { return SubscriptionChargedSuccessfullySampleXml(id); } else if (kind == WebhookKind.SUBSCRIPTION_CHARGED_UNSUCCESSFULLY) { return SubscriptionChargedUnsuccessfullySampleXml(id); } else if (kind == WebhookKind.CHECK) { return CheckSampleXml(); } else if (kind == WebhookKind.ACCOUNT_UPDATER_DAILY_REPORT) { return AccountUpdaterDailyReportSampleXml(id); } else if (kind == WebhookKind.GRANTOR_UPDATED_GRANTED_PAYMENT_METHOD) { return GrantedPaymentInstrumentUpdateSampleXml(); } else if (kind == WebhookKind.RECIPIENT_UPDATED_GRANTED_PAYMENT_METHOD) { return GrantedPaymentInstrumentUpdateSampleXml(); } else if (kind == WebhookKind.PAYMENT_METHOD_REVOKED_BY_CUSTOMER) { return PaymentMethodRevokedByCustomerSampleXml(id); } else if (kind == WebhookKind.GRANTED_PAYMENT_METHOD_REVOKED) { return GrantedPaymentMethodRevokedSampleXml(id); } else if (kind == WebhookKind.LOCAL_PAYMENT_COMPLETED) { return LocalPaymentCompletedSampleXml(); } else if (kind == WebhookKind.LOCAL_PAYMENT_EXPIRED) { return LocalPaymentExpiredSampleXml(); } else if (kind == WebhookKind.LOCAL_PAYMENT_FUNDED) { return LocalPaymentFundedSampleXml(); } else if (kind == WebhookKind.LOCAL_PAYMENT_REVERSED) { return LocalPaymentReversedSampleXml(); } else if (kind == WebhookKind.PAYMENT_METHOD_CUSTOMER_DATA_UPDATED) { return PaymentMethodCustomerDataUpdatedMetadataSampleXml(id); } else { return SubscriptionXml(id); } } private static readonly string TYPE_DATE = "type=\"date\""; private static readonly string TYPE_DATE_TIME = "type=\"datetime\""; private static readonly string TYPE_ARRAY = "type=\"array\""; private static readonly string TYPE_SYMBOL = "type=\"symbol\""; private static readonly string NIL_TRUE = "nil=\"true\""; private static readonly string TYPE_BOOLEAN = "type=\"boolean\""; private string MerchantAccountDeclinedSampleXml(string id) { return Node("api-error-response", Node("message", "Applicant declined due to OFAC."), NodeAttr("errors", TYPE_ARRAY, Node("merchant-account", NodeAttr("errors", TYPE_ARRAY, Node("error", Node("code", "82621"), Node("message", "Applicant declined due to OFAC."), NodeAttr("attribute", TYPE_SYMBOL, "base") ) ) ) ), Node("merchant-account", Node("id", id), Node("status", "suspended"), Node("master-merchant-account", Node("id", "master_ma_for_" + id), Node("status", "suspended") ) ) ); } private string TransactionDisbursedSampleXml(string id) { return Node("transaction", Node("id", id), Node("amount", "100.00"), Node("disbursement-details", NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09") ), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string TransactionSettledSampleXml(string id) { return Node("transaction", Node("id", id), Node("status", "settled"), Node("type", "sale"), Node("currency-iso-code", "USD"), Node("amount", "100.00"), Node("us-bank-account", Node("routing-number", "123456789"), Node("last-4", "1234"), Node("account-type", "checking"), Node("account-holder-name", "Dan Schulman")), Node("disbursement-details"), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string TransactionReviewedSampleXml(string id) { return Node("transaction-review", Node("transaction-id", "my_id"), Node("decision", "smart_decision"), Node("reviewer-email", "hey@girl.com"), Node("reviewer-note", "I made a smart decision."), NodeAttr("reviewed-time", TYPE_DATE_TIME, "2019-01-02T00:00:00Z") ); } private string TransactionSettlementDeclinedSampleXml(string id) { return Node("transaction", Node("id", id), Node("status", "settlement_declined"), Node("type", "sale"), Node("currency-iso-code", "USD"), Node("amount", "100.00"), Node("us-bank-account", Node("routing-number", "123456789"), Node("last-4", "1234"), Node("account-type", "checking"), Node("account-holder-name", "Dan Schulman")), Node("disbursement-details"), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ); } private string DisbursementExceptionSampleXml(string id) { return Node("disbursement", Node("id", id), Node("amount", "100.00"), Node("exception-message", "bank_rejected"), NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"), Node("follow-up-action", "update_funding_information"), NodeAttr("success", TYPE_BOOLEAN, "false"), NodeAttr("retry", TYPE_BOOLEAN, "false"), Node("merchant-account", Node("id", "merchant_account_id"), Node("master-merchant-account", Node("id", "master_ma"), Node("status", "active") ), Node("status", "active") ), NodeAttr("transaction-ids", TYPE_ARRAY, Node("item", "asdf"), Node("item", "qwer") ) ); } private string DisbursementSampleXml(string id) { return Node("disbursement", Node("id", id), Node("amount", "100.00"), NodeAttr("exception-message", NIL_TRUE, ""), NodeAttr("disbursement-date", TYPE_DATE, "2014-02-10"), NodeAttr("follow-up-action", NIL_TRUE, ""), NodeAttr("success", TYPE_BOOLEAN, "true"), NodeAttr("retry", TYPE_BOOLEAN, "false"), Node("merchant-account", Node("id", "merchant_account_id"), Node("master-merchant-account", Node("id", "master_ma"), Node("status", "active") ), Node("status", "active") ), NodeAttr("transaction-ids", TYPE_ARRAY, Node("item", "asdf"), Node("item", "qwer") ) ); } private string DisputeOpenedSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "open"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string DisputeLostSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "lost"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string DisputeWonSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "won"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21"), NodeAttr("date-won", TYPE_DATE, "2014-03-22") ); } private string DisputeAcceptedSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "accepted"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string DisputeDisputedSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "disputed"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string DisputeExpiredSampleXml(string id) { return Node("dispute", Node("id", id), Node("amount", "250.00"), Node("amount-disputed", "250.00"), Node("amount-won", "245.00"), NodeAttr("received-date", TYPE_DATE, "2014-03-21"), NodeAttr("reply-by-date", TYPE_DATE, "2014-03-21"), Node("currency-iso-code", "USD"), Node("kind", "chargeback"), Node("status", "expired"), Node("reason", "fraud"), Node("transaction", Node("id", id), Node("amount", "250.00") ), NodeAttr("date-opened", TYPE_DATE, "2014-03-21") ); } private string SubscriptionXml(string id) { return Node("subscription", Node("id", id), NodeAttr("transactions", TYPE_ARRAY), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string SubscriptionChargedSuccessfullySampleXml(string id) { return Node("subscription", Node("id", id), Node("transactions", Node("transaction", Node("id", id), Node("amount", "49.99"), Node("status", "submitted_for_settlement"), Node("disbursement-details", NodeAttr("disbursement-date", TYPE_DATE, "2013-07-09") ), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ) ), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string SubscriptionChargedUnsuccessfullySampleXml(string id) { return Node("subscription", Node("id", id), Node("transactions", Node("transaction", Node("id", id), Node("amount", "49.99"), Node("status", "failed"), Node("disbursement-details"), Node("billing"), Node("credit-card"), Node("customer"), Node("descriptor"), Node("shipping"), Node("subscription") ) ), NodeAttr("add_ons", TYPE_ARRAY), NodeAttr("discounts", TYPE_ARRAY) ); } private string CheckSampleXml() { return NodeAttr("check", TYPE_BOOLEAN, "true"); } private string MerchantAccountApprovedSampleXml(string id) { return Node("merchant-account", Node("id", id), Node("master-merchant-account", Node("id", "master_ma_for_" + id), Node("status", "active") ), Node("status", "active") ); } private string PartnerMerchantConnectedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123"), Node("merchant-public-id", "public_id"), Node("public-key", "public_key"), Node("private-key", "private_key"), Node("client-side-encryption-key", "cse_key") ); } private string PartnerMerchantDisconnectedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123") ); } private string ConnectedMerchantStatusTransitionedSampleXml(string id) { return Node("connected-merchant-status-transitioned", Node("oauth-application-client-id", "oauth_application_client_id"), Node("merchant-public-id", id), Node("status", "new_status") ); } private string ConnectedMerchantPayPalStatusChangedSampleXml(string id) { return Node("connected-merchant-paypal-status-changed", Node("oauth-application-client-id", "oauth_application_client_id"), Node("merchant-public-id", id), Node("action", "link") ); } private string PartnerMerchantDeclinedSampleXml(string id) { return Node("partner-merchant", Node("partner-merchant-id", "abc123") ); } private string OAuthAccessRevokedSampleXml(string id) { return Node("oauth-application-revocation", Node("merchant-id", id), Node("oauth-application-client-id", "oauth_application_client_id") ); } private string AccountUpdaterDailyReportSampleXml(string id) { return Node("account-updater-daily-report", NodeAttr("report-date", TYPE_DATE, "2016-01-14"), Node("report-url", "link-to-csv-report") ); } private string GrantedPaymentInstrumentUpdateSampleXml() { return Node("granted-payment-instrument-update", Node("grant-owner-merchant-id", "vczo7jqrpwrsi2px"), Node("grant-recipient-merchant-id", "cf0i8wgarszuy6hc"), Node("payment-method-nonce", Node("nonce", "ee257d98-de40-47e8-96b3-a6954ea7a9a4"), Node("consumed", TYPE_BOOLEAN, "false"), Node("locked", TYPE_BOOLEAN, "false") ), Node("token", "abc123z"), Node("updated-fields", TYPE_ARRAY, Node("item", "expiration-month"), Node("item", "expiration-year") ) ); } private static string PaymentMethodRevokedByCustomerSampleXml(string id) { return Node("paypal-account", Node("billing-agreement-id", "a-billing-agreement-id"), NodeAttr("created-at", TYPE_DATE_TIME, "2019-01-01T12:00:00Z"), Node("customer-id", "a-customer-id"), NodeAttr("default", TYPE_BOOLEAN, "true"), Node("email", "name@email.com"), Node("global-id", "cGF5bWVudG1ldGhvZF9jaDZieXNz"), Node("image-url", "https://assets.braintreegateway.com/payment_method_logo/paypal.png?environment=test"), Node("token", id), NodeAttr("updated-at", TYPE_DATE_TIME, "2019-01-02T12:00:00Z"), Node("is-channel-initiated", NIL_TRUE, ""), Node("payer-id", "a-payer-id"), Node("payer-info", NIL_TRUE, ""), Node("limited-use-order-id", NIL_TRUE, ""), NodeAttr("revoked-at", TYPE_DATE_TIME, "2019-01-02T12:00:00Z") ); } private static string GrantedPaymentMethodRevokedSampleXml(string id) { return VenmoAccountSampleXml(id); } private static string LocalPaymentCompletedSampleXml() { return Node("local-payment", Node("payment-id", "a-payment-id"), Node("payer-id", "a-payer-id"), Node("payment-method-nonce", "ee257d98-de40-47e8-96b3-a6954ea7a9a4"), Node("transaction", Node("id", "1"), Node("status", "authorizing"), Node("amount", "10.00"), Node("order-id", "order1234") ) ); } private static string LocalPaymentExpiredSampleXml() { return Node("local-payment-expired", Node("payment-id", "a-payment-id"), Node("payment-context-id", "a-payment-context-id") ); } private static string LocalPaymentFundedSampleXml() { return Node("local-payment-funded", Node("payment-id", "a-payment-id"), Node("payment-context-id", "a-payment-context-id"), Node("transaction", Node("id", "1"), Node("status", "settled"), Node("amount", "10.00"), Node("order-id", "order1234") ) ); } private static string LocalPaymentReversedSampleXml() { return Node("local-payment-reversed", Node("payment-id", "a-payment-id") ); } private static string PaymentMethodCustomerDataUpdatedMetadataSampleXml(string id) { return Node("payment-method-customer-data-updated-metadata", Node("token", "TOKEN12345"), Node("payment-method", VenmoAccountSampleXml(id)), NodeAttr("datetime-updated", TYPE_DATE_TIME, "2022-01-01T21:28:37Z"), Node("enriched-customer-data", Node("fields-updated", TYPE_ARRAY, Node("item", "username") ), Node("profile-data", Node("first-name", "John"), Node("last-name", "Doe"), Node("phone-number", "1231231234"), Node("email", "john.doe@paypal.com"), Node("username", "venmo_username") ) ) ); } private static string VenmoAccountSampleXml(string id) { return Node("venmo-account", NodeAttr("created-at", TYPE_DATE_TIME, "2021-05-05T21:28:37Z"), NodeAttr("updated-at", TYPE_DATE_TIME, "2021-05-05T21:28:37Z"), NodeAttr("default", TYPE_BOOLEAN, "true"), Node("image-url", "https://assets.braintreegateway.com/payment_method_logo/venmo.png?environment=test"), Node("token", id), Node("source-description", "Venmo Account: venmojoe"), Node("username", "venmojoe"), Node("venmo-user-id", "456"), NodeAttr("subscriptions", TYPE_ARRAY), Node("customer-id", "venmo_customer_id"), Node("global-id", "cGF5bWVudG1ldGhvZF92ZW5tb2FjY291bnQ") ); } private static string Node(string name, params string[] contents) { return NodeAttr(name, null, contents); } private static string NodeAttr(string name, string attributes, params string[] contents) { StringBuilder buffer = new StringBuilder(); buffer.Append('<').Append(name); if (attributes != null) { buffer.Append(" ").Append(attributes); } buffer.Append('>'); foreach (string content in contents) { buffer.Append(content); } buffer.Append("</").Append(name).Append('>'); return buffer.ToString(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UMA; public class UMACrowd : MonoBehaviour { public UMACrowdRandomSet[] randomPool; public UMAGeneratorBase generator; public UMAData umaData; public SlotLibrary slotLibrary; public OverlayLibrary overlayLibrary; public RaceLibrary raceLibrary; public RuntimeAnimatorController animationController; public float atlasResolutionScale; public bool generateUMA; public bool generateLotsUMA; public Vector2 umaCrowdSize; public bool randomDna; public float space = 1; public Transform zeroPoint; private Transform tempUMA; private int X; private int Y; private float umaTimer; public string[] keywords; void Awake() { if (space == 0) space = 1; string tempVersion = Application.unityVersion; tempVersion = tempVersion.Substring(0, 3); } void Update() { if (generateLotsUMA) { if (generator.IsIdle()) { GenerateOneUMA(); umaData.OnCharacterUpdated += new System.Action<UMAData>(umaData_OnUpdated); X = X + 1; if (X >= umaCrowdSize.x) { X = 0; Y = Y + 1; } if (Y >= umaCrowdSize.y) { generateLotsUMA = false; X = 0; Y = 0; } } } if (generateUMA) { GenerateOneUMA(); generateUMA = false; } } void umaData_OnUpdated(UMAData obj) { if (obj.cancelled) { Object.Destroy(obj.gameObject); } else { if (zeroPoint) { tempUMA.position = new Vector3(X * space + zeroPoint.position.x - umaCrowdSize.x * space * 0.5f + 0.5f, zeroPoint.position.y, Y * space + zeroPoint.position.z - umaCrowdSize.y * space * 0.5f + 0.5f); } else { tempUMA.position = new Vector3(X * space - umaCrowdSize.x * space * 0.5f + 0.5f, 0, Y * space - umaCrowdSize.y * space * 0.5f + 0.5f); } } } private void DefineSlots(UMACrowdRandomSet.CrowdRaceData race) { float skinTone = Random.Range(0.1f, 0.6f); Color skinColor = new Color(skinTone + Random.Range(0.35f, 0.4f), skinTone + Random.Range(0.25f, 0.4f), skinTone + Random.Range(0.35f, 0.4f), 1); Color HairColor = new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.5f)); var keywordsLookup = new HashSet<string>(keywords); UMACrowdRandomSet.Apply(umaData, race, skinColor, HairColor, keywordsLookup, slotLibrary, overlayLibrary); } void DefineSlots() { Color skinColor = new Color(1, 1, 1, 1); float skinTone; skinTone = Random.Range(0.1f, 0.6f); skinColor = new Color(skinTone + Random.Range(0.35f, 0.4f), skinTone + Random.Range(0.25f, 0.4f), skinTone + Random.Range(0.35f, 0.4f), 1); Color HairColor = new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1); if (umaData.umaRecipe.raceData.raceName == "HumanMale") { int randomResult = 0; //Male Avatar umaData.umaRecipe.slotDataList = new SlotData[15]; umaData.umaRecipe.slotDataList[0] = slotLibrary.InstantiateSlot("MaleEyes"); umaData.umaRecipe.slotDataList[0].AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlay")); umaData.umaRecipe.slotDataList[0].AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlayAdjust", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1] = slotLibrary.InstantiateSlot("MaleFace"); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead01", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead02", skinColor)); } } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1] = slotLibrary.InstantiateSlot("MaleHead_Head"); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead01", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead02", skinColor)); } umaData.umaRecipe.slotDataList[7] = slotLibrary.InstantiateSlot("MaleHead_Eyes", umaData.umaRecipe.slotDataList[1].GetOverlayList()); umaData.umaRecipe.slotDataList[9] = slotLibrary.InstantiateSlot("MaleHead_Mouth", umaData.umaRecipe.slotDataList[1].GetOverlayList()); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[10] = slotLibrary.InstantiateSlot("MaleHead_PigNose", umaData.umaRecipe.slotDataList[1].GetOverlayList()); umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHead_PigNose", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[10] = slotLibrary.InstantiateSlot("MaleHead_Nose", umaData.umaRecipe.slotDataList[1].GetOverlayList()); } randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[8] = slotLibrary.InstantiateSlot("MaleHead_ElvenEars"); umaData.umaRecipe.slotDataList[8].AddOverlay(overlayLibrary.InstantiateOverlay("ElvenEars", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[8] = slotLibrary.InstantiateSlot("MaleHead_Ears", umaData.umaRecipe.slotDataList[1].GetOverlayList()); } } randomResult = Random.Range(0, 3); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHair01", HairColor * 0.25f)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleHair02", HairColor * 0.25f)); } else { } randomResult = Random.Range(0, 4); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBeard01", HairColor * 0.15f)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBeard02", HairColor * 0.15f)); } else if (randomResult == 2) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBeard03", HairColor * 0.15f)); } else { } //Extra beard composition randomResult = Random.Range(0, 4); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBeard01", HairColor * 0.15f)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBeard02", HairColor * 0.15f)); } else if (randomResult == 2) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBeard03", HairColor * 0.15f)); } else { } randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleEyebrow01", HairColor * 0.05f)); } else { umaData.umaRecipe.slotDataList[1].AddOverlay(overlayLibrary.InstantiateOverlay("MaleEyebrow02", HairColor * 0.05f)); } umaData.umaRecipe.slotDataList[2] = slotLibrary.InstantiateSlot("MaleTorso"); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[2].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBody01", skinColor)); } else { umaData.umaRecipe.slotDataList[2].AddOverlay(overlayLibrary.InstantiateOverlay("MaleBody02", skinColor)); } randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[2].AddOverlay(overlayLibrary.InstantiateOverlay("MaleShirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } umaData.umaRecipe.slotDataList[3] = slotLibrary.InstantiateSlot("MaleHands", umaData.umaRecipe.slotDataList[2].GetOverlayList()); umaData.umaRecipe.slotDataList[4] = slotLibrary.InstantiateSlot("MaleInnerMouth"); umaData.umaRecipe.slotDataList[4].AddOverlay(overlayLibrary.InstantiateOverlay("InnerMouth")); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[5] = slotLibrary.InstantiateSlot("MaleLegs", umaData.umaRecipe.slotDataList[2].GetOverlayList()); umaData.umaRecipe.slotDataList[2].AddOverlay(overlayLibrary.InstantiateOverlay("MaleUnderwear01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else { umaData.umaRecipe.slotDataList[5] = slotLibrary.InstantiateSlot("MaleJeans01"); umaData.umaRecipe.slotDataList[5].AddOverlay(overlayLibrary.InstantiateOverlay("MaleJeans01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } umaData.umaRecipe.slotDataList[6] = slotLibrary.InstantiateSlot("MaleFeet", umaData.umaRecipe.slotDataList[2].GetOverlayList()); } else if (umaData.umaRecipe.raceData.raceName == "HumanFemale") { int randomResult = 0; //Female Avatar //Example of dynamic list List<SlotData> tempSlotList = new List<SlotData>(); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleEyes")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlay")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("EyeOverlayAdjust", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); int headIndex = 0; randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleFace")); headIndex = tempSlotList.Count - 1; tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleHead01", skinColor)); tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleEyebrow01", new Color(0.125f, 0.065f, 0.065f, 1.0f))); randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleLipstick01", new Color(skinColor.r + Random.Range(0.0f, 0.3f), skinColor.g, skinColor.b + Random.Range(0.0f, 0.2f), 1))); } } else if (randomResult == 1) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHead_Head")); headIndex = tempSlotList.Count - 1; tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleHead01", skinColor)); tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleEyebrow01", new Color(0.125f, 0.065f, 0.065f, 1.0f))); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHead_Eyes", tempSlotList[headIndex].GetOverlayList())); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHead_Mouth", tempSlotList[headIndex].GetOverlayList())); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHead_Nose", tempSlotList[headIndex].GetOverlayList())); randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHead_ElvenEars")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("ElvenEars", skinColor)); } else if (randomResult == 1) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHead_Ears", tempSlotList[headIndex].GetOverlayList())); } randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleLipstick01", new Color(skinColor.r + Random.Range(0.0f, 0.3f), skinColor.g, skinColor.b + Random.Range(0.0f, 0.2f), 1))); } } tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleEyelash")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleEyelash", Color.black)); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleTorso")); int bodyIndex = tempSlotList.Count - 1; randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList[bodyIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleBody01", skinColor)); } if (randomResult == 1) { tempSlotList[bodyIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleBody02", skinColor)); } tempSlotList[bodyIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleUnderwear01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); randomResult = Random.Range(0, 4); if (randomResult == 0) { tempSlotList[bodyIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleShirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else if (randomResult == 1) { tempSlotList[bodyIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleShirt02", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else if (randomResult == 2) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleTshirt01")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleTshirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else { } tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleHands", tempSlotList[bodyIndex].GetOverlayList())); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleInnerMouth")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("InnerMouth")); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleFeet", tempSlotList[bodyIndex].GetOverlayList())); randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleLegs", tempSlotList[bodyIndex].GetOverlayList())); } else if (randomResult == 1) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleLegs", tempSlotList[bodyIndex].GetOverlayList())); tempSlotList[bodyIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleJeans01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } randomResult = Random.Range(0, 3); if (randomResult == 0) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleShortHair01", tempSlotList[headIndex].GetOverlayList())); tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleShortHair01", HairColor)); } else if (randomResult == 1) { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleLongHair01", tempSlotList[headIndex].GetOverlayList())); tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleLongHair01", HairColor)); } else { tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleLongHair01", tempSlotList[headIndex].GetOverlayList())); tempSlotList[headIndex].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleLongHair01", HairColor)); tempSlotList.Add(slotLibrary.InstantiateSlot("FemaleLongHair01_Module")); tempSlotList[tempSlotList.Count - 1].AddOverlay(overlayLibrary.InstantiateOverlay("FemaleLongHair01_Module", HairColor)); } umaData.SetSlots(tempSlotList.ToArray()); } } protected virtual void SetUMAData() { umaData.atlasResolutionScale = atlasResolutionScale; umaData.OnCharacterUpdated += myColliderUpdateMethod; } void myColliderUpdateMethod(UMAData umaData) { CapsuleCollider tempCollider = umaData.umaRoot.gameObject.GetComponent("CapsuleCollider") as CapsuleCollider; if (tempCollider) { UMADnaHumanoid umaDna = umaData.umaRecipe.GetDna<UMADnaHumanoid>(); tempCollider.height = (umaDna.height + 0.5f) * 2 + 0.1f; tempCollider.center = new Vector3(0, tempCollider.height * 0.5f - 0.04f, 0); } } protected virtual void GenerateUMAShapes() { UMADnaHumanoid umaDna = new UMADnaHumanoid(); umaData.umaRecipe.AddDna(umaDna); if (randomDna) { umaDna.height = Random.Range(0.3f, 0.5f); umaDna.headSize = Random.Range(0.485f, 0.515f); umaDna.headWidth = Random.Range(0.4f, 0.6f); umaDna.neckThickness = Random.Range(0.495f, 0.51f); if (umaData.umaRecipe.raceData.raceName == "HumanMale") { umaDna.handsSize = Random.Range(0.485f, 0.515f); umaDna.feetSize = Random.Range(0.485f, 0.515f); umaDna.legSeparation = Random.Range(0.4f, 0.6f); umaDna.waist = 0.5f; } else { umaDna.handsSize = Random.Range(0.485f, 0.515f); umaDna.feetSize = Random.Range(0.485f, 0.515f); umaDna.legSeparation = Random.Range(0.485f, 0.515f); umaDna.waist = Random.Range(0.3f, 0.8f); } umaDna.armLength = Random.Range(0.485f, 0.515f); umaDna.forearmLength = Random.Range(0.485f, 0.515f); umaDna.armWidth = Random.Range(0.3f, 0.8f); umaDna.forearmWidth = Random.Range(0.3f, 0.8f); umaDna.upperMuscle = Random.Range(0.0f, 1.0f); umaDna.upperWeight = Random.Range(-0.2f, 0.2f) + umaDna.upperMuscle; if (umaDna.upperWeight > 1.0) { umaDna.upperWeight = 1.0f; } if (umaDna.upperWeight < 0.0) { umaDna.upperWeight = 0.0f; } umaDna.lowerMuscle = Random.Range(-0.2f, 0.2f) + umaDna.upperMuscle; if (umaDna.lowerMuscle > 1.0) { umaDna.lowerMuscle = 1.0f; } if (umaDna.lowerMuscle < 0.0) { umaDna.lowerMuscle = 0.0f; } umaDna.lowerWeight = Random.Range(-0.1f, 0.1f) + umaDna.upperWeight; if (umaDna.lowerWeight > 1.0) { umaDna.lowerWeight = 1.0f; } if (umaDna.lowerWeight < 0.0) { umaDna.lowerWeight = 0.0f; } umaDna.belly = umaDna.upperWeight; umaDna.legsSize = Random.Range(0.4f, 0.6f); umaDna.gluteusSize = Random.Range(0.4f, 0.6f); umaDna.earsSize = Random.Range(0.3f, 0.8f); umaDna.earsPosition = Random.Range(0.3f, 0.8f); umaDna.earsRotation = Random.Range(0.3f, 0.8f); umaDna.noseSize = Random.Range(0.3f, 0.8f); umaDna.noseCurve = Random.Range(0.3f, 0.8f); umaDna.noseWidth = Random.Range(0.3f, 0.8f); umaDna.noseInclination = Random.Range(0.3f, 0.8f); umaDna.nosePosition = Random.Range(0.3f, 0.8f); umaDna.nosePronounced = Random.Range(0.3f, 0.8f); umaDna.noseFlatten = Random.Range(0.3f, 0.8f); umaDna.chinSize = Random.Range(0.3f, 0.8f); umaDna.chinPronounced = Random.Range(0.3f, 0.8f); umaDna.chinPosition = Random.Range(0.3f, 0.8f); umaDna.mandibleSize = Random.Range(0.45f, 0.52f); umaDna.jawsSize = Random.Range(0.3f, 0.8f); umaDna.jawsPosition = Random.Range(0.3f, 0.8f); umaDna.cheekSize = Random.Range(0.3f, 0.8f); umaDna.cheekPosition = Random.Range(0.3f, 0.8f); umaDna.lowCheekPronounced = Random.Range(0.3f, 0.8f); umaDna.lowCheekPosition = Random.Range(0.3f, 0.8f); umaDna.foreheadSize = Random.Range(0.3f, 0.8f); umaDna.foreheadPosition = Random.Range(0.15f, 0.65f); umaDna.lipsSize = Random.Range(0.3f, 0.8f); umaDna.mouthSize = Random.Range(0.3f, 0.8f); umaDna.eyeRotation = Random.Range(0.3f, 0.8f); umaDna.eyeSize = Random.Range(0.3f, 0.8f); umaDna.breastSize = Random.Range(0.3f, 0.8f); } } void GenerateOneUMA() { var newGO = new GameObject("Generated Character"); newGO.transform.parent = transform; var umaDynamicAvatar = newGO.AddComponent<UMADynamicAvatar>(); umaDynamicAvatar.Initialize(); umaData = umaDynamicAvatar.umaData; umaDynamicAvatar.umaGenerator = generator; umaData.umaGenerator = generator; var umaRecipe = umaDynamicAvatar.umaData.umaRecipe; UMACrowdRandomSet.CrowdRaceData race = null; if (randomPool != null && randomPool.Length > 0) { int randomResult = Random.Range(0, randomPool.Length); race = randomPool[randomResult].data; umaRecipe.SetRace(raceLibrary.GetRace(race.raceID)); } else { int randomResult = Random.Range(0, 2); if (randomResult == 0) { umaRecipe.SetRace(raceLibrary.GetRace("HumanMale")); } else { umaRecipe.SetRace(raceLibrary.GetRace("HumanFemale")); } } SetUMAData(); if (race != null && race.slotElements.Length > 0) { DefineSlots(race); } else { DefineSlots(); } GenerateUMAShapes(); if (animationController != null) { umaDynamicAvatar.animationController = animationController; } umaDynamicAvatar.UpdateNewRace(); umaDynamicAvatar.umaData.myRenderer.enabled = false; tempUMA = newGO.transform; if (zeroPoint) { tempUMA.position = new Vector3(zeroPoint.position.x, zeroPoint.position.y, zeroPoint.position.z); } else { tempUMA.position = new Vector3(0, 0, 0); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Net; using System.Reflection; using log4net; using log4net.Config; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; namespace OpenSim { /// <summary> /// Starting class for the OpenSimulator Region /// </summary> public class Application { /// <summary> /// Text Console Logger /// </summary> private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Path to the main ini Configuration file /// </summary> public static string iniFilePath = ""; /// <summary> /// Save Crashes in the bin/crashes folder. Configurable with m_crashDir /// </summary> public static bool m_saveCrashDumps = false; /// <summary> /// Directory to save crash reports to. Relative to bin/ /// </summary> public static string m_crashDir = "crashes"; /// <summary> /// Instance of the OpenSim class. This could be OpenSim or OpenSimBackground depending on the configuration /// </summary> protected static OpenSimBase m_sim = null; //could move our main function into OpenSimMain and kill this class public static void Main(string[] args) { // First line, hook the appdomain to the crash reporter AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); ServicePointManager.DefaultConnectionLimit = 12; // Add the arguments supplied when running the application to the configuration ArgvConfigSource configSource = new ArgvConfigSource(args); // Configure Log4Net configSource.AddSwitch("Startup", "logconfig"); string logConfigFile = configSource.Configs["Startup"].GetString("logconfig", String.Empty); if (logConfigFile != String.Empty) { XmlConfigurator.Configure(new System.IO.FileInfo(logConfigFile)); m_log.InfoFormat("[OPENSIM MAIN]: configured log4net using \"{0}\" as configuration file", logConfigFile); } else { XmlConfigurator.Configure(); m_log.Info("[OPENSIM MAIN]: configured log4net using default OpenSim.exe.config"); } m_log.InfoFormat( "[OPENSIM MAIN]: System Locale is {0}", System.Threading.Thread.CurrentThread.CurrentCulture); string monoThreadsPerCpu = System.Environment.GetEnvironmentVariable("MONO_THREADS_PER_CPU"); m_log.InfoFormat( "[OPENSIM MAIN]: Environment variable MONO_THREADS_PER_CPU is {0}", monoThreadsPerCpu ?? "unset"); // Verify the Threadpool allocates or uses enough worker and IO completion threads // .NET 2.0 workerthreads default to 50 * numcores // .NET 3.0 workerthreads defaults to 250 * numcores // .NET 4.0 workerthreads are dynamic based on bitness and OS resources // Max IO Completion threads are 1000 on all 3 CLRs. int workerThreadsMin = 500; int workerThreadsMax = 1000; // may need further adjustment to match other CLR int iocpThreadsMin = 1000; int iocpThreadsMax = 2000; // may need further adjustment to match other CLR int workerThreads, iocpThreads; System.Threading.ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads); m_log.InfoFormat("[OPENSIM MAIN]: Runtime gave us {0} worker threads and {1} IOCP threads", workerThreads, iocpThreads); if (workerThreads < workerThreadsMin) { workerThreads = workerThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up to worker threads to {0}",workerThreads); } if (workerThreads > workerThreadsMax) { workerThreads = workerThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting worker threads to {0}",workerThreads); } // Increase the number of IOCP threads available. // Mono defaults to a tragically low number (24 on 6-core / 8GB Fedora 17) if (iocpThreads < iocpThreadsMin) { iocpThreads = iocpThreadsMin; m_log.InfoFormat("[OPENSIM MAIN]: Bumping up IO completion threads to {0}",iocpThreads); } // Make sure we don't overallocate IOCP threads and thrash system resources if ( iocpThreads > iocpThreadsMax ) { iocpThreads = iocpThreadsMax; m_log.InfoFormat("[OPENSIM MAIN]: Limiting IO completion threads to {0}",iocpThreads); } // set the resulting worker and IO completion thread counts back to ThreadPool if ( System.Threading.ThreadPool.SetMaxThreads(workerThreads, iocpThreads) ) { m_log.InfoFormat("[OPENSIM MAIN]: Threadpool set to {0} worker threads and {1} IO completion threads", workerThreads, iocpThreads); } else { m_log.Info("[OPENSIM MAIN]: Threadpool reconfiguration failed, runtime defaults still in effect."); } // Check if the system is compatible with OpenSimulator. // Ensures that the minimum system requirements are met string supported = String.Empty; if (Util.IsEnvironmentSupported(ref supported)) { m_log.Info("Environment is compatible.\n"); } else { m_log.Warn("Environment is unsupported (" + supported + ")\n"); } // Configure nIni aliases and localles Culture.SetCurrentCulture(); // Validate that the user has the most basic configuration done // If not, offer to do the most basic configuration for them warning them along the way of the importance of // reading these files. /* m_log.Info("Checking for reguired configuration...\n"); bool OpenSim_Ini = (File.Exists(Path.Combine(Util.configDir(), "OpenSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "opensim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "openSim.ini"))) || (File.Exists(Path.Combine(Util.configDir(), "Opensim.ini"))); bool StanaloneCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); bool StanaloneCommon_lowercased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "standalonecommon.ini")); bool GridCommon_ProperCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "GridCommon.ini")); bool GridCommon_lowerCased = File.Exists(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "gridcommon.ini")); if ((OpenSim_Ini) && ( (StanaloneCommon_ProperCased || StanaloneCommon_lowercased || GridCommon_ProperCased || GridCommon_lowerCased ))) { m_log.Info("Required Configuration Files Found\n"); } else { MainConsole.Instance = new LocalConsole("Region"); string resp = MainConsole.Instance.CmdPrompt( "\n\n*************Required Configuration files not found.*************\n\n OpenSimulator will not run without these files.\n\nRemember, these file names are Case Sensitive in Linux and Proper Cased.\n1. ./OpenSim.ini\nand\n2. ./config-include/StandaloneCommon.ini \nor\n3. ./config-include/GridCommon.ini\n\nAlso, you will want to examine these files in great detail because only the basic system will load by default. OpenSimulator can do a LOT more if you spend a little time going through these files.\n\n" + ": " + "Do you want to copy the most basic Defaults from standalone?", "yes"); if (resp == "yes") { if (!(OpenSim_Ini)) { try { File.Copy(Path.Combine(Util.configDir(), "OpenSim.ini.example"), Path.Combine(Util.configDir(), "OpenSim.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, Make sure OpenSim has have the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, The current directory is invalid.\n"); } } if (!(StanaloneCommon_ProperCased || StanaloneCommon_lowercased)) { try { File.Copy(Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini.example"), Path.Combine(Path.Combine(Util.configDir(), "config-include"), "StandaloneCommon.ini")); } catch (UnauthorizedAccessException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, Make sure OpenSim has the required permissions\n"); } catch (ArgumentException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } catch (System.IO.PathTooLongException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the Path to these files is too long.\n"); } catch (System.IO.DirectoryNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the current directory is reporting as not found.\n"); } catch (System.IO.FileNotFoundException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.IO.IOException) { // Destination file exists already or a hard drive failure... .. so we can just drop this one //MainConsole.Instance.Output("Unable to Copy OpenSim.ini.example to OpenSim.ini, the example is not found, please make sure that the example files exist.\n"); } catch (System.NotSupportedException) { MainConsole.Instance.Output("Unable to Copy StandaloneCommon.ini.example to StandaloneCommon.ini, The current directory is invalid.\n"); } } } MainConsole.Instance = null; } */ configSource.Alias.AddAlias("On", true); configSource.Alias.AddAlias("Off", false); configSource.Alias.AddAlias("True", true); configSource.Alias.AddAlias("False", false); configSource.Alias.AddAlias("Yes", true); configSource.Alias.AddAlias("No", false); configSource.AddSwitch("Startup", "background"); configSource.AddSwitch("Startup", "inifile"); configSource.AddSwitch("Startup", "inimaster"); configSource.AddSwitch("Startup", "inidirectory"); configSource.AddSwitch("Startup", "physics"); configSource.AddSwitch("Startup", "gui"); configSource.AddSwitch("Startup", "console"); configSource.AddSwitch("Startup", "save_crashes"); configSource.AddSwitch("Startup", "crash_dir"); configSource.AddConfig("StandAlone"); configSource.AddConfig("Network"); // Check if we're running in the background or not bool background = configSource.Configs["Startup"].GetBoolean("background", false); // Check if we're saving crashes m_saveCrashDumps = configSource.Configs["Startup"].GetBoolean("save_crashes", false); // load Crash directory config m_crashDir = configSource.Configs["Startup"].GetString("crash_dir", m_crashDir); if (background) { m_sim = new OpenSimBackground(configSource); m_sim.Startup(); } else { m_sim = new OpenSim(configSource); m_sim.Startup(); while (true) { try { // Block thread here for input MainConsole.Instance.Prompt(); } catch (Exception e) { m_log.ErrorFormat("Command error: {0}", e); } } } } private static bool _IsHandlingException = false; // Make sure we don't go recursive on ourself /// <summary> /// Global exception handler -- all unhandlet exceptions end up here :) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { if (_IsHandlingException) { return; } _IsHandlingException = true; // TODO: Add config option to allow users to turn off error reporting // TODO: Post error report (disabled for now) string msg = String.Empty; msg += "\r\n"; msg += "APPLICATION EXCEPTION DETECTED: " + e.ToString() + "\r\n"; msg += "\r\n"; msg += "Exception: " + e.ExceptionObject.ToString() + "\r\n"; Exception ex = (Exception) e.ExceptionObject; if (ex.InnerException != null) { msg += "InnerException: " + ex.InnerException.ToString() + "\r\n"; } msg += "\r\n"; msg += "Application is terminating: " + e.IsTerminating.ToString() + "\r\n"; m_log.ErrorFormat("[APPLICATION]: {0}", msg); if (m_saveCrashDumps) { // Log exception to disk try { if (!Directory.Exists(m_crashDir)) { Directory.CreateDirectory(m_crashDir); } string log = Util.GetUniqueFilename(ex.GetType() + ".txt"); using (StreamWriter m_crashLog = new StreamWriter(Path.Combine(m_crashDir, log))) { m_crashLog.WriteLine(msg); } File.Copy("OpenSim.ini", Path.Combine(m_crashDir, log + "_OpenSim.ini"), true); } catch (Exception e2) { m_log.ErrorFormat("[CRASH LOGGER CRASHED]: {0}", e2); } } _IsHandlingException = false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.IO; using System.Text.RegularExpressions; using System.Xml; namespace Nustache.Core { public delegate Template TemplateLocator(string name); public delegate TResult Lambda<TResult>(); public delegate TResult Lambda<T, TResult>(T arg); public delegate string RenderFunc(RenderContext context); public class RenderContext { private const int IncludeLimit = 1024; private readonly Stack<Section> _sectionStack = new Stack<Section>(); private readonly Stack<object> _dataStack = new Stack<object>(); private readonly TextWriter _writer; private readonly TemplateLocator _templateLocator; private readonly RenderContextBehaviour _renderContextBehaviour; private int _includeLevel; private string _indent; private bool _lineEnded; private readonly Regex _indenter = new Regex("\n(?!$)"); public string ActiveStartDelimiter { get; set; } public string ActiveEndDelimiter { get; set; } public RenderContext(Section section, object data, TextWriter writer, TemplateLocator templateLocator, RenderContextBehaviour renderContextBehaviour = null) { _sectionStack.Push(section); _dataStack.Push(data); _writer = writer; _templateLocator = templateLocator; _includeLevel = 0; _renderContextBehaviour = renderContextBehaviour ?? RenderContextBehaviour.GetDefaultRenderContextBehaviour(); } public RenderContext(RenderContext baseContext, TextWriter writer) { _sectionStack = baseContext._sectionStack; _dataStack = baseContext._dataStack; _writer = writer; _templateLocator = baseContext._templateLocator; _renderContextBehaviour = baseContext._renderContextBehaviour; _includeLevel = baseContext._includeLevel; _indent = baseContext._indent; _lineEnded = baseContext._lineEnded; } public object GetValue(string path) { if (path == ".") { object peekedObject = _dataStack.Peek(); if (peekedObject as XmlElement != null) { return ((XmlElement)peekedObject).InnerText; } return peekedObject; } foreach (var data in _dataStack) { if (data != null) { bool partialMatch; var value = GetValueFromPath(data, path, out partialMatch); if (partialMatch) break; if (!ReferenceEquals(value, ValueGetter.NoValue)) { if (value is string) { var valueAsString = (string)value; if (string.IsNullOrEmpty(valueAsString) && _renderContextBehaviour.RaiseExceptionOnEmptyStringValue) { throw new NustacheEmptyStringException( string.Format("Path : {0} is an empty string, RaiseExceptionOnEmptyStringValue : true.", path)); } } return value; } } } string name; IList<object> arguments; IDictionary<string, object> options; Helpers.Parse(this, path, out name, out arguments, out options); if (Helpers.Contains(name)) { var helper = Helpers.Get(name); return (HelperProxy)((fn, inverse) => helper(this, arguments, options, fn, inverse)); } if (_renderContextBehaviour.RaiseExceptionOnDataContextMiss) { throw new NustacheDataContextMissException(string.Format("Path : {0} is undefined, RaiseExceptionOnDataContextMiss : true.", path)); } return null; } private static object GetValueFromPath(object data, string path, out bool partialMatch) { partialMatch = false; var value = ValueGetter.GetValue(data, path); if (value != null && !ReferenceEquals(value, ValueGetter.NoValue)) { return value; } var names = path.Split('.'); if (names.Length > 1) { for (int i = 0; i < names.Length; i++ ) { data = ValueGetter.GetValue(data, names[i]); if (data == null || ReferenceEquals(data, ValueGetter.NoValue)) { if (i > 0) { partialMatch = true; } break; } } return data; } return value; } public IEnumerable<object> GetValues(string path) { object value = GetValue(path); if (value == null) { if (_renderContextBehaviour.RaiseExceptionOnDataContextMiss) { throw new NustacheDataContextMissException(string.Format("Path : {0} is undefined, RaiseExceptionOnDataContextMiss : true.", path)); } yield break; } else if (value is bool) { if ((bool)value) { yield return value; } } else if (value is string) { if (!string.IsNullOrEmpty((string)value)) { yield return value; } } else if (value.GetType().ToString().Equals("Newtonsoft.Json.Linq.JValue")) { yield return value; } else if (GenericIDictionaryUtil.IsInstanceOfGenericIDictionary(value)) { if ((value as IEnumerable).GetEnumerator().MoveNext()) { yield return value; } } else if (value is IDictionary) // Dictionaries also implement IEnumerable // so this has to be checked before it. { if (((IDictionary)value).Count > 0) { yield return value; } } else if (value is IEnumerable) { foreach (var item in ((IEnumerable)value)) { yield return item; } } else if (value is DataTable) { foreach (var item in ((DataTable)value).Rows) { yield return item; } } else { yield return value; } } public bool IsTruthy(string path) { return IsTruthy(GetValue(path)); } public bool IsTruthy(object value) { if (value == null) { return false; } if (value is bool) { return (bool)value; } if (value is string) { return !string.IsNullOrEmpty((string)value); } if (value is IEnumerable) { return ((IEnumerable)value).GetEnumerator().MoveNext(); } if (value is DataTable) { return ((DataTable)value).Rows.Count > 0; } return true; } public void WriteLiteral(string text) { if (_indent != null) { text = _indenter.Replace(text, m => "\n" + _indent); } Write(text); _lineEnded = text.Length > 0 && text[text.Length - 1] == '\n'; } public void Write(string text) { // Sometimes a literal gets cut in half by a variable and needs to be indented. if (_indent != null && _lineEnded) { text = _indent + text; _lineEnded = false; } _writer.Write(text); } public void Include(string templateName, string indent) { if (_includeLevel >= IncludeLimit) { throw new NustacheException( string.Format("You have reached the include limit of {0}. Are you trying to render infinitely recursive templates or data?", IncludeLimit)); } _includeLevel++; var oldIndent = _indent; _indent = (_indent ?? "") + (indent ?? ""); TemplateDefinition templateDefinition = GetTemplateDefinition(templateName); if (templateDefinition != null) { templateDefinition.Render(this); } else if (_templateLocator != null) { var template = _templateLocator(templateName); if (template != null) { // push the included template on the stack so that internally defined templates can be resolved properly later. // designed to pass test Describe_Template_Render.It_can_include_templates_over_three_levels_with_external_includes() this.Enter(template); template.Render(this); this.Exit(); } } _indent = oldIndent; _includeLevel--; } private TemplateDefinition GetTemplateDefinition(string name) { foreach (var section in _sectionStack) { var templateDefinition = section.GetTemplateDefinition(name); if (templateDefinition != null) { return templateDefinition; } } return null; } public void Enter(Section section) { _sectionStack.Push(section); } public void Exit() { _sectionStack.Pop(); } public void Push(object data) { _dataStack.Push(data); } public void Pop() { _dataStack.Pop(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { /// <summary> /// Definition of Protection Container mapping operations for the Site /// Recovery extension. /// </summary> public partial interface IProtectionContainerMappingOperations { /// <summary> /// Configures protection for given protection container /// </summary> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Container mapping name. /// </param> /// <param name='input'> /// Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginConfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Purges protection for given protection container /// </summary> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginPurgeProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Unconfigures protection for given protection container /// </summary> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Container mapping name. /// </param> /// <param name='input'> /// Unconfigure protection input. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginUnconfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Configures protection for given protection container /// </summary> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Container mapping name. /// </param> /// <param name='input'> /// Create mapping input. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> ConfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CreateProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Get the protected container mapping by name. /// </summary> /// <param name='fabricName'> /// Fabric Name. /// </param> /// <param name='protectionContainerName'> /// Protection Container Name. /// </param> /// <param name='mappingName'> /// Container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Protection Container mapping object. /// </returns> Task<ProtectionContainerMappingResponse> GetAsync(string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// protection container. /// </returns> Task<MappingOperationResponse> GetConfigureProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> GetPurgeProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Service response for operation which change status of mapping for /// protection container. /// </returns> Task<MappingOperationResponse> GetUnconfigureProtectionStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Get the list of all protection container mapping for the given /// container under a fabric. /// </summary> /// <param name='fabricName'> /// Fabric Unique name. /// </param> /// <param name='protectionContainerName'> /// Protection Container Name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The definition of a Protection Container mapping collection object. /// </returns> Task<ProtectionContainerMappingListResponse> ListAsync(string fabricName, string protectionContainerName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Get the list of all protection container mapping under a vault. /// </summary> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The definition of a Protection Container mapping collection object. /// </returns> Task<ProtectionContainerMappingListResponse> ListAllAsync(CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Purges protection for given protection container /// </summary> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Protection container mapping name. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> PurgeProtectionAsync(string fabricName, string protectionContainerName, string mappingName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); /// <summary> /// Unconfigures protection for given protection container /// </summary> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='mappingName'> /// Container mapping name. /// </param> /// <param name='input'> /// Unconfigure protection input. /// </param> /// <param name='customRequestHeaders'> /// Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> UnconfigureProtectionAsync(string fabricName, string protectionContainerName, string mappingName, RemoveProtectionContainerMappingInput input, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken); } }
// 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.Globalization; using System.Net.Internals; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net { /// <devdoc> /// <para>Provides simple /// domain name resolution functionality.</para> /// </devdoc> public static class Dns { // Host names any longer than this automatically fail at the winsock level. // If the host name is 255 chars, the last char must be a dot. private const int MaxHostName = 255; internal static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", hostName); IPHostEntry ipHostEntry = null; if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostByName: " + hostName); } NameResolutionPal.EnsureSocketsAreInitialized(); if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot. || hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.') { throw new ArgumentOutOfRangeException(nameof(hostName), SR.Format(SR.net_toolong, "hostName", MaxHostName.ToString(NumberFormatInfo.CurrentInfo))); } // // IPv6 Changes: IPv6 requires the use of getaddrinfo() rather // than the traditional IPv4 gethostbyaddr() / gethostbyname(). // getaddrinfo() is also protocol independant in that it will also // resolve IPv4 names / addresses. As a result, it is the preferred // resolution mechanism on platforms that support it (Windows 5.1+). // If getaddrinfo() is unsupported, IPv6 resolution does not work. // // Consider : If IPv6 is disabled, we could detect IPv6 addresses // and throw an unsupported platform exception. // // Note : Whilst getaddrinfo is available on WinXP+, we only // use it if IPv6 is enabled (platform is part of that // decision). This is done to minimize the number of // possible tests that are needed. // if (includeIPv6 || SocketProtocolSupportPal.OSSupportsIPv6) { // // IPv6 enabled: use getaddrinfo() to obtain DNS information. // int nativeErrorCode; SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode); if (errorCode != SocketError.Success) { throw new InternalSocketException(errorCode, nativeErrorCode); } } else { ipHostEntry = NameResolutionPal.GetHostByName(hostName); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry); return ipHostEntry; } // GetHostByName // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods). internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6) { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString()); } // // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions // for resolution of IPv6 addresses. // if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6) { // // Try to get the data for the host from it's address // // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string // will only return that address and not the full list. // Do a reverse lookup to get the host name. SocketError errorCode; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode); if (errorCode == SocketError.Success) { // Do the forward lookup to get the IPs for that host name IPHostEntry hostEntry; errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); if (errorCode == SocketError.Success) return hostEntry; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.Socket, "DNS", "InternalGetHostByAddress", new InternalSocketException(errorCode, nativeErrorCode)); } // One of two things happened: // 1. There was a ptr record in dns, but not a corollary A/AAA record. // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix. // - Workaround, Check "Use this connection's dns suffix in dns registration" on that network // adapter's advanced dns settings. // Just return the resolved host name and no IPs. return hostEntry; } throw new InternalSocketException(errorCode, nativeErrorCode); } // // If IPv6 is not enabled (maybe config switch) but we've been // given an IPv6 address then we need to bail out now. // else { if (address.AddressFamily == AddressFamily.InterNetworkV6) { // // Protocol not supported // throw new SocketException((int)SocketError.ProtocolNotSupported); } // // Use gethostbyaddr() to try to resolve the IP address // // End IPv6 Changes // return NameResolutionPal.GetHostByAddr(address); } } // InternalGetHostByAddress /***************************************************************************** Function : gethostname Abstract: Queries the hostname from DNS Input Parameters: Returns: String ******************************************************************************/ /// <devdoc> /// <para>Gets the host name of the local machine.</para> /// </devdoc> public static string GetHostName() { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostName"); } return NameResolutionPal.GetHostName(); } private class ResolveAsyncResult : ContextAwareResult { // Forward lookup internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.hostName = hostName; this.includeIPv6 = includeIPv6; } // Reverse lookup internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.includeIPv6 = includeIPv6; this.address = address; } internal readonly string hostName; internal bool includeIPv6; internal IPAddress address; } private static void ResolveCallback(object context) { ResolveAsyncResult result = (ResolveAsyncResult)context; IPHostEntry hostEntry; try { if (result.address != null) { hostEntry = InternalGetHostByAddress(result.address, result.includeIPv6); } else { hostEntry = InternalGetHostByName(result.hostName, result.includeIPv6); } } catch (OutOfMemoryException) { throw; } catch (Exception exception) { result.InvokeCallback(exception); return; } result.InvokeCallback(hostEntry); } // Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the orriginal address is returned. private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, AsyncCallback requestCallback, object state) { if (hostName == null) { throw new ArgumentNullException(nameof(hostName)); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionBeginHelper: " + hostName); } // See if it's an IP Address. IPAddress address; ResolveAsyncResult asyncResult; if (IPAddress.TryParse(hostName, out address)) { if ((address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))) { throw new ArgumentException(SR.net_invalid_ip_addr, "hostNameOrAddress"); } asyncResult = new ResolveAsyncResult(address, null, true, state, requestCallback); if (justReturnParsedIp) { IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address); asyncResult.StartPostingAsyncOp(false); asyncResult.InvokeCallback(hostEntry); asyncResult.FinishPostingAsyncOp(); return asyncResult; } } else { asyncResult = new ResolveAsyncResult(hostName, null, true, state, requestCallback); } // Set up the context, possibly flow. asyncResult.StartPostingAsyncOp(false); // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address)); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionBeginHelper: " + address); } // Set up the context, possibly flow. ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback); if (flowContext) { asyncResult.StartPostingAsyncOp(false); } // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult) { // // parameter validation // if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } ResolveAsyncResult castedResult = asyncResult as ResolveAsyncResult; if (castedResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndResolve")); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionEndHelper"); } castedResult.InternalWaitForCompletion(); castedResult.EndCalled = true; Exception exception = castedResult.Result as Exception; if (exception != null) { throw exception; } return (IPHostEntry)castedResult.Result; } private static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", hostNameOrAddress); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, requestCallback, stateObject); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult); return asyncResult; } // BeginResolve private static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", address); IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult); return asyncResult; } // BeginResolve private static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", ipHostEntry); return ipHostEntry; } // EndResolve() private static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", hostNameOrAddress); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, requestCallback, state); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", asyncResult); return asyncResult; } // BeginResolve private static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", ipHostEntry); return ipHostEntry.AddressList; } // EndResolveToAddresses //************* Task-based async public methods ************************* public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress) { return Task<IPAddress[]>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostAddresses(arg, requestCallback, stateObject), asyncResult => EndGetHostAddresses(asyncResult), hostNameOrAddress, null); } public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address) { return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), address, null); } public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress) { return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), hostNameOrAddress, null); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Elasticsearch.Net; using FluentAssertions; using Tests.Framework.MockResponses; using System.Net; namespace Tests.Framework { public class VirtualClusterConnection : InMemoryConnection { private static readonly object _lock = new object(); private class State { public int Pinged = 0; public int Sniffed = 0; public int Called = 0; public int Successes = 0; public int Failures = 0; } private IDictionary<int, State> Calls = new Dictionary<int, State> { }; private VirtualCluster _cluster; private TestableDateTimeProvider _dateTimeProvider; public VirtualClusterConnection(VirtualCluster cluster, TestableDateTimeProvider dateTimeProvider) { this.UpdateCluster(cluster); this._dateTimeProvider = dateTimeProvider; } public void UpdateCluster(VirtualCluster cluster) { if (cluster == null) return; lock (_lock) { this._cluster = cluster; this.Calls = cluster.Nodes.ToDictionary(n => n.Uri.Port, v => new State()); } } public bool IsSniffRequest(RequestData requestData) => requestData.Path.StartsWith("_nodes/_all/settings", StringComparison.Ordinal); public bool IsPingRequest(RequestData requestData) => requestData.Path == "/" && requestData.Method == HttpMethod.HEAD; public override ElasticsearchResponse<TReturn> Request<TReturn>(RequestData requestData) { this.Calls.Should().ContainKey(requestData.Uri.Port); try { var state = this.Calls[requestData.Uri.Port]; if (IsSniffRequest(requestData)) { var sniffed = Interlocked.Increment(ref state.Sniffed); return HandleRules<TReturn, ISniffRule>( requestData, this._cluster.SniffingRules, requestData.RequestTimeout, (r) => this.UpdateCluster(r.NewClusterState), () => SniffResponse.Create(this._cluster.Nodes, this._cluster.SniffShouldReturnFqnd) ); } if (IsPingRequest(requestData)) { var pinged = Interlocked.Increment(ref state.Pinged); return HandleRules<TReturn, IRule>( requestData, this._cluster.PingingRules, requestData.PingTimeout, (r) => { }, () => null //HEAD request ); } var called = Interlocked.Increment(ref state.Called); return HandleRules<TReturn, IClientCallRule>( requestData, this._cluster.ClientCallRules, requestData.RequestTimeout, (r) => { }, CallResponse ); } #if DOTNETCORE catch (System.Net.Http.HttpRequestException e) #else catch (WebException e) #endif { var builder = new ResponseBuilder<TReturn>(requestData); builder.Exception = e; return builder.ToResponse(); } } private ElasticsearchResponse<TReturn> HandleRules<TReturn, TRule>( RequestData requestData, IEnumerable<TRule> rules, TimeSpan timeout, Action<TRule> beforeReturn, Func<byte[]> successResponse ) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; foreach (var rule in rules.Where(s => s.OnPort.HasValue)) { var always = rule.Times.Match(t => true, t => false); var times = rule.Times.Match(t => -1, t => t); if (rule.OnPort.Value == requestData.Uri.Port) { if (always) return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule); return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times); } } foreach (var rule in rules.Where(s => !s.OnPort.HasValue)) { var always = rule.Times.Match(t => true, t => false); var times = rule.Times.Match(t => -1, t => t); if (always) return Always<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, rule); return Sometimes<TReturn, TRule>(requestData, timeout, beforeReturn, successResponse, state, rule, times); } return this.ReturnConnectionStatus<TReturn>(requestData, successResponse()); } private ElasticsearchResponse<TReturn> Always<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<byte[]> successResponse, TRule rule) where TReturn : class where TRule : IRule { if (rule.Takes.HasValue) { var time = timeout < rule.Takes.Value ? timeout: rule.Takes.Value; this._dateTimeProvider.ChangeTime(d=> d.Add(time)); if (rule.Takes.Value > requestData.RequestTimeout) #if DOTNETCORE throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #else throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #endif } return rule.Succeeds ? Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule) : Fail<TReturn, TRule>(requestData, rule); } private ElasticsearchResponse<TReturn> Sometimes<TReturn, TRule>(RequestData requestData, TimeSpan timeout, Action<TRule> beforeReturn, Func<byte[]> successResponse, State state, TRule rule, int times) where TReturn : class where TRule : IRule { if (rule.Takes.HasValue) { var time = timeout < rule.Takes.Value ? timeout : rule.Takes.Value; this._dateTimeProvider.ChangeTime(d=> d.Add(time)); if (rule.Takes.Value > requestData.RequestTimeout) #if DOTNETCORE throw new System.Net.Http.HttpRequestException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #else throw new WebException($"Request timed out after {time} : call configured to take {rule.Takes.Value} while requestTimeout was: {timeout}"); #endif } if (rule.Succeeds && times >= state.Successes) return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule); else if (rule.Succeeds) return Fail<TReturn, TRule>(requestData, rule); if (!rule.Succeeds && times >= state.Failures) return Fail<TReturn, TRule>(requestData, rule); return Success<TReturn, TRule>(requestData, beforeReturn, successResponse, rule); } private ElasticsearchResponse<TReturn> Fail<TReturn, TRule>(RequestData requestData, TRule rule) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; var failed = Interlocked.Increment(ref state.Failures); if (rule.Return == null) #if DOTNETCORE throw new System.Net.Http.HttpRequestException(); #else throw new WebException(); #endif return rule.Return.Match( (e) => { throw e; }, (statusCode) => this.ReturnConnectionStatus<TReturn>(requestData, CallResponse(), statusCode) ); } private ElasticsearchResponse<TReturn> Success<TReturn, TRule>(RequestData requestData, Action<TRule> beforeReturn, Func<byte[]> successResponse, TRule rule) where TReturn : class where TRule : IRule { var state = this.Calls[requestData.Uri.Port]; var succeeded = Interlocked.Increment(ref state.Successes); beforeReturn?.Invoke(rule); return this.ReturnConnectionStatus<TReturn>(requestData, successResponse()); } private byte[] CallResponse() { var response = new { name = "Razor Fist", cluster_name = "elasticsearch-test-cluster", version = new { number = "2.0.0", build_hash = "af1dc6d8099487755c3143c931665b709de3c764", build_timestamp = "2015-07-07T11:28:47Z", build_snapshot = true, lucene_version = "5.2.1" }, tagline = "You Know, for Search" }; using (var ms = new MemoryStream()) { new ElasticsearchDefaultSerializer().Serialize(response, ms); return ms.ToArray(); } } public override Task<ElasticsearchResponse<TReturn>> RequestAsync<TReturn>(RequestData requestData) { return Task.FromResult(this.Request<TReturn>(requestData)); } } }
// 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.Diagnostics; using System.Net; using System.Net.Sockets; using System.Net.Sockets.Tests; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Xunit.Abstractions; namespace System.Net.Sockets.Performance.Tests { public abstract class SocketTestClient { protected readonly ITestOutputHelper _log; protected string _server; protected int _port; protected EndPoint _endpoint; protected Socket _s; protected byte[] _sendBuffer; protected int _sendBufferIndex = 0; protected byte[] _recvBuffer; protected int _recvBufferIndex = 0; protected int _iterations; private string _sendString; private Stopwatch _timeInit = new Stopwatch(); private Stopwatch _timeProgramStart; private const string _format = "{0, -20}, {1, -25}, {2, 15}, {3, 15}, {4, 15}, {5, 15}, {6, 15}, {7, 15}, {8, 15}"; private int _bufferLen; private int _send_iterations = 0; private int _receive_iterations = 0; private Stopwatch _timeConnect = new Stopwatch(); private Stopwatch _timeSendRecv = new Stopwatch(); private Stopwatch _timeClose = new Stopwatch(); private TaskCompletionSource<long> _tcs = new TaskCompletionSource<long>(); public SocketTestClient( ITestOutputHelper log, string server, int port, int iterations, string message, Stopwatch timeProgramStart) { _log = log; _server = server; _port = port; _endpoint = new DnsEndPoint(server, _port); _sendString = message; _sendBuffer = Encoding.UTF8.GetBytes(_sendString); _bufferLen = _sendBuffer.Length; _recvBuffer = new byte[_bufferLen]; _timeProgramStart = timeProgramStart; _timeInit.Start(); _s = new Socket(SocketType.Stream, ProtocolType.Tcp); _timeInit.Stop(); _iterations = iterations; } public static SocketTestClient SocketTestClientFactory( ITestOutputHelper log, SocketImplementationType type, string server, int port, int iterations, string message, Stopwatch timeProgramStart) { switch (type) { case SocketImplementationType.APM: var socketAPM = new SocketTestClientAPM(log, server, port, iterations, message, timeProgramStart); log.WriteLine(socketAPM.GetHashCode() + " SocketTestClientAPM(..)"); return socketAPM; case SocketImplementationType.Async: var socketAsync = new SocketTestClientAsync(log, server, port, iterations, message, timeProgramStart); log.WriteLine(socketAsync.GetHashCode() + " SocketTestClientAsync(..)"); return socketAsync; default: throw new ArgumentOutOfRangeException("type"); } } public abstract void Connect(Action<SocketError> onConnectCallback); private void OnConnect(SocketError error) { _timeConnect.Stop(); _log.WriteLine(this.GetHashCode() + " OnConnect({0}) _timeConnect={1}", error, _timeConnect.ElapsedMilliseconds); // TODO: an error should fail the test. if (error != SocketError.Success) { _timeClose.Start(); Close(OnClose); return; } _timeSendRecv.Start(); // TODO: It might be more efficient to have more than one outstanding Send/Receive. // IMPORTANT: The code currently assumes one outstanding Send and one Receive. Interlocked operations // are required to handle re-entrancy. Send(OnSend); Receive(OnReceive); } public abstract void Send(Action<int, SocketError> onSendCallback); // Called when the entire _sendBuffer has been sent. private void OnSend(int bytesSent, SocketError error) { _log.WriteLine(this.GetHashCode() + " OnSend({0}, {1})", bytesSent, error); // TODO: an error should fail the test. if (error != SocketError.Success) { _timeClose.Start(); Close(OnClose); return; } if (bytesSent == _sendBuffer.Length) { OnSendMessage(); } else { _log.WriteLine( "OnSend: Unexpected bytesSent={0}, expected {1}", bytesSent, _sendBuffer.Length); } } private void OnSendMessage() { _send_iterations++; _log.WriteLine(this.GetHashCode() + " OnSendMessage() _send_iterations={0}", _send_iterations); if (_send_iterations < _iterations) { Send(OnSend); } //TODO: _s.Shutdown(SocketShutdown.Send); } public abstract void Receive(Action<int, SocketError> onReceiveCallback); // Called when the entire _recvBuffer has been received. private void OnReceive(int receivedBytes, SocketError error) { _log.WriteLine(this.GetHashCode() + " OnSend({0}, {1})", receivedBytes, error); _recvBufferIndex += receivedBytes; // TODO: an error should fail the test. if (error != SocketError.Success) { _timeClose.Start(); Close(OnClose); return; } if (_recvBufferIndex == _recvBuffer.Length) { OnReceiveMessage(); } else if (receivedBytes == 0) { _log.WriteLine("Socket unexpectedly closed."); } else { Receive(OnReceive); } } private void OnReceiveMessage() { _receive_iterations++; _log.WriteLine(this.GetHashCode() + " OnReceiveMessage() _receive_iterations={0}", _receive_iterations); _recvBufferIndex = 0; // Expect echo server. if (!SocketTestMemcmp.Compare(_sendBuffer, _recvBuffer)) { _log.WriteLine("Received different data from echo server"); } if (_receive_iterations >= _iterations) { _timeSendRecv.Stop(); _timeClose.Start(); Close(OnClose); } else { Array.Clear(_recvBuffer, 0, _recvBuffer.Length); Receive(OnReceive); } } public abstract void Close(Action onCloseCallback); private void OnClose() { _timeClose.Stop(); _log.WriteLine(this.GetHashCode() + " OnClose() _timeClose={0}", _timeClose.ElapsedMilliseconds); try { _log.WriteLine( _format, "Socket", ImplementationName(), _bufferLen, _receive_iterations, _timeInit.ElapsedMilliseconds, _timeConnect.ElapsedMilliseconds, _timeSendRecv.ElapsedMilliseconds, _timeClose.ElapsedMilliseconds, _timeProgramStart.ElapsedMilliseconds); } catch (Exception ex) { _log.WriteLine("Exception while writing the report: {0}", ex); } _log.WriteLine( this.GetHashCode() + " OnClose() setting tcs result : {0}", _timeSendRecv.ElapsedMilliseconds); _tcs.TrySetResult(_timeSendRecv.ElapsedMilliseconds); } public Task<long> RunTest() { _timeConnect.Start(); Connect(OnConnect); return _tcs.Task; } protected abstract string ImplementationName(); } }
// 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; namespace Microsoft.ApiDesignGuidelines.Analyzers { /// <summary> /// CA1711: Identifiers should not have incorrect suffix /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldNotHaveIncorrectSuffixAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1711"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeNoAlternate = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageTypeNoAlternate), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberNewerVersion = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageMemberNewerVersion), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeNewerVersion = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageTypeNewerVersion), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberWithAlternate = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageMemberWithAlternate), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private const string HelpLinkUri = "https://msdn.microsoft.com/en-us/library/ms182247.aspx"; internal static DiagnosticDescriptor TypeNoAlternateRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageTypeNoAlternate, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MemberNewerVersionRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMemberNewerVersion, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor TypeNewerVersionRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageTypeNewerVersion, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MemberWithAlternateRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMemberWithAlternate, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create( TypeNoAlternateRule, MemberNewerVersionRule, TypeNewerVersionRule, MemberWithAlternateRule); internal const string AttributeSuffix = "Attribute"; internal const string CollectionSuffix = "Collection"; internal const string DictionarySuffix = "Dictionary"; internal const string EventArgsSuffix = "EventArgs"; internal const string EventHandlerSuffix = "EventHandler"; internal const string ExSuffix = "Ex"; internal const string ExceptionSuffix = "Exception"; internal const string NewSuffix = "New"; internal const string PermissionSuffix = "Permission"; internal const string StreamSuffix = "Stream"; internal const string DelegateSuffix = "Delegate"; internal const string EnumSuffix = "Enum"; internal const string ImplSuffix = "Impl"; internal const string CoreSuffix = "Core"; internal const string QueueSuffix = "Queue"; internal const string StackSuffix = "Stack"; // Dictionary that maps from a type name suffix to the set of base types from which // a type with that suffix is permitted to derive. private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_suffixToBaseTypeNamesDictionary = ImmutableDictionary.CreateRange( new Dictionary<string, ImmutableArray<string>> { [AttributeSuffix] = ImmutableArray.CreateRange(new[] { "System.Attribute" }), [CollectionSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.IEnumerable" }), [DictionarySuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.IDictionary", "System.Collections.Generic.IReadOnlyDictionary`2" }), [EventArgsSuffix] = ImmutableArray.CreateRange(new[] { "System.EventArgs" }), [ExceptionSuffix] = ImmutableArray.CreateRange(new[] { "System.Exception" }), [PermissionSuffix] = ImmutableArray.CreateRange(new[] { "System.Security.IPermission" }), [StreamSuffix] = ImmutableArray.CreateRange(new[] { "System.IO.Stream" }), [QueueSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.Queue", "System.Collections.Generic.Queue`1" }), [StackSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.Stack", "System.Collections.Generic.Stack`1" }) }); // Dictionary from type name suffix to an array containing the only types that are // allowed to have that suffix. private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_suffixToAllowedTypesDictionary = ImmutableDictionary.CreateRange( new Dictionary<string, ImmutableArray<string>> { [DelegateSuffix] = ImmutableArray.CreateRange(new[] { "System.Delegate", "System.MulticastDelegate" }), [EventHandlerSuffix] = ImmutableArray.CreateRange(new[] { "System.EventHandler" }), [EnumSuffix] = ImmutableArray.CreateRange(new[] { "System.Enum" }) }); public override void Initialize(AnalysisContext analysisContext) { // Analyze type names. analysisContext.RegisterCompilationStartAction( (CompilationStartAnalysisContext compilationStartAnalysisContext) => { var suffixToBaseTypeDictionaryBuilder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<INamedTypeSymbol>>(); foreach (string suffix in s_suffixToBaseTypeNamesDictionary.Keys) { ImmutableArray<string> typeNames = s_suffixToBaseTypeNamesDictionary[suffix]; ImmutableArray<INamedTypeSymbol> namedTypeSymbolArray = ImmutableArray.CreateRange( typeNames.Select(typeName => compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(typeName).OriginalDefinition)); suffixToBaseTypeDictionaryBuilder.Add(suffix, namedTypeSymbolArray); } var suffixToBaseTypeDictionary = suffixToBaseTypeDictionaryBuilder.ToImmutableDictionary(); compilationStartAnalysisContext.RegisterSymbolAction( (SymbolAnalysisContext symbolAnalysisContext) => { var namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; if (namedTypeSymbol.GetResultantVisibility()!= SymbolVisibility.Public) { return; } string name = namedTypeSymbol.Name; Compilation compilation = symbolAnalysisContext.Compilation; foreach (string suffix in s_suffixToBaseTypeNamesDictionary.Keys) { if (IsNotChildOfAnyButHasSuffix( namedTypeSymbol, suffixToBaseTypeDictionary[suffix], suffix, compilation)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, suffix)); return; } } foreach (string suffix in s_suffixToAllowedTypesDictionary.Keys) { if (name.HasSuffix(suffix) && !s_suffixToAllowedTypesDictionary[suffix].Contains(name)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, suffix)); return; } } if (name.HasSuffix(ImplSuffix)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(MemberWithAlternateRule, ImplSuffix, name, CoreSuffix)); return; } // FxCop performed the length check for "Ex", but not for any of the other // suffixes, because alone among the suffixes, "Ex" is the only one that // isn't itself a known type or a language keyword. if (name.HasSuffix(ExSuffix) && name.Length > ExSuffix.Length) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNewerVersionRule, ExSuffix, name)); return; } if (name.HasSuffix(NewSuffix)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNewerVersionRule, NewSuffix, name)); return; } }, SymbolKind.NamedType); }); // Analyze method names. analysisContext.RegisterSymbolAction( (SymbolAnalysisContext context) => { var memberSymbol = context.Symbol; if (memberSymbol.GetResultantVisibility() != SymbolVisibility.Public) { return; } if (memberSymbol.IsOverride || memberSymbol.IsImplementationOfAnyInterfaceMember()) { return; } // If this is a method, and it's actually the getter or setter of a property, // then don't complain. We'll complain about the property itself. var methodSymbol = memberSymbol as IMethodSymbol; if (methodSymbol != null && methodSymbol.IsPropertyAccessor()) { return; } string name = memberSymbol.Name; if (name.HasSuffix(ExSuffix)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberNewerVersionRule, ExSuffix, name)); return; } // We only fire on member suffix "New" if the type already defines // another member minus the suffix, e.g., we only fire on "MemberNew" if // "Member" already exists. For some reason FxCop did not apply the // same logic to the "Ex" suffix, and we follow FxCop's implementation. if (name.HasSuffix(NewSuffix)) { string nameWithoutSuffix = name.WithoutSuffix(NewSuffix); INamedTypeSymbol containingType = memberSymbol.ContainingType; if (MemberNameExistsInHierarchy(nameWithoutSuffix, containingType, memberSymbol.Kind)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberNewerVersionRule, NewSuffix, name)); return; } } if (name.HasSuffix(ImplSuffix)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberWithAlternateRule, ImplSuffix, name, CoreSuffix)); } }, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } private bool MemberNameExistsInHierarchy(string memberName, INamedTypeSymbol containingType, SymbolKind kind) { for (INamedTypeSymbol baseType = containingType; baseType != null; baseType = baseType.BaseType) { if (baseType.GetMembers(memberName).Any(member => member.Kind == kind)) { return true; } } return false; } private bool IsNotChildOfAnyButHasSuffix( INamedTypeSymbol namedTypeSymbol, IEnumerable<INamedTypeSymbol> parentTypes, string suffix, Compilation compilation) { return namedTypeSymbol.Name.HasSuffix(suffix) && !parentTypes.Any(parentType => namedTypeSymbol.DerivesFromOrImplementsAnyConstructionOf(parentType, compilation)); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Claudy.Input; namespace Cliffhanger { public class Menu : Microsoft.Xna.Framework.GameComponent { public readonly Color colorSelectYES = Color.Red, colorSelectNO = Color.SlateGray, colorTitle = Color.Gold; Vector2 playMenuItemPos, helpMenuItempPos, exitMenuItemPos, titleMenuItemPos; private ClaudyInput input; enum MenuState { TopMost, Help, InGame, Exit } /// <summary> /// Finite State Machine of the menu. /// </summary> MenuState currentMenuState; enum MenuChoice // THIS ENUMERATION MUST BE IN ORDER. { Play, Help, Exit // THIS MUST BE LAST. } MenuChoice currentlySelectedMenuChoice; Texture2D helpScreenTexture; Texture2D menuScreenTexture; SpriteFont tahoma, consolas; public Menu(CliffhangerGame game) : base(game) { currentMenuState = MenuState.TopMost; currentlySelectedMenuChoice = MenuChoice.Help; playMenuItemPos = new Vector2(Game.GraphicsDevice.Viewport.Width / 6.0f, Game.GraphicsDevice.Viewport.Height / 2.0f - Game.GraphicsDevice.Viewport.Height * 0.2f); helpMenuItempPos = new Vector2(Game.GraphicsDevice.Viewport.Width / 6.0f, Game.GraphicsDevice.Viewport.Height / 2.0f - Game.GraphicsDevice.Viewport.Height * 0.1f); exitMenuItemPos = new Vector2(Game.GraphicsDevice.Viewport.Width / 6.0f, Game.GraphicsDevice.Viewport.Height / 2.0f + Game.GraphicsDevice.Viewport.Height * 0.0f); titleMenuItemPos = new Vector2(Game.GraphicsDevice.Viewport.Width / 2.0f - Game.GraphicsDevice.Viewport.Width * 0.1f, Game.GraphicsDevice.Viewport.Height * 0.05f); helpScreenTexture = Game.Content.Load<Texture2D>("helpScreenTexture"); menuScreenTexture = Game.Content.Load<Texture2D>("menuScreenTexture"); tahoma = Game.Content.Load<SpriteFont>("Tahoma"); consolas = Game.Content.Load<SpriteFont>("consolas"); input = game.input; } public override void Initialize() { base.Initialize(); } public void Update(GameTime gameTime, CliffhangerGame game) { #region Main Menu switch (currentMenuState) { case MenuState.TopMost: for (int pi = 1; pi <= 2; pi++) { if (input.GamepadByID[pi].IsConnected) { if ((input.GamepadByID[pi].DPad.Up == ButtonState.Pressed && input.PreviousGamepadByID[pi].DPad.Up == ButtonState.Released) || (input.GamepadByID[pi].ThumbSticks.Left.Y > 0.5f && input.PreviousGamepadByID[pi].ThumbSticks.Left.Y <= 0.5f) || (input.GamepadByID[pi].ThumbSticks.Right.Y > 0.5f && input.PreviousGamepadByID[pi].ThumbSticks.Right.Y <= 0.5f) || input.isFirstPress(Keys.Up)) { if (currentlySelectedMenuChoice != MenuChoice.Play) currentlySelectedMenuChoice--; } } if (input.GamepadByID[pi].IsConnected) { if (input.GamepadByID[pi].DPad.Down == ButtonState.Pressed && input.PreviousGamepadByID[pi].DPad.Down == ButtonState.Released || (input.GamepadByID[pi].ThumbSticks.Left.Y < -0.5f && input.PreviousGamepadByID[pi].ThumbSticks.Left.Y >= -0.5f) || (input.GamepadByID[pi].ThumbSticks.Right.Y < -0.5f && input.PreviousGamepadByID[pi].ThumbSticks.Right.Y >= -0.5f) || input.isFirstPress(Keys.Down)) { if (currentlySelectedMenuChoice != MenuChoice.Exit) currentlySelectedMenuChoice++; } } if ((input.isFirstPress(Buttons.A, PlayerIndex.One) || input.isFirstPress(Buttons.A, PlayerIndex.Two))) { switch (currentlySelectedMenuChoice) { case MenuChoice.Play: currentMenuState = MenuState.InGame; game.currentGameState = CliffhangerGame.LevelStateFSM.Level1; break; case MenuChoice.Help: currentMenuState = MenuState.Help; break; case MenuChoice.Exit: currentMenuState = MenuState.Exit; break; default: break; } } } break; case MenuState.Help: for (int pi = 1; pi <= 4; pi++) { if (input.GamepadByID[pi].IsConnected) { if (input.isFirstPress(Buttons.B, pi)) { game.currentGameState = CliffhangerGame.LevelStateFSM.AlphaMenu; currentMenuState = MenuState.TopMost; currentlySelectedMenuChoice = MenuChoice.Play; } } } break; case MenuState.Exit: game.Exit(); break; default: break; } #endregion base.Update(gameTime); } /// <summary> /// /// </summary> /// <param name="spriteBatch">The spriteBatch passed MUST have its .Begin() call first.</param> public void Draw(SpriteBatch spriteBatch) { //Assumes SpriteBatch has begun already. switch (currentMenuState) { case MenuState.TopMost: spriteBatch.Draw(menuScreenTexture, Game.GraphicsDevice.Viewport.Bounds, Color.White); spriteBatch.DrawString(tahoma, "Cliffhanger", titleMenuItemPos, colorTitle); switch (currentlySelectedMenuChoice) { case MenuChoice.Play: spriteBatch.DrawString(tahoma, "Play", playMenuItemPos, colorSelectYES); spriteBatch.DrawString(tahoma, "Help", helpMenuItempPos, colorSelectNO); spriteBatch.DrawString(tahoma, "Exit", exitMenuItemPos, colorSelectNO); break; case MenuChoice.Help: spriteBatch.DrawString(tahoma, "Play", playMenuItemPos, colorSelectNO); spriteBatch.DrawString(tahoma, "Help", helpMenuItempPos, colorSelectYES); spriteBatch.DrawString(tahoma, "Exit", exitMenuItemPos, colorSelectNO); break; case MenuChoice.Exit: spriteBatch.DrawString(tahoma, "Play", playMenuItemPos, colorSelectNO); spriteBatch.DrawString(tahoma, "Help", helpMenuItempPos, colorSelectNO); spriteBatch.DrawString(tahoma, "Exit", exitMenuItemPos, colorSelectYES); break; default: spriteBatch.DrawString(tahoma, "Play", playMenuItemPos, colorSelectNO); spriteBatch.DrawString(tahoma, "Help", helpMenuItempPos, colorSelectNO); spriteBatch.DrawString(tahoma, "Exit", exitMenuItemPos, colorSelectNO); break; } break; case MenuState.Help: //TODO: Draw 1920x1080 texture which explains how to play the game. spriteBatch.Draw(helpScreenTexture, Game.GraphicsDevice.Viewport.Bounds, Color.White); break; case MenuState.Exit: break; default: break; } } } }
// <copyright file="MetricReader.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { /// <summary> /// MetricReader base class. /// </summary> public abstract partial class MetricReader : IDisposable { private const AggregationTemporality AggregationTemporalityUnspecified = (AggregationTemporality)0; private readonly object newTaskLock = new object(); private readonly object onCollectLock = new object(); private readonly TaskCompletionSource<bool> shutdownTcs = new TaskCompletionSource<bool>(); private AggregationTemporality temporality = AggregationTemporalityUnspecified; private int shutdownCount; private TaskCompletionSource<bool> collectionTcs; private BaseProvider parentProvider; public AggregationTemporality Temporality { get { if (this.temporality == AggregationTemporalityUnspecified) { this.temporality = AggregationTemporality.Cumulative; } return this.temporality; } set { if (this.temporality != AggregationTemporalityUnspecified) { throw new NotSupportedException($"The temporality cannot be modified (the current value is {this.temporality})."); } this.temporality = value; } } /// <summary> /// Attempts to collect the metrics, blocks the current thread until /// metrics collection completed, shutdown signaled or timed out. /// If there are asynchronous instruments involved, their callback /// functions will be triggered. /// </summary> /// <param name="timeoutMilliseconds"> /// The number (non-negative) of milliseconds to wait, or /// <c>Timeout.Infinite</c> to wait indefinitely. /// </param> /// <returns> /// Returns <c>true</c> when metrics collection succeeded; otherwise, /// <c>false</c>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown when the <c>timeoutMilliseconds</c> is smaller than -1. /// </exception> /// <remarks> /// This function guarantees thread-safety. If multiple calls occurred /// simultaneously, they might get folded and result in less calls to /// the <c>OnCollect</c> callback for improved performance, as long as /// the semantic can be preserved. /// </remarks> public bool Collect(int timeoutMilliseconds = Timeout.Infinite) { Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.Collect method called."); var shouldRunCollect = false; var tcs = this.collectionTcs; if (tcs == null) { lock (this.newTaskLock) { tcs = this.collectionTcs; if (tcs == null) { shouldRunCollect = true; tcs = new TaskCompletionSource<bool>(); this.collectionTcs = tcs; } } } if (!shouldRunCollect) { return Task.WaitAny(tcs.Task, this.shutdownTcs.Task, Task.Delay(timeoutMilliseconds)) == 0 ? tcs.Task.Result : false; } var result = false; try { lock (this.onCollectLock) { this.collectionTcs = null; result = this.OnCollect(timeoutMilliseconds); } } catch (Exception ex) { OpenTelemetrySdkEventSource.Log.MetricReaderException(nameof(this.Collect), ex); } tcs.TrySetResult(result); if (result) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.Collect succeeded."); } else { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.Collect failed."); } return result; } /// <summary> /// Attempts to shutdown the processor, blocks the current thread until /// shutdown completed or timed out. /// </summary> /// <param name="timeoutMilliseconds"> /// The number (non-negative) of milliseconds to wait, or /// <c>Timeout.Infinite</c> to wait indefinitely. /// </param> /// <returns> /// Returns <c>true</c> when shutdown succeeded; otherwise, <c>false</c>. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown when the <c>timeoutMilliseconds</c> is smaller than -1. /// </exception> /// <remarks> /// This function guarantees thread-safety. Only the first call will /// win, subsequent calls will be no-op. /// </remarks> public bool Shutdown(int timeoutMilliseconds = Timeout.Infinite) { Guard.ThrowIfInvalidTimeout(timeoutMilliseconds); OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.Shutdown called."); if (Interlocked.CompareExchange(ref this.shutdownCount, 1, 0) != 0) { return false; // shutdown already called } var result = false; try { result = this.OnShutdown(timeoutMilliseconds); } catch (Exception ex) { OpenTelemetrySdkEventSource.Log.MetricReaderException(nameof(this.Shutdown), ex); } this.shutdownTcs.TrySetResult(result); if (result) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.Shutdown succeeded."); } else { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.Shutdown failed."); } return result; } /// <inheritdoc/> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } internal virtual void SetParentProvider(BaseProvider parentProvider) { this.parentProvider = parentProvider; } /// <summary> /// Processes a batch of metrics. /// </summary> /// <param name="metrics">Batch of metrics to be processed.</param> /// <param name="timeoutMilliseconds"> /// The number (non-negative) of milliseconds to wait, or /// <c>Timeout.Infinite</c> to wait indefinitely. /// </param> /// <returns> /// Returns <c>true</c> when metrics processing succeeded; otherwise, /// <c>false</c>. /// </returns> internal virtual bool ProcessMetrics(in Batch<Metric> metrics, int timeoutMilliseconds) { return true; } /// <summary> /// Called by <c>Collect</c>. This function should block the current /// thread until metrics collection completed, shutdown signaled or /// timed out. /// </summary> /// <param name="timeoutMilliseconds"> /// The number (non-negative) of milliseconds to wait, or /// <c>Timeout.Infinite</c> to wait indefinitely. /// </param> /// <returns> /// Returns <c>true</c> when metrics collection succeeded; otherwise, /// <c>false</c>. /// </returns> /// <remarks> /// This function is called synchronously on the threads which called /// <c>Collect</c>. This function should not throw exceptions. /// </remarks> protected virtual bool OnCollect(int timeoutMilliseconds) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("MetricReader.OnCollect called."); var sw = timeoutMilliseconds == Timeout.Infinite ? null : Stopwatch.StartNew(); var collectObservableInstruments = this.parentProvider.GetObservableInstrumentCollectCallback(); collectObservableInstruments?.Invoke(); OpenTelemetrySdkEventSource.Log.MetricReaderEvent("Observable instruments collected."); var metrics = this.GetMetricsBatch(); bool result; if (sw == null) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("ProcessMetrics called."); result = this.ProcessMetrics(metrics, Timeout.Infinite); if (result) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("ProcessMetrics succeeded."); } else { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("ProcessMetrics failed."); } return result; } else { var timeout = timeoutMilliseconds - sw.ElapsedMilliseconds; if (timeout <= 0) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("OnCollect failed timeout period has elapsed."); return false; } OpenTelemetrySdkEventSource.Log.MetricReaderEvent("ProcessMetrics called."); result = this.ProcessMetrics(metrics, (int)timeout); if (result) { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("ProcessMetrics succeeded."); } else { OpenTelemetrySdkEventSource.Log.MetricReaderEvent("ProcessMetrics failed."); } return result; } } /// <summary> /// Called by <c>Shutdown</c>. This function should block the current /// thread until shutdown completed or timed out. /// </summary> /// <param name="timeoutMilliseconds"> /// The number (non-negative) of milliseconds to wait, or /// <c>Timeout.Infinite</c> to wait indefinitely. /// </param> /// <returns> /// Returns <c>true</c> when shutdown succeeded; otherwise, <c>false</c>. /// </returns> /// <remarks> /// This function is called synchronously on the thread which made the /// first call to <c>Shutdown</c>. This function should not throw /// exceptions. /// </remarks> protected virtual bool OnShutdown(int timeoutMilliseconds) { return this.Collect(timeoutMilliseconds); } /// <summary> /// Releases the unmanaged resources used by this class and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"> /// <see langword="true"/> to release both managed and unmanaged resources; /// <see langword="false"/> to release only unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { } } }