context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System.Collections.Generic; using GLTF.Extensions; using Newtonsoft.Json; namespace GLTF.Schema { /// <summary> /// Geometry to be rendered with the given material. /// </summary> public class MeshPrimitive : GLTFProperty { /// <summary> /// A dictionary object, where each key corresponds to mesh attribute semantic /// and each value is the index of the accessor containing attribute's data. /// </summary> public Dictionary<string, AccessorId> Attributes = new Dictionary<string, AccessorId>(); /// <summary> /// The index of the accessor that contains mesh indices. /// When this is not defined, the primitives should be rendered without indices /// using `drawArrays()`. When defined, the accessor must contain indices: /// the `bufferView` referenced by the accessor must have a `target` equal /// to 34963 (ELEMENT_ARRAY_BUFFER); a `byteStride` that is tightly packed, /// i.e., 0 or the byte size of `componentType` in bytes; /// `componentType` must be 5121 (UNSIGNED_BYTE), 5123 (UNSIGNED_SHORT) /// or 5125 (UNSIGNED_INT), the latter is only allowed /// when `OES_element_index_uint` extension is used; `type` must be `\"SCALAR\"`. /// </summary> public AccessorId Indices; /// <summary> /// The index of the material to apply to this primitive when rendering. /// </summary> public MaterialId Material; /// <summary> /// The type of primitives to render. All valid values correspond to WebGL enums. /// </summary> public DrawMode Mode = DrawMode.Triangles; /// <summary> /// An array of Morph Targets, each Morph Target is a dictionary mapping /// attributes (only "POSITION" and "NORMAL" supported) to their deviations /// in the Morph Target (index of the accessor containing the attribute /// displacements' data). /// </summary> /// TODO: Make dictionary key enums? public List<Dictionary<string, AccessorId>> Targets; public List<string> TargetNames; public MeshPrimitive() { } public MeshPrimitive(MeshPrimitive meshPrimitive, GLTFRoot gltfRoot) : base(meshPrimitive) { if (meshPrimitive == null) return; if (meshPrimitive.Attributes != null) { Attributes = new Dictionary<string, AccessorId>(meshPrimitive.Attributes.Count); foreach (KeyValuePair<string, AccessorId> attributeKeyValuePair in meshPrimitive.Attributes) { Attributes[attributeKeyValuePair.Key] = new AccessorId(attributeKeyValuePair.Value, gltfRoot); } } if (meshPrimitive.Indices != null) { Indices = new AccessorId(meshPrimitive.Indices, gltfRoot); } if (meshPrimitive.Material != null) { Material = new MaterialId(meshPrimitive.Material, gltfRoot); } Mode = meshPrimitive.Mode; if (meshPrimitive.Targets != null) { Targets = new List<Dictionary<string, AccessorId>>(meshPrimitive.Targets.Count); foreach (Dictionary<string, AccessorId> targetToCopy in meshPrimitive.Targets) { Dictionary<string, AccessorId> target = new Dictionary<string, AccessorId>(targetToCopy.Count); foreach (KeyValuePair<string, AccessorId> targetKeyValuePair in targetToCopy) { target[targetKeyValuePair.Key] = new AccessorId(targetKeyValuePair.Value, gltfRoot); } Targets.Add(target); } } if (meshPrimitive.TargetNames != null) { TargetNames = new List<string>(meshPrimitive.TargetNames); } } public static int[] GenerateIndices(int vertCount) { var indices = new int[vertCount]; for (var i = 0; i < vertCount; i++) { indices[i] = i; } return indices; } // Taken from: http://answers.unity3d.com/comments/190515/view.html // Official support for Mesh.RecalculateTangents should be coming in 5.6 // https://feedback.unity3d.com/suggestions/recalculatetangents /*private MeshPrimitiveAttributes CalculateAndSetTangents(MeshPrimitiveAttributes attributes) { var triangleCount = attributes.Triangles.Length; var vertexCount = attributes.Vertices.Length; var tan1 = new Vector3[vertexCount]; var tan2 = new Vector3[vertexCount]; attributes.Tangents = new Vector4[vertexCount]; for (long a = 0; a < triangleCount; a += 3) { long i1 = attributes.Triangles[a + 0]; long i2 = attributes.Triangles[a + 1]; long i3 = attributes.Triangles[a + 2]; var v1 = attributes.Vertices[i1]; var v2 = attributes.Vertices[i2]; var v3 = attributes.Vertices[i3]; var w1 = attributes.Uv[i1]; var w2 = attributes.Uv[i2]; var w3 = attributes.Uv[i3]; var x1 = v2.X - v1.X; var x2 = v3.X - v1.X; var y1 = v2.Y - v1.Y; var y2 = v3.Y - v1.Y; var z1 = v2.Z - v1.Z; var z2 = v3.Z - v1.Z; var s1 = w2.X - w1.X; var s2 = w3.X - w1.X; var t1 = w2.Y - w1.Y; var t2 = w3.Y - w1.Y; var r = 1.0f / (s1 * t2 - s2 * t1); var sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r); var tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r); tan1[i1] += sdir; tan1[i2] += sdir; tan1[i3] += sdir; tan2[i1] += tdir; tan2[i2] += tdir; tan2[i3] += tdir; } for (long a = 0; a < vertexCount; ++a) { var n = attributes.Normals[a]; var t = tan1[a]; Vector3.OrthoNormalize(ref n, ref t); attributes.Tangents[a].X = t.X; attributes.Tangents[a].Y = t.Y; attributes.Tangents[a].Z = t.Z; attributes.Tangents[a].W = (Vector3.Dot(Vector3.Cross(n, t), tan2[a]) < 0.0f) ? -1.0f : 1.0f; } return attributes; }*/ public static MeshPrimitive Deserialize(GLTFRoot root, JsonReader reader) { var primitive = new MeshPrimitive(); while (reader.Read() && reader.TokenType == JsonToken.PropertyName) { var curProp = reader.Value.ToString(); switch (curProp) { case "attributes": primitive.Attributes = reader.ReadAsDictionary(() => new AccessorId { Id = reader.ReadAsInt32().Value, Root = root }); break; case "indices": primitive.Indices = AccessorId.Deserialize(root, reader); break; case "material": primitive.Material = MaterialId.Deserialize(root, reader); break; case "mode": primitive.Mode = (DrawMode)reader.ReadAsInt32().Value; break; case "targets": primitive.Targets = reader.ReadList(() => { return reader.ReadAsDictionary(() => new AccessorId { Id = reader.ReadAsInt32().Value, Root = root }, skipStartObjectRead: true); }); break; case "extras": // GLTF does not support morph target names, serialize in extras for now // https://github.com/KhronosGroup/glTF/issues/1036 if (reader.Read() && reader.TokenType == JsonToken.StartObject) { while (reader.Read() && reader.TokenType == JsonToken.PropertyName) { var extraProperty = reader.Value.ToString(); switch (extraProperty) { case "targetNames": primitive.TargetNames = reader.ReadStringList(); break; } } } break; default: primitive.DefaultPropertyDeserializer(root, reader); break; } } return primitive; } public override void Serialize(JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("attributes"); writer.WriteStartObject(); foreach (var attribute in Attributes) { writer.WritePropertyName(attribute.Key); writer.WriteValue(attribute.Value.Id); } writer.WriteEndObject(); if (Indices != null) { writer.WritePropertyName("indices"); writer.WriteValue(Indices.Id); } if (Material != null) { writer.WritePropertyName("material"); writer.WriteValue(Material.Id); } if (Mode != DrawMode.Triangles) { writer.WritePropertyName("mode"); writer.WriteValue((int)Mode); } if (Targets != null && Targets.Count > 0) { writer.WritePropertyName("targets"); writer.WriteStartArray(); foreach (var target in Targets) { writer.WriteStartObject(); foreach (var attribute in target) { writer.WritePropertyName(attribute.Key); writer.WriteValue(attribute.Value.Id); } writer.WriteEndObject(); } writer.WriteEndArray(); } // GLTF does not support morph target names, serialize in extras for now // https://github.com/KhronosGroup/glTF/issues/1036 if (TargetNames != null && TargetNames.Count > 0) { writer.WritePropertyName("extras"); writer.WriteStartObject(); writer.WritePropertyName("targetNames"); writer.WriteStartArray(); foreach (var targetName in TargetNames) { writer.WriteValue(targetName); } writer.WriteEndArray(); writer.WriteEndObject(); } base.Serialize(writer); writer.WriteEndObject(); } } public static class SemanticProperties { public const string POSITION = "POSITION"; public const string NORMAL = "NORMAL"; public const string TANGENT = "TANGENT"; public const string INDICES = "INDICES"; public const string TEXCOORD_0 = "TEXCOORD_0"; public const string TEXCOORD_1 = "TEXCOORD_1"; public const string TEXCOORD_2 = "TEXCOORD_2"; public const string TEXCOORD_3 = "TEXCOORD_3"; public static readonly string[] TexCoord = { TEXCOORD_0, TEXCOORD_1, TEXCOORD_2, TEXCOORD_3 }; public const string COLOR_0 = "COLOR_0"; public static readonly string[] Color = { COLOR_0 }; public const string WEIGHTS_0 = "WEIGHTS_0"; public static readonly string[] Weight = { WEIGHTS_0 }; public const string JOINTS_0 = "JOINTS_0"; public static readonly string[] Joint = { JOINTS_0 }; /// <summary> /// Parse out the index of a given semantic property. /// </summary> /// <param name="property">Semantic property to parse</param> /// <param name="index">Parsed index to assign</param> /// <returns></returns> public static bool ParsePropertyIndex(string property, out int index) { index = -1; var parts = property.Split('_'); if (parts.Length != 2) { return false; } if (!int.TryParse(parts[1], out index)) { return false; } return true; } } public enum DrawMode { Points = 0, Lines = 1, LineLoop = 2, LineStrip = 3, Triangles = 4, TriangleStrip = 5, TriangleFan = 6 } }
using System; using System.Collections.Generic; using System.Text; using LumiSoft.Net.MIME; namespace LumiSoft.Net.MIME { /// <summary> /// Provides MIME related utility methods. /// </summary> public class MIME_Utils { #region static method DateTimeToRfc2822 /// <summary> /// Converts date to RFC 2822 date time string. /// </summary> /// <param name="dateTime">Date time value to convert..</param> /// <returns>Returns RFC 2822 date time string.</returns> public static string DateTimeToRfc2822(DateTime dateTime) { return dateTime.ToString("ddd, dd MMM yyyy HH':'mm':'ss ",System.Globalization.DateTimeFormatInfo.InvariantInfo) + dateTime.ToString("zzz").Replace(":",""); } #endregion #region static method ParseRfc2822DateTime /// <summary> /// Parses RFC 2822 date-time from the specified value. /// </summary> /// <param name="value">RFC 2822 date-time string value.</param> /// <returns>Returns parsed datetime value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public static DateTime ParseRfc2822DateTime(string value) { if(value == null){ throw new ArgumentNullException(value); } /* RFC 2822 3. * date-time = [ day-of-week "," ] date FWS time [CFWS] * day-of-week = ([FWS] day-name) / obs-day-of-week * day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" * date = day month year * year = 4*DIGIT / obs-year * month = (FWS month-name FWS) / obs-month * month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" * day = ([FWS] 1*2DIGIT) / obs-day * time = time-of-day FWS zone * time-of-day = hour ":" minute [ ":" second ] * hour = 2DIGIT / obs-hour * minute = 2DIGIT / obs-minute * second = 2DIGIT / obs-second * zone = (( "+" / "-" ) 4DIGIT) / obs-zone * * The date and time-of-day SHOULD express local time. */ try{ MIME_Reader r = new MIME_Reader(value); string v = r.Atom(); // Skip optional [ day-of-week "," ] and read "day". if(v.Length == 3){ r.Char(true); v = r.Atom(); } int day = Convert.ToInt32(v); v = r.Atom().ToLower(); int month = 1; if(v == "jan"){ month = 1; } else if(v == "feb"){ month = 2; } else if(v == "mar"){ month = 3; } else if(v == "apr"){ month = 4; } else if(v == "may"){ month = 5; } else if(v == "jun"){ month = 6; } else if(v == "jul"){ month = 7; } else if(v == "aug"){ month = 8; } else if(v == "sep"){ month = 9; } else if(v == "oct"){ month = 10; } else if(v == "nov"){ month = 11; } else if(v == "dec"){ month = 12; } else{ throw new ArgumentException("Invalid month-name value '" + value + "'."); } int year = Convert.ToInt32(r.Atom()); int hour = Convert.ToInt32(r.Atom()); r.Char(true); int minute = Convert.ToInt32(r.Atom()); int second = 0; // We have optional "second". if(r.Peek(true) == ':'){ r.Char(true); second = Convert.ToInt32(r.Atom()); } int timeZoneMinutes = 0; v = r.Atom(); // We have RFC 2822 date. For example: +2000. if(v[0] == '+' || v[0] == '-'){ if(v[0] == '+'){ timeZoneMinutes = (Convert.ToInt32(v.Substring(1,2)) * 60 + Convert.ToInt32(v.Substring(3,2))); } else{ timeZoneMinutes = -(Convert.ToInt32(v.Substring(1,2)) * 60 + Convert.ToInt32(v.Substring(3,2))); } } // We have RFC 822 date with abbrevated time zone name. For example: GMT. else{ v = v.ToUpper(); #region time zones // Alpha Time Zone (military). if(v == "A"){ timeZoneMinutes = ((01 * 60) + 00); } // Australian Central Daylight Time. else if(v == "ACDT"){ timeZoneMinutes = ((10 * 60) + 30); } // Australian Central Standard Time. else if(v == "ACST"){ timeZoneMinutes = ((09 * 60) + 30); } // Atlantic Daylight Time. else if(v == "ADT"){ timeZoneMinutes = -((03 * 60) + 00); } // Australian Eastern Daylight Time. else if(v == "AEDT"){ timeZoneMinutes = ((11 * 60) + 00); } // Australian Eastern Standard Time. else if(v == "AEST"){ timeZoneMinutes = ((10 * 60) + 00); } // Alaska Daylight Time. else if(v == "AKDT"){ timeZoneMinutes = -((08 * 60) + 00); } // Alaska Standard Time. else if(v == "AKST"){ timeZoneMinutes = -((09 * 60) + 00); } // Atlantic Standard Time. else if(v == "AST"){ timeZoneMinutes = -((04 * 60) + 00); } // Australian Western Daylight Time. else if(v == "AWDT"){ timeZoneMinutes = ((09 * 60) + 00); } // Australian Western Standard Time. else if(v == "AWST"){ timeZoneMinutes = ((08 * 60) + 00); } // Bravo Time Zone (millitary). else if(v == "B"){ timeZoneMinutes = ((02 * 60) + 00); } // British Summer Time. else if(v == "BST"){ timeZoneMinutes = ((01 * 60) + 00); } // Charlie Time Zone (millitary). else if(v == "C"){ timeZoneMinutes = ((03 * 60) + 00); } // Central Daylight Time. else if(v == "CDT"){ timeZoneMinutes = -((05 * 60) + 00); } // Central European Daylight Time. else if(v == "CEDT"){ timeZoneMinutes = ((02 * 60) + 00); } // Central European Summer Time. else if(v == "CEST"){ timeZoneMinutes = ((02 * 60) + 00); } // Central European Time. else if(v == "CET"){ timeZoneMinutes = ((01 * 60) + 00); } // Central Standard Time. else if(v == "CST"){ timeZoneMinutes = -((06 * 60) + 00); } // Christmas Island Time. else if(v == "CXT"){ timeZoneMinutes = ((01 * 60) + 00); } // Delta Time Zone (military). else if(v == "D"){ timeZoneMinutes = ((04 * 60) + 00); } // Echo Time Zone (military). else if(v == "E"){ timeZoneMinutes = ((05 * 60) + 00); } // Eastern Daylight Time. else if(v == "EDT"){ timeZoneMinutes = -((04 * 60) + 00); } // Eastern European Daylight Time. else if(v == "EEDT"){ timeZoneMinutes = ((03 * 60) + 00); } // Eastern European Summer Time. else if(v == "EEST"){ timeZoneMinutes = ((03 * 60) + 00); } // Eastern European Time. else if(v == "EET"){ timeZoneMinutes = ((02 * 60) + 00); } // Eastern Standard Time. else if(v == "EST"){ timeZoneMinutes = -((05 * 60) + 00); } // Foxtrot Time Zone (military). else if(v == "F"){ timeZoneMinutes = (06 * 60 + 00); } // Golf Time Zone (military). else if(v == "G"){ timeZoneMinutes = ((07 * 60) + 00); } // Greenwich Mean Time. else if(v == "GMT"){ timeZoneMinutes = 0000; } // Hotel Time Zone (military). else if(v == "H"){ timeZoneMinutes = ((08 * 60) + 00); } // India Time Zone (military). else if(v == "I"){ timeZoneMinutes = ((09 * 60) + 00); } // Irish Summer Time. else if(v == "IST"){ timeZoneMinutes = ((01 * 60) + 00); } // Kilo Time Zone (millitary). else if(v == "K"){ timeZoneMinutes = ((10 * 60) + 00); } // Lima Time Zone (millitary). else if(v == "L"){ timeZoneMinutes = ((11 * 60) + 00); } // Mike Time Zone (millitary). else if(v == "M"){ timeZoneMinutes = ((12 * 60) + 00); } // Mountain Daylight Time. else if(v == "MDT"){ timeZoneMinutes = -((06 * 60) + 00); } // Mountain Standard Time. else if(v == "MST"){ timeZoneMinutes = -((07 * 60) + 00); } // November Time Zone (military). else if(v == "N"){ timeZoneMinutes = -((01 * 60) + 00); } // Newfoundland Daylight Time. else if(v == "NDT"){ timeZoneMinutes = -((02 * 60) + 30); } // Norfolk (Island) Time. else if(v == "NFT"){ timeZoneMinutes = ((11 * 60) + 30); } // Newfoundland Standard Time. else if(v == "NST"){ timeZoneMinutes = -((03 * 60) + 30); } // Oscar Time Zone (military). else if(v == "O"){ timeZoneMinutes = -((02 * 60) + 00); } // Papa Time Zone (military). else if(v == "P"){ timeZoneMinutes = -((03 * 60) + 00); } // Pacific Daylight Time. else if(v == "PDT"){ timeZoneMinutes = -((07 * 60) + 00); } // Pacific Standard Time. else if(v == "PST"){ timeZoneMinutes = -((08 * 60) + 00); } // Quebec Time Zone (military). else if(v == "Q"){ timeZoneMinutes = -((04 * 60) + 00); } // Romeo Time Zone (military). else if(v == "R"){ timeZoneMinutes = -((05 * 60) + 00); } // Sierra Time Zone (military). else if(v == "S"){ timeZoneMinutes = -((06 * 60) + 00); } // Tango Time Zone (military). else if(v == "T"){ timeZoneMinutes = -((07 * 60) + 00); } // Uniform Time Zone (military). else if(v == ""){ timeZoneMinutes = -((08 * 60) + 00); } // Coordinated Universal Time. else if(v == "UTC"){ timeZoneMinutes = 0000; } // Victor Time Zone (militray). else if(v == "V"){ timeZoneMinutes = -((09 * 60) + 00); } // Whiskey Time Zone (military). else if(v == "W"){ timeZoneMinutes = -((10 * 60) + 00); } // Western European Daylight Time. else if(v == "WEDT"){ timeZoneMinutes = ((01 * 60) + 00); } // Western European Summer Time. else if(v == "WEST"){ timeZoneMinutes = ((01 * 60) + 00); } // Western European Time. else if(v == "WET"){ timeZoneMinutes = 0000; } // Western Standard Time. else if(v == "WST"){ timeZoneMinutes = ((08 * 60) + 00); } // X-ray Time Zone (military). else if(v == "X"){ timeZoneMinutes = -((11 * 60) + 00); } // Yankee Time Zone (military). else if(v == "Y"){ timeZoneMinutes = -((12 * 60) + 00); } // Zulu Time Zone (military). else if(v == "Z"){ timeZoneMinutes = 0000; } #endregion } // Convert time to UTC and then back to local. DateTime timeUTC = new DateTime(year,month,day,hour,minute,second).AddMinutes(-(timeZoneMinutes)); return new DateTime(timeUTC.Year,timeUTC.Month,timeUTC.Day,timeUTC.Hour,timeUTC.Minute,timeUTC.Second,DateTimeKind.Utc).ToLocalTime(); } catch(Exception x){ string dymmy = x.Message; throw new ArgumentException("Argumnet 'value' value '" + value + "' is not valid RFC 822/2822 date-time string."); } } #endregion #region static method UnfoldHeader /// <summary> /// Unfolds folded header field. /// </summary> /// <param name="value">Header field.</param> /// <returns>Returns unfolded header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> public static string UnfoldHeader(string value) { if(value == null){ throw new ArgumentNullException("value"); } /* RFC 2822 2.2.3 Long Header Fields. The process of moving from this folded multiple-line representation of a header field to its single line representation is called "unfolding". Unfolding is accomplished by simply removing any CRLF that is immediately followed by WSP. */ return value.Replace("\r\n",""); } #endregion #region static method CreateMessageID /// <summary> /// Creates Rfc 2822 3.6.4 message-id. Syntax: '&lt;' id-left '@' id-right '&gt;'. /// </summary> /// <returns></returns> public static string CreateMessageID() { return "<" + Guid.NewGuid().ToString().Replace("-","").Substring(16) + "@" + Guid.NewGuid().ToString().Replace("-","").Substring(16) + ">"; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// HeaderOperations operations. /// </summary> internal partial class HeaderOperations : Microsoft.Rest.IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IHeaderOperations { /// <summary> /// Initializes a new instance of the HeaderOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal HeaderOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request /// </summary> /// <param name='fooClientRequestId'> /// The fooRequestId /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeadersInner>> CustomNamedRequestIdWithHttpMessagesAsync(string fooClientRequestId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (fooClientRequestId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fooClientRequestId"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("fooClientRequestId", fooClientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestId", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestId").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString()); } if (fooClientRequestId != null) { if (_httpRequest.Headers.Contains("foo-client-request-id")) { _httpRequest.Headers.Remove("foo-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("foo-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdHeadersInner>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the /// header of the request, via a parameter group /// </summary> /// <param name='headerCustomNamedRequestIdParamGroupingParameters'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdParamGroupingHeadersInner>> CustomNamedRequestIdParamGroupingWithHttpMessagesAsync(HeaderCustomNamedRequestIdParamGroupingParametersInner headerCustomNamedRequestIdParamGroupingParameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (headerCustomNamedRequestIdParamGroupingParameters == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "headerCustomNamedRequestIdParamGroupingParameters"); } if (headerCustomNamedRequestIdParamGroupingParameters != null) { headerCustomNamedRequestIdParamGroupingParameters.Validate(); } string fooClientRequestId = default(string); if (headerCustomNamedRequestIdParamGroupingParameters != null) { fooClientRequestId = headerCustomNamedRequestIdParamGroupingParameters.FooClientRequestId; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("fooClientRequestId", fooClientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CustomNamedRequestIdParamGrouping", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/customNamedRequestIdParamGrouping").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (fooClientRequestId != null) { if (_httpRequest.Headers.Contains("foo-client-request-id")) { _httpRequest.Headers.Remove("foo-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("foo-client-request-id", fooClientRequestId); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationHeaderResponse<HeaderCustomNamedRequestIdParamGroupingHeadersInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("foo-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("foo-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<HeaderCustomNamedRequestIdParamGroupingHeadersInner>(Newtonsoft.Json.JsonSerializer.Create(this.Client.DeserializationSettings)); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * Copyright 2011 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: PuTTYPrivateKeyLoader.cs,v 1.1 2011/11/03 16:27:38 kzmi Exp $ */ using System; using System.Globalization; using System.IO; using System.Text; using System.Security.Cryptography; using Granados.Crypto; using Granados.PKI; using Granados.IO.SSH2; using Granados.Util; namespace Granados.Poderosa.KeyFormat { /// <summary> /// PuTTY SSH2 private key loader /// </summary> internal class PuTTYPrivateKeyLoader : ISSH2PrivateKeyLoader { private readonly string keyFilePath; private readonly byte[] keyFile; private enum KeyType { RSA, DSA, } /// <summary> /// Constructor /// </summary> /// <param name="keyFile">key file data</param> /// <param name="keyFilePath">Path of a key file</param> public PuTTYPrivateKeyLoader(byte[] keyFile, string keyFilePath) { this.keyFilePath = keyFilePath; this.keyFile = keyFile; } /// <summary> /// Read PuTTY SSH2 private key parameters. /// </summary> /// <param name="passphrase">passphrase for decrypt the key file</param> /// <param name="keyPair">key pair</param> /// <param name="comment">comment or empty if it didn't exist</param> public void Load(string passphrase, out KeyPair keyPair, out string comment) { if (keyFile == null) throw new SSHException("A key file is not loaded yet"); int version; string keyTypeName; KeyType keyType; string encryptionName; CipherAlgorithm? encryption; byte[] publicBlob; byte[] privateBlob; string privateMac; string privateHash; using (StreamReader sreader = GetStreamReader()) { //*** Read header and key type ReadHeaderLine(sreader, out version, out keyTypeName); if (keyTypeName == "ssh-rsa") keyType = KeyType.RSA; else if (keyTypeName == "ssh-dss") keyType = KeyType.DSA; else throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected key type)"); //*** Read encryption ReadItemLine(sreader, "Encryption", out encryptionName); if (encryptionName == "aes256-cbc") encryption = CipherAlgorithm.AES256; else if (encryptionName == "none") encryption = null; else throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected encryption)"); //*** Read comment ReadItemLine(sreader, "Comment", out comment); //*** Read public lines string publicLinesStr; ReadItemLine(sreader, "Public-Lines", out publicLinesStr); int publicLines; if (!Int32.TryParse(publicLinesStr, out publicLines) || publicLines < 0) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid public lines)"); ReadBlob(sreader, publicLines, out publicBlob); //*** Read private lines string privateLinesStr; ReadItemLine(sreader, "Private-Lines", out privateLinesStr); int privateLines; if (!Int32.TryParse(privateLinesStr, out privateLines) || privateLines < 0) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid private lines)"); ReadBlob(sreader, privateLines, out privateBlob); //*** Read private MAC ReadPrivateMACLine(sreader, version, out privateMac, out privateHash); } if (encryption.HasValue) { byte[] key = PuTTYPassphraseToKey(passphrase); byte[] iv = new byte[16]; Cipher cipher = CipherFactory.CreateCipher(SSHProtocol.SSH2, encryption.Value, key, iv); if (privateBlob.Length % cipher.BlockSize != 0) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid key data size)"); cipher.Decrypt(privateBlob, 0, privateBlob.Length, privateBlob, 0); } bool verified = Verify(version, privateMac, privateHash, passphrase, keyTypeName, encryptionName, comment, publicBlob, privateBlob); if (!verified) { if (encryption.HasValue) throw new SSHException(Strings.GetString("WrongPassphrase")); else throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (HMAC verification failed)"); } if (keyType == KeyType.RSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); byte[] magic = reader.ReadString(); if (!ByteArrayUtil.AreEqual(magic, Encoding.ASCII.GetBytes("ssh-rsa"))) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing magic)"); BigInteger e = reader.ReadMPInt(); BigInteger n = reader.ReadMPInt(); reader = new SSH2DataReader(privateBlob); BigInteger d = reader.ReadMPInt(); BigInteger p = reader.ReadMPInt(); BigInteger q = reader.ReadMPInt(); BigInteger iqmp = reader.ReadMPInt(); BigInteger u = p.modInverse(q); keyPair = new RSAKeyPair(e, d, n, u, p, q); } else if (keyType == KeyType.DSA) { SSH2DataReader reader = new SSH2DataReader(publicBlob); byte[] magic = reader.ReadString(); if (!ByteArrayUtil.AreEqual(magic, Encoding.ASCII.GetBytes("ssh-dss"))) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing magic)"); BigInteger p = reader.ReadMPInt(); BigInteger q = reader.ReadMPInt(); BigInteger g = reader.ReadMPInt(); BigInteger y = reader.ReadMPInt(); reader = new SSH2DataReader(privateBlob); BigInteger x = reader.ReadMPInt(); keyPair = new DSAKeyPair(p, g, q, y, x); } else { throw new SSHException("Unknown file type. This should not happen."); } } private void ReadHeaderLine(StreamReader sreader, out int version, out string keyTypeName) { string line = sreader.ReadLine(); if (line == null) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)"); if (line.StartsWith(PrivateKeyFileHeader.SSH2_PUTTY_HEADER_1)) version = 1; else if (line.StartsWith(PrivateKeyFileHeader.SSH2_PUTTY_HEADER_2)) version = 2; else throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected format type)"); keyTypeName = GetValueOf(line); } private void ReadItemLine(StreamReader sreader, string itemName, out string itemValue) { string line = sreader.ReadLine(); if (line == null) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)"); if (!line.StartsWith(itemName + ":")) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing " + itemName + ")"); itemValue = GetValueOf(line); } private void ReadPrivateMACLine(StreamReader sreader, int version, out string privateMac, out string privateHash) { string line = sreader.ReadLine(); if (line == null) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)"); if (line.StartsWith("Private-MAC:")) { privateMac = GetValueOf(line); privateHash = null; } else if (version == 1 && line.StartsWith("Private-Hash:")) { privateMac = null; privateHash = GetValueOf(line); } else { throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing " + (version == 1 ? "Private-Hash" : "Private-MAC") + ")"); } } private void ReadBlob(StreamReader sreader, int lines, out byte[] blob) { StringBuilder base64Buff = new StringBuilder(); for (int i = 0; i < lines; i++) { string line = sreader.ReadLine(); if (line == null) throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)"); base64Buff.Append(line); } blob = Base64.Decode(Encoding.ASCII.GetBytes(base64Buff.ToString())); } private static byte[] PuTTYPassphraseToKey(string passphrase) { const int HASH_SIZE = 20; SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] pp = Encoding.UTF8.GetBytes(passphrase); byte[] buf = new byte[HASH_SIZE * 2]; sha1.TransformBlock(new byte[] { 0, 0, 0, 0 }, 0, 4, null, 0); sha1.TransformFinalBlock(pp, 0, pp.Length); Buffer.BlockCopy(sha1.Hash, 0, buf, 0, HASH_SIZE); sha1.Initialize(); sha1.TransformBlock(new byte[] { 0, 0, 0, 1 }, 0, 4, null, 0); sha1.TransformFinalBlock(pp, 0, pp.Length); Buffer.BlockCopy(sha1.Hash, 0, buf, HASH_SIZE, HASH_SIZE); sha1.Clear(); byte[] key = new byte[32]; Buffer.BlockCopy(buf, 0, key, 0, key.Length); return key; } private bool Verify(int version, string privateMac, string privateHash, string passphrase, string keyTypeName, string encryptionName, string comment, byte[] publicBlob, byte[] privateBlob) { byte[] macData; using (MemoryStream macDataBuff = new MemoryStream()) { if (version == 1) { WriteMacData(macDataBuff, privateBlob); } else { WriteMacData(macDataBuff, keyTypeName); WriteMacData(macDataBuff, encryptionName); WriteMacData(macDataBuff, comment); WriteMacData(macDataBuff, publicBlob); WriteMacData(macDataBuff, privateBlob); } macDataBuff.Close(); macData = macDataBuff.ToArray(); } if (privateMac != null) { SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] a = Encoding.ASCII.GetBytes("putty-private-key-file-mac-key"); sha1.TransformBlock(a, 0, a.Length, null, 0); byte[] b = Encoding.UTF8.GetBytes(passphrase); sha1.TransformFinalBlock(b, 0, b.Length); byte[] key = sha1.Hash; sha1.Clear(); System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key); byte[] hash = hmacsha1.ComputeHash(macData); hmacsha1.Clear(); string mac = BinToHex(hash); return mac == privateMac; } else if (privateHash != null) { SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(macData); sha1.Clear(); string mac = BinToHex(hash); return mac == privateHash; } else { return true; } } // Extract value from "Name: value" line private static string GetValueOf(string line) { int p = line.IndexOf(':'); if (p < 0) return null; if (p + 1 >= line.Length || line[p + 1] != ' ') return null; return line.Substring(p + 2); } private static void WriteMacData(MemoryStream mem, string s) { WriteMacData(mem, Encoding.UTF8.GetBytes(s)); } private static void WriteMacData(MemoryStream mem, byte[] data) { byte[] dw = BitConverter.GetBytes(data.Length); if (BitConverter.IsLittleEndian) Array.Reverse(dw); mem.Write(dw, 0, dw.Length); mem.Write(data, 0, data.Length); } private static string BinToHex(byte[] data) { StringBuilder s = new StringBuilder(); foreach (byte b in data) { s.Append(b.ToString("x2", NumberFormatInfo.InvariantInfo)); } return s.ToString(); } private StreamReader GetStreamReader() { MemoryStream mem = new MemoryStream(keyFile, false); return new StreamReader(mem, Encoding.ASCII); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F11_City_Child (editable child object).<br/> /// This is a generated base class of <see cref="F11_City_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F10_City"/> collection. /// </remarks> [Serializable] public partial class F11_City_Child : BusinessBase<F11_City_Child> { #region State Fields [NotUndoable] [NonSerialized] internal int city_ID1 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name"); /// <summary> /// Gets or sets the CityRoads Child Name. /// </summary> /// <value>The CityRoads Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F11_City_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="F11_City_Child"/> object.</returns> internal static F11_City_Child NewF11_City_Child() { return DataPortal.CreateChild<F11_City_Child>(); } /// <summary> /// Factory method. Loads a <see cref="F11_City_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F11_City_Child"/> object.</returns> internal static F11_City_Child GetF11_City_Child(SafeDataReader dr) { F11_City_Child obj = new F11_City_Child(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F11_City_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F11_City_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F11_City_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F11_City_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name")); // parent properties city_ID1 = dr.GetInt32("City_ID1"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F11_City_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddF11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="F11_City_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F10_City parent) { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateF11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@City_Child_Name", ReadProperty(City_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="F11_City_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F10_City parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteF11_City_Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@City_ID1", parent.City_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using McMaster.Extensions.CommandLineUtils; using SteamDatabase.ValvePak; using ValveResourceFormat; using ValveResourceFormat.Blocks; using ValveResourceFormat.IO; using ValveResourceFormat.ResourceTypes; using ValveResourceFormat.ToolsAssetInfo; namespace Decompiler { [Command(Name = "vrf_decompiler", Description = "A test bed command line interface for the VRF library")] [VersionOptionFromMember(MemberName = nameof(GetVersion))] public class Decompiler { private readonly Dictionary<string, uint> OldPakManifest = new(); private readonly Dictionary<string, ResourceStat> stats = new(); private readonly Dictionary<string, string> uniqueSpecialDependancies = new(); private readonly object ConsoleWriterLock = new(); private int CurrentFile; private int TotalFiles; [Required] [Option("-i|--input", "Input file to be processed. With no additional arguments, a summary of the input(s) will be displayed.", CommandOptionType.SingleValue)] public string InputFile { get; private set; } [Option("--recursive", "If specified and given input is a folder, all sub directories will be scanned too.", CommandOptionType.NoValue)] public bool RecursiveSearch { get; private set; } [Option("-o|--output", "Writes DATA output to file.", CommandOptionType.SingleValue)] public string OutputFile { get; private set; } [Option("-a|--all", "Prints the content of each resource block in the file.", CommandOptionType.NoValue)] public bool PrintAllBlocks { get; } [Option("-b|--block", "Print the content of a specific block. Specify the block via its 4CC name - case matters! (eg. DATA, RERL, REDI, NTRO).", CommandOptionType.SingleValue)] public string BlockToPrint { get; } [Option("--stats", "Collect stats on all input files and then print them. (This is testing VRF over all files at once)", CommandOptionType.NoValue)] public bool CollectStats { get; } [Option("--threads", "If more than 1, files will be processed concurrently.", CommandOptionType.SingleValue)] public int MaxParallelismThreads { get; } = 1; [Option("--vpk_dir", "Write a file with files in given VPK and their CRC.", CommandOptionType.NoValue)] public bool OutputVPKDir { get; } [Option("--vpk_verify", "Verify checksums and signatures.", CommandOptionType.NoValue)] public bool VerifyVPKChecksums { get; } [Option("--vpk_cache", "Use cached VPK manifest to keep track of updates. Only changed files will be written to disk.", CommandOptionType.NoValue)] public bool CachedManifest { get; } [Option("-d|--vpk_decompile", "Decompile supported files", CommandOptionType.NoValue)] public bool Decompile { get; } [Option("-e|--vpk_extensions", "File extension(s) filter, example: \"vcss_c,vjs_c,vxml_c\"", CommandOptionType.SingleValue)] public string ExtFilter { get; } [Option("-f|--vpk_filepath", "File path filter, example: panorama\\ or \"panorama\\\\\"", CommandOptionType.SingleValue)] public string FileFilter { get; private set; } [Option("-l|--vpk_list", "Lists all resources in given VPK. File extension and path filters apply.", CommandOptionType.NoValue)] public bool ListResources { get; } [Option("--gltf_export_format", "Exports meshes/models in given glTF format. Must be either 'gltf' (default) or 'glb'", CommandOptionType.SingleValue)] public string GltfExportFormat { get; } = "gltf"; [Option("--gltf_export_materials", "Whether to export materials during glTF exports (warning: slow!)", CommandOptionType.NoValue)] public bool GltfExportMaterials { get; } private string[] ExtFilterList; private bool IsInputFolder; // This decompiler is a test bed for our library, // don't expect to see any quality code in here public static int Main(string[] args) { CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; return CommandLineApplication.Execute<Decompiler>(args); } private int OnExecute() { InputFile = Path.GetFullPath(InputFile); if (OutputFile != null) { OutputFile = Path.GetFullPath(OutputFile); OutputFile = FixPathSlashes(OutputFile); } if (FileFilter != null) { FileFilter = FixPathSlashes(FileFilter); } if (ExtFilter != null) { ExtFilterList = ExtFilter.Split(','); } if (GltfExportFormat != "gltf" && GltfExportFormat != "glb") { Console.Error.WriteLine("glTF export format must be either 'gltf' or 'glb'."); return 1; } var paths = new List<string>(); if (Directory.Exists(InputFile)) { if (OutputFile != null && File.Exists(OutputFile)) { Console.Error.WriteLine("Output path is an existing file, but input is a folder."); return 1; } IsInputFolder = true; var dirs = Directory .EnumerateFiles(InputFile, "*.*", RecursiveSearch ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly) .Where(s => { if (ExtFilterList != null) { foreach (var ext in ExtFilterList) { if (s.EndsWith(ext, StringComparison.Ordinal)) { return true; } } return false; } return s.EndsWith("_c", StringComparison.Ordinal) || s.EndsWith(".vcs", StringComparison.Ordinal); }) .ToList(); if (RecursiveSearch && CollectStats) { var vpkRegex = new Regex(@"_[0-9]{3}\.vpk$"); var vpks = Directory .EnumerateFiles(InputFile, "*.vpk", SearchOption.AllDirectories) .Where(s => !vpkRegex.IsMatch(s)); dirs.AddRange(vpks); } if (!dirs.Any()) { Console.Error.WriteLine( "Unable to find any \"_c\" compiled files in \"{0}\" folder.{1}", InputFile, RecursiveSearch ? " Did you mean to include --recursive parameter?" : string.Empty); return 1; } paths.AddRange(dirs); } else if (File.Exists(InputFile)) { if (RecursiveSearch) { Console.Error.WriteLine("File passed in with --recursive option. Either pass in a folder or remove --recursive."); return 1; } paths.Add(InputFile); } else { Console.Error.WriteLine("Input \"{0}\" is not a file or a folder.", InputFile); return 1; } CurrentFile = 0; TotalFiles = paths.Count; if (MaxParallelismThreads > 1) { Console.WriteLine("Will use {0} threads concurrently.", MaxParallelismThreads); var queue = new ConcurrentQueue<string>(paths); var tasks = new List<Task>(); ThreadPool.GetMinThreads(out var workerThreads, out var completionPortThreads); if (workerThreads < MaxParallelismThreads) { ThreadPool.SetMinThreads(MaxParallelismThreads, MaxParallelismThreads); } for (var n = 0; n < MaxParallelismThreads; n++) { tasks.Add(Task.Run(() => { while (queue.TryDequeue(out var path)) { ProcessFile(path); } })); } Task.WhenAll(tasks).GetAwaiter().GetResult(); } else { foreach (var path in paths) { ProcessFile(path); } } if (CollectStats) { Console.WriteLine(); Console.WriteLine("Processed resource stats:"); foreach (var stat in stats.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key)) { var info = string.IsNullOrEmpty(stat.Value.Info) ? string.Empty : $" ({stat.Value.Info})"; Console.WriteLine($"{stat.Value.Count,5} resources of version {stat.Value.Version} and type {stat.Value.Type}{info}"); foreach (var file in stat.Value.FilePaths) { Console.WriteLine($"\t\t{file}"); } } Console.WriteLine(); Console.WriteLine("Unique special dependancies:"); foreach (var stat in uniqueSpecialDependancies) { Console.WriteLine("{0} in {1}", stat.Key, stat.Value); } } return 0; } private void ProcessFile(string path) { using var fs = new FileStream(path, FileMode.Open, FileAccess.Read); ProcessFile(path, fs); } private void ProcessFile(string path, Stream stream, string originalPath = null) { var magicData = new byte[4]; int bytesRead; var totalRead = 0; while ((bytesRead = stream.Read(magicData, totalRead, magicData.Length - totalRead)) != 0) { totalRead += bytesRead; } stream.Seek(-totalRead, SeekOrigin.Current); var magic = BitConverter.ToUInt32(magicData, 0); switch (magic) { case Package.MAGIC: ParseVPK(path, stream); return; case CompiledShader.MAGIC: ParseVCS(path, stream); return; case ToolsAssetInfo.MAGIC2: case ToolsAssetInfo.MAGIC: ParseToolsAssetInfo(path, stream); return; case BinaryKV3.MAGIC3: case BinaryKV3.MAGIC2: case BinaryKV3.MAGIC: ParseKV3(path, stream); return; } var pathExtension = Path.GetExtension(path); if (pathExtension == ".vfont") { ParseVFont(path); return; } lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("[{0}/{1}] {2}", ++CurrentFile, TotalFiles, path); Console.ResetColor(); } var resource = new Resource { FileName = path, }; try { resource.Read(stream); var extension = FileExtract.GetExtension(resource); if (extension == null) { extension = Path.GetExtension(path); if (extension.EndsWith("_c", StringComparison.Ordinal)) { extension = extension[..^2]; } } if (CollectStats) { var id = $"{resource.ResourceType}_{resource.Version}"; var info = string.Empty; switch (resource.ResourceType) { case ResourceType.Texture: var texture = (Texture)resource.DataBlock; info = texture.Format.ToString(); texture.GenerateBitmap(); break; case ResourceType.Sound: info = ((Sound)resource.DataBlock).SoundType.ToString(); break; } if (!string.IsNullOrEmpty(info)) { id = string.Concat(id, "_", info); } lock (stats) { if (stats.ContainsKey(id)) { if (stats[id].Count++ < 10) { stats[id].FilePaths.Add(path); } } else { stats.Add(id, new ResourceStat(resource, info, path)); } } if (resource.EditInfo != null && resource.EditInfo.Structs.ContainsKey(ResourceEditInfo.REDIStruct.SpecialDependencies)) { lock (uniqueSpecialDependancies) { foreach (var dep in ((ValveResourceFormat.Blocks.ResourceEditInfoStructs.SpecialDependencies)resource.EditInfo.Structs[ResourceEditInfo.REDIStruct.SpecialDependencies]).List) { uniqueSpecialDependancies[$"{dep.CompilerIdentifier} \"{dep.String}\""] = path; } } } foreach (var block in resource.Blocks) { block.ToString(); } } if (OutputFile != null) { var data = FileExtract.Extract(resource); var filePath = Path.ChangeExtension(path, extension); if (IsInputFolder) { // I bet this is prone to breaking, is there a better way? filePath = filePath.Remove(0, InputFile.TrimEnd(Path.DirectorySeparatorChar).Length + 1); } else { filePath = Path.GetFileName(filePath); } DumpFile(filePath, data, !IsInputFolder); } } catch (Exception e) { LogException(e, path, originalPath); } if (CollectStats) { return; } //Console.WriteLine("\tInput Path: \"{0}\"", args[fi]); //Console.WriteLine("\tResource Name: \"{0}\"", "???"); //Console.WriteLine("\tID: {0:x16}", 0); lock (ConsoleWriterLock) { // Highlight resource type line if undetermined if (resource.ResourceType == ResourceType.Unknown) { Console.ForegroundColor = ConsoleColor.Cyan; } Console.WriteLine("\tResource Type: {0} [Version {1}] [Header Version: {2}]", resource.ResourceType, resource.Version, resource.HeaderVersion); Console.ResetColor(); } Console.WriteLine("\tFile Size: {0} bytes", resource.FileSize); Console.WriteLine(Environment.NewLine); if (resource.ContainsBlockType(BlockType.RERL)) { Console.WriteLine("--- Resource External Refs: ---"); Console.WriteLine("\t{0,-16} {1,-48}", "Id:", "Resource Name:"); foreach (var res in resource.ExternalReferences.ResourceRefInfoList) { Console.WriteLine("\t{0:X16} {1,-48}", res.Id, res.Name); } } else { Console.WriteLine("--- (No External Resource References Found)"); } Console.WriteLine(Environment.NewLine); // TODO: Resource Deferred Refs: Console.WriteLine("--- (No Deferred Resource References Found)"); Console.WriteLine(Environment.NewLine); Console.WriteLine("--- Resource Blocks: Count {0} ---", resource.Blocks.Count); foreach (var block in resource.Blocks) { Console.WriteLine("\t-- Block: {0,-4} Size: {1,-6} bytes [Offset: {2,6}]", block.Type, block.Size, block.Offset); } if (PrintAllBlocks || !string.IsNullOrEmpty(BlockToPrint)) { Console.WriteLine(Environment.NewLine); foreach (var block in resource.Blocks) { if (!PrintAllBlocks && BlockToPrint != block.Type.ToString()) { continue; } Console.WriteLine("--- Data for block \"{0}\" ---", block.Type); Console.WriteLine(block.ToString()); } } } private void ParseToolsAssetInfo(string path, Stream stream) { var assetsInfo = new ToolsAssetInfo(); try { assetsInfo.Read(stream); if (OutputFile != null) { var fileName = Path.GetFileName(path); fileName = Path.ChangeExtension(fileName, "txt"); DumpFile(fileName, assetsInfo.ToString(), true); } else { Console.WriteLine(assetsInfo.ToString()); } } catch (Exception e) { LogException(e, path); } } private void ParseVCS(string path, Stream stream) { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("--- Loading shader file \"{0}\" ---", path); Console.ResetColor(); } var shader = new CompiledShader(); try { shader.Read(path, stream); } catch (Exception e) { LogException(e, path); } shader.Dispose(); } private void ParseVFont(string path) // TODO: Accept Stream { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("--- Loading font file \"{0}\" ---", path); Console.ResetColor(); } var font = new ValveFont(); try { var output = font.Read(path); if (OutputFile != null) { var fileName = Path.GetFileName(path); fileName = Path.ChangeExtension(fileName, "ttf"); DumpFile(fileName, output, true); } } catch (Exception e) { LogException(e, path); } } private void ParseKV3(string path, Stream stream) { var kv3 = new BinaryKV3(); try { using (var binaryReader = new BinaryReader(stream)) { kv3.Size = (uint)stream.Length; kv3.Read(binaryReader, null); } Console.WriteLine(kv3.ToString()); } catch (Exception e) { LogException(e, path); } } private void ParseVPK(string path, Stream stream) { lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("--- Listing files in package \"{0}\" ---", path); Console.ResetColor(); } var package = new Package(); package.SetFileName(path); try { package.Read(stream); } catch (Exception e) { LogException(e, path); return; } if (VerifyVPKChecksums) { try { package.VerifyHashes(); Console.WriteLine("VPK verification succeeded"); } catch (Exception e) { LogException(e, path); } return; } if (OutputFile == null) { Console.WriteLine("--- Files in package:"); var orderedEntries = package.Entries.OrderByDescending(x => x.Value.Count).ThenBy(x => x.Key).ToList(); if (ExtFilterList != null) { orderedEntries = orderedEntries.Where(x => ExtFilterList.Contains(x.Key)).ToList(); } else if (CollectStats) { orderedEntries = orderedEntries.Where(x => x.Key.EndsWith("_c", StringComparison.Ordinal)).ToList(); } if (ListResources) { var listEntries = orderedEntries.SelectMany(x => x.Value); foreach (var entry in listEntries) { var filePath = FixPathSlashes(entry.GetFullPath()); if (FileFilter != null && !filePath.StartsWith(FileFilter, StringComparison.Ordinal)) { continue; } Console.WriteLine("\t{0}", filePath); } return; } if (CollectStats) { TotalFiles += orderedEntries.Sum(x => x.Value.Count); } foreach (var entry in orderedEntries) { Console.WriteLine("\t{0}: {1} files", entry.Key, entry.Value.Count); if (CollectStats) { foreach (var file in entry.Value) { package.ReadEntry(file, out var output); using var entryStream = new MemoryStream(output); ProcessFile(file.GetFullPath(), entryStream, path); } } } } else { Console.WriteLine("--- Dumping decompiled files..."); var manifestPath = string.Concat(path, ".manifest.txt"); if (CachedManifest && File.Exists(manifestPath)) { var file = new StreamReader(manifestPath); string line; while ((line = file.ReadLine()) != null) { var split = line.Split(new[] { ' ' }, 2); if (split.Length == 2) { OldPakManifest.Add(split[1], uint.Parse(split[0], CultureInfo.InvariantCulture)); } } file.Close(); } foreach (var type in package.Entries) { DumpVPK(package, type.Key); } if (CachedManifest) { using var file = new StreamWriter(manifestPath); foreach (var hash in OldPakManifest) { if (package.FindEntry(hash.Key) == null) { Console.WriteLine("\t{0} no longer exists in VPK", hash.Key); } file.WriteLine("{0} {1}", hash.Value, hash.Key); } } } if (OutputVPKDir) { foreach (var type in package.Entries) { foreach (var file in type.Value) { Console.WriteLine(file); } } } } private void DumpVPK(Package package, string type) { if (ExtFilterList != null && !ExtFilterList.Contains(type)) { return; } if (!package.Entries.ContainsKey(type)) { Console.WriteLine("There are no files of type \"{0}\".", type); return; } var fileLoader = new BasicVpkFileLoader(package); var entries = package.Entries[type]; foreach (var file in entries) { var extension = type; var filePath = FixPathSlashes(file.GetFullPath()); if (FileFilter != null && !filePath.StartsWith(FileFilter, StringComparison.Ordinal)) { continue; } if (OutputFile != null) { if (CachedManifest && OldPakManifest.TryGetValue(filePath, out var oldCrc32) && oldCrc32 == file.CRC32) { continue; } OldPakManifest[filePath] = file.CRC32; } Console.WriteLine("\t[archive index: {0:D3}] {1}", file.ArchiveIndex, filePath); package.ReadEntry(file, out var output); if (type.EndsWith("_c", StringComparison.Ordinal) && Decompile) { using var resource = new Resource { FileName = filePath, }; using var memory = new MemoryStream(output); try { resource.Read(memory); extension = FileExtract.GetExtension(resource) ?? type[..^2]; // TODO: Hook this up in FileExtract if (resource.ResourceType == ResourceType.Mesh || resource.ResourceType == ResourceType.Model) { var outputExtension = GltfExportFormat; var outputFile = Path.Combine(OutputFile, Path.ChangeExtension(filePath, outputExtension)); Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); var exporter = new GltfModelExporter { ExportMaterials = GltfExportMaterials, ProgressReporter = new Progress<string>(progress => Console.WriteLine($"--- {progress}")), FileLoader = fileLoader }; if (resource.ResourceType == ResourceType.Mesh) { exporter.ExportToFile(file.GetFileName(), outputFile, new Mesh(resource)); } else if (resource.ResourceType == ResourceType.Model) { exporter.ExportToFile(file.GetFileName(), outputFile, (Model)resource.DataBlock); } continue; } output = FileExtract.Extract(resource).ToArray(); } catch (Exception e) { LogException(e, filePath, package.FileName); } } if (OutputFile != null) { if (type != extension) { filePath = Path.ChangeExtension(filePath, extension); } DumpFile(filePath, output); } } } private void DumpFile(string path, Span<byte> data, bool useOutputAsFullPath = false) { var outputFile = useOutputAsFullPath ? Path.GetFullPath(OutputFile) : Path.Combine(OutputFile, path); Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); File.WriteAllBytes(outputFile, data.ToArray()); Console.WriteLine("--- Dump written to \"{0}\"", outputFile); } private void DumpFile(string path, string data, bool useOutputAsFullPath = false) { var outputFile = useOutputAsFullPath ? Path.GetFullPath(OutputFile) : Path.Combine(OutputFile, path); Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); File.WriteAllText(outputFile, data); Console.WriteLine("--- Dump written to \"{0}\"", outputFile); } private void LogException(Exception e, string path, string parentPath = null) { var exceptionsFileName = CollectStats ? $"exceptions{Path.GetExtension(path)}.txt" : "exceptions.txt"; lock (ConsoleWriterLock) { Console.ForegroundColor = ConsoleColor.Cyan; if (parentPath == null) { Console.Error.WriteLine($"File: {path}\n{e}"); File.AppendAllText(exceptionsFileName, $"---------------\nFile: {path}\nException: {e}\n\n"); } else { Console.Error.WriteLine($"File: {path} (parent: {parentPath})\n{e}"); File.AppendAllText(exceptionsFileName, $"---------------\nParent file: {parentPath}\nFile: {path}\nException: {e}\n\n"); } Console.ResetColor(); } } private static string FixPathSlashes(string path) { path = path.Replace('\\', '/'); if (Path.DirectorySeparatorChar != '/') { path = path.Replace('/', Path.DirectorySeparatorChar); } return path; } private static string GetVersion() { var info = new StringBuilder(); info.Append("VRF Version: "); info.AppendLine(typeof(Decompiler).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion); info.Append("Runtime: "); info.AppendLine(RuntimeInformation.FrameworkDescription); info.Append("OS: "); info.AppendLine(RuntimeInformation.OSDescription); info.AppendLine("Website: https://vrf.steamdb.info"); info.Append("GitHub: https://github.com/SteamDatabase/ValveResourceFormat"); return info.ToString(); } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.IMAP.Server { /// <summary> /// Provides data to event GetMessageItems. /// </summary> public class IMAP_eArgs_MessageItems { private IMAP_Session m_pSession = null; private IMAP_Message m_pMessageInfo = null; private IMAP_MessageItems_enum m_MessageItems = IMAP_MessageItems_enum.Message; private bool m_CloseMessageStream = true; private Stream m_MessageStream = null; private long m_MessageStartOffset = 0; private byte[] m_Header = null; private string m_Envelope = null; private string m_BodyStructure = null; private bool m_MessageExists = true; /// <summary> /// Default constructor. /// </summary> /// <param name="session">Reference to current IMAP session.</param> /// <param name="messageInfo">Message info what message items to get.</param> /// <param name="messageItems">Specifies message items what must be filled.</param> public IMAP_eArgs_MessageItems(IMAP_Session session,IMAP_Message messageInfo,IMAP_MessageItems_enum messageItems) { m_pSession = session; m_pMessageInfo = messageInfo; m_MessageItems = messageItems; } /// <summary> /// Default deconstructor. /// </summary> ~IMAP_eArgs_MessageItems() { Dispose(); } #region method Dispose /// <summary> /// Clean up any resources being used. /// </summary> public void Dispose() { if(m_CloseMessageStream && m_MessageStream != null){ m_MessageStream.Dispose(); m_MessageStream = null; } } #endregion #region internal method Validate /// <summary> /// Checks that all required data items are provided, if not throws exception. /// </summary> internal void Validate() { if((m_MessageItems & IMAP_MessageItems_enum.BodyStructure) != 0 && m_BodyStructure == null){ throw new Exception("IMAP BODYSTRUCTURE is required, but not provided to IMAP server component !"); } if((m_MessageItems & IMAP_MessageItems_enum.Envelope) != 0 && m_Envelope == null){ throw new Exception("IMAP ENVELOPE is required, but not provided to IMAP server component !"); } if((m_MessageItems & IMAP_MessageItems_enum.Header) != 0 && m_Header == null){ throw new Exception("Message header is required, but not provided to IMAP server component !"); } if((m_MessageItems & IMAP_MessageItems_enum.Message) != 0 && m_MessageStream == null){ throw new Exception("Full message is required, but not provided to IMAP server component !"); } } #endregion #region Properties Implementation /// <summary> /// Gets reference to current IMAP session. /// </summary> public IMAP_Session Session { get{ return m_pSession; } } /// <summary> /// Gets message info what message items to get. /// </summary> public IMAP_Message MessageInfo { get{ return m_pMessageInfo; } } /// <summary> /// Gets what message items must be filled. /// </summary> public IMAP_MessageItems_enum MessageItems { get{ return m_MessageItems; } } /// <summary> /// Gets or sets if message stream is closed automatically if all actions on it are completed. /// Default value is true. /// </summary> public bool CloseMessageStream { get{ return m_CloseMessageStream; } set{ m_CloseMessageStream = value; } } /// <summary> /// Gets or sets message stream. When setting this property Stream position must be where message begins. /// Fill this property only if IMAP_MessageItems_enum.Message flag is specified. /// </summary> public Stream MessageStream { get{ if(m_MessageStream != null){ m_MessageStream.Position = m_MessageStartOffset; } return m_MessageStream; } set{ if(value == null){ throw new ArgumentNullException("Property MessageStream value can't be null !"); } if(!value.CanSeek){ throw new Exception("Stream must support seeking !"); } m_MessageStream = value; m_MessageStartOffset = m_MessageStream.Position; } } /// <summary> /// Gets message size in bytes. /// </summary> public long MessageSize { get{ if(m_MessageStream == null){ throw new Exception("You must set MessageStream property first to use this property !"); } else{ return m_MessageStream.Length - m_MessageStream.Position; } } } /// <summary> /// Gets or sets message main header. /// Fill this property only if IMAP_MessageItems_enum.Header flag is specified. /// </summary> public byte[] Header { get{ return m_Header; } set{ if(value == null){ throw new ArgumentNullException("Property Header value can't be null !"); } m_Header = value; } } /// <summary> /// Gets or sets IMAP ENVELOPE string. /// Fill this property only if IMAP_MessageItems_enum.Envelope flag is specified. /// </summary> public string Envelope { get{ return m_Envelope; } set{ if(value == null){ throw new ArgumentNullException("Property Envelope value can't be null !"); } m_Envelope = value; } } /// <summary> /// Gets or sets IMAP BODYSTRUCTURE string. /// Fill this property only if IMAP_MessageItems_enum.BodyStructure flag is specified. /// </summary> public string BodyStructure { get{ return m_BodyStructure; } set{ if(value == null){ throw new ArgumentNullException("Property BodyStructure value can't be null !"); } m_BodyStructure = value; } } /// <summary> /// Gets or sets if message exists. Set this false, if message actually doesn't exist any more. /// </summary> public bool MessageExists { get{ return m_MessageExists; } set{ m_MessageExists = value; } } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Sql.Database.Model; using Microsoft.Azure.Commands.Sql.Database.Services; using Microsoft.Azure.Commands.Sql.ElasticPool.Model; using Microsoft.Azure.Commands.Sql.Server.Adapter; using Microsoft.Azure.Commands.Sql.Services; using Microsoft.Azure.Management.Sql.Models; using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Commands.Common.Authentication.Abstractions; using DatabaseEdition = Microsoft.Azure.Commands.Sql.Database.Model.DatabaseEdition; namespace Microsoft.Azure.Commands.Sql.ElasticPool.Services { /// <summary> /// Adapter for ElasticPool operations /// </summary> public class AzureSqlElasticPoolAdapter { /// <summary> /// Gets or sets the AzureEndpointsCommunicator which has all the needed management clients /// </summary> private AzureSqlElasticPoolCommunicator Communicator { get; set; } /// <summary> /// Gets or sets the Azure profile /// </summary> public IAzureContext Context { get; set; } /// <summary> /// Gets or sets the Azure Subscription /// </summary> private IAzureSubscription _subscription { get; set; } /// <summary> /// Constructs a database adapter /// </summary> /// <param name="profile">The current azure profile</param> /// <param name="subscription">The current azure subscription</param> public AzureSqlElasticPoolAdapter(IAzureContext context) { _subscription = context.Subscription; Context = context; Communicator = new AzureSqlElasticPoolCommunicator(Context); } /// <summary> /// Gets an Azure Sql Database ElasticPool by name. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the Azure Sql Database ElasticPool</param> /// <returns>The Azure Sql Database ElasticPool object</returns> internal AzureSqlElasticPoolModel GetElasticPool(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.Get(resourceGroupName, serverName, poolName); return CreateElasticPoolModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure Sql Databases ElasticPool. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlElasticPoolModel> ListElasticPools(string resourceGroupName, string serverName) { var resp = Communicator.List(resourceGroupName, serverName); return resp.Select((db) => { return CreateElasticPoolModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Creates or updates an Azure Sql Database ElasticPool. /// </summary> /// <param name="resourceGroup">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="model">The input parameters for the create/update operation</param> /// <returns>The upserted Azure Sql Database ElasticPool</returns> internal AzureSqlElasticPoolModel UpsertElasticPool(AzureSqlElasticPoolModel model) { var resp = Communicator.CreateOrUpdate(model.ResourceGroupName, model.ServerName, model.ElasticPoolName, new Management.Sql.Models.ElasticPool { Location = model.Location, Tags = model.Tags, DatabaseDtuMax = model.DatabaseDtuMax, DatabaseDtuMin = model.DatabaseDtuMin, Edition = model.Edition.ToString(), Dtu = model.Dtu, StorageMB = model.StorageMB, ZoneRedundant = model.ZoneRedundant }); return CreateElasticPoolModelFromResponse(model.ResourceGroupName, model.ServerName, resp); } /// <summary> /// Deletes a database /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="databaseName">The name of the Azure Sql Database to delete</param> public void RemoveElasticPool(string resourceGroupName, string serverName, string databaseName) { Communicator.Remove(resourceGroupName, serverName, databaseName); } /// <summary> /// Gets a database in an elastic pool /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the Azure Sql Database ElasticPool</param> /// <param name="databaseName">The name of the database</param> /// <returns></returns> public AzureSqlDatabaseModel GetElasticPoolDatabase(string resourceGroupName, string serverName, string poolName, string databaseName) { var resp = Communicator.GetDatabase(resourceGroupName, serverName, poolName, databaseName); return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, resp); } /// <summary> /// Gets a list of Azure Sql Databases in an ElasticPool. /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the elastic pool the database are in</param> /// <returns>A list of database objects</returns> internal ICollection<AzureSqlDatabaseModel> ListElasticPoolDatabases(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.ListDatabases(resourceGroupName, serverName, poolName); return resp.Select((db) => { return AzureSqlDatabaseAdapter.CreateDatabaseModelFromResponse(resourceGroupName, serverName, db); }).ToList(); } /// <summary> /// Gets a list of Elastic Pool Activity /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the elastic pool</param> /// <returns>A list of Elastic Pool Activities</returns> internal IList<AzureSqlElasticPoolActivityModel> GetElasticPoolActivity(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.ListActivity(resourceGroupName, serverName, poolName); return resp.Select((activity) => { return CreateActivityModelFromResponse(activity); }).ToList(); } /// <summary> /// Gets a list of Elastic Pool Database Activity /// </summary> /// <param name="resourceGroupName">The name of the resource group</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="poolName">The name of the elastic pool</param> /// <returns>A list of Elastic Pool Database Activities</returns> internal IList<AzureSqlDatabaseActivityModel> ListElasticPoolDatabaseActivity(string resourceGroupName, string serverName, string poolName) { var resp = Communicator.ListDatabaseActivity(resourceGroupName, serverName, poolName); return resp.Select((activity) => { return CreateDatabaseActivityModelFromResponse(activity); }).ToList(); } /// <summary> /// Converts a model received from the server to a powershell model /// </summary> /// <param name="model">The model to transform</param> /// <returns>The transformed model</returns> private AzureSqlDatabaseActivityModel CreateDatabaseActivityModelFromResponse(ElasticPoolDatabaseActivity model) { AzureSqlDatabaseActivityModel activity = new AzureSqlDatabaseActivityModel(); //activity.CurrentElasticPoolName = model.Properties.CurrentElasticPoolName; //activity.CurrentServiceObjectiveName = model.Properties.CurrentServiceObjectiveName; //activity.DatabaseName = model.Properties.DatabaseName; //activity.EndTime = model.Properties.EndTime; //activity.ErrorCode = model.Properties.ErrorCode; //activity.ErrorMessage = model.Properties.ErrorMessage; //activity.ErrorSeverity = model.Properties.ErrorSeverity; //activity.Operation = model.Properties.Operation; //activity.OperationId = model.Properties.OperationId; //activity.PercentComplete = model.Properties.PercentComplete; //activity.RequestedElasticPoolName = model.Properties.RequestedElasticPoolName; //activity.RequestedServiceObjectiveName = model.Properties.RequestedServiceObjectiveName; //activity.ServerName = model.Properties.ServerName; //activity.StartTime = model.Properties.StartTime; //activity.State = model.Properties.State; return activity; } /// <summary> /// Converts a ElascitPoolAcitivy model to the powershell model. /// </summary> /// <param name="model">The model from the service</param> /// <returns>The converted model</returns> private AzureSqlElasticPoolActivityModel CreateActivityModelFromResponse(ElasticPoolActivity model) { AzureSqlElasticPoolActivityModel activity = new AzureSqlElasticPoolActivityModel { ElasticPoolName = model.ElasticPoolName, EndTime = model.EndTime, ErrorCode = model.ErrorCode, ErrorMessage = model.ErrorMessage, ErrorSeverity = model.ErrorSeverity, Operation = model.Operation, OperationId = model.OperationId, PercentComplete = model.PercentComplete, RequestedDatabaseDtuMax = model.RequestedDatabaseDtuMax, RequestedDatabaseDtuMin = model.RequestedDatabaseDtuMin, RequestedDtu = model.RequestedDtu, RequestedElasticPoolName = model.RequestedElasticPoolName, RequestedStorageLimitInGB = model.RequestedStorageLimitInGB, ServerName = model.ServerName, StartTime = model.StartTime, State = model.State }; return activity; } /// <summary> /// Gets the Location of the server. /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the server</param> /// <returns></returns> public string GetServerLocation(string resourceGroupName, string serverName) { AzureSqlServerAdapter serverAdapter = new AzureSqlServerAdapter(Context); var server = serverAdapter.GetServer(resourceGroupName, serverName); return server.Location; } /// <summary> /// Converts the response from the service to a powershell database object /// </summary> /// <param name="resourceGroupName">The resource group the server is in</param> /// <param name="serverName">The name of the Azure Sql Database Server</param> /// <param name="pool">The service response</param> /// <returns>The converted model</returns> private AzureSqlElasticPoolModel CreateElasticPoolModelFromResponse(string resourceGroup, string serverName, Management.Sql.Models.ElasticPool pool) { DatabaseEdition edition = DatabaseEdition.None; Enum.TryParse<DatabaseEdition>(pool.Edition, out edition); AzureSqlElasticPoolModel model = new AzureSqlElasticPoolModel { ResourceId = pool.Id, ResourceGroupName = resourceGroup, ServerName = serverName, ElasticPoolName = pool.Name, CreationDate = pool.CreationDate ?? DateTime.MinValue, DatabaseDtuMax = pool.DatabaseDtuMax.Value, DatabaseDtuMin = pool.DatabaseDtuMin.Value, Dtu = pool.Dtu, State = pool.State, StorageMB = pool.StorageMB, Tags = TagsConversionHelper.CreateTagDictionary(TagsConversionHelper.CreateTagHashtable(pool.Tags), false), Location = pool.Location, Edition = edition, ZoneRedundant = pool.ZoneRedundant }; return model; } } }
using System; using NUnit.Framework; using Raksha.Crypto; using Raksha.Crypto.Digests; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Crypto { /** * standard vector test for MD2 * from RFC1319 by B.Kaliski of RSA Laboratories April 1992 * */ [TestFixture] public class MD2DigestTest : ITest { static private string testVec1 = ""; static private string resVec1 = "8350e5a3e24c153df2275c9f80692773"; static private string testVec2 = "61"; static private string resVec2 = "32ec01ec4a6dac72c0ab96fb34c0b5d1"; static private string testVec3 = "616263"; static private string resVec3 = "da853b0d3f88d99b30283a69e6ded6bb"; static private string testVec4 = "6d65737361676520646967657374"; static private string resVec4 = "ab4f496bfb2a530b219ff33031fe06b0"; static private string testVec5 = "6162636465666768696a6b6c6d6e6f707172737475767778797a"; static private string resVec5 = "4e8ddff3650292ab5a4108c3aa47940b"; static private string testVec6 = "4142434445464748494a4b4c4d4e4f505152535455565758595a6162636465666768696a6b6c6d6e6f707172737475767778797a30313233343536373839"; static private string resVec6 = "da33def2a42df13975352846c30338cd"; static private string testVec7 = "3132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930"; static private string resVec7 = "d5976f79d83d3a0dc9806c3c66f3efd8"; public string Name { get { return "MD2"; } } public ITestResult Perform() { IDigest digest = new MD2Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; string resStr; // // test 1 // byte[] bytes = Hex.Decode(testVec1); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec1.Equals(resStr)) { return new SimpleTestResult(false, "MD2 failing standard vector test 1" + SimpleTest.NewLine + " expected: " + resVec1 + SimpleTest.NewLine + " got : " + resStr); } // // test 2 // bytes = Hex.Decode(testVec2); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec2.Equals(resStr)) { return new SimpleTestResult(false, "MD2 failing standard vector test 2" + SimpleTest.NewLine + " expected: " + resVec2 + SimpleTest.NewLine + " got : " + resStr); } // // test 3 // bytes = Hex.Decode(testVec3); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec3.Equals(resStr)) { return new SimpleTestResult(false, "MD2 failing standard vector test 3" + SimpleTest.NewLine + " expected: " + resVec3 + SimpleTest.NewLine + " got : " + resStr); } // // test 4 // bytes = Hex.Decode(testVec4); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec4.Equals(resStr)) { return new SimpleTestResult(false, "MD2 failing standard vector test 4" + SimpleTest.NewLine + " expected: " + resVec4 + SimpleTest.NewLine + " got : " + resStr); } // // test 5 // bytes = Hex.Decode(testVec5); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec5.Equals(resStr)) { return new SimpleTestResult(false, //System.err.println( "MD2 failing standard vector test 5" + SimpleTest.NewLine + " expected: " + resVec5 + SimpleTest.NewLine + " got : " + resStr); } // // test 6 // bytes = Hex.Decode(testVec6); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec6.Equals(resStr)) { return new SimpleTestResult(false, "MD2 failing standard vector test 6" + SimpleTest.NewLine + " expected: " + resVec6 + SimpleTest.NewLine + " got : " + resStr); } // // test 7 // bytes = Hex.Decode(testVec7); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); resStr = Hex.ToHexString(resBuf); if (!resVec7.Equals(resStr)) { return new SimpleTestResult(false, "MD2 failing standard vector test 7" + SimpleTest.NewLine + " expected: " + resVec7 + SimpleTest.NewLine + " got : " + resStr); } return new SimpleTestResult(true, Name + ": Okay"); } public static void Main( string[] args) { ITest test = new MD2DigestTest(); ITestResult result = test.Perform(); Console.WriteLine(result); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.Serialization.JsonFx; using Pathfinding.Serialization; namespace Pathfinding { /** Basic point graph. * \ingroup graphs * The List graph is the most basic graph structure, it consists of a number of interconnected points in space, waypoints or nodes.\n * The list graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node. * It will then check if any connections between the nodes can be made, first it will check if the distance between the nodes isn't too large ( #maxDistance ) * and then it will check if the axis aligned distance isn't too high. The axis aligned distance, named #limits, * is useful because usually an AI cannot climb very high, but linking nodes far away from each other, * but on the same Y level should still be possible. #limits and #maxDistance won't affect anything if the values are 0 (zero) though. \n * Lastly it will check if there are any obstructions between the nodes using * <a href="http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html">raycasting</a> which can optionally be thick.\n * One thing to think about when using raycasting is to either place the nodes a small * distance above the ground in your scene or to make sure that the ground is not in the raycast \a mask to avoid the raycast from hitting the ground.\n * \note Does not support linecast because of obvious reasons. * \shadowimage{pointgraph_graph.png} \shadowimage{pointgraph_inspector.png} */ [JsonOptIn] public class PointGraph : NavGraph { [JsonMember] /** Childs of this transform are treated as nodes */ public Transform root; [JsonMember] /** If no #root is set, all nodes with the tag is used as nodes */ public string searchTag; [JsonMember] /** Max distance for a connection to be valid. * The value 0 (zero) will be read as infinity and thus all nodes not restricted by * other constraints will be added as connections. * * A negative value will disable any neighbours to be added. * It will completely stop the connection processing to be done, so it can save you processing * power if you don't these connections. */ public float maxDistance = 0; [JsonMember] /** Max distance along the axis for a connection to be valid. 0 = infinity */ public Vector3 limits; [JsonMember] /** Use raycasts to check connections */ public bool raycast = true; [JsonMember] /** Use thick raycast */ public bool thickRaycast = false; [JsonMember] /** Thick raycast radius */ public float thickRaycastRadius = 1; [JsonMember] /** Recursively search for childnodes to the #root */ public bool recursive = true; [JsonMember] public bool autoLinkNodes = true; [JsonMember] /** Layer mask to use for raycast */ public LayerMask mask; /** GameObjects which defined the node in the #nodes array. * Entries are permitted to be null in case no GameObject was used to define a node. * * \note Set, but not used at the moment. Does not work after deserialization. */ GameObject[] nodeGameObjects; /** All nodes in this graph. * Note that only the first #nodeCount will be non-null. * * You can also use the GetNodes method to get all nodes. */ public PointNode[] nodes; /** Number of nodes in this graph. * * \warning Do not edit directly */ public int nodeCount; public override void GetNodes (GraphNodeDelegateCancelable del) { if (nodes == null) return; for (int i=0;i<nodeCount && del (nodes[i]);i++) {} } public override NNInfo GetNearest (Vector3 position, NNConstraint constraint, GraphNode hint) { return GetNearestForce (position, constraint); } public override NNInfo GetNearestForce (Vector3 position, NNConstraint constraint) { //Debug.LogError ("This function (GetNearest) is not implemented in the navigation graph generator : Type "+this.GetType ().Name); if (nodes == null) return new NNInfo(); float maxDistSqr = constraint.constrainDistance ? AstarPath.active.maxNearestNodeDistanceSqr : float.PositiveInfinity; float minDist = float.PositiveInfinity; GraphNode minNode = null; float minConstDist = float.PositiveInfinity; GraphNode minConstNode = null; for (int i=0;i<nodeCount;i++) { PointNode node = nodes[i]; float dist = (position-(Vector3)node.position).sqrMagnitude; if (dist < minDist) { minDist = dist; minNode = node; } if (constraint == null || (dist < minConstDist && dist < maxDistSqr && constraint.Suitable (node))) { minConstDist = dist; minConstNode = node; } } NNInfo nnInfo = new NNInfo (minNode); nnInfo.constrainedNode = minConstNode; if (minConstNode != null) { nnInfo.constClampedPosition = (Vector3)minConstNode.position; } else if (minNode != null) { nnInfo.constrainedNode = minNode; nnInfo.constClampedPosition = (Vector3)minNode.position; } return nnInfo; } /** Add a node to the graph at the specified position. * \note Vector3 can be casted to Int3 using (Int3)myVector. */ public PointNode AddNode (Int3 position) { return AddNode ( new PointNode (active), position ); } /** Add a node with the specified type to the graph at the specified position. * \note Vector3 can be casted to Int3 using (Int3)myVector. * * \param nd This must be a node created using T(AstarPath.active) right before the call to this method. * The node parameter is only there because there is no new(AstarPath) constraint on * generic type parameters. */ public T AddNode<T> (T nd, Int3 position) where T : PointNode { if ( nodes == null || nodeCount == nodes.Length ) { PointNode[] nds = new PointNode[nodes != null ? System.Math.Max (nodes.Length+4, nodes.Length*2) : 4]; for ( int i = 0; i < nodeCount; i++ ) nds[i] = nodes[i]; nodes = nds; } //T nd = new T( active );//new PointNode ( active ); nd.SetPosition (position); nd.GraphIndex = graphIndex; nd.Walkable = true; nodes[nodeCount] = nd; nodeCount++; AddToLookup ( nd ); return nd; } /** Recursively counds children of a transform */ public static int CountChildren (Transform tr) { int c = 0; foreach (Transform child in tr) { c++; c+= CountChildren (child); } return c; } /** Recursively adds childrens of a transform as nodes */ public void AddChildren (ref int c, Transform tr) { foreach (Transform child in tr) { (nodes[c] as PointNode).SetPosition ((Int3)child.position); nodes[c].Walkable = true; nodeGameObjects[c] = child.gameObject; c++; AddChildren (ref c,child); } } /** Rebuilds the lookup structure for nodes. * * This is used when #optimizeForSparseGraph is enabled. * * You should call this method every time you move a node in the graph manually and * you are using #optimizeForSparseGraph, otherwise pathfinding might not work correctly. * * \astarpro */ public void RebuildNodeLookup () { // A* Pathfinding Project Pro Only } public void AddToLookup ( PointNode node ) { // A* Pathfinding Project Pro Only } public override void ScanInternal (OnScanStatus statusCallback) { if (root == null) { //If there is no root object, try to find nodes with the specified tag instead GameObject[] gos = GameObject.FindGameObjectsWithTag (searchTag); nodeGameObjects = gos; if (gos == null) { nodes = new PointNode[0]; nodeCount = 0; return; } //Create and set up the found nodes nodes = new PointNode[gos.Length]; nodeCount = nodes.Length; for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active); //CreateNodes (gos.Length); for (int i=0;i<gos.Length;i++) { (nodes[i] as PointNode).SetPosition ((Int3)gos[i].transform.position); nodes[i].Walkable = true; } } else { //Search the root for children and create nodes for them if (!recursive) { nodes = new PointNode[root.childCount]; nodeCount = nodes.Length; for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active); nodeGameObjects = new GameObject[nodes.Length]; int c = 0; foreach (Transform child in root) { (nodes[c] as PointNode).SetPosition ((Int3)child.position); nodes[c].Walkable = true; nodeGameObjects[c] = child.gameObject; c++; } } else { nodes = new PointNode[CountChildren(root)]; nodeCount = nodes.Length; for (int i=0;i<nodes.Length;i++) nodes[i] = new PointNode(active); //CreateNodes (CountChildren (root)); nodeGameObjects = new GameObject[nodes.Length]; int startID = 0; AddChildren (ref startID,root); } } if (maxDistance >= 0) { //To avoid too many allocations, these lists are reused for each node List<PointNode> connections = new List<PointNode>(3); List<uint> costs = new List<uint>(3); //Loop through all nodes and add connections to other nodes for (int i=0;i<nodes.Length;i++) { connections.Clear (); costs.Clear (); PointNode node = nodes[i]; // Only brute force is available in the free version for (int j=0;j<nodes.Length;j++) { if (i == j) continue; PointNode other = nodes[j]; float dist = 0; if (IsValidConnection (node,other,out dist)) { connections.Add (other); /** \todo Is this equal to .costMagnitude */ costs.Add ((uint)Mathf.RoundToInt (dist*Int3.FloatPrecision)); } } node.connections = connections.ToArray(); node.connectionCosts = costs.ToArray(); } } //GC can clear this up now. nodeGameObjects = null; } /** Returns if the connection between \a a and \a b is valid. * Checks for obstructions using raycasts (if enabled) and checks for height differences.\n * As a bonus, it outputs the distance between the nodes too if the connection is valid */ public virtual bool IsValidConnection (GraphNode a, GraphNode b, out float dist) { dist = 0; if (!a.Walkable || !b.Walkable) return false; Vector3 dir = (Vector3)(a.position-b.position); if ( (!Mathf.Approximately (limits.x,0) && Mathf.Abs (dir.x) > limits.x) || (!Mathf.Approximately (limits.y,0) && Mathf.Abs (dir.y) > limits.y) || (!Mathf.Approximately (limits.z,0) && Mathf.Abs (dir.z) > limits.z)) { return false; } dist = dir.magnitude; if (maxDistance == 0 || dist < maxDistance) { if (raycast) { Ray ray = new Ray ((Vector3)a.position,(Vector3)(b.position-a.position)); Ray invertRay = new Ray ((Vector3)b.position,(Vector3)(a.position-b.position)); if (thickRaycast) { if (!Physics.SphereCast (ray,thickRaycastRadius,dist,mask) && !Physics.SphereCast (invertRay,thickRaycastRadius,dist,mask)) { return true; } } else { if (!Physics.Raycast (ray,dist,mask) && !Physics.Raycast (invertRay,dist,mask)) { return true; } } } else { return true; } } return false; } public override void PostDeserialization () { RebuildNodeLookup (); } public override void RelocateNodes (Matrix4x4 oldMatrix, Matrix4x4 newMatrix) { base.RelocateNodes (oldMatrix, newMatrix); RebuildNodeLookup (); } public override void SerializeExtraInfo (GraphSerializationContext ctx) { if (nodes == null) ctx.writer.Write (-1); ctx.writer.Write (nodeCount); for (int i=0;i<nodeCount;i++) { if (nodes[i] == null) ctx.writer.Write (-1); else { ctx.writer.Write (0); nodes[i].SerializeNode(ctx); } } } public override void DeserializeExtraInfo (GraphSerializationContext ctx) { int count = ctx.reader.ReadInt32(); if (count == -1) { nodes = null; return; } nodes = new PointNode[count]; nodeCount = count; for (int i=0;i<nodes.Length;i++) { if (ctx.reader.ReadInt32() == -1) continue; nodes[i] = new PointNode(active); nodes[i].DeserializeNode(ctx); } } } }
// -- FILE ------------------------------------------------------------------ // name : CalendarDateAdd.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.04.04 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace Itenso.TimePeriod { // ------------------------------------------------------------------------ public class CalendarDateAdd : DateAdd { // ---------------------------------------------------------------------- public CalendarDateAdd() : this( new TimeCalendar( new TimeCalendarConfig { EndOffset = TimeSpan.Zero } ) ) { } // CalendarDateAdd // ---------------------------------------------------------------------- public CalendarDateAdd( ITimeCalendar calendar ) { if ( calendar == null ) { throw new ArgumentNullException( "calendar" ); } if ( calendar.StartOffset != TimeSpan.Zero ) { throw new ArgumentOutOfRangeException( "calendar", "start offset" ); } if ( calendar.EndOffset != TimeSpan.Zero ) { throw new ArgumentOutOfRangeException( "calendar", "end offset" ); } this.calendar = calendar; } // CalendarDateAdd // ---------------------------------------------------------------------- public IList<DayOfWeek> WeekDays { get { return weekDays; } } // WeekDays // ---------------------------------------------------------------------- public IList<HourRange> WorkingHours { get { return workingHours; } } // WorkingHours // ---------------------------------------------------------------------- public IList<DayHourRange> WorkingDayHours { get { return workingDayHours; } } // WorkingDayHours // ---------------------------------------------------------------------- public ITimeCalendar Calendar { get { return calendar; } } // Calendar // ---------------------------------------------------------------------- public new ITimePeriodCollection IncludePeriods { get { throw new NotSupportedException(); } } // IncludePeriods // ---------------------------------------------------------------------- public void AddWorkingWeekDays() { weekDays.Add( DayOfWeek.Monday ); weekDays.Add( DayOfWeek.Tuesday ); weekDays.Add( DayOfWeek.Wednesday ); weekDays.Add( DayOfWeek.Thursday ); weekDays.Add( DayOfWeek.Friday ); } // AddWorkingWeekDays // ---------------------------------------------------------------------- public void AddWeekendWeekDays() { weekDays.Add( DayOfWeek.Saturday ); weekDays.Add( DayOfWeek.Sunday ); } // AddWeekendWeekDays // ---------------------------------------------------------------------- public override DateTime? Subtract( DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next ) { if ( weekDays.Count == 0 && ExcludePeriods.Count == 0 && workingHours.Count == 0 ) { return start.Subtract( offset ); } return offset < TimeSpan.Zero ? CalculateEnd( start, offset.Negate(), SeekDirection.Forward, seekBoundaryMode ) : CalculateEnd( start, offset, SeekDirection.Backward, seekBoundaryMode ); } // Subtract // ---------------------------------------------------------------------- public override DateTime? Add( DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next ) { if ( weekDays.Count == 0 && ExcludePeriods.Count == 0 && workingHours.Count == 0 ) { return start.Add( offset ); } return offset < TimeSpan.Zero ? CalculateEnd( start, offset.Negate(), SeekDirection.Backward, seekBoundaryMode ) : CalculateEnd( start, offset, SeekDirection.Forward, seekBoundaryMode ); } // Add // ---------------------------------------------------------------------- protected DateTime? CalculateEnd( DateTime start, TimeSpan offset, SeekDirection seekDirection, SeekBoundaryMode seekBoundaryMode ) { if ( offset < TimeSpan.Zero ) { throw new InvalidOperationException( "time span must be positive" ); } DateTime? endDate = null; DateTime moment = start; TimeSpan? remaining = offset; Week week = new Week( start, calendar ); // search end date, iteraring week by week while ( week != null ) { base.IncludePeriods.Clear(); base.IncludePeriods.AddAll( GetAvailableWeekPeriods( week ) ); endDate = CalculateEnd( moment, remaining.Value, seekDirection, seekBoundaryMode, out remaining ); if ( endDate != null || !remaining.HasValue ) { break; } switch ( seekDirection ) { case SeekDirection.Forward: week = FindNextWeek( week ); if ( week != null ) { moment = week.Start; } break; case SeekDirection.Backward: week = FindPreviousWeek( week ); if ( week != null ) { moment = week.End; } break; } } return endDate; } // CalculateEnd // ---------------------------------------------------------------------- private Week FindNextWeek( Week current ) { if ( ExcludePeriods.Count == 0 ) { return current.GetNextWeek(); } TimeRange limits = new TimeRange( current.End.AddTicks( 1 ), DateTime.MaxValue ); TimeGapCalculator<TimeRange> gapCalculator = new TimeGapCalculator<TimeRange>( calendar ); ITimePeriodCollection remainingPeriods = gapCalculator.GetGaps( ExcludePeriods, limits ); return remainingPeriods.Count > 0 ? new Week( remainingPeriods[ 0 ].Start ) : null; } // FindNextWeek // ---------------------------------------------------------------------- private Week FindPreviousWeek( Week current ) { if ( ExcludePeriods.Count == 0 ) { return current.GetPreviousWeek(); } TimeRange limits = new TimeRange( DateTime.MinValue, current.Start.AddTicks( -1 ) ); TimeGapCalculator<TimeRange> gapCalculator = new TimeGapCalculator<TimeRange>( calendar ); ITimePeriodCollection remainingPeriods = gapCalculator.GetGaps( ExcludePeriods, limits ); return remainingPeriods.Count > 0 ? new Week( remainingPeriods[ remainingPeriods.Count - 1 ].End ) : null; } // FindPreviousWeek // ---------------------------------------------------------------------- protected virtual IEnumerable<ITimePeriod> GetAvailableWeekPeriods( Week week ) { if ( weekDays.Count == 0 && workingHours.Count == 0 && WorkingDayHours.Count == 0 ) { return new TimePeriodCollection { week }; } CalendarPeriodCollectorFilter filter = new CalendarPeriodCollectorFilter(); // days foreach ( DayOfWeek weekDay in weekDays ) { filter.WeekDays.Add( weekDay ); } // hours foreach ( HourRange workingHour in workingHours ) { filter.CollectingHours.Add( workingHour ); } // day hours foreach ( DayHourRange workingDayHour in workingDayHours ) { filter.CollectingDayHours.Add( workingDayHour ); } CalendarPeriodCollector weekCollector = new CalendarPeriodCollector( filter, week, SeekDirection.Forward, calendar ); weekCollector.CollectHours(); return weekCollector.Periods; } // GetAvailableWeekPeriods // ---------------------------------------------------------------------- // members private readonly List<DayOfWeek> weekDays = new List<DayOfWeek>(); private readonly List<HourRange> workingHours = new List<HourRange>(); private readonly List<DayHourRange> workingDayHours = new List<DayHourRange>(); private readonly ITimeCalendar calendar; } // class CalendarDateAdd } // namespace Itenso.TimePeriod // -- EOF -------------------------------------------------------------------
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Remoting; using System.Threading; using System.Threading.Tasks; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Interpreter.Ast; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; namespace Microsoft.IronPythonTools.Interpreter { internal class IronPythonInterpreter : IPythonInterpreter, IDotNetPythonInterpreter, IPythonInterpreterWithProjectReferences { private readonly Dictionary<ObjectIdentityHandle, IMember> _members = new Dictionary<ObjectIdentityHandle, IMember>(); private readonly ConcurrentDictionary<string, IPythonModule> _modules = new ConcurrentDictionary<string, IPythonModule>(); private readonly ConcurrentBag<string> _assemblyLoadSet = new ConcurrentBag<string>(); private readonly HashSet<ProjectReference> _projectReferenceSet = new HashSet<ProjectReference>(); private readonly ConcurrentDictionary<string, XamlProjectEntry> _xamlByFilename = new ConcurrentDictionary<string, XamlProjectEntry>(); private RemoteInterpreterProxy _remote; private DomainUnloader _unloader; private PythonAnalyzer _state; private readonly IronPythonAstInterpreterFactory _factory; private readonly IPythonInterpreter _pythonInterpreter; private readonly IronPythonBuiltinModule _builtinModule; #if DEBUG private int _id; private static int _interpreterCount; #endif public IronPythonInterpreter(IronPythonAstInterpreterFactory factory, IPythonInterpreter pythonInterpreter) { #if DEBUG _id = Interlocked.Increment(ref _interpreterCount); Debug.WriteLine(String.Format("IronPython Interpreter {0} created from {1}", _id, factory.GetType().FullName)); try { Debug.WriteLine(new StackTrace(true).ToString()); } catch (System.Security.SecurityException) { } #endif _factory = factory; _pythonInterpreter = pythonInterpreter; AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver.Instance.CurrentDomain_AssemblyResolve; InitializeRemoteDomain(); try { LoadAssemblies(); } catch { // IronPython not installed in the GAC... } var mod = Remote.ImportBuiltinModule("__builtin__"); var newMod = new IronPythonBuiltinModule(this, mod, "__builtin__"); _modules[newMod.Name] = _builtinModule = newMod; LoadModules(); } private void InitializeRemoteDomain() { var remoteDomain = CreateDomain(out _remote); _unloader = new DomainUnloader(remoteDomain); } private AppDomain CreateDomain(out RemoteInterpreterProxy remoteInterpreter) { // We create a sacrificial domain for loading all of our assemblies into. var ironPythonAssemblyPath = Path.GetDirectoryName(_factory.Configuration.GetWindowsInterpreterPath()); AppDomainSetup setup = new AppDomainSetup(); setup.ShadowCopyFiles = "true"; // We are in ...\Extensions\Microsoft\IronPython Interpreter\2.0 // We need to be able to load assemblies from: // Python Tools for Visual Studio\2.0 // IronPython Interpreter\2.0 // // So setup the application base to be Extensions\Microsoft\, and then add the other 2 dirs to the private bin path. setup.ApplicationBase = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))); setup.PrivateBinPath = Path.GetDirectoryName(typeof(IronPythonInterpreter).Assembly.Location) + ";" + Path.GetDirectoryName(typeof(IPythonFunction).Assembly.Location) + ";" + Path.Combine(ironPythonAssemblyPath, "DLLs") + ";" + ironPythonAssemblyPath; setup.PrivateBinPathProbe = ""; if (Directory.Exists(_factory.Configuration.GetPrefixPath())) { setup.AppDomainInitializer = IronPythonResolver.Initialize; setup.AppDomainInitializerArguments = new[] { _factory.Configuration.GetPrefixPath() }; } var domain = AppDomain.CreateDomain("IronPythonAnalysisDomain", null, setup); using (new RemoteAssemblyResolver(domain, ironPythonAssemblyPath)) { remoteInterpreter = (RemoteInterpreterProxy) domain.CreateInstanceAndUnwrap( typeof(RemoteInterpreterProxy).Assembly.FullName, typeof(RemoteInterpreterProxy).FullName); } #if DEBUG var assertListener = Debug.Listeners["Microsoft.PythonTools.AssertListener"]; if (assertListener != null) { var init = (AssertListenerInitializer)domain.CreateInstanceAndUnwrap( typeof(AssertListenerInitializer).Assembly.FullName, typeof(AssertListenerInitializer).FullName ); init.Initialize(assertListener); } #endif return domain; } #if DEBUG class AssertListenerInitializer : MarshalByRefObject { public AssertListenerInitializer() { } public void Initialize(TraceListener listener) { if (Debug.Listeners[listener.Name] == null) { Debug.Listeners.Add(listener); Debug.Listeners.Remove("Default"); } } } #endif [Serializable] class RemoteAssemblyResolver : IDisposable { private readonly AppDomain _appDomain; private readonly string _ironPythonRootPath; public RemoteAssemblyResolver(AppDomain appDomain, string ironPythonRootPath) { _appDomain = appDomain; _ironPythonRootPath = ironPythonRootPath; _appDomain.AssemblyResolve += AppDomainOnAssemblyResolve; } private Assembly AppDomainOnAssemblyResolve(object sender, ResolveEventArgs args) { var name = new AssemblyName(args.Name).Name; switch (name) { case "IronPython": return AssemblyLoadFrom(Path.Combine(_ironPythonRootPath, "IronPython.dll")); case "IronPython.Modules": return AssemblyLoadFrom(Path.Combine(_ironPythonRootPath, "IronPython.Modules.dll")); case "IronPython.Wpf": return AssemblyLoadFrom(Path.Combine(_ironPythonRootPath, "DLLs", "IronPython.Wpf.dll")); case "Microsoft.Scripting": return AssemblyLoadFrom(Path.Combine(_ironPythonRootPath, "Microsoft.Scripting.dll")); case "Microsoft.Dynamic": return AssemblyLoadFrom(Path.Combine(_ironPythonRootPath, "Microsoft.Dynamic.dll")); default: return null; } } public void Dispose() { _appDomain.AssemblyResolve -= AppDomainOnAssemblyResolve; } private static Assembly AssemblyLoadFrom(string assemblyPath) { try { return Assembly.LoadFrom(assemblyPath); } catch (FileLoadException) { return null; } catch (IOException) { return null; } catch (BadImageFormatException) { return null; } } } class AssemblyResolver { internal static AssemblyResolver Instance = new AssemblyResolver(); public Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (new AssemblyName(args.Name).FullName == typeof(RemoteInterpreterProxy).Assembly.FullName) { return typeof(RemoteInterpreterProxy).Assembly; } return null; } } public RemoteInterpreterProxy Remote { get { return _remote; } } private void LoadModules() { if (!string.IsNullOrEmpty(_factory.Configuration.GetPrefixPath())) { var dlls = PathUtils.GetAbsoluteDirectoryPath(_factory.Configuration.GetPrefixPath(), "DLLs"); if (Directory.Exists(dlls)) { foreach (var dll in PathUtils.EnumerateFiles(dlls, "*.dll", recurse: false)) { try { var assem = Remote.LoadAssemblyFromFileWithPath(dll); if (assem != null) { Remote.AddAssembly(assem); } } catch (Exception ex) { Debug.Fail(ex.ToString()); } } } } foreach (string modName in Remote.GetBuiltinModuleNames()) { try { var mod = Remote.ImportBuiltinModule(modName); if (modName != "__builtin__") { _modules[modName] = new IronPythonModule(this, mod, modName); } } catch { // importing can throw, ignore that module continue; } } } public void Initialize(PythonAnalyzer state) { _pythonInterpreter.Initialize(state); if (_state != null) { _state.SearchPathsChanged -= PythonAnalyzer_SearchPathsChanged; } _state = state; SpecializeClrFunctions(); if (_state != null) { _state.SearchPathsChanged += PythonAnalyzer_SearchPathsChanged; PythonAnalyzer_SearchPathsChanged(_state, EventArgs.Empty); } } private void SpecializeClrFunctions() { // cached for quick checks to see if we're a call to clr.AddReference _state.SpecializeFunction("wpf", "LoadComponent", LoadComponent); _state.SpecializeFunction("clr", "AddReference", (n, u, p, kw) => AddReference(n, null), true); _state.SpecializeFunction("clr", "AddReferenceByPartialName", (n, u, p, kw) => AddReference(n, LoadAssemblyByPartialName), true); _state.SpecializeFunction("clr", "AddReferenceByName", (n, u, p, kw) => AddReference(n, null), true); _state.SpecializeFunction("clr", "AddReferenceToFile", (n, u, p, kw) => AddReference(n, LoadAssemblyFromFile), true); _state.SpecializeFunction("clr", "AddReferenceToFileAndPath", (n, u, p, kw) => AddReference(n, LoadAssemblyFromFileWithPath), true); } private IAnalysisSet LoadComponent(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { if (args.Length != 2 || !(unit.State.Interpreter is IDotNetPythonInterpreter interpreter)) { return AnalysisSet.Empty; } var self = args[0]; var xaml = args[1]; foreach (var arg in xaml) { var strConst = arg.GetConstantValueAsString(); if (string.IsNullOrEmpty(strConst)) { continue; } // process xaml file, add attributes to self string xamlPath = Path.Combine(Path.GetDirectoryName(unit.ProjectEntry.FilePath), strConst); if (_xamlByFilename.TryGetValue(xamlPath, out var xamlProject)) { // TODO: Get existing analysis if it hasn't changed. var analysis = xamlProject.Analysis; if (analysis == null) { xamlProject.Analyze(CancellationToken.None); analysis = xamlProject.Analysis; if (analysis == null) { return self; } } xamlProject.AddDependency(unit.ProjectEntry); var evalUnit = unit.CopyForEval(); // add named objects to instance foreach (var keyValue in analysis.NamedObjects) { var type = keyValue.Value; if (type.Type.UnderlyingType != null) { var ns = (IAnalysisValue)unit.State.GetAnalysisValueFromObjects(interpreter.GetBuiltinType(type.Type.UnderlyingType)); if (ns is IBuiltinClassInfo bci) { ns = bci.Instance; } self.SetMember(node, evalUnit, keyValue.Key, ns.SelfSet); } // TODO: Better would be if SetMember took something other than a node, then we'd // track references w/o this extra effort. foreach (var inst in self) { if (inst is IInstanceInfo instInfo && instInfo.InstanceAttributes != null) { if (instInfo.InstanceAttributes.TryGetValue(keyValue.Key, out var def)) { def.AddAssignment( new EncodedLocation( new LocationInfo(xamlProject.FilePath, xamlProject.DocumentUri, type.LineNumber, type.LineOffset), null ), xamlProject ); } } } } // add references to event handlers foreach (var keyValue in analysis.EventHandlers) { // add reference to methods... var member = keyValue.Value; // TODO: Better would be if SetMember took something other than a node, then we'd // track references w/o this extra effort. foreach (var inst in self) { if (inst is IInstanceInfo instInfo) { var ci = instInfo.ClassInfo; if (ci.Scope.TryGetVariable(keyValue.Key, out var def)) { def.AddReference( new EncodedLocation( new LocationInfo(xamlProject.FilePath, xamlProject.DocumentUri, member.LineNumber, member.LineOffset), null ), xamlProject ); } } } } } } // load component returns self return self; } private void PythonAnalyzer_SearchPathsChanged(object sender, EventArgs e) { switch (_remote.SetAnalysisDirectories(_state.AnalysisDirectories.ToArray())) { case SetAnalysisDirectoriesResult.NoChange: break; case SetAnalysisDirectoriesResult.ModulesChanged: ClearAssemblyLoadSet(); RaiseModuleNamesChanged(); break; case SetAnalysisDirectoriesResult.Reload: // we are unloading an assembly so we need to create a new app domain because the CLR will continue // to return the assemblies that we've already loaded ReloadRemoteDomain(); break; } } private void ClearAssemblyLoadSet() { string asm; while (_assemblyLoadSet.TryTake(out asm)) { } } private void ReloadRemoteDomain() { var oldUnloaded = _unloader; var evt = UnloadingDomain; if (evt != null) { evt(this, EventArgs.Empty); } lock (this) { _members.Clear(); _modules.Clear(); ClearAssemblyLoadSet(); InitializeRemoteDomain(); LoadModules(); } RaiseModuleNamesChanged(); oldUnloaded.Dispose(); } public event EventHandler UnloadingDomain; private ObjectHandle LoadAssemblyByName(string name) { return Remote.LoadAssemblyByName(name); } private ObjectHandle LoadAssemblyByPartialName(string name) { return Remote.LoadAssemblyByPartialName(name); } private ObjectHandle LoadAssemblyFromFile(string name) { return Remote.LoadAssemblyFromFile(name); } private ObjectHandle LoadAssemblyFromFileWithPath(string name) { return Remote.LoadAssemblyFromFileWithPath(name); } /// <summary> /// VS seems to load extensions via Assembly.LoadFrom. When an assembly is being loaded via Assembly.Load the CLR fusion probes privatePath /// set in App.config (devenv.exe.config) first and then tries the code base of the assembly that called Assembly.Load if it was itself loaded via LoadFrom. /// In order to locate IronPython.Modules correctly, the call to Assembly.Load must originate from an assembly in IronPythonTools installation folder. /// Although Microsoft.Scripting is also in that folder it can be loaded first by IronRuby and that causes the Assembly.Load to search in IronRuby's /// installation folder. Adding a reference to IronPython.Modules also makes sure that the assembly is loaded from the same location as IronPythonToolsCore. /// </summary> private static void LoadAssemblies() { GC.KeepAlive(typeof(IronPython.Modules.ArrayModule)); // IronPython.Modules } private static bool IronPythonExistsIn(string/*!*/ dir) { return File.Exists(Path.Combine(dir, "ipy.exe")); } private IAnalysisSet AddReference(Node node, Func<string, ObjectHandle> partialLoader) { // processes a call to clr.AddReference updating project state // so that it contains the newly loaded assembly. var callExpr = node as CallExpression; if (callExpr == null) { return AnalysisSet.Empty; } foreach (var arg in callExpr.Args) { var cexpr = arg.Expression as ConstantExpression; if (cexpr == null || !(cexpr.Value is string || cexpr.Value is AsciiString)) { // can't process this add reference continue; } // TODO: Should we do a .NET reflection only load rather than // relying on the CLR module here? That would prevent any code from // running although at least we don't taint our own modules which // are loaded with this current code. var asmName = cexpr.Value as string; if (asmName == null) { // check for byte string var bytes = cexpr.Value as AsciiString; if (bytes != null) { asmName = bytes.String; } } if (asmName != null && !_assemblyLoadSet.Contains(asmName)) { _assemblyLoadSet.Add(asmName); ObjectHandle asm = null; try { if (partialLoader != null) { asm = partialLoader(asmName); } else { try { asm = LoadAssemblyByName(asmName); } catch { asm = null; } if (asm == null) { asm = LoadAssemblyByPartialName(asmName); } } if (asm == null && _state != null) { foreach (var dir in _state.AnalysisDirectories) { if (!PathUtils.IsValidPath(dir) && !PathUtils.IsValidPath(asmName)) { string path = Path.Combine(dir, asmName); if (File.Exists(path)) { asm = Remote.LoadAssemblyFrom(path); } else if (File.Exists(path + ".dll")) { asm = Remote.LoadAssemblyFrom(path + ".dll"); } else if (File.Exists(path + ".exe")) { asm = Remote.LoadAssemblyFrom(path + ".exe"); } } } } } catch { } if (asm != null && Remote.AddAssembly(asm)) { RaiseModuleNamesChanged(); } } } return AnalysisSet.Empty; } internal void RaiseModuleNamesChanged() { ModuleNamesChanged?.Invoke(this, EventArgs.Empty); } #region IPythonInterpreter Members public IPythonType GetBuiltinType(BuiltinTypeId id) { var res = GetTypeFromType(Remote.GetBuiltinType(id)); if (res == null) { throw new KeyNotFoundException(string.Format("{0} ({1})", id, (int)id)); } return res; } public IList<string> GetModuleNames() { List<string> res = new List<string>(_modules.Keys); res.AddRange(Remote.GetModuleNames()); return res; } public event EventHandler ModuleNamesChanged; public IPythonModule GetModule(string name) { return _modules[name]; } public IPythonModule ImportModule(string name) { if (string.IsNullOrWhiteSpace(name)) { return null; } if (name == _builtinModule?.Name) { return _builtinModule; } if (_modules.TryGetValue(name, out var mod)) { return mod; } var handle = Remote.LookupNamespace(name); if (!handle.IsNull) { mod = MakeObject(handle) as IPythonModule; if (mod != null) { return _modules.GetOrAdd(name, mod); } } var pythonModule = _pythonInterpreter.ImportModule(name); if (pythonModule != null) { _modules.GetOrAdd(name, pythonModule); return pythonModule; } var nameParts = name.Split('.'); if (nameParts.Length > 1 && (mod = ImportModule(nameParts[0])) != null) { for (var i = 1; i < nameParts.Length && mod != null; ++i) { mod = mod.GetMember(IronPythonModuleContext.ShowClrInstance, nameParts[i]) as IPythonModule; } } return _modules.GetOrAdd(name, mod); } public IModuleContext CreateModuleContext() { return new IronPythonModuleContext(); } public Task AddReferenceAsync(ProjectReference reference, CancellationToken cancellationToken = default(CancellationToken)) { switch (reference.Kind) { case ProjectReferenceKind.Assembly: var asmRef = (ProjectAssemblyReference)reference; return Task.Factory.StartNew(() => { if (File.Exists(asmRef.Name)) { if (!Remote.LoadAssemblyReference(asmRef.Name)) { throw new Exception("Failed to load assembly: " + asmRef.Name); } } else { if (!Remote.LoadAssemblyReferenceByName(asmRef.AssemblyName.FullName) && !Remote.LoadAssemblyReferenceByName(asmRef.AssemblyName.Name)) { throw new Exception("Failed to load assembly: " + asmRef.AssemblyName.FullName); } } lock (_projectReferenceSet) { _projectReferenceSet.Add(reference); } // re-analyze clr.AddReference calls w/ new assemblie names ClearAssemblyLoadSet(); // the names haven't changed yet, but we want to re-analyze the clr.AddReference calls, // and then the names may change for real.. RaiseModuleNamesChanged(); }); } return Task.Factory.StartNew(() => { }); } public void RemoveReference(ProjectReference reference) { switch (reference.Kind) { case ProjectReferenceKind.Assembly: var asmRef = (ProjectAssemblyReference)reference; if (Remote.UnloadAssemblyReference(asmRef.Name)) { ReloadRemoteDomain(); lock (_projectReferenceSet) { _projectReferenceSet.Remove(reference); foreach (var prevRef in _projectReferenceSet) { Remote.LoadAssemblyReference(prevRef.Name); } } } break; } } public IEnumerable<ProjectReference> GetReferences() { lock (_projectReferenceSet) { return _projectReferenceSet.ToArray(); } } #endregion internal IPythonType GetTypeFromType(ObjectIdentityHandle type) { if (type.IsNull) { return null; } lock (this) { IMember res; if (!_members.TryGetValue(type, out res)) { _members[type] = res = new IronPythonType(this, type); } return res as IPythonType; } } internal IMember MakeObject(ObjectIdentityHandle obj) { if (obj.IsNull) { return null; } lock (this) { if (_members.TryGetValue(obj, out var res)) { return res; } switch (_remote.GetObjectKind(obj)) { case ObjectKind.Module: res = new IronPythonModule(this, obj); break; case ObjectKind.Type: res = new IronPythonType(this, obj); break; case ObjectKind.ConstructorFunction: res = new IronPythonConstructorFunction(this, _remote.GetConstructorFunctionTargets(obj), GetTypeFromType(_remote.GetConstructorFunctionDeclaringType(obj))); break; case ObjectKind.BuiltinFunction: res = new IronPythonBuiltinFunction(this, obj); break; case ObjectKind.BuiltinMethodDesc: res = new IronPythonBuiltinMethodDescriptor(this, obj); break; case ObjectKind.ReflectedEvent: res = new IronPythonEvent(this, obj); break; case ObjectKind.ReflectedExtensionProperty: res = new IronPythonExtensionProperty(this, obj); break; case ObjectKind.ReflectedField: res = new IronPythonField(this, obj); break; case ObjectKind.ReflectedProperty: res = new IronPythonProperty(this, obj); break; case ObjectKind.TypeGroup: res = new IronPythonTypeGroup(this, obj); break; case ObjectKind.NamespaceTracker: res = new IronPythonNamespace(this, obj); break; case ObjectKind.Constant: res = new IronPythonConstant(this, obj); break; case ObjectKind.ClassMethod: res = new IronPythonGenericMember(this, obj, PythonMemberType.Method); break; case ObjectKind.Method: res = new IronPythonGenericMember(this, obj, PythonMemberType.Method); break; case ObjectKind.PythonTypeSlot: res = new IronPythonGenericMember(this, obj, PythonMemberType.Property); break; case ObjectKind.PythonTypeTypeSlot: res = new IronPythonGenericMember(this, obj, PythonMemberType.Property); break; case ObjectKind.Unknown: res = new PythonObject(this, obj); break; default: throw new InvalidOperationException(); } _members[obj] = res; return res; } } #region IDotNetPythonInterpreter Members public IPythonType GetBuiltinType(Type type) { return GetTypeFromType(Remote.GetBuiltinTypeFromType(type)); } public IProjectEntry AddXamlEntry(string filePath, Uri documentUri) { var entry = new XamlProjectEntry(filePath, documentUri); _xamlByFilename[filePath] = entry; return entry; } #endregion class DomainUnloader : IDisposable { private readonly AppDomain _domain; private bool _isDisposed; public DomainUnloader(AppDomain domain) { _domain = domain; } ~DomainUnloader() { // The CLR doesn't allow unloading an app domain from the finalizer thread, // so instead we unload it from a thread pool thread when we're finalized. ThreadPool.QueueUserWorkItem(Unload); } private void Unload(object state) { try { AppDomain.Unload(_domain); } catch (CannotUnloadAppDomainException) { // if we fail to unload, keep trying by creating a new finalizable object... Debug.Fail("should have unloaded"); new DomainUnloader(_domain); } } #region IDisposable Members public void Dispose() { if (!_isDisposed) { _isDisposed = true; AppDomain.Unload(_domain); GC.SuppressFinalize(this); } } #endregion } #region IDisposable Members public void Dispose() { _pythonInterpreter.Dispose(); var evt = UnloadingDomain; evt?.Invoke(this, EventArgs.Empty); AppDomain.CurrentDomain.AssemblyResolve -= AssemblyResolver.Instance.CurrentDomain_AssemblyResolve; _unloader.Dispose(); #if DEBUG GC.SuppressFinalize(this); #endif } #endregion #if DEBUG ~IronPythonInterpreter() { Debug.WriteLine(String.Format("IronPythonInterpreter leaked {0}", _id)); } #endif } }
using System; using System.Threading.Tasks; using Orleans; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Streams; using Orleans.TestingHost; using Tester; using TestExtensions; using Xunit; namespace UnitTests.StreamingTests { public class PubSubRendezvousGrainTests : OrleansTestingBase, IClassFixture<PubSubRendezvousGrainTests.Fixture> { private readonly Fixture fixture; public class Fixture : BaseTestClusterFixture { protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.AddSiloBuilderConfigurator<SiloHostConfigurator>(); } public class SiloHostConfigurator : ISiloBuilderConfigurator { public void Configure(ISiloHostBuilder hostBuilder) { hostBuilder.AddFaultInjectionMemoryStorage("PubSubStore"); } } } public PubSubRendezvousGrainTests(Fixture fixture) { this.fixture = fixture; } [Fact, TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")] public async Task RegisterConsumerFaultTest() { this.fixture.Logger.Info("************************ RegisterConsumerFaultTest *********************************"); var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace"); var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>( streamId.Guid, keyExtension: streamId.ProviderName + "_" + streamId.Namespace); var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName); // clean call, to make sure everything is happy and pubsub has state. await pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null, null); int consumers = await pubSubGrain.ConsumerCount(streamId); Assert.Equal(1, consumers); // inject fault await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write")); // expect exception when registering a new consumer await Assert.ThrowsAsync<OrleansException>( () => pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null, null)); // pubsub grain should recover and still function await pubSubGrain.RegisterConsumer(GuidId.GetGuidId(Guid.NewGuid()), streamId, null, null); consumers = await pubSubGrain.ConsumerCount(streamId); Assert.Equal(2, consumers); } [Fact, TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")] public async Task UnregisterConsumerFaultTest() { this.fixture.Logger.Info("************************ UnregisterConsumerFaultTest *********************************"); var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace"); var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>( streamId.Guid, keyExtension: streamId.ProviderName + "_" + streamId.Namespace); var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName); // Add two consumers so when we remove the first it does a storage write, not a storage clear. GuidId subscriptionId1 = GuidId.GetGuidId(Guid.NewGuid()); GuidId subscriptionId2 = GuidId.GetGuidId(Guid.NewGuid()); await pubSubGrain.RegisterConsumer(subscriptionId1, streamId, null, null); await pubSubGrain.RegisterConsumer(subscriptionId2, streamId, null, null); int consumers = await pubSubGrain.ConsumerCount(streamId); Assert.Equal(2, consumers); // inject fault await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write")); // expect exception when unregistering a consumer await Assert.ThrowsAsync<OrleansException>( () => pubSubGrain.UnregisterConsumer(subscriptionId1, streamId)); // pubsub grain should recover and still function await pubSubGrain.UnregisterConsumer(subscriptionId1, streamId); consumers = await pubSubGrain.ConsumerCount(streamId); Assert.Equal(1, consumers); // inject clear fault, because removing last consumer should trigger a clear storage call. await faultGrain.AddFaultOnClear(pubSubGrain as GrainReference, new ApplicationException("Write")); // expect exception when unregistering a consumer await Assert.ThrowsAsync<OrleansException>( () => pubSubGrain.UnregisterConsumer(subscriptionId2, streamId)); // pubsub grain should recover and still function await pubSubGrain.UnregisterConsumer(subscriptionId2, streamId); consumers = await pubSubGrain.ConsumerCount(streamId); Assert.Equal(0, consumers); } /// <summary> /// This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension in the producer management calls. /// TODO: Fix rendezvous implementation. /// </summary> /// <returns></returns> [Fact(Skip = "This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension"), TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")] public async Task RegisterProducerFaultTest() { this.fixture.Logger.Info("************************ RegisterProducerFaultTest *********************************"); var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace"); var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>( streamId.Guid, keyExtension: streamId.ProviderName + "_" + streamId.Namespace); var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName); // clean call, to make sure everything is happy and pubsub has state. await pubSubGrain.RegisterProducer(streamId, null); int producers = await pubSubGrain.ProducerCount(streamId); Assert.Equal(1, producers); // inject fault await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write")); // expect exception when registering a new producer await Assert.ThrowsAsync<OrleansException>( () => pubSubGrain.RegisterProducer(streamId, null)); // pubsub grain should recover and still function await pubSubGrain.RegisterProducer(streamId, null); producers = await pubSubGrain.ProducerCount(streamId); Assert.Equal(2, producers); } /// <summary> /// This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension in the producer management calls. /// TODO: Fix rendezvous implementation. /// </summary> [Fact(Skip = "This test fails because the producer must be grain reference which is not implied by the IStreamProducerExtension"), TestCategory("BVT"), TestCategory("Streaming"), TestCategory("PubSub")] public async Task UnregisterProducerFaultTest() { this.fixture.Logger.Info("************************ UnregisterProducerFaultTest *********************************"); var streamId = StreamId.GetStreamId(Guid.NewGuid(), "ProviderName", "StreamNamespace"); var pubSubGrain = this.fixture.GrainFactory.GetGrain<IPubSubRendezvousGrain>( streamId.Guid, keyExtension: streamId.ProviderName + "_" + streamId.Namespace); var faultGrain = this.fixture.GrainFactory.GetGrain<IStorageFaultGrain>(typeof(PubSubRendezvousGrain).FullName); IStreamProducerExtension firstProducer = new DummyStreamProducerExtension(); IStreamProducerExtension secondProducer = new DummyStreamProducerExtension(); // Add two producers so when we remove the first it does a storage write, not a storage clear. await pubSubGrain.RegisterProducer(streamId, firstProducer); await pubSubGrain.RegisterProducer(streamId, secondProducer); int producers = await pubSubGrain.ProducerCount(streamId); Assert.Equal(2, producers); // inject fault await faultGrain.AddFaultOnWrite(pubSubGrain as GrainReference, new ApplicationException("Write")); // expect exception when unregistering a producer await Assert.ThrowsAsync<OrleansException>( () => pubSubGrain.UnregisterProducer(streamId, firstProducer)); // pubsub grain should recover and still function await pubSubGrain.UnregisterProducer(streamId, firstProducer); producers = await pubSubGrain.ProducerCount(streamId); Assert.Equal(1, producers); // inject clear fault, because removing last producers should trigger a clear storage call. await faultGrain.AddFaultOnClear(pubSubGrain as GrainReference, new ApplicationException("Write")); // expect exception when unregistering a consumer await Assert.ThrowsAsync<OrleansException>( () => pubSubGrain.UnregisterProducer(streamId, secondProducer)); // pubsub grain should recover and still function await pubSubGrain.UnregisterProducer(streamId, secondProducer); producers = await pubSubGrain.ConsumerCount(streamId); Assert.Equal(0, producers); } [Serializable] private class DummyStreamProducerExtension : IStreamProducerExtension { private readonly Guid id; public DummyStreamProducerExtension() { id = Guid.NewGuid(); } public Task AddSubscriber(GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { return Task.CompletedTask; } public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId) { return Task.CompletedTask; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((DummyStreamProducerExtension)obj); } public override int GetHashCode() { return id.GetHashCode(); } private bool Equals(DummyStreamProducerExtension other) { return id.Equals(other.id); } } } }
// ************************ ParseSMGroupDeclaration : char ************************ // // Char0 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // 'g' = Char1, default = decline; // Char1 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // 'r' = Char2, default = decline; // Char2 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // 'o' = Char3, default = decline; // Char3 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // 'u' = Char4, default = decline; // Char4 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // 'p' = Char5, default = decline; // Char5 : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // ' ' = accept, '\t' = accept, '\r' = accept, '\n' = accept, default = decline; // ParseSingleQuotes : ParseSingleQuotes ? decline : decline; // ParseDoubleQuotes : ParseDoubleQuotes ? decline : decline; // // // This file was automatically generated from a tool that converted the // above state machine definition into this state machine class. // Any changes to this code will be replaced the next time the code is generated. using System; using System.Collections.Generic; namespace StateMachineParser { public class ParseSMGroupDeclaration { public enum States { Char0 = 0, Char1 = 1, Char2 = 2, Char3 = 3, Char4 = 4, Char5 = 5, ParseSingleQuotes = 6, ParseDoubleQuotes = 7, } private States? state = null; public States? CurrentState { get { return state; } } private char currentCommand; public char CurrentCommand { get { return currentCommand; } } private bool reset = false; private Action<char> onChar0State = null; private Action<char> onChar0Enter = null; private Action<char> onChar0Exit = null; private Action<char> onChar1State = null; private Action<char> onChar1Enter = null; private Action<char> onChar1Exit = null; private Action<char> onChar2State = null; private Action<char> onChar2Enter = null; private Action<char> onChar2Exit = null; private Action<char> onChar3State = null; private Action<char> onChar3Enter = null; private Action<char> onChar3Exit = null; private Action<char> onChar4State = null; private Action<char> onChar4Enter = null; private Action<char> onChar4Exit = null; private Action<char> onChar5State = null; private Action<char> onChar5Enter = null; private Action<char> onChar5Exit = null; private Action<char> onParseSingleQuotesState = null; private Action<char> onParseSingleQuotesEnter = null; private Action<char> onParseSingleQuotesExit = null; private Action<char> onParseDoubleQuotesState = null; private Action<char> onParseDoubleQuotesEnter = null; private Action<char> onParseDoubleQuotesExit = null; private Action<char> onAccept = null; private Action<char> onDecline = null; private Action<char> onEnd = null; public readonly ParseSingleQuotes ParseSingleQuotesMachine = new ParseSingleQuotes(); public readonly ParseDoubleQuotes ParseDoubleQuotesMachine = new ParseDoubleQuotes(); public bool? Input(Queue<char> data) { if (reset) state = null; bool? result = null; if (data == null) return null; bool? nestResult; Reset: reset = false; switch (state) { case null: if (data.Count > 0) { state = States.Char0; goto ResumeChar0; } else goto End; case States.Char0: goto ResumeChar0; case States.Char1: goto ResumeChar1; case States.Char2: goto ResumeChar2; case States.Char3: goto ResumeChar3; case States.Char4: goto ResumeChar4; case States.Char5: goto ResumeChar5; case States.ParseSingleQuotes: goto ResumeParseSingleQuotes; case States.ParseDoubleQuotes: goto ResumeParseDoubleQuotes; } EnterChar0: state = States.Char0; if (onChar0Enter != null) onChar0Enter(currentCommand); if (onChar0State != null) onChar0State(currentCommand); ResumeChar0: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onChar0Exit != null) onChar0Exit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onChar0Exit != null) onChar0Exit(currentCommand); goto EnterParseDoubleQuotes; case 'g': if (onChar0Exit != null) onChar0Exit(currentCommand); goto EnterChar1; default: if (onChar0Exit != null) onChar0Exit(currentCommand); goto Decline; } EnterChar1: state = States.Char1; if (onChar1Enter != null) onChar1Enter(currentCommand); if (onChar1State != null) onChar1State(currentCommand); ResumeChar1: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onChar1Exit != null) onChar1Exit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onChar1Exit != null) onChar1Exit(currentCommand); goto EnterParseDoubleQuotes; case 'r': if (onChar1Exit != null) onChar1Exit(currentCommand); goto EnterChar2; default: if (onChar1Exit != null) onChar1Exit(currentCommand); goto Decline; } EnterChar2: state = States.Char2; if (onChar2Enter != null) onChar2Enter(currentCommand); if (onChar2State != null) onChar2State(currentCommand); ResumeChar2: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onChar2Exit != null) onChar2Exit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onChar2Exit != null) onChar2Exit(currentCommand); goto EnterParseDoubleQuotes; case 'o': if (onChar2Exit != null) onChar2Exit(currentCommand); goto EnterChar3; default: if (onChar2Exit != null) onChar2Exit(currentCommand); goto Decline; } EnterChar3: state = States.Char3; if (onChar3Enter != null) onChar3Enter(currentCommand); if (onChar3State != null) onChar3State(currentCommand); ResumeChar3: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onChar3Exit != null) onChar3Exit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onChar3Exit != null) onChar3Exit(currentCommand); goto EnterParseDoubleQuotes; case 'u': if (onChar3Exit != null) onChar3Exit(currentCommand); goto EnterChar4; default: if (onChar3Exit != null) onChar3Exit(currentCommand); goto Decline; } EnterChar4: state = States.Char4; if (onChar4Enter != null) onChar4Enter(currentCommand); if (onChar4State != null) onChar4State(currentCommand); ResumeChar4: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onChar4Exit != null) onChar4Exit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onChar4Exit != null) onChar4Exit(currentCommand); goto EnterParseDoubleQuotes; case 'p': if (onChar4Exit != null) onChar4Exit(currentCommand); goto EnterChar5; default: if (onChar4Exit != null) onChar4Exit(currentCommand); goto Decline; } EnterChar5: state = States.Char5; if (onChar5Enter != null) onChar5Enter(currentCommand); if (onChar5State != null) onChar5State(currentCommand); ResumeChar5: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onChar5Exit != null) onChar5Exit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onChar5Exit != null) onChar5Exit(currentCommand); goto EnterParseDoubleQuotes; case ' ': if (onChar5Exit != null) onChar5Exit(currentCommand); goto Accept; case '\t': if (onChar5Exit != null) onChar5Exit(currentCommand); goto Accept; case '\r': if (onChar5Exit != null) onChar5Exit(currentCommand); goto Accept; case '\n': if (onChar5Exit != null) onChar5Exit(currentCommand); goto Accept; default: if (onChar5Exit != null) onChar5Exit(currentCommand); goto Decline; } EnterParseSingleQuotes: state = States.ParseSingleQuotes; if (onParseSingleQuotesEnter != null) onParseSingleQuotesEnter(currentCommand); if (onParseSingleQuotesState != null) onParseSingleQuotesState(currentCommand); ResumeParseSingleQuotes: nestResult = ParseSingleQuotesMachine.Input(data); switch (nestResult) { case null: goto End; case true: if (onParseSingleQuotesExit != null) onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand); goto Decline; case false: if (onParseSingleQuotesExit != null) onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand); goto Decline; } EnterParseDoubleQuotes: state = States.ParseDoubleQuotes; if (onParseDoubleQuotesEnter != null) onParseDoubleQuotesEnter(currentCommand); if (onParseDoubleQuotesState != null) onParseDoubleQuotesState(currentCommand); ResumeParseDoubleQuotes: nestResult = ParseDoubleQuotesMachine.Input(data); switch (nestResult) { case null: goto End; case true: if (onParseDoubleQuotesExit != null) onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand); goto Decline; case false: if (onParseDoubleQuotesExit != null) onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand); goto Decline; } Accept: result = true; state = null; if (onAccept != null) onAccept(currentCommand); goto End; Decline: result = false; state = null; if (onDecline != null) onDecline(currentCommand); goto End; End: if (onEnd != null) onEnd(currentCommand); if (reset) { goto Reset; } return result; } public void AddOnChar0(Action<char> addedFunc) { onChar0State += addedFunc; } public void AddOnChar1(Action<char> addedFunc) { onChar1State += addedFunc; } public void AddOnChar2(Action<char> addedFunc) { onChar2State += addedFunc; } public void AddOnChar3(Action<char> addedFunc) { onChar3State += addedFunc; } public void AddOnChar4(Action<char> addedFunc) { onChar4State += addedFunc; } public void AddOnChar5(Action<char> addedFunc) { onChar5State += addedFunc; } public void AddOnParseSingleQuotes(Action<char> addedFunc) { AddOnParseSingleQuotesEnter(addedFunc); ParseSingleQuotesMachine.addOnAllStates(addedFunc); } public void AddOnParseDoubleQuotes(Action<char> addedFunc) { AddOnParseDoubleQuotesEnter(addedFunc); ParseDoubleQuotesMachine.addOnAllStates(addedFunc); } public void AddOnChar0Enter(Action<char> addedFunc) { onChar0Enter += addedFunc; } public void AddOnChar1Enter(Action<char> addedFunc) { onChar1Enter += addedFunc; } public void AddOnChar2Enter(Action<char> addedFunc) { onChar2Enter += addedFunc; } public void AddOnChar3Enter(Action<char> addedFunc) { onChar3Enter += addedFunc; } public void AddOnChar4Enter(Action<char> addedFunc) { onChar4Enter += addedFunc; } public void AddOnChar5Enter(Action<char> addedFunc) { onChar5Enter += addedFunc; } public void AddOnParseSingleQuotesEnter(Action<char> addedFunc) { onParseSingleQuotesEnter += addedFunc; } public void AddOnParseDoubleQuotesEnter(Action<char> addedFunc) { onParseDoubleQuotesEnter += addedFunc; } public void AddOnChar0Exit(Action<char> addedFunc) { onChar0Exit += addedFunc; } public void AddOnChar1Exit(Action<char> addedFunc) { onChar1Exit += addedFunc; } public void AddOnChar2Exit(Action<char> addedFunc) { onChar2Exit += addedFunc; } public void AddOnChar3Exit(Action<char> addedFunc) { onChar3Exit += addedFunc; } public void AddOnChar4Exit(Action<char> addedFunc) { onChar4Exit += addedFunc; } public void AddOnChar5Exit(Action<char> addedFunc) { onChar5Exit += addedFunc; } public void AddOnParseSingleQuotesExit(Action<char> addedFunc) { onParseSingleQuotesExit += addedFunc; } public void AddOnParseDoubleQuotesExit(Action<char> addedFunc) { onParseDoubleQuotesExit += addedFunc; } public void AddOnAccept(Action<char> addedFunc) { onAccept += addedFunc; } public void AddOnDecline(Action<char> addedFunc) { onDecline += addedFunc; } public void AddOnEnd(Action<char> addedFunc) { onEnd += addedFunc; } internal void addOnAllStates( Action<char> addedFunc ) { onChar0State += addedFunc; onChar1State += addedFunc; onChar2State += addedFunc; onChar3State += addedFunc; onChar4State += addedFunc; onChar5State += addedFunc; AddOnParseSingleQuotes(addedFunc); AddOnParseDoubleQuotes(addedFunc); } public void ResetStateOnEnd() { state = null; reset = true; ParseSingleQuotesMachine.ResetStateOnEnd(); ParseDoubleQuotesMachine.ResetStateOnEnd(); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR.Abstractions { using System; using System.Collections.Generic; using Microsoft.Zelig.MetaData; using Microsoft.Zelig.MetaData.Normalized; using Microsoft.Zelig.Runtime.TypeSystem; using Microsoft.Zelig.TargetModel.ArmProcessor; public abstract class Platform : ITransformationContextTarget, Operator.IOperatorLevelHelper { // // State // protected TypeSystemForCodeTransformation m_typeSystem; // // Constructor Methods // protected Platform() // Default constructor required by TypeSystemSerializer. { } protected Platform( TypeSystemForCodeTransformation typeSystem ) { m_typeSystem = typeSystem; } // // Helper Methods // public virtual void ApplyTransformation( TransformationContext context ) { TransformationContextForCodeTransformation context2 = (TransformationContextForCodeTransformation)context; context2.Push( this ); context2.Transform( ref m_typeSystem ); context2.Pop(); } //--// public abstract void RegisterForNotifications( TypeSystemForCodeTransformation ts , CompilationSteps.DelegationCache cache ); public abstract TypeRepresentation GetRuntimeType( TypeSystemForCodeTransformation ts , Abstractions.RegisterDescriptor regDesc ); public virtual void ExpandCallsClosure( CompilationSteps.ComputeCallsClosure computeCallsClosure ) { foreach(var regDesc in this.GetRegisters()) { computeCallsClosure.Expand( GetRuntimeType( computeCallsClosure.TypeSystem, regDesc ) ); } } //--// public abstract bool CanUseMultipleConditionCodes { get; } public abstract int EstimatedCostOfLoadOperation { get; } public abstract int EstimatedCostOfStoreOperation { get; } public abstract uint MemoryAlignment { get; } public abstract void GetListOfMemoryBlocks( List< Runtime.Memory.Range > list ); public abstract PlacementRequirements GetMemoryRequirements( object obj ); public abstract IR.ImageBuilders.CompilationState CreateCompilationState( IR.ImageBuilders.Core core , ControlFlowGraphStateForCodeTransformation cfg ); //--// public abstract string CodeGenerator { get; } public abstract uint PlatformFamily { get; } public abstract uint PlatformVersion { get; } public abstract uint PlatformVFP { get; } public abstract bool PlatformBigEndian { get; } public abstract InstructionSet GetInstructionSetProvider(); public abstract RegisterDescriptor[] GetRegisters(); public abstract RegisterDescriptor GetRegisterForEncoding( uint regNum ); public abstract RegisterDescriptor GetScratchRegister(); public abstract void ComputeNumberOfFragmentsForExpression( TypeRepresentation sourceTd , ControlFlowGraphStateForCodeTransformation.KindOfFragment kind , out uint sourceFragments , out bool fDirect ); public abstract bool CanFitInRegister( TypeRepresentation td ); //--// public abstract TypeRepresentation GetMethodWrapperType(); public abstract bool HasRegisterContextArgument( MethodRepresentation md ); public abstract void ComputeSetOfRegistersToSave( Abstractions.CallingConvention cc , ControlFlowGraphStateForCodeTransformation cfg , BitVector modifiedRegisters , out BitVector registersToSave , out Runtime.HardwareException he ); //--// bool Operator.IOperatorLevelHelper.FitsInPhysicalRegister( TypeRepresentation td ) { return CanFitTypeInPhysicalRegister( td ); } protected abstract bool CanFitTypeInPhysicalRegister( TypeRepresentation td ); //--// public abstract bool CanPropagateCopy( SingleAssignmentOperator opSrc , Operator opDst , int exIndexInDst , VariableExpression[] variables , BitVector[] variableUses , BitVector[] variableDefinitions , Operator[] operators ); //--// public static void SetConstraintOnResultsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , VariableExpression[] results ) { for(int i = 0; i < results.Length; i++) { SetConstraintOnLhsBasedOnType( nc, results, i ); } } public static void SetConstraintOnLhsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , VariableExpression[] lhs , int varIndex ) { SetConstraintBasedOnType( nc, lhs[varIndex], varIndex, true ); } public static void SetConstraintOnArgumentsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , Expression[] arguments ) { for(int i = 0; i < arguments.Length; i++) { SetConstraintOnRhsBasedOnType( nc, arguments, i ); } } public static void SetConstraintOnRhsBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , Expression[] rhs , int varIndex ) { SetConstraintBasedOnType( nc, rhs[varIndex], varIndex, false ); } public static void SetConstraintBasedOnType( CompilationSteps.PhaseExecution.NotificationContext nc , Expression ex , int varIndex , bool fIsResult ) { if(ex != null) { TypeRepresentation td = ex.Type; if(td.IsFloatingPoint) { if(td.SizeOfHoldingVariableInWords == 1) { SetConstraint( nc, varIndex, fIsResult, RegisterClass.SinglePrecision ); } else { SetConstraint( nc, varIndex, fIsResult, RegisterClass.DoublePrecision ); } } else if(td is PointerTypeRepresentation) { SetConstraint( nc, varIndex, fIsResult, RegisterClass.Address ); } else { SetConstraint( nc, varIndex, fIsResult, RegisterClass.Integer ); } } } public static void SetConstraintOnLHS( CompilationSteps.PhaseExecution.NotificationContext nc , int varIndex , RegisterClass constraint ) { SetConstraint( nc, varIndex, true, constraint ); } public static void SetConstraintOnRHS( CompilationSteps.PhaseExecution.NotificationContext nc , int varIndex , RegisterClass constraint ) { SetConstraint( nc, varIndex, false, constraint ); } public static void SetConstraint( CompilationSteps.PhaseExecution.NotificationContext nc , int varIndex , bool fIsResult , RegisterClass constraint ) { nc.CurrentOperator.AddAnnotation( RegisterAllocationConstraintAnnotation.Create( nc.TypeSystem, varIndex, fIsResult, constraint ) ); } //--// public static bool MoveToPseudoRegisterIfConstant( ControlFlowGraphStateForCodeTransformation cfg , Operator op , Expression ex ) { if(ex is ConstantExpression) { MoveToPseudoRegister( cfg, op, ex ); return true; } return false; } public static VariableExpression MoveToPseudoRegister( ControlFlowGraphStateForCodeTransformation cfg , Operator op , Expression ex ) { VariableExpression exReg = cfg.AllocatePseudoRegister( ex.Type ); op.AddOperatorBefore( SingleAssignmentOperator.New( op.DebugInfo, exReg, ex ) ); op.SubstituteUsage( ex, exReg ); return exReg; } public static PseudoRegisterExpression AllocatePseudoRegisterIfNeeded( ControlFlowGraphStateForCodeTransformation cfg , Expression ex ) { var var = ex as VariableExpression; if(var != null) { var exStack = var.AliasedVariable as StackLocationExpression; if(exStack != null) { return cfg.AllocatePseudoRegister( exStack.Type, exStack.DebugName ); } } return null; } public static PseudoRegisterExpression AllocatePseudoRegisterIfNeeded( ControlFlowGraphStateForCodeTransformation cfg , Expression ex , bool fConstantOk ) { var res = AllocatePseudoRegisterIfNeeded( cfg, ex ); if(res == null) { if(fConstantOk == false && ex is ConstantExpression) { res = cfg.AllocatePseudoRegister( ex.Type ); } } return res; } } }
// // SemanticOperation.cs // s.im.pl serialization // // Generated by DotNetTranslator on 11/16/10. // Copyright 2010 Interface Ecology Lab. // using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Ecologylab.BigSemantics.Collecting; //using Ecologylab.Semantics.Documentparsers; using Ecologylab.BigSemantics.Documentparsers; using Ecologylab.BigSemantics.MetadataNS.Builtins; using Ecologylab.BigSemantics.MetaMetadataNS; using Ecologylab.Collections; using Ecologylab.BigSemantics.MetadataNS; using Simpl.Fundamental.Net; using Simpl.Serialization.Attributes; using Ecologylab.BigSemantics.Connectors; using Ecologylab.BigSemantics.MetadataNS.Scalar; using Simpl.Serialization; using Ecologylab.BigSemantics.Actions; namespace Ecologylab.BigSemantics.Actions { /// <summary> /// missing java doc comments or could not find the source file. /// </summary> public abstract class SemanticOperation : ElementState { /// <summary> /// missing java doc comments or could not find the source file. /// </summary> [SimplCollection] [SimplScope("condition_scope")] [SimplNoWrap] private List<Condition> checks; /// <summary> /// missing java doc comments or could not find the source file. /// </summary> [SimplNoWrap] [SimplMap("arg")] private Dictionary<String, Argument> args; /// <summary> /// missing java doc comments or could not find the source file. /// </summary> [SimplScalar] [SimplTag("object")] private String objectStr; /// <summary> /// missing java doc comments or could not find the source file. /// </summary> [SimplScalar] private String name; /// <summary> /// missing java doc comments or could not find the source file. /// </summary> [SimplScalar] private String error; public List<Condition> Checks { get{return checks;} set{checks = value;} } public Dictionary<String, Argument> Args { get{return args;} set{args = value;} } public String ObjectStr { get{return objectStr;} set{objectStr = value;} } public String Name { get{return name;} set{name = value;} } public String Error { get{return error;} set{error = value;} } protected SemanticsGlobalScope sessionScope; protected SemanticOperationHandler semanticOperationHandler; protected DocumentParser documentParser; public SemanticOperation() { args = new Dictionary<string, Argument>(); } public String GetReturnObjectName() { return name; } public bool HasArguments() { return args != null && args.Count > 0; } public String GetArgumentValueName(String argName) { String result = null; if (args != null) { Argument argument = args[argName]; //edit if (argument != null) { result = argument.Value; } } return result; } public String GetArgumentAltValueName(String argName) { String result = null; if (args != null) { Argument argument = args[argName]; //edit if (argument != null) { result = argument.AltValue; } } return result; } public Object GetArgumentObject(String argName) { Object result = null; if (args != null) { if (args.ContainsKey(argName)) { Argument argument = args[argName]; String argumentValueName = argument.Value; if (argumentValueName != null) { Scope<Object> semanticOperationVariableMap = semanticOperationHandler.SemanticOperationVariableMap; result = semanticOperationVariableMap.Get(argumentValueName); //edit if (result == null) { argumentValueName = argument.AltValue; if (argumentValueName != null) { result = semanticOperationVariableMap.Get(argumentValueName); //edit } } } if (result != null && result is MetadataScalarBase<Object>) result = ((MetadataScalarBase<Object>) result).Value; //edit } } return result; } public int GetArgumentInteger(String argName, int defaultValue) { int? value = (int?) GetArgumentObject(argName); return value.GetValueOrDefault(); } public bool GetArgumentBoolean(String argName, bool defaultValue) { bool? value = (bool?) GetArgumentObject(argName); return value.GetValueOrDefault(); } public float GetArgumentFloat(String argName, float defaultValue) { float? value = (float?) GetArgumentObject(argName); return value.GetValueOrDefault(); } public SemanticsGlobalScope SessionScope { set { this.sessionScope = value; } } public SemanticOperationHandler SemanticOperationHandler { get { return this.semanticOperationHandler; } set { this.semanticOperationHandler = value; } } public DocumentParser DocumentParser { set { this.documentParser = documentParser; } } ///<summary> /// return the name of the operation. ///</summary> public abstract String GetOperationName(); ///<summary> /// handle error during operation performing. ///<summary> public abstract void HandleError(); ///<summary> /// Perform this semantic operation. User defined semantic operations should override this method. /// /// @param obj /// The object the operation operates on. /// @return The result of this semantic operation (if any), or null. ///<summary> public abstract Object Perform(Object obj); //throw IOException; ///<summary> /// Register a user defined semantic operation to the system. This method should be called before /// compiling or using the MetaMetadata repository. /// <p /> /// To override an existing semantic operation, subclass your own semantic operation class, use the same /// tag (indicated in @simpl_tag), and override perform(). /// /// @param semanticOperationClass /// @param canBeNested /// indicates if this semantic operation can be nested by other semantic operations, like /// <code>for</code> or <code>if</code>. if so, it will also be registered to /// NestedSemanticOperationTranslationScope. ///</summary> public static void Register(Type[] semanticOperationClasses) //edit { foreach (Type semanticOperationClass in semanticOperationClasses) { SemanticOperationTranslationScope.Get().AddTranslation(semanticOperationClass); } } protected MetaMetadata GetMetaMetadata() { return GetMetaMetadata(this); } static public MetaMetadata GetMetaMetadata(ElementState that) { if (that is MetaMetadata) { return (MetaMetadata) that; } ElementState parent = that.Parent; return (parent == null) ? null : GetMetaMetadata(parent); } protected Document ResolveSourceDocument() { Document sourceDocument = (Document)GetArgumentObject(SemanticOperationNamedArguments.SourceDocument); if (sourceDocument == null) { sourceDocument = this.semanticOperationHandler.SemanticOperationVariableMap[SemanticOperationKeyWords.Metadata] as Document; //sourceDocument = documentParser.Document; } return sourceDocument; } public Document GetOrCreateDocument(DocumentParser documentParser/*, LinkType linkType*/) { Document result = (Document)GetArgumentObject(SemanticOperationNamedArguments.Document); // get the ancestor container Document sourceDocument = ResolveSourceDocument(); // get the seed. Non null only for search types . //Seed seed = documentParser.getSeed(); if (result == null) { Object outlinkPurlObject = GetArgumentObject(SemanticOperationNamedArguments.Location); if (outlinkPurlObject != null) { ParsedUri outlinkPurl = ((MetadataParsedURL)outlinkPurlObject).Value; //result = sessionScope.GetOrConstructDocument(outlinkPurl); } } if (result == null) result = sourceDocument; //direct binding?! if (result != null /*&& !result.IsRecycled()*/ && (result.Location != null)) { result.SemanticsSessionScope = (SemanticsSessionScope)sessionScope; MetadataNS.Metadata mixin = (MetadataNS.Metadata)GetArgumentObject(SemanticOperationNamedArguments.Mixin); if (mixin != null) result.AddMixin(mixin); /* if (seed != null) { seed.bindToDocument(result); } */ MetadataString anchorText = (MetadataString)GetArgumentObject(SemanticOperationNamedArguments.AnchorText); // create anchor text from Document title if there is none passed in directly, and we won't // be setting metadata // if (anchorText == null) // anchorText = result.Title; // work to avoid honey pots! MetadataString anchorContextString = (MetadataString)GetArgumentObject(SemanticOperationNamedArguments.AnchorContext); bool citationSignificance = GetArgumentBoolean(SemanticOperationNamedArguments.CitationSignificance, false); float significanceVal = GetArgumentFloat(SemanticOperationNamedArguments.SignificanceValue, 1); bool traversable = GetArgumentBoolean(SemanticOperationNamedArguments.Traversable, true); bool ignoreContextForTv = GetArgumentBoolean(SemanticOperationNamedArguments.IgnoreContextForTv, false); ParsedUri location = result.Location.Value; /* if (traversable) { Seeding seeding = sessionScope.getSeeding(); if (seeding != null) seeding.traversable(location); } bool anchorIsInSource = false; if (sourceDocument != null) { // Chain the significance from the ancestor SemanticInLinks sourceInLinks = sourceDocument.getSemanticInlinks(); if (sourceInLinks != null) { significanceVal *= sourceInLinks.meanSignificance(); anchorIsInSource = sourceInLinks.containsKey(location); } } if(! anchorIsInSource) { //By default use the boost, unless explicitly stated in this site's MMD SemanticsSite site = result.GetSite; boolean useSemanticBoost = !site.ignoreSemanticBoost(); if (citationSignificance) linkType = LinkType.CITATION_SEMANTIC_ACTION; else if (useSemanticBoost && linkType == LinkType.OTHER_SEMANTIC_ACTION) linkType = LinkType.SITE_BOOSTED_SEMANTIC_ACTION; SemanticAnchor semanticAnchor = new SemanticAnchor(linkType, location, null, sourceDocument.getLocation(), significanceVal);// this is not fromContentBody, // but is fromSemanticActions if(ignoreContextForTv) semanticAnchor.addAnchorContextToTV(anchorText, null); else semanticAnchor.addAnchorContextToTV(anchorText, anchorContextString); result.addSemanticInlink(semanticAnchor, sourceDocument); } else { Console.WriteLine("Ignoring inlink, because ancestor contains the same, we don't want cycles in the graph just yet: sourceContainer -- outlinkPurl :: " + sourceDocument + " -- " + location); }*/ } // adding the return value to map Scope<Object> semanticActionVariableMap = SemanticOperationHandler.SemanticOperationVariableMap; if (semanticActionVariableMap != null) { if (GetReturnObjectName() != null) semanticActionVariableMap.Put(GetReturnObjectName(), result); } else Debug.WriteLine("semanticActionVariableMap is null !! Not frequently reproducible either. Place a breakpoint here to try fixing it next time."); // set flags if any // setFlagIfAny(action, localContainer); // return the value. Right now no need for it. Later it might be used. return result; } public static readonly int INIT = 0; // this operation has not been started public static readonly int INTER = 10; // this operation has been started but not yet finished public static readonly int FIN = 20; // this operation has already been finished public virtual void SetNestedOperationState(String name, Object value) { } public SemanticOperationHandler GetSemanticOperationHandler() { SemanticOperationHandler result = this.semanticOperationHandler; if (result == null) { ElementState parentES = Parent; if (parentES != null && parentES is SemanticOperation) { SemanticOperation parent = (SemanticOperation) parentES; result = parent.GetSemanticOperationHandler(); this.semanticOperationHandler = result; } } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; namespace System { public partial class String { // //Native Static Methods // private unsafe static int CompareOrdinalIgnoreCaseHelper(String strA, String strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); int length = Math.Min(strA.Length, strB.Length); fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) { char* a = ap; char* b = bp; int charA = 0, charB = 0; while (length != 0) { charA = *a; charB = *b; Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII"); // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; //Return the (case-insensitive) difference between them. if (charA != charB) return charA - charB; // Next char a++; b++; length--; } return strA.Length - strB.Length; } } // native call to COMString::CompareOrdinalEx [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int CompareOrdinalHelper(String strA, int indexA, int countA, String strB, int indexB, int countB); //This will not work in case-insensitive mode for any character greater than 0x80. //We'll throw an ArgumentException. [MethodImplAttribute(MethodImplOptions.InternalCall)] unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte* strBBytes); // // // NATIVE INSTANCE METHODS // // // // Search/Query methods // private unsafe static bool EqualsHelper(String strA, String strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); Debug.Assert(strA.Length == strB.Length); int length = strA.Length; fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) { char* a = ap; char* b = bp; #if BIT64 // Single int read aligns pointers for the following long reads // PERF: No length check needed as there is always an int32 worth of string allocated // This read can also include the null terminator which both strings will have if (*(int*)a != *(int*)b) return false; length -= 2; a += 2; b += 2; // for AMD64 bit platform we unroll by 12 and // check 3 qword at a time. This is less code // than the 32 bit case and is a shorter path length. while (length >= 12) { if (*(long*)a != *(long*)b) return false; if (*(long*)(a + 4) != *(long*)(b + 4)) return false; if (*(long*)(a + 8) != *(long*)(b + 8)) return false; length -= 12; a += 12; b += 12; } #else while (length >= 10) { if (*(int*)a != *(int*)b) return false; if (*(int*)(a + 2) != *(int*)(b + 2)) return false; if (*(int*)(a + 4) != *(int*)(b + 4)) return false; if (*(int*)(a + 6) != *(int*)(b + 6)) return false; if (*(int*)(a + 8) != *(int*)(b + 8)) return false; length -= 10; a += 10; b += 10; } #endif // This depends on the fact that the String objects are // always zero terminated and that the terminating zero is not included // in the length. For odd string sizes, the last compare will include // the zero terminator. while (length > 0) { if (*(int*)a != *(int*)b) return false; length -= 2; a += 2; b += 2; } return true; } } private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB) { Debug.Assert(strA != null); Debug.Assert(strB != null); Debug.Assert(strA.Length == strB.Length); int length = strA.Length; fixed (char* ap = &strA._firstChar) fixed (char* bp = &strB._firstChar) { char* a = ap; char* b = bp; while (length != 0) { int charA = *a; int charB = *b; Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII"); // Ordinal equals or lowercase equals if the result ends up in the a-z range if (charA == charB || ((charA | 0x20) == (charB | 0x20) && (uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a'))) { a++; b++; length--; } else { return false; } } return true; } } private unsafe static bool StartsWithOrdinalHelper(String str, String startsWith) { Debug.Assert(str != null); Debug.Assert(startsWith != null); Debug.Assert(str.Length >= startsWith.Length); int length = startsWith.Length; fixed (char* ap = &str._firstChar) fixed (char* bp = &startsWith._firstChar) { char* a = ap; char* b = bp; #if BIT64 // Single int read aligns pointers for the following long reads // No length check needed as this method is called when length >= 2 Debug.Assert(length >= 2); if (*(int*)a != *(int*)b) return false; length -= 2; a += 2; b += 2; while (length >= 12) { if (*(long*)a != *(long*)b) return false; if (*(long*)(a + 4) != *(long*)(b + 4)) return false; if (*(long*)(a + 8) != *(long*)(b + 8)) return false; length -= 12; a += 12; b += 12; } #else while (length >= 10) { if (*(int*)a != *(int*)b) return false; if (*(int*)(a+2) != *(int*)(b+2)) return false; if (*(int*)(a+4) != *(int*)(b+4)) return false; if (*(int*)(a+6) != *(int*)(b+6)) return false; if (*(int*)(a+8) != *(int*)(b+8)) return false; length -= 10; a += 10; b += 10; } #endif while (length >= 2) { if (*(int*)a != *(int*)b) return false; length -= 2; a += 2; b += 2; } // PERF: This depends on the fact that the String objects are always zero terminated // and that the terminating zero is not included in the length. For even string sizes // this compare can include the zero terminator. Bitwise OR avoids a branch. return length == 0 | *a == *b; } } private unsafe static int CompareOrdinalHelper(string strA, string strB) { int length = Math.Min(strA.Length, strB.Length); fixed (char* ap = strA) fixed (char* bp = strB) { char* a = ap; char* b = bp; // Check if the second chars are different here // The reason we check if _firstChar is different is because // it's the most common case and allows us to avoid a method call // to here. // The reason we check if the second char is different is because // if the first two chars the same we can increment by 4 bytes, // leaving us word-aligned on both 32-bit (12 bytes into the string) // and 64-bit (16 bytes) platforms. // For empty strings, the second char will be null due to padding. // The start of the string (not including sync block pointer) // is the method table pointer + string length, which takes up // 8 bytes on 32-bit, 12 on x64. For empty strings the null // terminator immediately follows, leaving us with an object // 10/14 bytes in size. Since everything needs to be a multiple // of 4/8, this will get padded and zeroed out. // For one-char strings the second char will be the null terminator. // NOTE: If in the future there is a way to read the second char // without pinning the string (e.g. System.Runtime.CompilerServices.Unsafe // is exposed to mscorlib, or a future version of C# allows inline IL), // then do that and short-circuit before the fixed. if (*(a + 1) != *(b + 1)) goto DiffOffset1; // Since we know that the first two chars are the same, // we can increment by 2 here and skip 4 bytes. // This leaves us 8-byte aligned, which results // on better perf for 64-bit platforms. length -= 2; a += 2; b += 2; // unroll the loop #if BIT64 while (length >= 12) { if (*(long*)a != *(long*)b) goto DiffOffset0; if (*(long*)(a + 4) != *(long*)(b + 4)) goto DiffOffset4; if (*(long*)(a + 8) != *(long*)(b + 8)) goto DiffOffset8; length -= 12; a += 12; b += 12; } #else // BIT64 while (length >= 10) { if (*(int*)a != *(int*)b) goto DiffOffset0; if (*(int*)(a + 2) != *(int*)(b + 2)) goto DiffOffset2; if (*(int*)(a + 4) != *(int*)(b + 4)) goto DiffOffset4; if (*(int*)(a + 6) != *(int*)(b + 6)) goto DiffOffset6; if (*(int*)(a + 8) != *(int*)(b + 8)) goto DiffOffset8; length -= 10; a += 10; b += 10; } #endif // BIT64 // Fallback loop: // go back to slower code path and do comparison on 4 bytes at a time. // This depends on the fact that the String objects are // always zero terminated and that the terminating zero is not included // in the length. For odd string sizes, the last compare will include // the zero terminator. while (length > 0) { if (*(int*)a != *(int*)b) goto DiffNextInt; length -= 2; a += 2; b += 2; } // At this point, we have compared all the characters in at least one string. // The longer string will be larger. return strA.Length - strB.Length; #if BIT64 DiffOffset8: a += 4; b += 4; DiffOffset4: a += 4; b += 4; #else // BIT64 // Use jumps instead of falling through, since // otherwise going to DiffOffset8 will involve // 8 add instructions before getting to DiffNextInt DiffOffset8: a += 8; b += 8; goto DiffOffset0; DiffOffset6: a += 6; b += 6; goto DiffOffset0; DiffOffset4: a += 2; b += 2; DiffOffset2: a += 2; b += 2; #endif // BIT64 DiffOffset0: // If we reached here, we already see a difference in the unrolled loop above #if BIT64 if (*(int*)a == *(int*)b) { a += 2; b += 2; } #endif // BIT64 DiffNextInt: if (*a != *b) return *a - *b; DiffOffset1: Debug.Assert(*(a + 1) != *(b + 1), "This char must be different if we reach here!"); return *(a + 1) - *(b + 1); } } // Provides a culture-correct string comparison. StrA is compared to StrB // to determine whether it is lexicographically less, equal, or greater, and then returns // either a negative integer, 0, or a positive integer; respectively. // public static int Compare(String strA, String strB) { return Compare(strA, strB, StringComparison.CurrentCulture); } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase // public static int Compare(String strA, String strB, bool ignoreCase) { var comparisonType = ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; return Compare(strA, strB, comparisonType); } // Provides a more flexible function for string comparision. See StringComparison // for meaning of different comparisonType. public static int Compare(String strA, String strB, StringComparison comparisonType) { // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase] if ((uint)(comparisonType - StringComparison.CurrentCulture) > (uint)(StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture)) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } if (object.ReferenceEquals(strA, strB)) { return 0; } // They can't both be null at this point. if (strA == null) { return -1; } if (strB == null) { return 1; } switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase); case StringComparison.Ordinal: // Most common case: first character is different. // Returns false for empty strings. if (strA._firstChar != strB._firstChar) { return strA._firstChar - strB._firstChar; } return CompareOrdinalHelper(strA, strB); case StringComparison.OrdinalIgnoreCase: // If both strings are ASCII strings, we can take the fast path. if (strA.IsAscii() && strB.IsAscii()) { return (CompareOrdinalIgnoreCaseHelper(strA, strB)); } return CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length); default: throw new NotSupportedException(SR.NotSupported_StringComparison); } } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } return culture.CompareInfo.Compare(strA, strB, options); } // Provides a culture-correct string comparison. strA is compared to strB // to determine whether it is lexicographically less, equal, or greater, and then a // negative integer, 0, or a positive integer is returned; respectively. // The case-sensitive option is set by ignoreCase, and the culture is set // by culture // public static int Compare(String strA, String strB, bool ignoreCase, CultureInfo culture) { var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return Compare(strA, strB, culture, options); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length count is compared with the substring of strB // beginning at indexB of the same length. // public static int Compare(String strA, int indexA, String strB, int indexB, int length) { // NOTE: It's important we call the boolean overload, and not the StringComparison // one. The two have some subtly different behavior (see notes in the former). return Compare(strA, indexA, strB, indexB, length, ignoreCase: false); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length count is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean. // public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase) { // Ideally we would just forward to the string.Compare overload that takes // a StringComparison parameter, and just pass in CurrentCulture/CurrentCultureIgnoreCase. // That function will return early if an optimization can be applied, e.g. if // (object)strA == strB && indexA == indexB then it will return 0 straightaway. // There are a couple of subtle behavior differences that prevent us from doing so // however: // - string.Compare(null, -1, null, -1, -1, StringComparison.CurrentCulture) works // since that method also returns early for nulls before validation. It shouldn't // for this overload. // - Since we originally forwarded to CompareInfo.Compare for all of the argument // validation logic, the ArgumentOutOfRangeExceptions thrown will contain different // parameter names. // Therefore, we have to duplicate some of the logic here. int lengthA = length; int lengthB = length; if (strA != null) { lengthA = Math.Min(lengthA, strA.Length - indexA); } if (strB != null) { lengthB = Math.Min(lengthB, strB.Length - indexB); } var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length length is compared with the substring of strB // beginning at indexB of the same length. Case sensitivity is determined by the ignoreCase boolean, // and the culture is set by culture. // public static int Compare(String strA, int indexA, String strB, int indexB, int length, bool ignoreCase, CultureInfo culture) { var options = ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; return Compare(strA, indexA, strB, indexB, length, culture, options); } // Determines whether two string regions match. The substring of strA beginning // at indexA of length length is compared with the substring of strB // beginning at indexB of the same length. // public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } int lengthA = length; int lengthB = length; if (strA != null) { lengthA = Math.Min(lengthA, strA.Length - indexA); } if (strB != null) { lengthB = Math.Min(lengthB, strB.Length - indexB); } return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options); } public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType) { if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } if (strA == null || strB == null) { if (object.ReferenceEquals(strA, strB)) { // They're both null return 0; } return strA == null ? -1 : 1; } if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength); } if (indexA < 0 || indexB < 0) { string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (strA.Length - indexA < 0 || strB.Length - indexB < 0) { string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB)) { return 0; } int lengthA = Math.Min(length, strA.Length - indexA); int lengthB = Math.Min(length, strB.Length - indexB); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB); case StringComparison.OrdinalIgnoreCase: return (CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB)); default: throw new ArgumentException(SR.NotSupported_StringComparison); } } // Compares strA and strB using an ordinal (code-point) comparison. // public static int CompareOrdinal(String strA, String strB) { if (object.ReferenceEquals(strA, strB)) { return 0; } // They can't both be null at this point. if (strA == null) { return -1; } if (strB == null) { return 1; } // Most common case, first character is different. // This will return false for empty strings. if (strA._firstChar != strB._firstChar) { return strA._firstChar - strB._firstChar; } return CompareOrdinalHelper(strA, strB); } // TODO https://github.com/dotnet/corefx/issues/21395: Expose this publicly? internal static int CompareOrdinal(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB) { // TODO: This needs to be optimized / unrolled. It can't just use CompareOrdinalHelper(str, str) // (changed to accept spans) because its implementation is based on a string layout, // in a way that doesn't work when there isn't guaranteed to be a null terminator. int minLength = Math.Min(strA.Length, strB.Length); for (int i = 0; i < minLength; i++) { if (strA[i] != strB[i]) { return strA[i] - strB[i]; } } return strA.Length - strB.Length; } // Compares strA and strB using an ordinal (code-point) comparison. // public static int CompareOrdinal(String strA, int indexA, String strB, int indexB, int length) { if (strA == null || strB == null) { if (object.ReferenceEquals(strA, strB)) { // They're both null return 0; } return strA == null ? -1 : 1; } // COMPAT: Checking for nulls should become before the arguments are validated, // but other optimizations which allow us to return early should come after. if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount); } if (indexA < 0 || indexB < 0) { string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } int lengthA = Math.Min(length, strA.Length - indexA); int lengthB = Math.Min(length, strB.Length - indexB); if (lengthA < 0 || lengthB < 0) { string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB)) { return 0; } return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB); } // Compares this String to another String (cast as object), returning an integer that // indicates the relationship. This method returns a value less than 0 if this is less than value, 0 // if this is equal to value, or a value greater than 0 if this is greater than value. // public int CompareTo(Object value) { if (value == null) { return 1; } string other = value as string; if (other == null) { throw new ArgumentException(SR.Arg_MustBeString); } return CompareTo(other); // will call the string-based overload } // Determines the sorting relation of StrB to the current instance. // public int CompareTo(String strB) { return string.Compare(this, strB, StringComparison.CurrentCulture); } // Determines whether a specified string is a suffix of the current instance. // // The case-sensitive and culture-sensitive option is set by options, // and the default culture is used. // public Boolean EndsWith(String value) { return EndsWith(value, StringComparison.CurrentCulture); } public Boolean EndsWith(String value, StringComparison comparisonType) { if ((Object)value == null) { throw new ArgumentNullException(nameof(value)); } if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } if ((Object)this == (Object)value) { return true; } if (value.Length == 0) { return true; } switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase); case StringComparison.Ordinal: return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0); case StringComparison.OrdinalIgnoreCase: return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture) { if (null == value) { throw new ArgumentNullException(nameof(value)); } if ((object)this == (object)value) { return true; } CultureInfo referenceCulture; if (culture == null) referenceCulture = CultureInfo.CurrentCulture; else referenceCulture = culture; return referenceCulture.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool EndsWith(char value) { int thisLen = Length; return thisLen != 0 && this[thisLen - 1] == value; } // Determines whether two strings match. public override bool Equals(Object obj) { if (object.ReferenceEquals(this, obj)) return true; string str = obj as string; if (str == null) return false; if (this.Length != str.Length) return false; return EqualsHelper(this, str); } // Determines whether two strings match. public bool Equals(String value) { if (object.ReferenceEquals(this, value)) return true; // NOTE: No need to worry about casting to object here. // If either side of an == comparison between strings // is null, Roslyn generates a simple ceq instruction // instead of calling string.op_Equality. if (value == null) return false; if (this.Length != value.Length) return false; return EqualsHelper(this, value); } public bool Equals(String value, StringComparison comparisonType) { if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); if ((Object)this == (Object)value) { return true; } if ((Object)value == null) { return false; } switch (comparisonType) { case StringComparison.CurrentCulture: return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0); case StringComparison.CurrentCultureIgnoreCase: return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0); case StringComparison.InvariantCulture: return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0); case StringComparison.InvariantCultureIgnoreCase: return (CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0); case StringComparison.Ordinal: if (this.Length != value.Length) return false; return EqualsHelper(this, value); case StringComparison.OrdinalIgnoreCase: if (this.Length != value.Length) return false; // If both strings are ASCII strings, we can take the fast path. if (this.IsAscii() && value.IsAscii()) { return EqualsIgnoreCaseAsciiHelper(this, value); } return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } // Determines whether two Strings match. public static bool Equals(String a, String b) { if ((Object)a == (Object)b) { return true; } if ((Object)a == null || (Object)b == null || a.Length != b.Length) { return false; } return EqualsHelper(a, b); } public static bool Equals(String a, String b, StringComparison comparisonType) { if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); if ((Object)a == (Object)b) { return true; } if ((Object)a == null || (Object)b == null) { return false; } switch (comparisonType) { case StringComparison.CurrentCulture: return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0); case StringComparison.CurrentCultureIgnoreCase: return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0); case StringComparison.InvariantCulture: return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0); case StringComparison.InvariantCultureIgnoreCase: return (CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0); case StringComparison.Ordinal: if (a.Length != b.Length) return false; return EqualsHelper(a, b); case StringComparison.OrdinalIgnoreCase: if (a.Length != b.Length) return false; else { // If both strings are ASCII strings, we can take the fast path. if (a.IsAscii() && b.IsAscii()) { return EqualsIgnoreCaseAsciiHelper(a, b); } // Take the slow path. return (CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0); } default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public static bool operator ==(String a, String b) { return String.Equals(a, b); } public static bool operator !=(String a, String b) { return !String.Equals(a, b); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalMarvin32HashString(string s); // Gets a hash code for this string. If strings A and B are such that A.Equals(B), then // they will return the same hash code. public override int GetHashCode() { return InternalMarvin32HashString(this); } // Gets a hash code for this string and this comparison. If strings A and B and comparition C are such // that String.Equals(A, B, C), then they will return the same hash code with this comparison C. public int GetHashCode(StringComparison comparisonType) => StringComparer.FromComparison(comparisonType).GetHashCode(this); // Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile // hash table). internal int GetLegacyNonRandomizedHashCode() { unsafe { fixed (char* src = &_firstChar) { Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'"); Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary"); #if BIT64 int hash1 = 5381; #else // !BIT64 (32) int hash1 = (5381<<16) + 5381; #endif int hash2 = hash1; #if BIT64 int c; char* s = src; while ((c = s[0]) != 0) { hash1 = ((hash1 << 5) + hash1) ^ c; c = s[1]; if (c == 0) break; hash2 = ((hash2 << 5) + hash2) ^ c; s += 2; } #else // !BIT64 (32) // 32 bit machines. int* pint = (int *)src; int len = this.Length; while (len > 2) { hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0]; hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1]; pint += 2; len -= 4; } if (len > 0) { hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0]; } #endif #if DEBUG // We want to ensure we can change our hash function daily. // This is perfectly fine as long as you don't persist the // value from GetHashCode to disk or count on String A // hashing before string B. Those are bugs in your code. hash1 ^= ThisAssembly.DailyBuildNumber; #endif return hash1 + (hash2 * 1566083941); } } } // Determines whether a specified string is a prefix of the current instance // public Boolean StartsWith(String value) { if ((Object)value == null) { throw new ArgumentNullException(nameof(value)); } return StartsWith(value, StringComparison.CurrentCulture); } public Boolean StartsWith(String value, StringComparison comparisonType) { if ((Object)value == null) { throw new ArgumentNullException(nameof(value)); } if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) { throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } if ((Object)this == (Object)value) { return true; } if (value.Length == 0) { return true; } switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase); case StringComparison.InvariantCulture: return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None); case StringComparison.InvariantCultureIgnoreCase: return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase); case StringComparison.Ordinal: if (this.Length < value.Length || _firstChar != value._firstChar) { return false; } return (value.Length == 1) ? true : // First char is the same and thats all there is to compare StartsWithOrdinalHelper(this, value); case StringComparison.OrdinalIgnoreCase: if (this.Length < value.Length) { return false; } return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0); default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture) { if (null == value) { throw new ArgumentNullException(nameof(value)); } if ((object)this == (object)value) { return true; } CultureInfo referenceCulture; if (culture == null) referenceCulture = CultureInfo.CurrentCulture; else referenceCulture = culture; return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool StartsWith(char value) => Length != 0 && _firstChar == value; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.Events; using Zeltex.AI; using Zeltex.Util; using Zeltex.Voxels; using Zeltex.Characters; using Zeltex.Skeletons; using Zeltex.Physics; // Need to decouple this script // to do: // record animation curves of the body falling // stop recording curve when the body stops moving // reverse the curve to make it get back up when its ressurected // merge with explode script - that use for voxels // so i can blow up parts of the body itself // add in function for removing just parts of the body // an example would be // remove body parts that intersect with a sphere at x location - or that intersect with a raycast // Ideally on death, activate a post processing effect script // and activate particle system // activate sounds of dying // another one would be, convert only the bottom parts of the body, ie feet, then calves etc, until it is just a head namespace Zeltex.Skeletons { /// <summary> /// Rag doll is a system of bones but connected using joints instead of transforms. /// </summary> public class Ragdoll : MonoBehaviour { public EditorAction ActionRagdoll; public EditorAction ActionReverseRagdoll; private SkeletonHandler MySkeleton; public bool IsBodyPartsItems = false; public bool IsApplyJoints = true; private float ExplosionForce = 100f; private float DownExplosionForce = 20f; private static float ExplosionPauseTime = 0.25f; private static float ExplosionPower = 24; private Characters.Character MyCharacter; private void Awake() { if (transform.parent) { MyCharacter = transform.parent.GetComponent<Characters.Character>(); } } private void Update() { if (ActionRagdoll.IsTriggered()) { RagDoll(); } if (ActionReverseRagdoll.IsTriggered()) { // Stop Dying and reverse if (MyCharacter) { MyCharacter.StopDeath(); } ReverseRagdoll(); } } private Zeltine RagdollHandle; // gets any child body with a mesh // keeps its mesh and position/rotation // creates a new body in that position with that, and a rigidbody public void RagDoll() { RagdollHandle = RoutineManager.Get().StartCoroutine(RagDollRoutine()); } private Vector3 RagdolledPosition; private Quaternion RagdolledRotation; private IEnumerator RagDollRoutine() { RagdolledPosition = MyCharacter.transform.position; RagdolledRotation = MyCharacter.transform.rotation; CapsuleCollider MyCapsule = transform.parent.GetComponent<CapsuleCollider>(); Rigidbody MyRigidbody = transform.parent.gameObject.GetComponent<Rigidbody>(); Zanimator MyAnimator = gameObject.GetComponent<Zanimator>(); MySkeleton = gameObject.GetComponent<SkeletonHandler>(); UnityEngine.Networking.NetworkTransform MyNetworkTransform = transform.parent.gameObject.GetComponent<UnityEngine.Networking.NetworkTransform>(); if (MyCapsule) { MyCapsule.enabled = false; } if (MyNetworkTransform) { MyNetworkTransform.enabled = false; //Destroy(MyNetworkTransform); } if (MyRigidbody) { MyRigidbody.isKinematic = true; } if (MyAnimator) { MyAnimator.Stop(); } BasicController MyController = transform.parent.gameObject.GetComponent<BasicController>(); if (MyController) { MyController.enabled = false; } Mover MyMover = transform.parent.gameObject.GetComponent<Mover>(); if (MyMover) { MyMover.enabled = false; } //MyAnimator.Stop(); // the bone lines //Debug.Log("Reversing Bone Positions."); for (int i = 0; i < MySkeleton.GetBones().Count; i++) { MySkeleton.GetBones()[i].SetBodyCubePosition(); // reverse transform positions in bone structure } yield return null; //for (int i = MySkeleton.MyBones.Count - 1; i >= 0; i--) for (int i = 0; i < MySkeleton.GetBones().Count; i++) { //Vector3 BeforePosition = MySkeleton.MyBones[i].MyTransform.position; RemoveBone(MySkeleton.GetBones()[i], transform); /*float TimeStarted = Time.time; while (Time.time - TimeStarted <= 3f) { yield return null; } Vector3 AfterPosition = MySkeleton.MyBones[i].MyTransform.position; Debug.LogError(MySkeleton.MyBones[i].MyTransform.name + ": " + i + " before : " + BeforePosition.ToString() + " --- " + AfterPosition.ToString());*/ } yield return null; if (IsApplyJoints) { ApplyJoints(); } float TimeBegun = Time.time; while (Time.time - TimeBegun <= ExplosionPauseTime) { yield return null; } for (int i = 0; i < MySkeleton.GetBones().Count; i++) { Transform BoneTransform = MySkeleton.GetBones()[i].MyTransform; if (BoneTransform) { Rigidbody BoneRigidbody = BoneTransform.GetComponent<Rigidbody>(); if (BoneRigidbody != null) { BoneRigidbody.isKinematic = false; BoneRigidbody.AddExplosionForce(ExplosionForce, transform.position, ExplosionPower * MySkeleton.GetSkeleton().GetBounds().extents.magnitude); BoneRigidbody.AddForce(DownExplosionForce * -Vector3.up); } } } // finally release kinematics } /// <summary> /// Applies joints between all the bones /// </summary> private void ApplyJoints() { for (int i = 0; i < MySkeleton.GetBones().Count; i++) { Transform ChildPart = MySkeleton.GetBones()[i].MyTransform; Transform ParentPart = MySkeleton.GetBones()[i].ParentTransform; if (ParentPart != null && ParentPart != transform) { HingeJoint MyJoint = ChildPart.gameObject.GetComponent<HingeJoint>(); if (MyJoint == null) { MyJoint = ChildPart.gameObject.AddComponent<HingeJoint>(); } MyJoint.breakForce = Mathf.Infinity; MyJoint.connectedBody = ParentPart.GetComponent<Rigidbody>(); MyJoint.enableCollision = true; MyJoint.useSpring = true; MyJoint.autoConfigureConnectedAnchor = false; for (int j = 0; j < MySkeleton.GetBones().Count; j++) { if (MySkeleton.GetBones()[i].ParentTransform == MySkeleton.GetBones()[j].MyTransform) // find parent bone transform { //MyJoint.anchor = MySkeleton.MyBones[j].MyJointCube.transform.localPosition; //MyJoint.anchor = MySkeleton.MyBones[j].MyTransform.localPosition; // get parent Bone MyJoint.anchor = MySkeleton.GetBones()[j].GetJointPosition(); MyJoint.connectedAnchor = MySkeleton.GetBones()[j].GetJointPosition(); break; } } Vector3 OldLocal = ChildPart.localPosition; ChildPart.localPosition -= OldLocal; for (int j = 0; j < ChildPart.childCount; j++) { ChildPart.GetChild(j).localPosition += OldLocal; } } else { //ChildPart.GetComponent<Rigidbody>().freezeRotation = true; } } } /// <summary> /// Detatch the bone from the skeleton heirarchy and attach it to the root bone /// </summary> private void RemoveBone(Bone MyBone, Transform MyRoot) { if (MyBone != null) { MyBone.Detatch(); } } public void AttachBone(Bone MyBone) { if (MyBone != null) { MyBone.AttachBoneToParent(false); MyBone.RemoveDetatchComponents(); } } public void ReverseRagdoll(float ReverseTime = 5) { RagdollHandle = RoutineManager.Get().StartCoroutine(RagdollHandle, ReverseRagdollRoutine(ReverseTime)); } private IEnumerator ReverseRagdollRoutine(float ReverseTime) { if (MySkeleton) { CapsuleCollider MyCapsule = transform.parent.GetComponent<CapsuleCollider>(); if (MyCapsule) { MyCapsule.enabled = true; } Rigidbody MyRigidbody = transform.parent.gameObject.GetComponent<Rigidbody>(); if (MyRigidbody) { MyRigidbody.isKinematic = false; } UnityEngine.Networking.NetworkTransform MyNetworkTransform = transform.parent.gameObject.GetComponent<UnityEngine.Networking.NetworkTransform>(); if (MyNetworkTransform) { MyNetworkTransform.enabled = true; } Zanimator MyAnimator = gameObject.GetComponent<Zanimator>(); if (MyAnimator != null) { MyAnimator.enabled = true; } for (int i = 0; i < MySkeleton.GetBones().Count; i++) { AttachBone(MySkeleton.GetBones()[i]); } MySkeleton.GetSkeleton().RestoreDefaultPose(ReverseTime); Vector3 StartPosition = MyCharacter.transform.position; Quaternion StartRotation = MyCharacter.transform.rotation; float TimeStarted = Time.time; float LerpTime = 0; while (Time.time - TimeStarted <= ReverseTime) { LerpTime = ((Time.time - TimeStarted) / ReverseTime); MyCharacter.transform.position = Vector3.Lerp(StartPosition, RagdolledPosition, LerpTime); MyCharacter.transform.rotation = Quaternion.Lerp(StartRotation, RagdolledRotation, LerpTime); yield return null; } BasicController MyController = transform.parent.gameObject.GetComponent<BasicController>(); if (MyController) { MyController.RefreshRigidbody(); MyController.enabled = true; } Mover MyMover = transform.parent.gameObject.GetComponent<Mover>(); if (MyMover) { MyMover.RefreshRigidbody(); MyMover.enabled = true; } } } } }
#region Apache License // // 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. // #endregion using System; using System.IO; using log4net.Util; namespace log4net.ObjectRenderer { /// <summary> /// Map class objects to an <see cref="IObjectRenderer"/>. /// </summary> /// <remarks> /// <para> /// Maintains a mapping between types that require special /// rendering and the <see cref="IObjectRenderer"/> that /// is used to render them. /// </para> /// <para> /// The <see cref="M:FindAndRender(object)"/> method is used to render an /// <c>object</c> using the appropriate renderers defined in this map. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class RendererMap { private readonly static Type declaringType = typeof(RendererMap); #region Member Variables private System.Collections.Hashtable m_map; private System.Collections.Hashtable m_cache = new System.Collections.Hashtable(); private static IObjectRenderer s_defaultRenderer = new DefaultRenderer(); #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public RendererMap() { m_map = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable()); } #endregion /// <summary> /// Render <paramref name="obj"/> using the appropriate renderer. /// </summary> /// <param name="obj">the object to render to a string</param> /// <returns>the object rendered as a string</returns> /// <remarks> /// <para> /// This is a convenience method used to render an object to a string. /// The alternative method <see cref="M:FindAndRender(object,TextWriter)"/> /// should be used when streaming output to a <see cref="TextWriter"/>. /// </para> /// </remarks> public string FindAndRender(object obj) { // Optimisation for strings string strData = obj as String; if (strData != null) { return strData; } StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); FindAndRender(obj, stringWriter); return stringWriter.ToString(); } /// <summary> /// Render <paramref name="obj"/> using the appropriate renderer. /// </summary> /// <param name="obj">the object to render to a string</param> /// <param name="writer">The writer to render to</param> /// <remarks> /// <para> /// Find the appropriate renderer for the type of the /// <paramref name="obj"/> parameter. This is accomplished by calling the /// <see cref="M:Get(Type)"/> method. Once a renderer is found, it is /// applied on the object <paramref name="obj"/> and the result is returned /// as a <see cref="string"/>. /// </para> /// </remarks> public void FindAndRender(object obj, TextWriter writer) { if (obj == null) { writer.Write(SystemInfo.NullText); } else { // Optimisation for strings string str = obj as string; if (str != null) { writer.Write(str); } else { // Lookup the renderer for the specific type try { Get(obj.GetType()).RenderObject(this, obj, writer); } catch(Exception ex) { // Exception rendering the object log4net.Util.LogLog.Error(declaringType, "Exception while rendering object of type ["+obj.GetType().FullName+"]", ex); // return default message string objectTypeName = ""; if (obj != null && obj.GetType() != null) { objectTypeName = obj.GetType().FullName; } writer.Write("<log4net.Error>Exception rendering object type ["+objectTypeName+"]"); if (ex != null) { string exceptionText = null; try { exceptionText = ex.ToString(); } catch { // Ignore exception } writer.Write("<stackTrace>" + exceptionText + "</stackTrace>"); } writer.Write("</log4net.Error>"); } } } } /// <summary> /// Gets the renderer for the specified object type /// </summary> /// <param name="obj">the object to lookup the renderer for</param> /// <returns>the renderer for <paramref name="obj"/></returns> /// <remarks> /// <param> /// Gets the renderer for the specified object type. /// </param> /// <param> /// Syntactic sugar method that calls <see cref="M:Get(Type)"/> /// with the type of the object parameter. /// </param> /// </remarks> public IObjectRenderer Get(Object obj) { if (obj == null) { return null; } else { return Get(obj.GetType()); } } /// <summary> /// Gets the renderer for the specified type /// </summary> /// <param name="type">the type to lookup the renderer for</param> /// <returns>the renderer for the specified type</returns> /// <remarks> /// <para> /// Returns the renderer for the specified type. /// If no specific renderer has been defined the /// <see cref="DefaultRenderer"/> will be returned. /// </para> /// </remarks> public IObjectRenderer Get(Type type) { if (type == null) { throw new ArgumentNullException("type"); } IObjectRenderer result = null; // Check cache result = (IObjectRenderer)m_cache[type]; if (result == null) { for(Type cur = type; cur != null; cur = cur.BaseType) { // Search the type's interfaces result = SearchTypeAndInterfaces(cur); if (result != null) { break; } } // if not set then use the default renderer if (result == null) { result = s_defaultRenderer; } // Add to cache m_cache[type] = result; } return result; } /// <summary> /// Internal function to recursively search interfaces /// </summary> /// <param name="type">the type to lookup the renderer for</param> /// <returns>the renderer for the specified type</returns> private IObjectRenderer SearchTypeAndInterfaces(Type type) { IObjectRenderer r = (IObjectRenderer)m_map[type]; if (r != null) { return r; } else { foreach(Type t in type.GetInterfaces()) { r = SearchTypeAndInterfaces(t); if (r != null) { return r; } } } return null; } /// <summary> /// Get the default renderer instance /// </summary> /// <value>the default renderer</value> /// <remarks> /// <para> /// Get the default renderer /// </para> /// </remarks> public IObjectRenderer DefaultRenderer { get { return s_defaultRenderer; } } /// <summary> /// Clear the map of renderers /// </summary> /// <remarks> /// <para> /// Clear the custom renderers defined by using /// <see cref="Put"/>. The <see cref="DefaultRenderer"/> /// cannot be removed. /// </para> /// </remarks> public void Clear() { m_map.Clear(); m_cache.Clear(); } /// <summary> /// Register an <see cref="IObjectRenderer"/> for <paramref name="typeToRender"/>. /// </summary> /// <param name="typeToRender">the type that will be rendered by <paramref name="renderer"/></param> /// <param name="renderer">the renderer for <paramref name="typeToRender"/></param> /// <remarks> /// <para> /// Register an object renderer for a specific source type. /// This renderer will be returned from a call to <see cref="M:Get(Type)"/> /// specifying the same <paramref name="typeToRender"/> as an argument. /// </para> /// </remarks> public void Put(Type typeToRender, IObjectRenderer renderer) { m_cache.Clear(); if (typeToRender == null) { throw new ArgumentNullException("typeToRender"); } if (renderer == null) { throw new ArgumentNullException("renderer"); } m_map[typeToRender] = renderer; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net { #region usings using System; using System.Text; using MIME; using SIP.Message; #endregion /// <summary> /// Implements SIP-URI. Defined in 3261. /// </summary> /// <remarks> /// <code> /// RFC 3261 Syntax: /// SIP-URI = "sip:" [ userinfo ] hostport uri-parameters [ headers ] /// SIPS-URI = "sips:" [ userinfo ] hostport uri-parameters [ headers ] /// userinfo = ( user / telephone-subscriber ) [ ":" password ] "@") /// hostport = host [ ":" port ] /// host = hostname / IPv4address / IPv6reference /// </code> /// </remarks> public class SIP_Uri : AbsoluteUri { #region Members private readonly SIP_ParameterCollection m_pParameters; private string m_Header; private string m_Host = ""; private int m_Port = -1; private string m_User; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_Uri() { m_pParameters = new SIP_ParameterCollection(); } #endregion #region Properties /// <summary> /// Gets address from SIP URI. Examples: ivar@lumisoft.ee,ivar@195.222.10.1. /// </summary> public string Address { get { return m_User + "@" + m_Host; } } /// <summary> /// Gets or sets header. /// </summary> public string Header { get { return m_Header; } set { m_Header = value; } } /// <summary> /// Gets or sets host name or IP. /// </summary> public string Host { get { return m_Host; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Property Host value can't be null or '' !"); } m_Host = value; } } /// <summary> /// Gets host with optional port. If port specified returns Host:Port, otherwise Host. /// </summary> public string HostPort { get { if (m_Port == -1) { return m_Host; } else { return m_Host + ":" + m_Port; } } } /// <summary> /// Gets or sets if secure SIP. If true then sips: uri, otherwise sip: uri. /// </summary> public bool IsSecure { get; set; } /// <summary> /// Gets or sets 'cause' parameter value. Value -1 means not specified. /// Cause is a URI parameter that is used to indicate the service that /// the User Agent Server (UAS) receiving the message should perform. /// Defined in RFC 4458. /// </summary> public int Param_Cause { get { SIP_Parameter parameter = Parameters["cause"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("cause"); } else { Parameters.Set("cause", value.ToString()); } } } /// <summary> /// Gets or sets 'comp' parameter value. Value null means not specified. Defined in RFC 3486. /// </summary> public string Param_Comp { get { SIP_Parameter parameter = Parameters["comp"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("comp"); } else { Parameters.Set("comp", value); } } } /// <summary> /// Gets or sets 'content-type' parameter value. Value null means not specified. Defined in RFC 4240. /// </summary> public string Param_ContentType { get { SIP_Parameter parameter = Parameters["content-type"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("content-type"); } else { Parameters.Set("content-type", value); } } } /// <summary> /// Gets or sets 'delay' prameter value. Value -1 means not specified. /// Specifies a delay interval between announcement repetitions. The delay is measured in milliseconds. /// Defined in RFC 4240. /// </summary> public int Param_Delay { get { SIP_Parameter parameter = Parameters["delay"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("delay"); } else { Parameters.Set("delay", value.ToString()); } } } /// <summary> /// Gets or sets 'duration' prameter value. Value -1 means not specified. /// Specifies the maximum duration of the announcement. The media server will discontinue /// the announcement and end the call if the maximum duration has been reached. The duration /// is measured in milliseconds. Defined in RFC 4240. /// </summary> public int Param_Duration { get { SIP_Parameter parameter = Parameters["duration"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("duration"); } else { Parameters.Set("duration", value.ToString()); } } } /// <summary> /// Gets or sets 'locale' prameter value. Specifies the language and optionally country /// variant of the announcement sequence named in the "play=" parameter. Defined in RFC 4240. /// </summary> public string Param_Locale { get { SIP_Parameter parameter = Parameters["locale"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("locale"); } else { Parameters.Set("locale", value); } } } /// <summary> /// Gets or sets 'lr' parameter. The lr parameter, when present, indicates that the element /// responsible for this resource implements the routing mechanisms /// specified in this document. Defined in RFC 3261. /// </summary> public bool Param_Lr { get { SIP_Parameter parameter = Parameters["lr"]; if (parameter != null) { return true; } else { return false; } } set { if (!value) { Parameters.Remove("lr"); } else { Parameters.Set("lr", null); } } } /// <summary> /// Gets or sets 'maddr' parameter value. Value null means not specified. /// <a style="font-weight: bold; color: red">NOTE: This value is deprecated in since SIP 2.0.</a> /// The maddr parameter indicates the server address to be contacted for this user, /// overriding any address derived from the host field. Defined in RFC 3261. /// </summary> public string Param_Maddr { get { SIP_Parameter parameter = Parameters["maddr"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("maddr"); } else { Parameters.Set("maddr", value); } } } /// <summary> /// Gets or sets 'method' prameter value. Value null means not specified. Defined in RFC 3261. /// </summary> public string Param_Method { get { SIP_Parameter parameter = Parameters["method"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("method"); } else { Parameters.Set("method", value); } } } // param[n] No [RFC4240] /// <summary> /// Gets or sets 'play' parameter value. Value null means not specified. /// Specifies the resource or announcement sequence to be played. Defined in RFC 4240. /// </summary> public string Param_Play { get { SIP_Parameter parameter = Parameters["play"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("play"); } else { Parameters.Set("play", value); } } } /// <summary> /// Gets or sets 'repeat' parameter value. Value -1 means not specified, value int.MaxValue means 'forever'. /// Specifies how many times the media server should repeat the announcement or sequence named by /// the "play=" parameter. Defined in RFC 4240. /// </summary> public int Param_Repeat { get { SIP_Parameter parameter = Parameters["ttl"]; if (parameter != null) { if (parameter.Value.ToLower() == "forever") { return int.MaxValue; } else { return Convert.ToInt32(parameter.Value); } } else { return -1; } } set { if (value == -1) { Parameters.Remove("ttl"); } else if (value == int.MaxValue) { Parameters.Set("ttl", "forever"); } else { Parameters.Set("ttl", value.ToString()); } } } /// <summary> /// Gets or sets 'target' parameter value. Value null means not specified. Defined in RFC 4240. /// </summary> public string Param_Target { get { SIP_Parameter parameter = Parameters["target"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("target"); } else { Parameters.Set("target", value); } } } /// <summary> /// Gets or sets 'transport' parameter value. Value null means not specified. /// The transport parameter determines the transport mechanism to /// be used for sending SIP messages. Defined in RFC 3261. /// </summary> public string Param_Transport { get { SIP_Parameter parameter = Parameters["transport"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("transport"); } else { Parameters.Set("transport", value); } } } /// <summary> /// Gets or sets 'ttl' parameter value. Value -1 means not specified. /// <a style="font-weight: bold; color: red">NOTE: This value is deprecated in since SIP 2.0.</a> /// The ttl parameter determines the time-to-live value of the UDP /// multicast packet and MUST only be used if maddr is a multicast /// address and the transport protocol is UDP. Defined in RFC 3261. /// </summary> public int Param_Ttl { get { SIP_Parameter parameter = Parameters["ttl"]; if (parameter != null) { return Convert.ToInt32(parameter.Value); } else { return -1; } } set { if (value == -1) { Parameters.Remove("ttl"); } else { Parameters.Set("ttl", value.ToString()); } } } /// <summary> /// Gets or sets 'user' parameter value. Value null means not specified. Defined in RFC 3261. /// </summary> public string Param_User { get { SIP_Parameter parameter = Parameters["user"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("user"); } else { Parameters.Set("user", value); } } } /// <summary> /// Gets or sets 'voicexml' parameter value. Value null means not specified. Defined in RFC 4240. /// </summary> public string Param_Voicexml { get { SIP_Parameter parameter = Parameters["voicexml"]; if (parameter != null) { return parameter.Value; } else { return null; } } set { if (value == null) { Parameters.Remove("voicexml"); } else { Parameters.Set("voicexml", value); } } } /// <summary> /// Gets URI parameters. /// </summary> public SIP_ParameterCollection Parameters { get { return m_pParameters; } } /// <summary> /// Gets or sets host port. Value -1 means not specified. /// </summary> public int Port { get { return m_Port; } set { m_Port = value; } } /// <summary> /// Gets URI scheme. /// </summary> public override string Scheme { get { if (IsSecure) { return "sips"; } else { return "sip"; } } } /// <summary> /// Gets or sets user name. Value null means not specified. /// </summary> public string User { get { return m_User; } set { m_User = value; } } #endregion #region Methods /// <summary> /// Parse SIP or SIPS URI from string value. /// </summary> /// <param name="value">String URI value.</param> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when <b>value</b> is not valid SIP or SIPS URI.</exception> public new static SIP_Uri Parse(string value) { AbsoluteUri uri = AbsoluteUri.Parse(value); if (uri is SIP_Uri) { return (SIP_Uri) uri; } else { throw new ArgumentException("Argument 'value' is not valid SIP or SIPS URI."); } } /// <summary> /// Compares the current instance with another object of the same type. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>Returns true if two objects are equal.</returns> public override bool Equals(object obj) { /* RFC 3261 19.1.4 URI Comparison. SIP and SIPS URIs are compared for equality according to the following rules: o A SIP and SIPS URI are never equivalent. o Comparison of the userinfo of SIP and SIPS URIs is case- sensitive. This includes userinfo containing passwords or formatted as telephone-subscribers. Comparison of all other components of the URI is case-insensitive unless explicitly defined otherwise. o The ordering of parameters and header fields is not significant in comparing SIP and SIPS URIs. o Characters other than those in the "reserved" set (see RFC 2396 [5]) are equivalent to their ""%" HEX HEX" encoding. o An IP address that is the result of a DNS lookup of a host name does not match that host name. o For two URIs to be equal, the user, password, host, and port components must match. A URI omitting the user component will not match a URI that includes one. A URI omitting the password component will not match a URI that includes one. A URI omitting any component with a default value will not match a URI explicitly containing that component with its default value. For instance, a URI omitting the optional port component will not match a URI explicitly declaring port 5060. The same is true for the transport-parameter, ttl-parameter, user-parameter, and method components. o URI uri-parameter components are compared as follows: - Any uri-parameter appearing in both URIs must match. - A user, ttl, or method uri-parameter appearing in only one URI never matches, even if it contains the default value. - A URI that includes an maddr parameter will not match a URI that contains no maddr parameter. - All other uri-parameters appearing in only one URI are ignored when comparing the URIs. o URI header components are never ignored. Any present header component MUST be present in both URIs and match for the URIs to match. */ if (obj == null) { return false; } if (!(obj is SIP_Uri)) { return false; } SIP_Uri sipUri = (SIP_Uri) obj; if (IsSecure && !sipUri.IsSecure) { return false; } if (User != sipUri.User) { return false; } /* if(this.Password != sipUri.Password){ return false; }*/ if (Host.ToLower() != sipUri.Host.ToLower()) { return false; } if (Port != sipUri.Port) { return false; } // TODO: prameters compare // TODO: header fields compare return true; } /// <summary> /// Returns the hash code. /// </summary> /// <returns>Returns the hash code.</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Converts SIP_Uri to valid SIP-URI string. /// </summary> /// <returns>Returns SIP-URI string.</returns> public override string ToString() { // Syntax: sip:/sips: username@host *[;parameter] [?header *[&header]] StringBuilder retVal = new StringBuilder(); if (IsSecure) { retVal.Append("sips:"); } else { retVal.Append("sip:"); } if (User != null) { retVal.Append(User + "@"); } retVal.Append(Host); if (Port > -1) { retVal.Append(":" + Port); } // Add URI parameters. foreach (SIP_Parameter parameter in m_pParameters) { /* * If value is token value is not quoted(quoted-string). * If value contains `tspecials', value should be represented as quoted-string. * If value is empty string, only parameter name is added. */ if (parameter.Value != null) { if (MIME_Reader.IsToken(parameter.Value)) { retVal.Append(";" + parameter.Name + "=" + parameter.Value); } else { retVal.Append(";" + parameter.Name + "=" + TextUtils.QuoteString(parameter.Value)); } } else { retVal.Append(";" + parameter.Name); } } if (Header != null) { retVal.Append("?" + Header); } return retVal.ToString(); } #endregion #region Overrides /// <summary> /// Parses SIP_Uri from SIP-URI string. /// </summary> /// <param name="value">SIP-URI string.</param> /// <returns>Returns parsed SIP_Uri object.</returns> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> protected override void ParseInternal(string value) { // Syntax: sip:/sips: username@host:port *[;parameter] [?header *[&header]] if (value == null) { throw new ArgumentNullException("value"); } value = Uri.UnescapeDataString(value); if (!(value.ToLower().StartsWith("sip:") || value.ToLower().StartsWith("sips:"))) { throw new SIP_ParseException("Specified value is invalid SIP-URI !"); } StringReader r = new StringReader(value); // IsSecure IsSecure = r.QuotedReadToDelimiter(':').ToLower() == "sips"; // Get username if (r.SourceString.IndexOf('@') > -1) { User = r.QuotedReadToDelimiter('@'); } // Gets host[:port] string[] host_port = r.QuotedReadToDelimiter(new[] {';', '?'}, false).Split(':'); Host = host_port[0]; // Optional port specified if (host_port.Length == 2) { Port = Convert.ToInt32(host_port[1]); } // We have parameters and/or header if (r.Available > 0) { // Get parameters string[] parameters = TextUtils.SplitQuotedString(r.QuotedReadToDelimiter('?'), ';'); foreach (string parameter in parameters) { if (parameter.Trim() != "") { string[] name_value = parameter.Trim().Split(new[] {'='}, 2); if (name_value.Length == 2) { Parameters.Add(name_value[0], TextUtils.UnQuoteString(name_value[1])); } else { Parameters.Add(name_value[0], null); } } } // We have header if (r.Available > 0) { m_Header = r.ReadToEnd(); } } } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.UnitTests.Targets { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Xunit; using Xunit.Extensions; using NLog.Config; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; using NLog.Internal; using NLog.LayoutRenderers; public class FileTargetTests : NLogTestBase { private readonly ILogger logger = LogManager.GetLogger("NLog.UnitTests.Targets.FileTargetTests"); private void GenerateArchives(int count, string archiveDateFormat, string archiveFileName, ArchiveNumberingMode archiveNumbering) { string logFileName = Path.GetTempFileName(); const int logFileMaxSize = 1; var ft = new FileTarget { FileName = logFileName, ArchiveFileName = archiveFileName, ArchiveDateFormat = archiveDateFormat, ArchiveNumbering = archiveNumbering, ArchiveAboveSize = logFileMaxSize }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); for (int currentSequenceNumber = 0; currentSequenceNumber < count; currentSequenceNumber++) logger.Debug("Test {0}", currentSequenceNumber); } [Fact] public void SimpleFileTest1() { var tempFile = Path.GetTempFileName(); try { var ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } [Fact] public void CsvHeaderTest() { var tempFile = Path.GetTempFileName(); try { for (var i = 0; i < 2; i++) { var layout = new CsvLayout { Delimiter = CsvColumnDelimiterMode.Semicolon, WithHeader = true, Columns = { new CsvColumn("name", "${logger}"), new CsvColumn("level", "${level}"), new CsvColumn("message", "${message}"), } }; var ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = layout, OpenFileCacheTimeout = 0, ReplaceFileContentsOnEachWrite = false }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); LogManager.Configuration = null; } AssertFileContents(tempFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } [Fact] public void DeleteFileOnStartTest() { var tempFile = Path.GetTempFileName(); try { var ft = new FileTarget { DeleteOldFileOnStartup = false, FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, without // DeleteOldFileOnStartup ft = new FileTarget { DeleteOldFileOnStartup = false, FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // configure again, this time with // DeleteOldFileOnStartup ft = new FileTarget { FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", DeleteOldFileOnStartup = true }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); } } [Fact] public void ArchiveFileOnStartTest() { ArchiveFileOnStartTests(enableCompression: false); } #if NET4_5 [Fact] public void ArchiveFileOnStartTest_WithCompression() { ArchiveFileOnStartTests(enableCompression: true); } #endif private void ArchiveFileOnStartTests(bool enableCompression) { var tempFile = Path.GetTempFileName(); var tempArchiveFolder = Path.Combine(Path.GetTempPath(), "Archive"); var archiveExtension = enableCompression ? "zip" : "txt"; try { // Configure first time with ArchiveOldFileOnStartup = false. var ft = new FileTarget { ArchiveOldFileOnStartup = false, FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // Configure second time with ArchiveOldFileOnStartup = false again. // Expected behavior: Extra content to be appended to the file. ft = new FileTarget { ArchiveOldFileOnStartup = false, FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); // Configure third time with ArchiveOldFileOnStartup = true again. // Expected behavior: Extra content will be stored in a new file; the // old content should be moved into a new location. var archiveTempName = Path.Combine(tempArchiveFolder, "archive." + archiveExtension); ft = new FileTarget { #if NET4_5 EnableArchiveFileCompression = enableCompression, #endif FileName = SimpleLayout.Escape(tempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", ArchiveOldFileOnStartup = true, ArchiveFileName = archiveTempName, ArchiveNumbering = ArchiveNumberingMode.Sequence, MaxArchiveFiles = 1 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("ddd"); logger.Info("eee"); logger.Warn("fff"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug ddd\nInfo eee\nWarn fff\n", Encoding.UTF8); Assert.True(File.Exists(archiveTempName)); var assertFileContents = #if NET4_5 enableCompression ? new Action<string, string, Encoding>(AssertZipFileContents) : AssertFileContents; #else new Action<string, string, Encoding>(AssertFileContents); #endif assertFileContents(archiveTempName, "Debug aaa\nInfo bbb\nWarn ccc\nDebug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempArchiveFolder)) Directory.Delete(tempArchiveFolder, true); } } [Fact] public void CreateDirsTest() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, LineEnding = LineEndingMode.LF, Layout = "${level} ${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); LogManager.Configuration = null; AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void SequentialArchiveTest1() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"), ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 3, ArchiveNumbering = ArchiveNumberingMode.Sequence }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); // we emit 5 * 250 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives Generate1000BytesLog('a'); Generate1000BytesLog('b'); Generate1000BytesLog('c'); Generate1000BytesLog('d'); Generate1000BytesLog('e'); LogManager.Configuration = null; AssertFileContents(tempFile, StringRepeat(250, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0001.txt"), StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0002.txt"), StringRepeat(250, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0003.txt"), StringRepeat(250, "ddd\n"), Encoding.UTF8); //0000 should not extists because of MaxArchiveFiles=3 Assert.True(!File.Exists(Path.Combine(tempPath, "archive/0000.txt"))); Assert.True(!File.Exists(Path.Combine(tempPath, "archive/0004.txt"))); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void SequentialArchiveTest1_MaxArchiveFiles_0() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"), ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", MaxArchiveFiles = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); // we emit 5 * 250 *(3 x aaa + \n) bytes // so that we should get a full file + 4 archives Generate1000BytesLog('a'); Generate1000BytesLog('b'); Generate1000BytesLog('c'); Generate1000BytesLog('d'); Generate1000BytesLog('e'); LogManager.Configuration = null; AssertFileContents(tempFile, StringRepeat(250, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0000.txt"), StringRepeat(250, "aaa\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0001.txt"), StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0002.txt"), StringRepeat(250, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0003.txt"), StringRepeat(250, "ddd\n"), Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(tempPath, "archive/0004.txt"))); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact(Skip = "this is not supported, because we cannot create multiple archive files with ArchiveNumberingMode.Date (for one day)")] public void ArchiveAboveSizeWithArchiveNumberingModeDate_maxfiles_o() { var tempPath = Path.Combine(Path.GetTempPath(), "ArchiveEveryCombinedWithArchiveAboveSize_" + Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"), ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, Layout = "${message}", ArchiveNumbering = ArchiveNumberingMode.Date }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //e.g. 20150804 var archiveFileName = DateTime.Now.ToString("yyyyMMdd"); // we emit 5 * 250 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives for (var i = 0; i < 250; ++i) { logger.Debug("aaa"); } for (var i = 0; i < 250; ++i) { logger.Debug("bbb"); } for (var i = 0; i < 250; ++i) { logger.Debug("ccc"); } for (var i = 0; i < 250; ++i) { logger.Debug("ddd"); } for (var i = 0; i < 250; ++i) { logger.Debug("eee"); } LogManager.Configuration = null; //we expect only eee and all other in the archive AssertFileContents(tempFile, StringRepeat(250, "eee\n"), Encoding.UTF8); //DUNNO what to expected! //try (which fails) AssertFileContents( Path.Combine(tempPath, string.Format("archive/{0}.txt", archiveFileName)), StringRepeat(250, "aaa\n") + StringRepeat(250, "bbb\n") + StringRepeat(250, "ccc\n") + StringRepeat(250, "ddd\n"), Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void DeleteArchiveFilesByDate() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{#}.txt"), ArchiveAboveSize = 50, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = 3 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing 19 times 10 bytes (9 char + linefeed) will result in 3 archive files and 1 current file for (var i = 0; i < 19; ++i) { logger.Debug("123456789"); //build in a small sleep to make sure the current time is reflected in the filename //do this every 5 entries if (i % 5 == 0) Thread.Sleep(50); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; var archivePath = Path.Combine(tempPath, "archive"); var files = Directory.GetFiles(archivePath).OrderBy(s => s); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(ft.MaxArchiveFiles, files.Count()); SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing just one line of 11 bytes will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest file logger.Debug("1234567890"); LogManager.Configuration = null; var files2 = Directory.GetFiles(archivePath).OrderBy(s => s); Assert.Equal(ft.MaxArchiveFiles, files2.Count()); //the oldest file should be deleted Assert.DoesNotContain(files.ElementAt(0), files2); //two files should still be there Assert.Equal(files.ElementAt(1), files2.ElementAt(0)); Assert.Equal(files.ElementAt(2), files2.ElementAt(1)); //one new archive file shoud be created Assert.DoesNotContain(files2.ElementAt(2), files); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void DeleteArchiveFilesByDateWithDateName() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "${date:format=yyyyMMddHHmmssfff}.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "{#}.txt"), ArchiveEvery = FileArchivePeriod.Minute, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = 3 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing 4 times 10 bytes (9 char + linefeed) will result in 2 archive files and 1 current file for (var i = 0; i < 4; ++i) { logger.Debug("123456789"); //build in a sleep to make sure the current time is reflected in the filename Thread.Sleep(50); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; var files = Directory.GetFiles(tempPath).OrderBy(s => s); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(ft.MaxArchiveFiles, files.Count()); SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing 50ms later will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest file Thread.Sleep(50); logger.Debug("123456789"); LogManager.Configuration = null; var files2 = Directory.GetFiles(tempPath).OrderBy(s => s); Assert.Equal(ft.MaxArchiveFiles, files2.Count()); //the oldest file should be deleted Assert.DoesNotContain(files.ElementAt(0), files2); //two files should still be there Assert.Equal(files.ElementAt(1), files2.ElementAt(0)); Assert.Equal(files.ElementAt(2), files2.ElementAt(1)); //one new archive file shoud be created Assert.DoesNotContain(files2.ElementAt(2), files); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } public static IEnumerable<object[]> DateArchive_UsesDateFromCurrentTimeSource_TestParameters { get { var booleanValues = new[] { true, false }; var timeKindValues = new[] { DateTimeKind.Utc, DateTimeKind.Local }; return from concurrentWrites in booleanValues from keepFileOpen in booleanValues from networkWrites in booleanValues from timeKind in timeKindValues select new object[] { timeKind, concurrentWrites, keepFileOpen, networkWrites }; } } [Theory] [PropertyData("DateArchive_UsesDateFromCurrentTimeSource_TestParameters")] public void DateArchive_UsesDateFromCurrentTimeSource(DateTimeKind timeKind, bool concurrentWrites, bool keepFileOpen, bool networkWrites) { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); var defaultTimeSource = TimeSource.Current; try { var timeSource = new TimeSourceTests.ShiftedTimeSource(timeKind); TimeSource.Current = timeSource; var archiveFileNameTemplate = Path.Combine(tempPath, "archive/{#}.txt"); var ft = new FileTarget { FileName = tempFile, ArchiveFileName = archiveFileNameTemplate, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveEvery = FileArchivePeriod.Day, ArchiveDateFormat = "yyyyMMdd", Layout = "${date:format=O}|${message}", MaxArchiveFiles = 3, ConcurrentWrites = concurrentWrites, KeepFileOpen = keepFileOpen, NetworkWrites = networkWrites, }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); logger.Debug("123456789"); DateTime previousWriteTime = timeSource.Time; const int daysToTestLogging = 5; const int intervalsPerDay = 24; var loggingInterval = TimeSpan.FromHours(1); for (var i = 0; i < daysToTestLogging * intervalsPerDay; ++i) { timeSource.AddToLocalTime(loggingInterval); var eventInfo = new LogEventInfo(LogLevel.Debug, logger.Name, "123456789"); logger.Log(eventInfo); var dayIsChanged = eventInfo.TimeStamp.Date != previousWriteTime.Date; // ensure new archive is created only when the day part of time is changed var archiveFileName = archiveFileNameTemplate.Replace("{#}", previousWriteTime.ToString(ft.ArchiveDateFormat)); var archiveExists = File.Exists(archiveFileName); if (dayIsChanged) Assert.True(archiveExists, string.Format("new archive should be created when the day part of {0} time is changed", timeKind)); else Assert.False(archiveExists, string.Format("new archive should not be create when day part of {0} time is unchanged", timeKind)); previousWriteTime = eventInfo.TimeStamp.Date; if (dayIsChanged) timeSource.AddToSystemTime(TimeSpan.FromDays(1)); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; var archivePath = Path.Combine(tempPath, "archive"); var files = Directory.GetFiles(archivePath).OrderBy(s => s).ToList(); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(ft.MaxArchiveFiles, files.Count); SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing one line on a new day will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest file timeSource.AddToLocalTime(TimeSpan.FromDays(1)); logger.Debug("1234567890"); LogManager.Configuration = null; var files2 = Directory.GetFiles(archivePath).OrderBy(s => s).ToList(); Assert.Equal(ft.MaxArchiveFiles, files2.Count); //the oldest file should be deleted Assert.DoesNotContain(files[0], files2); //two files should still be there Assert.Equal(files[1], files2[0]); Assert.Equal(files[2], files2[1]); //one new archive file shoud be created Assert.DoesNotContain(files2[2], files); } finally { TimeSource.Current = defaultTimeSource; // restore default time source LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void DeleteArchiveFilesByDate_MaxArchiveFiles_0() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{#}.txt"), ArchiveAboveSize = 50, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing 19 times 10 bytes (9 char + linefeed) will result in 3 archive files and 1 current file for (var i = 0; i < 19; ++i) { logger.Debug("123456789"); //build in a small sleep to make sure the current time is reflected in the filename //do this every 5 entries if (i % 5 == 0) { Thread.Sleep(50); } } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; var archivePath = Path.Combine(tempPath, "archive"); var fileCount = Directory.EnumerateFiles(archivePath).Count(); Assert.Equal(3, fileCount); SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //create 1 new file for archive logger.Debug("1234567890"); LogManager.Configuration = null; var fileCount2 = Directory.EnumerateFiles(archivePath).Count(); //there should be 1 more file Assert.Equal(4, fileCount2); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } } } [Fact] public void DeleteArchiveFilesByDate_AlteredMaxArchive() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{#}.txt"), ArchiveAboveSize = 50, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Date, ArchiveDateFormat = "yyyyMMddHHmmssfff", //make sure the milliseconds are set in the filename Layout = "${message}", MaxArchiveFiles = 5 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing 29 times 10 bytes (9 char + linefeed) will result in 3 archive files and 1 current file for (var i = 0; i < 29; ++i) { logger.Debug("123456789"); //build in a small sleep to make sure the current time is reflected in the filename //do this every 5 entries if (i % 5 == 0) Thread.Sleep(50); } //Setting the Configuration to [null] will result in a 'Dump' of the current log entries LogManager.Configuration = null; var archivePath = Path.Combine(tempPath, "archive"); var files = Directory.GetFiles(archivePath).OrderBy(s => s); //the amount of archived files may not exceed the set 'MaxArchiveFiles' Assert.Equal(ft.MaxArchiveFiles, files.Count()); //alter the MaxArchivedFiles ft.MaxArchiveFiles = 2; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //writing just one line of 11 bytes will trigger the cleanup of old archived files //as stated by the MaxArchiveFiles property, but will only delete the oldest files logger.Debug("1234567890"); LogManager.Configuration = null; var files2 = Directory.GetFiles(archivePath).OrderBy(s => s); Assert.Equal(ft.MaxArchiveFiles, files2.Count()); //the oldest files should be deleted Assert.DoesNotContain(files.ElementAt(0), files2); Assert.DoesNotContain(files.ElementAt(1), files2); Assert.DoesNotContain(files.ElementAt(2), files2); Assert.DoesNotContain(files.ElementAt(3), files2); //one files should still be there Assert.Equal(files.ElementAt(4), files2.ElementAt(0)); //one new archive file shoud be created Assert.DoesNotContain(files2.ElementAt(1), files); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void RepeatingHeaderTest() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { const string header = "Headerline"; var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"), ArchiveAboveSize = 51, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Sequence, Layout = "${message}", Header = header, MaxArchiveFiles = 2, }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); for (var i = 0; i < 16; ++i) { logger.Debug("123456789"); } LogManager.Configuration = null; AssertFileContentsStartsWith(tempFile, header, Encoding.UTF8); AssertFileContentsStartsWith(Path.Combine(tempPath, "archive/0002.txt"), header, Encoding.UTF8); AssertFileContentsStartsWith(Path.Combine(tempPath, "archive/0001.txt"), header, Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(tempPath, "archive/0000.txt"))); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void RollingArchiveTest1() { RollingArchiveTests(enableCompression: false); } #if NET4_5 [Fact] public void RollingArchiveCompressionTest1() { RollingArchiveTests(enableCompression: true); } #endif private void RollingArchiveTests(bool enableCompression) { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); var archiveExtension = enableCompression ? "zip" : "txt"; try { var ft = new FileTarget { #if NET4_5 EnableArchiveFileCompression = enableCompression, #endif FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{####}." + archiveExtension), ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Rolling, Layout = "${message}", MaxArchiveFiles = 3 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); // we emit 5 * 250 * (3 x aaa + \n) bytes // so that we should get a full file + 3 archives Generate1000BytesLog('a'); Generate1000BytesLog('b'); Generate1000BytesLog('c'); Generate1000BytesLog('d'); Generate1000BytesLog('e'); LogManager.Configuration = null; var assertFileContents = #if NET4_5 enableCompression ? new Action<string, string, Encoding>(AssertZipFileContents) : AssertFileContents; #else new Action<string, string, Encoding>(AssertFileContents); #endif AssertFileContents(tempFile, StringRepeat(250, "eee\n"), Encoding.UTF8); assertFileContents( Path.Combine(tempPath, "archive/0000." + archiveExtension), StringRepeat(250, "ddd\n"), Encoding.UTF8); assertFileContents( Path.Combine(tempPath, "archive/0001." + archiveExtension), StringRepeat(250, "ccc\n"), Encoding.UTF8); assertFileContents( Path.Combine(tempPath, "archive/0002." + archiveExtension), StringRepeat(250, "bbb\n"), Encoding.UTF8); Assert.True(!File.Exists(Path.Combine(tempPath, "archive/0003." + archiveExtension))); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void RollingArchiveTest_MaxArchiveFiles_0() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{####}.txt"), ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, ArchiveNumbering = ArchiveNumberingMode.Rolling, Layout = "${message}", MaxArchiveFiles = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); // we emit 5 * 250 * (3 x aaa + \n) bytes // so that we should get a full file + 4 archives Generate1000BytesLog('a'); Generate1000BytesLog('b'); Generate1000BytesLog('c'); Generate1000BytesLog('d'); Generate1000BytesLog('e'); LogManager.Configuration = null; AssertFileContents(tempFile, StringRepeat(250, "eee\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0000.txt"), StringRepeat(250, "ddd\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0001.txt"), StringRepeat(250, "ccc\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0002.txt"), StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/0003.txt"), StringRepeat(250, "aaa\n"), Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(tempPath)) { Directory.Delete(tempPath, true); } } } [Fact] public void MultiFileWrite() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var ft = new FileTarget { FileName = Path.Combine(tempPath, "${level}.txt"), LineEnding = LineEndingMode.LF, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); for (var i = 0; i < 250; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("ddd"); logger.Fatal("eee"); } LogManager.Configuration = null; Assert.False(File.Exists(Path.Combine(tempPath, "Trace.txt"))); AssertFileContents(Path.Combine(tempPath, "Debug.txt"), StringRepeat(250, "aaa\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Info.txt"), StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Warn.txt"), StringRepeat(250, "ccc\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Error.txt"), StringRepeat(250, "ddd\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Fatal.txt"), StringRepeat(250, "eee\n"), Encoding.UTF8); } finally { //if (File.Exists(tempFile)) // File.Delete(tempFile); LogManager.Configuration = null; if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void BufferedMultiFileWrite() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var ft = new FileTarget { FileName = Path.Combine(tempPath, "${level}.txt"), LineEnding = LineEndingMode.LF, Layout = "${message}" }; SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 10), LogLevel.Debug); for (var i = 0; i < 250; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("ddd"); logger.Fatal("eee"); } LogManager.Configuration = null; Assert.False(File.Exists(Path.Combine(tempPath, "Trace.txt"))); AssertFileContents(Path.Combine(tempPath, "Debug.txt"), StringRepeat(250, "aaa\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Info.txt"), StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Warn.txt"), StringRepeat(250, "ccc\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Error.txt"), StringRepeat(250, "ddd\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Fatal.txt"), StringRepeat(250, "eee\n"), Encoding.UTF8); } finally { //if (File.Exists(tempFile)) // File.Delete(tempFile); LogManager.Configuration = null; if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void AsyncMultiFileWrite() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); try { var ft = new FileTarget { FileName = Path.Combine(tempPath, "${level}.txt"), LineEnding = LineEndingMode.LF, Layout = "${message} ${threadid}" }; // this also checks that thread-volatile layouts // such as ${threadid} are properly cached and not recalculated // in logging threads. var threadID = Thread.CurrentThread.ManagedThreadId.ToString(); SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 1000, AsyncTargetWrapperOverflowAction.Grow), LogLevel.Debug); LogManager.ThrowExceptions = true; for (var i = 0; i < 250; ++i) { logger.Trace("@@@"); logger.Debug("aaa"); logger.Info("bbb"); logger.Warn("ccc"); logger.Error("ddd"); logger.Fatal("eee"); } LogManager.Flush(); LogManager.Configuration = null; Assert.False(File.Exists(Path.Combine(tempPath, "Trace.txt"))); AssertFileContents(Path.Combine(tempPath, "Debug.txt"), StringRepeat(250, "aaa " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Info.txt"), StringRepeat(250, "bbb " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Warn.txt"), StringRepeat(250, "ccc " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Error.txt"), StringRepeat(250, "ddd " + threadID + "\n"), Encoding.UTF8); AssertFileContents(Path.Combine(tempPath, "Fatal.txt"), StringRepeat(250, "eee " + threadID + "\n"), Encoding.UTF8); } finally { //if (File.Exists(tempFile)) // File.Delete(tempFile); LogManager.Configuration = null; if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); // Clean up configuration change, breaks onetimeonlyexceptioninhandlertest LogManager.ThrowExceptions = true; } } [Fact] public void BatchErrorHandlingTest() { var fileTarget = new FileTarget { FileName = "${logger}", Layout = "${message}" }; fileTarget.Initialize(null); // make sure that when file names get sorted, the asynchronous continuations are sorted with them as well var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Info, "file99.txt", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "", "msg1").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "", "msg2").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "", "msg3").WithContinuation(exceptions.Add) }; fileTarget.WriteAsyncLogEvents(events); Assert.Equal(4, exceptions.Count); Assert.Null(exceptions[0]); Assert.NotNull(exceptions[1]); Assert.NotNull(exceptions[2]); Assert.NotNull(exceptions[3]); } [Fact] public void DisposingFileTarget_WhenNotIntialized_ShouldNotThrow() { var exceptionThrown = false; var fileTarget = new FileTarget(); try { fileTarget.Dispose(); } catch { exceptionThrown = true; } Assert.False(exceptionThrown); } [Fact] public void FileTarget_ArchiveNumbering_DateAndSequence() { FileTarget_ArchiveNumbering_DateAndSequenceTests(enableCompression: false); } #if NET4_5 [Fact] public void FileTarget_ArchiveNumbering_DateAndSequence_WithCompression() { FileTarget_ArchiveNumbering_DateAndSequenceTests(enableCompression: true); } #endif private void FileTarget_ArchiveNumbering_DateAndSequenceTests(bool enableCompression) { var tempPath = ArchiveFilenameHelper.GenerateTempPath(); var tempFile = Path.Combine(tempPath, "file.txt"); var archiveExtension = enableCompression ? "zip" : "txt"; try { var ft = new FileTarget { #if NET4_5 EnableArchiveFileCompression = enableCompression, #endif FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{#}." + archiveExtension), ArchiveDateFormat = "yyyy-MM-dd", ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 3, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, ArchiveEvery = FileArchivePeriod.Day }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); // we emit 5 * 250 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives Generate1000BytesLog('a'); Generate1000BytesLog('b'); Generate1000BytesLog('c'); Generate1000BytesLog('d'); Generate1000BytesLog('e'); string archiveFilename = DateTime.Now.ToString(ft.ArchiveDateFormat); LogManager.Configuration = null; #if NET4_5 var assertFileContents = enableCompression ? new Action<string, string, Encoding>(AssertZipFileContents) : AssertFileContents; #else var assertFileContents = new Action<string, string, Encoding>(AssertFileContents); #endif ArchiveFilenameHelper helper = new ArchiveFilenameHelper(Path.Combine(tempPath, "archive"), archiveFilename, archiveExtension); AssertFileContents(tempFile, StringRepeat(250, "eee\n"), Encoding.UTF8); assertFileContents(helper.GetFullPath(1), StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileSize(helper.GetFullPath(1), ft.ArchiveAboveSize); assertFileContents(helper.GetFullPath(2), StringRepeat(250, "ccc\n"), Encoding.UTF8); AssertFileSize(helper.GetFullPath(2), ft.ArchiveAboveSize); assertFileContents(helper.GetFullPath(3), StringRepeat(250, "ddd\n"), Encoding.UTF8); AssertFileSize(helper.GetFullPath(3), ft.ArchiveAboveSize); Assert.True(!helper.Exists(0), "old one removed - max files"); Assert.True(!helper.Exists(4), "stop at 3"); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void FileTarget_WithArchiveFileNameEndingInNumberPlaceholder_ShouldArchiveFile() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/test.log.{####}"), ArchiveAboveSize = 1000 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); for (var i = 0; i < 100; ++i) { logger.Debug("a"); } LogManager.Configuration = null; Assert.True(File.Exists(tempFile)); Assert.True(File.Exists(Path.Combine(tempPath, "archive/test.log.0000"))); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } [Fact] public void FileTarget_InvalidFileNameCorrection() { var tempFile = Path.GetTempFileName(); var invalidTempFile = tempFile + Path.GetInvalidFileNameChars()[0]; var expectedCorrectedTempFile = tempFile + "_"; try { var ft = new FileTarget { FileName = SimpleLayout.Escape(invalidTempFile), LineEnding = LineEndingMode.LF, Layout = "${level} ${message}", OpenFileCacheTimeout = 0 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Fatal); logger.Fatal("aaa"); LogManager.Configuration = null; AssertFileContents(expectedCorrectedTempFile, "Fatal aaa\n", Encoding.UTF8); } finally { if (File.Exists(invalidTempFile)) File.Delete(invalidTempFile); if (File.Exists(expectedCorrectedTempFile)) File.Delete(expectedCorrectedTempFile); } } [Fact] public void FileTarget_LogAndArchiveFilesWithSameName_ShouldArchive() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var logFile = Path.Combine(tempPath, "Application.log"); var tempDirectory = new DirectoryInfo(tempPath); try { var archiveFile = Path.Combine(tempPath, "Application{#}.log"); var archiveFileMask = "Application*.log"; var ft = new FileTarget { FileName = logFile, ArchiveFileName = archiveFile, ArchiveAboveSize = 1, //Force immediate archival ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, MaxArchiveFiles = 5 }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); //Creates 5 archive files. for (int i = 0; i <= 5; i++) { logger.Debug("a"); } Assert.True(File.Exists(logFile)); //Five archive files, plus the log file itself. Assert.True(tempDirectory.GetFiles(archiveFileMask).Count() == 5 + 1); } finally { LogManager.Configuration = null; if (tempDirectory.Exists) { tempDirectory.Delete(true); } } } [Fact] public void Single_Archive_File_Rolls_Correctly() { var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var tempFile = Path.Combine(tempPath, "file.txt"); try { var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/file.txt2"), ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = 1, }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); // we emit 5 * 250 *(3 x aaa + \n) bytes // so that we should get a full file + 3 archives for (var i = 0; i < 250; ++i) { logger.Debug("aaa"); } for (var i = 0; i < 250; ++i) { logger.Debug("bbb"); } LogManager.Configuration = null; AssertFileContents(tempFile, StringRepeat(250, "bbb\n"), Encoding.UTF8); AssertFileContents( Path.Combine(tempPath, "archive/file.txt2"), StringRepeat(250, "aaa\n"), Encoding.UTF8); } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } /// <summary> /// Remove archived files in correct order /// </summary> [Fact] public void FileTarget_ArchiveNumbering_remove_correct_order() { var tempPath = ArchiveFilenameHelper.GenerateTempPath(); var tempFile = Path.Combine(tempPath, "file.txt"); var archiveExtension = "txt"; try { var maxArchiveFiles = 10; var ft = new FileTarget { FileName = tempFile, ArchiveFileName = Path.Combine(tempPath, "archive/{#}." + archiveExtension), ArchiveDateFormat = "yyyy-MM-dd", ArchiveAboveSize = 1000, LineEnding = LineEndingMode.LF, Layout = "${message}", MaxArchiveFiles = maxArchiveFiles, ArchiveNumbering = ArchiveNumberingMode.DateAndSequence, }; SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug); ArchiveFilenameHelper helper = new ArchiveFilenameHelper(Path.Combine(tempPath, "archive"), DateTime.Now.ToString(ft.ArchiveDateFormat), archiveExtension); Generate1000BytesLog('a'); for (int i = 0; i < maxArchiveFiles; i++) { Generate1000BytesLog('a'); Assert.True(helper.Exists(i), string.Format("file {0} is missing", i)); } for (int i = maxArchiveFiles; i < 100; i++) { Generate1000BytesLog('b'); var numberToBeRemoved = i - maxArchiveFiles; // number 11, we need to remove 1 etc Assert.True(!helper.Exists(numberToBeRemoved), string.Format("archive file {0} has not been removed! We are created file {1}", numberToBeRemoved, i)); } } finally { LogManager.Configuration = null; if (File.Exists(tempFile)) File.Delete(tempFile); if (Directory.Exists(tempPath)) Directory.Delete(tempPath, true); } } private void Generate1000BytesLog(char c) { for (var i = 0; i < 250; ++i) { //3 chars with newlines = 4 bytes logger.Debug(new string(c, 3)); } } /// <summary> /// Archive file helepr /// </summary> /// <remarks>TODO rewrite older test</remarks> private class ArchiveFilenameHelper { public string FolderName { get; private set; } public string FileName { get; private set; } /// <summary> /// Ext without dot /// </summary> public string Ext { get; set; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public ArchiveFilenameHelper(string folderName, string fileName, string ext) { Ext = ext; FileName = fileName; FolderName = folderName; } public bool Exists(int number) { return File.Exists(GetFullPath(number)); } public string GetFullPath(int number) { return Path.Combine(String.Format("{0}/{1}.{2}.{3}", FolderName, FileName, number, Ext)); } public static string GenerateTempPath() { return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); } } [Theory] [InlineData("##", 0, "00")] [InlineData("###", 1, "001")] [InlineData("#", 20, "20")] public void FileTarget_WithDateAndSequenceArchiveNumbering_ShouldPadSequenceNumberInArchiveFileName( string placeHolderSharps, int sequenceNumber, string expectedSequenceInArchiveFileName) { string archivePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); const string archiveDateFormat = "yyyy-MM-dd"; string archiveFileName = Path.Combine(archivePath, String.Format("{{{0}}}.log", placeHolderSharps)); string expectedArchiveFullName = String.Format("{0}/{1}.{2}.log", archivePath, DateTime.Now.ToString(archiveDateFormat), expectedSequenceInArchiveFileName); GenerateArchives(count: sequenceNumber + 1, archiveDateFormat: archiveDateFormat, archiveFileName: archiveFileName, archiveNumbering: ArchiveNumberingMode.DateAndSequence); bool resultArchiveWithExpectedNameExists = File.Exists(expectedArchiveFullName); Assert.True(resultArchiveWithExpectedNameExists); } [Theory] [InlineData("yyyy-MM-dd HHmm")] [InlineData("y")] [InlineData("D")] public void FileTarget_WithDateAndSequenceArchiveNumbering_ShouldRespectArchiveDateFormat( string archiveDateFormat) { string archivePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); string archiveFileName = Path.Combine(archivePath, "{#}.log"); string expectedDateInArchiveFileName = DateTime.Now.ToString(archiveDateFormat); string expectedArchiveFullName = String.Format("{0}/{1}.1.log", archivePath, expectedDateInArchiveFileName); // We generate 2 archives so that the algorithm that seeks old archives is also tested. GenerateArchives(count: 2, archiveDateFormat: archiveDateFormat, archiveFileName: archiveFileName, archiveNumbering: ArchiveNumberingMode.DateAndSequence); bool resultArchiveWithExpectedNameExists = File.Exists(expectedArchiveFullName); Assert.True(resultArchiveWithExpectedNameExists); } } } #endif
// ==++== // // Copyright(c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Reflection { using System; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using System.Threading; // // Invocation cached flags. Those are used in unmanaged code as well // so be careful if you change them // [Flags] internal enum INVOCATION_FLAGS : uint { INVOCATION_FLAGS_UNKNOWN = 0x00000000, INVOCATION_FLAGS_INITIALIZED = 0x00000001, // it's used for both method and field to signify that no access is allowed INVOCATION_FLAGS_NO_INVOKE = 0x00000002, INVOCATION_FLAGS_NEED_SECURITY = 0x00000004, // Set for static ctors and ctors on abstract types, which // can be invoked only if the "this" object is provided (even if it's null). INVOCATION_FLAGS_NO_CTOR_INVOKE = 0x00000008, // because field and method are different we can reuse the same bits // method INVOCATION_FLAGS_IS_CTOR = 0x00000010, INVOCATION_FLAGS_RISKY_METHOD = 0x00000020, INVOCATION_FLAGS_NON_W8P_FX_API = 0x00000040, INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080, INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100, // field INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010, INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020, // temporary flag used for flagging invocation of method vs ctor // this flag never appears on the instance m_invocationFlag and is simply // passed down from within ConstructorInfo.Invoke() INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000, } [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodBase))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract partial class MethodBase : MemberInfo, _MethodBase { #region Static Members public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); #if MONO MethodBase m = GetMethodFromHandleInternalType (handle.Value, IntPtr.Zero); if (m == null) throw new ArgumentException ("The handle is invalid."); #else MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo()); #endif Type declaringType = m.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"), m, declaringType.GetGenericTypeDefinition())); return m; } [System.Runtime.InteropServices.ComVisible(false)] public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); #if MONO MethodBase m = GetMethodFromHandleInternalType (handle.Value, declaringType.Value); if (m == null) throw new ArgumentException ("The handle is invalid."); return m; #else return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo()); #endif } #if MONO [MethodImplAttribute (MethodImplOptions.InternalCall)] public extern static MethodBase GetCurrentMethod (); #else [System.Security.DynamicSecurityMethod] // Specify DynamicSecurityMethod attribute to prevent inlining of the caller. [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static MethodBase GetCurrentMethod() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark); } #endif #endregion #region Constructor protected MethodBase() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(MethodBase left, MethodBase right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null) return false; MethodInfo method1, method2; ConstructorInfo constructor1, constructor2; if ((method1 = left as MethodInfo) != null && (method2 = right as MethodInfo) != null) return method1 == method2; else if ((constructor1 = left as ConstructorInfo) != null && (constructor2 = right as ConstructorInfo) != null) return constructor1 == constructor2; return false; } public static bool operator !=(MethodBase left, MethodBase right) { return !(left == right); } #endif // !FEATURE_CORECLR #if FEATURE_NETCORE || !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #endif //FEATURE_NETCORE || !FEATURE_CORECLR #region Internal Members // used by EE [System.Security.SecurityCritical] private IntPtr GetMethodDesc() { return MethodHandle.Value; } #if FEATURE_APPX // The C# dynamic and VB late bound binders need to call this API. Since we don't have time to make this // public in Dev11, the C# and VB binders currently call this through a delegate. // When we make this API public (hopefully) in Dev12 we need to change the C# and VB binders to call this // probably statically. The code is located in: // C#: ndp\fx\src\CSharp\Microsoft\CSharp\SymbolTable.cs - Microsoft.CSharp.RuntimeBinder.SymbolTable..cctor // VB: vb\runtime\msvbalib\helpers\Symbols.vb - Microsoft.VisualBasic.CompilerServices.Symbols..cctor internal virtual bool IsDynamicallyInvokable { get { return true; } } #endif #endregion #region Public Abstract\Virtual Members internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters (); } [System.Diagnostics.Contracts.Pure] public abstract ParameterInfo[] GetParameters(); public virtual MethodImplAttributes MethodImplementationFlags { get { return GetMethodImplementationFlags(); } } public abstract MethodImplAttributes GetMethodImplementationFlags(); public abstract RuntimeMethodHandle MethodHandle { get; } public abstract MethodAttributes Attributes { get; } public abstract Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); public virtual CallingConventions CallingConvention { get { return CallingConventions.Standard; } } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual bool IsGenericMethodDefinition { get { return false; } } public virtual bool ContainsGenericParameters { get { return false; } } public virtual bool IsGenericMethod { get { return false; } } public virtual bool IsSecurityCritical { get { throw new NotImplementedException(); } } public virtual bool IsSecuritySafeCritical { get { throw new NotImplementedException(); } } public virtual bool IsSecurityTransparent { get { throw new NotImplementedException(); } } #endregion #region _MethodBase Implementation Type _MethodBase.GetType() { return base.GetType(); } bool _MethodBase.IsPublic { get { return IsPublic; } } bool _MethodBase.IsPrivate { get { return IsPrivate; } } bool _MethodBase.IsFamily { get { return IsFamily; } } bool _MethodBase.IsAssembly { get { return IsAssembly; } } bool _MethodBase.IsFamilyAndAssembly { get { return IsFamilyAndAssembly; } } bool _MethodBase.IsFamilyOrAssembly { get { return IsFamilyOrAssembly; } } bool _MethodBase.IsStatic { get { return IsStatic; } } bool _MethodBase.IsFinal { get { return IsFinal; } } bool _MethodBase.IsVirtual { get { return IsVirtual; } } bool _MethodBase.IsHideBySig { get { return IsHideBySig; } } bool _MethodBase.IsAbstract { get { return IsAbstract; } } bool _MethodBase.IsSpecialName { get { return IsSpecialName; } } bool _MethodBase.IsConstructor { get { return IsConstructor; } } #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public Object Invoke(Object obj, Object[] parameters) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. return Invoke(obj, BindingFlags.Default, null, parameters, null); } public bool IsPublic { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } } public bool IsPrivate { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } } public bool IsFamily { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } } public bool IsAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } } public bool IsFamilyAndAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } } public bool IsFamilyOrAssembly { get {return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } } public bool IsStatic { get { return(Attributes & MethodAttributes.Static) != 0; } } public bool IsFinal { get { return(Attributes & MethodAttributes.Final) != 0; } } public bool IsVirtual { get { return(Attributes & MethodAttributes.Virtual) != 0; } } public bool IsHideBySig { get { return(Attributes & MethodAttributes.HideBySig) != 0; } } public bool IsAbstract { get { return(Attributes & MethodAttributes.Abstract) != 0; } } public bool IsSpecialName { get { return(Attributes & MethodAttributes.SpecialName) != 0; } } [System.Runtime.InteropServices.ComVisible(true)] public bool IsConstructor { get { // To be backward compatible we only return true for instance RTSpecialName ctors. return (this is ConstructorInfo && !IsStatic && ((Attributes & MethodAttributes.RTSpecialName) == MethodAttributes.RTSpecialName)); } } [System.Security.SecuritySafeCritical] #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 public virtual MethodBody GetMethodBody() { throw new InvalidOperationException(); } #endregion #region Internal Methods // helper method to construct the string representation of the parameter list // internal static string ConstructParameters(Type[] parameterTypes, CallingConventions callingConvention, bool serialization) { StringBuilder sbParamList = new StringBuilder(); string comma = ""; for (int i = 0; i < parameterTypes.Length; i++) { Type t = parameterTypes[i]; sbParamList.Append(comma); string typeName = t.FormatTypeName(serialization); // Legacy: Why use "ByRef" for by ref parameters? What language is this? // VB uses "ByRef" but it should precede (not follow) the parameter name. // Why don't we just use "&"? if (t.IsByRef && !serialization) { sbParamList.Append(typeName.TrimEnd(new char[] { '&' })); sbParamList.Append(" ByRef"); } else { sbParamList.Append(typeName); } comma = ", "; } if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { sbParamList.Append(comma); sbParamList.Append("..."); } return sbParamList.ToString(); } internal string FullName { get { return String.Format("{0}.{1}", DeclaringType.FullName, FormatNameAndSig()); } } internal string FormatNameAndSig() { return FormatNameAndSig(false); } internal virtual string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } internal virtual Type[] GetParameterTypes() { ParameterInfo[] paramInfo = GetParametersNoCopy(); Type[] parameterTypes = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) parameterTypes[i] = paramInfo[i].ParameterType; return parameterTypes; } #if !MONO [System.Security.SecuritySafeCritical] internal Object[] CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) { // copy the arguments in a different array so we detach from any user changes Object[] copyOfParameters = new Object[parameters.Length]; ParameterInfo[] p = null; for (int i = 0; i < parameters.Length; i++) { Object arg = parameters[i]; RuntimeType argRT = sig.Arguments[i]; if (arg == Type.Missing) { if (p == null) p = GetParametersNoCopy(); if (p[i].DefaultValue == System.DBNull.Value) throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters"); arg = p[i].DefaultValue; } copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr); } return copyOfParameters; } #endif #endregion void _MethodBase.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodBase.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _MethodBase.Invoke in VM\DangerousAPIs.h and // include _MethodBase in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _MethodBase.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Batch { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// BatchAccountOperations operations. /// </summary> public partial interface IBatchAccountOperations { /// <summary> /// Creates a new Batch account with the specified parameters. Existing /// accounts cannot be updated with this API and should instead be /// updated with the Update Batch Account API. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the new Batch account. /// </param> /// <param name='accountName'> /// A name for the Batch account which must be unique within the /// region. Batch account names must be between 3 and 24 characters in /// length and must use only numbers and lowercase letters. This name /// is used as part of the DNS name that is used to access the Batch /// service in the region in which the account is created. For example: /// http://accountname.region.batch.azure.com/. /// </param> /// <param name='parameters'> /// Additional parameters for account creation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<BatchAccount,BatchAccountCreateHeaders>> CreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates the properties of an existing Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the account. /// </param> /// <param name='parameters'> /// Additional parameters for account update. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<BatchAccount>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account to /// be deleted. /// </param> /// <param name='accountName'> /// The name of the account to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<BatchAccountDeleteHeaders>> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<BatchAccount>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the Batch accounts associated with the /// subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<BatchAccount>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the Batch accounts associated within the /// specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group whose Batch accounts to list. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<BatchAccount>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Synchronizes access keys for the auto storage account configured /// for the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the Batch account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> SynchronizeAutoStorageKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the specified account key for the Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the account. /// </param> /// <param name='keyName'> /// The type of account key to regenerate. Possible values include: /// 'Primary', 'Secondary' /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<BatchAccountKeys>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string accountName, AccountKeyType keyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the account keys for the specified Batch account. /// </summary> /// <remarks> /// This operation applies only to Batch accounts created with a /// poolAllocationMode of 'BatchService'. If the Batch account was /// created with a poolAllocationMode of 'UserSubscription', clients /// cannot use access to keys to authenticate, and must use Azure /// Active Directory instead. In this case, getting the keys will fail. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account. /// </param> /// <param name='accountName'> /// The name of the account. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<BatchAccountKeys>> GetKeysWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new Batch account with the specified parameters. Existing /// accounts cannot be updated with this API and should instead be /// updated with the Update Batch Account API. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the new Batch account. /// </param> /// <param name='accountName'> /// A name for the Batch account which must be unique within the /// region. Batch account names must be between 3 and 24 characters in /// length and must use only numbers and lowercase letters. This name /// is used as part of the DNS name that is used to access the Batch /// service in the region in which the account is created. For example: /// http://accountname.region.batch.azure.com/. /// </param> /// <param name='parameters'> /// Additional parameters for account creation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<BatchAccount,BatchAccountCreateHeaders>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, BatchAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified Batch account. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the Batch account to /// be deleted. /// </param> /// <param name='accountName'> /// The name of the account to be deleted. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationHeaderResponse<BatchAccountDeleteHeaders>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the Batch accounts associated with the /// subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<BatchAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the Batch accounts associated within the /// specified resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<BatchAccount>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// NewAccountDefinition /// </summary> [DataContract] public partial class NewAccountDefinition : IEquatable<NewAccountDefinition>, IValidatableObject { public NewAccountDefinition() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="NewAccountDefinition" /> class. /// </summary> /// <param name="AccountName">The account name for the new account..</param> /// <param name="AccountSettings">AccountSettings.</param> /// <param name="AddressInformation">AddressInformation.</param> /// <param name="CreditCardInformation">CreditCardInformation.</param> /// <param name="DirectDebitProcessorInformation">DirectDebitProcessorInformation.</param> /// <param name="DistributorCode">The code that identifies the billing plan groups and plans for the new account..</param> /// <param name="DistributorPassword">The password for the distributorCode..</param> /// <param name="EnvelopePartitionId">EnvelopePartitionId.</param> /// <param name="InitialUser">InitialUser.</param> /// <param name="PaymentMethod">PaymentMethod.</param> /// <param name="PaymentProcessorInformation">PaymentProcessorInformation.</param> /// <param name="PlanInformation">PlanInformation.</param> /// <param name="ReferralInformation">ReferralInformation.</param> /// <param name="SocialAccountInformation">SocialAccountInformation.</param> /// <param name="TaxExemptId">TaxExemptId.</param> public NewAccountDefinition(string AccountName = default(string), AccountSettingsInformation AccountSettings = default(AccountSettingsInformation), AccountAddress AddressInformation = default(AccountAddress), CreditCardInformation CreditCardInformation = default(CreditCardInformation), DirectDebitProcessorInformation DirectDebitProcessorInformation = default(DirectDebitProcessorInformation), string DistributorCode = default(string), string DistributorPassword = default(string), string EnvelopePartitionId = default(string), UserInformation InitialUser = default(UserInformation), string PaymentMethod = default(string), PaymentProcessorInformation PaymentProcessorInformation = default(PaymentProcessorInformation), PlanInformation PlanInformation = default(PlanInformation), ReferralInformation ReferralInformation = default(ReferralInformation), SocialAccountInformation SocialAccountInformation = default(SocialAccountInformation), string TaxExemptId = default(string)) { this.AccountName = AccountName; this.AccountSettings = AccountSettings; this.AddressInformation = AddressInformation; this.CreditCardInformation = CreditCardInformation; this.DirectDebitProcessorInformation = DirectDebitProcessorInformation; this.DistributorCode = DistributorCode; this.DistributorPassword = DistributorPassword; this.EnvelopePartitionId = EnvelopePartitionId; this.InitialUser = InitialUser; this.PaymentMethod = PaymentMethod; this.PaymentProcessorInformation = PaymentProcessorInformation; this.PlanInformation = PlanInformation; this.ReferralInformation = ReferralInformation; this.SocialAccountInformation = SocialAccountInformation; this.TaxExemptId = TaxExemptId; } /// <summary> /// The account name for the new account. /// </summary> /// <value>The account name for the new account.</value> [DataMember(Name="accountName", EmitDefaultValue=false)] public string AccountName { get; set; } /// <summary> /// Gets or Sets AccountSettings /// </summary> [DataMember(Name="accountSettings", EmitDefaultValue=false)] public AccountSettingsInformation AccountSettings { get; set; } /// <summary> /// Gets or Sets AddressInformation /// </summary> [DataMember(Name="addressInformation", EmitDefaultValue=false)] public AccountAddress AddressInformation { get; set; } /// <summary> /// Gets or Sets CreditCardInformation /// </summary> [DataMember(Name="creditCardInformation", EmitDefaultValue=false)] public CreditCardInformation CreditCardInformation { get; set; } /// <summary> /// Gets or Sets DirectDebitProcessorInformation /// </summary> [DataMember(Name="directDebitProcessorInformation", EmitDefaultValue=false)] public DirectDebitProcessorInformation DirectDebitProcessorInformation { get; set; } /// <summary> /// The code that identifies the billing plan groups and plans for the new account. /// </summary> /// <value>The code that identifies the billing plan groups and plans for the new account.</value> [DataMember(Name="distributorCode", EmitDefaultValue=false)] public string DistributorCode { get; set; } /// <summary> /// The password for the distributorCode. /// </summary> /// <value>The password for the distributorCode.</value> [DataMember(Name="distributorPassword", EmitDefaultValue=false)] public string DistributorPassword { get; set; } /// <summary> /// Gets or Sets EnvelopePartitionId /// </summary> [DataMember(Name="envelopePartitionId", EmitDefaultValue=false)] public string EnvelopePartitionId { get; set; } /// <summary> /// Gets or Sets InitialUser /// </summary> [DataMember(Name="initialUser", EmitDefaultValue=false)] public UserInformation InitialUser { get; set; } /// <summary> /// Gets or Sets PaymentMethod /// </summary> [DataMember(Name="paymentMethod", EmitDefaultValue=false)] public string PaymentMethod { get; set; } /// <summary> /// Gets or Sets PaymentProcessorInformation /// </summary> [DataMember(Name="paymentProcessorInformation", EmitDefaultValue=false)] public PaymentProcessorInformation PaymentProcessorInformation { get; set; } /// <summary> /// Gets or Sets PlanInformation /// </summary> [DataMember(Name="planInformation", EmitDefaultValue=false)] public PlanInformation PlanInformation { get; set; } /// <summary> /// Gets or Sets ReferralInformation /// </summary> [DataMember(Name="referralInformation", EmitDefaultValue=false)] public ReferralInformation ReferralInformation { get; set; } /// <summary> /// Gets or Sets SocialAccountInformation /// </summary> [DataMember(Name="socialAccountInformation", EmitDefaultValue=false)] public SocialAccountInformation SocialAccountInformation { get; set; } /// <summary> /// Gets or Sets TaxExemptId /// </summary> [DataMember(Name="taxExemptId", EmitDefaultValue=false)] public string TaxExemptId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class NewAccountDefinition {\n"); sb.Append(" AccountName: ").Append(AccountName).Append("\n"); sb.Append(" AccountSettings: ").Append(AccountSettings).Append("\n"); sb.Append(" AddressInformation: ").Append(AddressInformation).Append("\n"); sb.Append(" CreditCardInformation: ").Append(CreditCardInformation).Append("\n"); sb.Append(" DirectDebitProcessorInformation: ").Append(DirectDebitProcessorInformation).Append("\n"); sb.Append(" DistributorCode: ").Append(DistributorCode).Append("\n"); sb.Append(" DistributorPassword: ").Append(DistributorPassword).Append("\n"); sb.Append(" EnvelopePartitionId: ").Append(EnvelopePartitionId).Append("\n"); sb.Append(" InitialUser: ").Append(InitialUser).Append("\n"); sb.Append(" PaymentMethod: ").Append(PaymentMethod).Append("\n"); sb.Append(" PaymentProcessorInformation: ").Append(PaymentProcessorInformation).Append("\n"); sb.Append(" PlanInformation: ").Append(PlanInformation).Append("\n"); sb.Append(" ReferralInformation: ").Append(ReferralInformation).Append("\n"); sb.Append(" SocialAccountInformation: ").Append(SocialAccountInformation).Append("\n"); sb.Append(" TaxExemptId: ").Append(TaxExemptId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as NewAccountDefinition); } /// <summary> /// Returns true if NewAccountDefinition instances are equal /// </summary> /// <param name="other">Instance of NewAccountDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(NewAccountDefinition other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.AccountName == other.AccountName || this.AccountName != null && this.AccountName.Equals(other.AccountName) ) && ( this.AccountSettings == other.AccountSettings || this.AccountSettings != null && this.AccountSettings.Equals(other.AccountSettings) ) && ( this.AddressInformation == other.AddressInformation || this.AddressInformation != null && this.AddressInformation.Equals(other.AddressInformation) ) && ( this.CreditCardInformation == other.CreditCardInformation || this.CreditCardInformation != null && this.CreditCardInformation.Equals(other.CreditCardInformation) ) && ( this.DirectDebitProcessorInformation == other.DirectDebitProcessorInformation || this.DirectDebitProcessorInformation != null && this.DirectDebitProcessorInformation.Equals(other.DirectDebitProcessorInformation) ) && ( this.DistributorCode == other.DistributorCode || this.DistributorCode != null && this.DistributorCode.Equals(other.DistributorCode) ) && ( this.DistributorPassword == other.DistributorPassword || this.DistributorPassword != null && this.DistributorPassword.Equals(other.DistributorPassword) ) && ( this.EnvelopePartitionId == other.EnvelopePartitionId || this.EnvelopePartitionId != null && this.EnvelopePartitionId.Equals(other.EnvelopePartitionId) ) && ( this.InitialUser == other.InitialUser || this.InitialUser != null && this.InitialUser.Equals(other.InitialUser) ) && ( this.PaymentMethod == other.PaymentMethod || this.PaymentMethod != null && this.PaymentMethod.Equals(other.PaymentMethod) ) && ( this.PaymentProcessorInformation == other.PaymentProcessorInformation || this.PaymentProcessorInformation != null && this.PaymentProcessorInformation.Equals(other.PaymentProcessorInformation) ) && ( this.PlanInformation == other.PlanInformation || this.PlanInformation != null && this.PlanInformation.Equals(other.PlanInformation) ) && ( this.ReferralInformation == other.ReferralInformation || this.ReferralInformation != null && this.ReferralInformation.Equals(other.ReferralInformation) ) && ( this.SocialAccountInformation == other.SocialAccountInformation || this.SocialAccountInformation != null && this.SocialAccountInformation.Equals(other.SocialAccountInformation) ) && ( this.TaxExemptId == other.TaxExemptId || this.TaxExemptId != null && this.TaxExemptId.Equals(other.TaxExemptId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.AccountName != null) hash = hash * 59 + this.AccountName.GetHashCode(); if (this.AccountSettings != null) hash = hash * 59 + this.AccountSettings.GetHashCode(); if (this.AddressInformation != null) hash = hash * 59 + this.AddressInformation.GetHashCode(); if (this.CreditCardInformation != null) hash = hash * 59 + this.CreditCardInformation.GetHashCode(); if (this.DirectDebitProcessorInformation != null) hash = hash * 59 + this.DirectDebitProcessorInformation.GetHashCode(); if (this.DistributorCode != null) hash = hash * 59 + this.DistributorCode.GetHashCode(); if (this.DistributorPassword != null) hash = hash * 59 + this.DistributorPassword.GetHashCode(); if (this.EnvelopePartitionId != null) hash = hash * 59 + this.EnvelopePartitionId.GetHashCode(); if (this.InitialUser != null) hash = hash * 59 + this.InitialUser.GetHashCode(); if (this.PaymentMethod != null) hash = hash * 59 + this.PaymentMethod.GetHashCode(); if (this.PaymentProcessorInformation != null) hash = hash * 59 + this.PaymentProcessorInformation.GetHashCode(); if (this.PlanInformation != null) hash = hash * 59 + this.PlanInformation.GetHashCode(); if (this.ReferralInformation != null) hash = hash * 59 + this.ReferralInformation.GetHashCode(); if (this.SocialAccountInformation != null) hash = hash * 59 + this.SocialAccountInformation.GetHashCode(); if (this.TaxExemptId != null) hash = hash * 59 + this.TaxExemptId.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.ComponentModel; using System.ComponentModel.Design; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Windows; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.PythonTools.Profiling { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true)] [Description("Python Tools Profiling Package")] // TODO: Localization: does this do anything? // This attribute is used to register the informations needed to show the this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [Guid(GuidList.guidPythonProfilingPkgString)] // set the window to dock where Toolbox/Performance Explorer dock by default [ProvideToolWindow(typeof(PerfToolWindow), Orientation = ToolWindowOrientation.Left, Style = VsDockStyle.Tabbed, Window = EnvDTE.Constants.vsWindowKindToolbox)] [ProvideFileFilterAttribute("{81da0100-e6db-4783-91ea-c38c3fa1b81e}", "/1", "Python Performance Session (*.pyperf);*.pyperf", 100)] // TODO: Localization [ProvideEditorExtension(typeof(ProfilingSessionEditorFactory), ".pyperf", 50, ProjectGuid = "{81da0100-e6db-4783-91ea-c38c3fa1b81e}", NameResourceID = 105, DefaultName = "PythonPerfSession")] [ProvideAutomationObject("PythonProfiling")] sealed class PythonProfilingPackage : Package { internal static PythonProfilingPackage Instance; private static ProfiledProcess _profilingProcess; // process currently being profiled internal static readonly string PythonProjectGuid = "{888888a0-9f3d-457c-b088-3a5042f75d52}"; internal static readonly string PerformanceFileFilter = Strings.PerformanceReportFilesFilter; private AutomationProfiling _profilingAutomation; private static OleMenuCommand _stopCommand, _startCommand; /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public PythonProfilingPackage() { Instance = this; } protected override void Dispose(bool disposing) { if (disposing) { var process = _profilingProcess; _profilingProcess = null; if (process != null) { process.Dispose(); } } base.Dispose(disposing); } /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initilaization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Ensure Python Tools package is loaded var shell = (IVsShell)GetService(typeof(SVsShell)); var ptvsPackage = GuidList.guidPythonToolsPackage; IVsPackage pkg; ErrorHandler.ThrowOnFailure(shell.LoadPackage(ptvsPackage, out pkg)); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidStartPythonProfiling); MenuCommand menuItem = new MenuCommand(StartProfilingWizard, menuCommandID); mcs.AddCommand(menuItem); // Create the command for the menu item. menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidPerfExplorer); var oleMenuItem = new OleMenuCommand(ShowPeformanceExplorer, menuCommandID); mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidAddPerfSession); menuItem = new MenuCommand(AddPerformanceSession, menuCommandID); mcs.AddCommand(menuItem); menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidStartProfiling); oleMenuItem = _startCommand = new OleMenuCommand(StartProfiling, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingActive; mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidStopProfiling); _stopCommand = oleMenuItem = new OleMenuCommand(StopProfiling, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingInactive; mcs.AddCommand(oleMenuItem); } //Create Editor Factory. Note that the base Package class will call Dispose on it. base.RegisterEditorFactory(new ProfilingSessionEditorFactory(this)); } protected override object GetAutomationObject(string name) { if (name == "PythonProfiling") { if (_profilingAutomation == null) { var pane = (PerfToolWindow)this.FindToolWindow(typeof(PerfToolWindow), 0, true); _profilingAutomation = new AutomationProfiling(pane.Sessions); } return _profilingAutomation; } return base.GetAutomationObject(name); } internal static Guid GetStartupProjectGuid(IServiceProvider serviceProvider) { var buildMgr = (IVsSolutionBuildManager)serviceProvider.GetService(typeof(IVsSolutionBuildManager)); IVsHierarchy hierarchy; if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out hierarchy)) && hierarchy != null) { Guid guid; if (ErrorHandler.Succeeded(hierarchy.GetGuidProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out guid ))) { return guid; } } return Guid.Empty; } internal IVsSolution Solution { get { return GetService(typeof(SVsSolution)) as IVsSolution; } } /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void StartProfilingWizard(object sender, EventArgs e) { if (!IsProfilingInstalled()) { MessageBox.Show(Strings.ProfilingSupportMissingError); return; } var targetView = new ProfilingTargetView(this); var dialog = new LaunchProfiling(this, targetView); var res = dialog.ShowModal() ?? false; if (res && targetView.IsValid) { var target = targetView.GetTarget(); if (target != null) { ProfileTarget(target); } } } internal SessionNode ProfileTarget(ProfilingTarget target, bool openReport = true) { return ThreadHelper.Generic.Invoke(() => { bool save; string name = target.GetProfilingName(this, out save); var session = ShowPerformanceExplorer().Sessions.AddTarget(target, name, save); StartProfiling(target, session, openReport); return session; }); } internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true) { ThreadHelper.Generic.Invoke(() => { if (!Utilities.SaveDirtyFiles()) { // Abort return; } if (target.ProjectTarget != null) { ProfileProjectTarget(session, target.ProjectTarget, openReport); } else if (target.StandaloneTarget != null) { ProfileStandaloneTarget(session, target.StandaloneTarget, openReport); } else { if (MessageBox.Show(Strings.ProfilingSessionNotConfigured, Strings.NoProfilingTargetTitle, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { var newTarget = session.OpenTargetProperties(); if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null)) { StartProfiling(newTarget, session, openReport); } } } }); } private void ProfileProjectTarget(SessionNode session, ProjectTarget projectTarget, bool openReport) { var targetGuid = projectTarget.TargetProject; var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); EnvDTE.Project projectToProfile = null; foreach (EnvDTE.Project project in dte.Solution.Projects) { var kind = project.Kind; if (String.Equals(kind, PythonProfilingPackage.PythonProjectGuid, StringComparison.OrdinalIgnoreCase)) { var guid = project.Properties.Item("Guid").Value as string; Guid guidVal; if (Guid.TryParse(guid, out guidVal) && guidVal == projectTarget.TargetProject) { projectToProfile = project; break; } } } if (projectToProfile != null) { ProfileProject(session, projectToProfile, openReport); } else { MessageBox.Show(Strings.ProjectNotFoundInSolution, Strings.ProductTitle); } } private static void ProfileProject(SessionNode session, EnvDTE.Project projectToProfile, bool openReport) { var project = projectToProfile.AsPythonProject(); var config = project?.GetLaunchConfigurationOrThrow(); if (config == null) { MessageBox.Show(Strings.ProjectInterpreterNotFound.FormatUI(projectToProfile.Name), Strings.ProductTitle); return; } if (string.IsNullOrEmpty(config.ScriptName)) { MessageBox.Show(Strings.NoProjectStartupFile, Strings.ProductTitle); return; } if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".") { config.WorkingDirectory = project.ProjectHome; if (string.IsNullOrEmpty(config.WorkingDirectory)) { config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName); } } RunProfiler(session, config, openReport); } private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport) { LaunchConfiguration config; if (runTarget.PythonInterpreter != null) { var registry = session._serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>(); var interpreter = registry.FindConfiguration(runTarget.PythonInterpreter.Id); if (interpreter == null) { return; } config = new LaunchConfiguration(interpreter); } else { config = new LaunchConfiguration(null); } config.InterpreterPath = runTarget.InterpreterPath; config.ScriptName = runTarget.Script; config.ScriptArguments = runTarget.Arguments; config.WorkingDirectory = runTarget.WorkingDirectory; RunProfiler(session, config, openReport); } private static void RunProfiler(SessionNode session, LaunchConfiguration config, bool openReport) { var process = new ProfiledProcess( (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)), config.GetInterpreterPath(), string.Join(" ", ProcessOutput.QuoteSingleArgument(config.ScriptName), config.ScriptArguments), config.WorkingDirectory, session._serviceProvider.GetPythonToolsService().GetFullEnvironment(config) ); string baseName = Path.GetFileNameWithoutExtension(session.Filename); string date = DateTime.Now.ToString("yyyyMMdd"); string outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp"); int count = 1; while (File.Exists(outPath)) { outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp"); count++; } process.ProcessExited += (sender, args) => { var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE)); _profilingProcess = null; _stopCommand.Enabled = false; _startCommand.Enabled = true; if (openReport && File.Exists(outPath)) { for (int retries = 10; retries > 0; --retries) { try { using (new FileStream(outPath, FileMode.Open, FileAccess.Read, FileShare.None)) { } break; } catch (IOException) { Thread.Sleep(100); } } dte.ItemOperations.OpenFile(outPath); } }; session.AddProfile(outPath); process.StartProfiling(outPath); _profilingProcess = process; _stopCommand.Enabled = true; _startCommand.Enabled = false; } /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void ShowPeformanceExplorer(object sender, EventArgs e) { try { ShowPerformanceExplorer(); } catch (Exception ex) when (!ex.IsCriticalException()) { MessageBox.Show(Strings.ProfilingSupportMissingError); } } internal PerfToolWindow ShowPerformanceExplorer() { if (!IsProfilingInstalled()) { throw new InvalidOperationException(); } var pane = this.FindToolWindow(typeof(PerfToolWindow), 0, true); if (pane == null) { throw new InvalidOperationException(); } IVsWindowFrame frame = pane.Frame as IVsWindowFrame; if (frame == null) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(frame.Show()); return pane as PerfToolWindow; } private void AddPerformanceSession(object sender, EventArgs e) { var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); string filename = Strings.PerformanceBaseFileName + ".pyperf"; bool save = false; if (dte.Solution.IsOpen && !String.IsNullOrEmpty(dte.Solution.FullName)) { filename = Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), filename); save = true; } ShowPerformanceExplorer().Sessions.AddTarget(new ProfilingTarget(), filename, save); } private void StartProfiling(object sender, EventArgs e) { ShowPerformanceExplorer().Sessions.StartProfiling(); } private void StopProfiling(object sender, EventArgs e) { var process = _profilingProcess; if (process != null) { process.StopProfiling(); } } private void IsProfilingActive(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = false; } else { oleMenu.Enabled = true; } } private void IsProfilingInactive(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = true; } else { oleMenu.Enabled = false; } } internal bool IsProfilingInstalled() { IVsShell shell = (IVsShell)GetService(typeof(IVsShell)); Guid perfGuid = GuidList.GuidPerfPkg; int installed; ErrorHandler.ThrowOnFailure( shell.IsPackageInstalled(ref perfGuid, out installed) ); return installed != 0; } public bool IsProfiling { get { return _profilingProcess != null; } } } }
using System; using System.Data; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// InvoiceInfo (read only object).<br/> /// This is a generated <see cref="InvoiceInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="InvoiceList"/> collection. /// </remarks> [Serializable] public partial class InvoiceInfo : ReadOnlyBase<InvoiceInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="InvoiceId"/> property. /// </summary> public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id", Guid.NewGuid()); /// <summary> /// The invoice internal identification /// </summary> /// <value>The Invoice Id.</value> public Guid InvoiceId { get { return GetProperty(InvoiceIdProperty); } } /// <summary> /// Maintains metadata about <see cref="InvoiceNumber"/> property. /// </summary> public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number"); /// <summary> /// The public invoice number /// </summary> /// <value>The Invoice Number.</value> public string InvoiceNumber { get { return GetProperty(InvoiceNumberProperty); } } /// <summary> /// Maintains metadata about <see cref="CustomerId"/> property. /// </summary> public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id"); /// <summary> /// Gets the Customer Id. /// </summary> /// <value>The Customer Id.</value> public string CustomerId { get { return GetProperty(CustomerIdProperty); } } /// <summary> /// Maintains metadata about <see cref="InvoiceDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date"); /// <summary> /// Gets the Invoice Date. /// </summary> /// <value>The Invoice Date.</value> public string InvoiceDate { get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); } } /// <summary> /// Maintains metadata about <see cref="TotalAmount"/> property. /// </summary> public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount"); /// <summary> /// Computed invoice total amount /// </summary> /// <value>The Total Amount.</value> public decimal TotalAmount { get { return GetProperty(TotalAmountProperty); } } /// <summary> /// Maintains metadata about <see cref="IsActive"/> property. /// </summary> public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(p => p.IsActive, "Is Active"); /// <summary> /// Gets the Is Active. /// </summary> /// <value><c>true</c> if Is Active; otherwise, <c>false</c>.</value> public bool IsActive { get { return GetProperty(IsActiveProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date", new SmartDate(DateTime.Now)); /// <summary> /// Gets the Create Date. /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return GetProperty(CreateDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateUser"/> property. /// </summary> public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User", Security.UserInformation.UserId); /// <summary> /// Gets the Create User. /// </summary> /// <value>The Create User.</value> public int CreateUser { get { return GetProperty(CreateUserProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date"); /// <summary> /// Gets the Change Date. /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return GetProperty(ChangeDateProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeUser"/> property. /// </summary> public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User"); /// <summary> /// Gets the Change User. /// </summary> /// <value>The Change User.</value> public int ChangeUser { get { return GetProperty(ChangeUserProperty); } } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="InvoiceInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public InvoiceInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="InvoiceInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Child_Fetch(SafeDataReader dr) { // Value properties LoadProperty(InvoiceIdProperty, dr.GetGuid("InvoiceId")); LoadProperty(InvoiceNumberProperty, dr.GetString("InvoiceNumber")); LoadProperty(CustomerIdProperty, dr.GetString("CustomerId")); LoadProperty(InvoiceDateProperty, dr.GetSmartDate("InvoiceDate", true)); LoadProperty(IsActiveProperty, dr.GetBoolean("IsActive")); LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true)); LoadProperty(CreateUserProperty, dr.GetInt32("CreateUser")); LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true)); LoadProperty(ChangeUserProperty, dr.GetInt32("ChangeUser")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
using System.Collections.Generic; using System.Runtime.Serialization; namespace Docker.DotNet.Models { [DataContract] public class HostConfig // (container.HostConfig) { public HostConfig() { } public HostConfig(Resources Resources) { if (Resources != null) { this.CPUShares = Resources.CPUShares; this.Memory = Resources.Memory; this.NanoCPUs = Resources.NanoCPUs; this.CgroupParent = Resources.CgroupParent; this.BlkioWeight = Resources.BlkioWeight; this.BlkioWeightDevice = Resources.BlkioWeightDevice; this.BlkioDeviceReadBps = Resources.BlkioDeviceReadBps; this.BlkioDeviceWriteBps = Resources.BlkioDeviceWriteBps; this.BlkioDeviceReadIOps = Resources.BlkioDeviceReadIOps; this.BlkioDeviceWriteIOps = Resources.BlkioDeviceWriteIOps; this.CPUPeriod = Resources.CPUPeriod; this.CPUQuota = Resources.CPUQuota; this.CPURealtimePeriod = Resources.CPURealtimePeriod; this.CPURealtimeRuntime = Resources.CPURealtimeRuntime; this.CpusetCpus = Resources.CpusetCpus; this.CpusetMems = Resources.CpusetMems; this.Devices = Resources.Devices; this.DiskQuota = Resources.DiskQuota; this.KernelMemory = Resources.KernelMemory; this.MemoryReservation = Resources.MemoryReservation; this.MemorySwap = Resources.MemorySwap; this.MemorySwappiness = Resources.MemorySwappiness; this.OomKillDisable = Resources.OomKillDisable; this.PidsLimit = Resources.PidsLimit; this.Ulimits = Resources.Ulimits; this.CPUCount = Resources.CPUCount; this.CPUPercent = Resources.CPUPercent; this.IOMaximumIOps = Resources.IOMaximumIOps; this.IOMaximumBandwidth = Resources.IOMaximumBandwidth; } } [DataMember(Name = "Binds", EmitDefaultValue = false)] public IList<string> Binds { get; set; } [DataMember(Name = "ContainerIDFile", EmitDefaultValue = false)] public string ContainerIDFile { get; set; } [DataMember(Name = "LogConfig", EmitDefaultValue = false)] public LogConfig LogConfig { get; set; } [DataMember(Name = "NetworkMode", EmitDefaultValue = false)] public string NetworkMode { get; set; } [DataMember(Name = "PortBindings", EmitDefaultValue = false)] public IDictionary<string, IList<PortBinding>> PortBindings { get; set; } [DataMember(Name = "RestartPolicy", EmitDefaultValue = false)] public RestartPolicy RestartPolicy { get; set; } [DataMember(Name = "AutoRemove", EmitDefaultValue = false)] public bool AutoRemove { get; set; } [DataMember(Name = "VolumeDriver", EmitDefaultValue = false)] public string VolumeDriver { get; set; } [DataMember(Name = "VolumesFrom", EmitDefaultValue = false)] public IList<string> VolumesFrom { get; set; } [DataMember(Name = "CapAdd", EmitDefaultValue = false)] public IList<string> CapAdd { get; set; } [DataMember(Name = "CapDrop", EmitDefaultValue = false)] public IList<string> CapDrop { get; set; } [DataMember(Name = "Dns", EmitDefaultValue = false)] public IList<string> DNS { get; set; } [DataMember(Name = "DnsOptions", EmitDefaultValue = false)] public IList<string> DNSOptions { get; set; } [DataMember(Name = "DnsSearch", EmitDefaultValue = false)] public IList<string> DNSSearch { get; set; } [DataMember(Name = "ExtraHosts", EmitDefaultValue = false)] public IList<string> ExtraHosts { get; set; } [DataMember(Name = "GroupAdd", EmitDefaultValue = false)] public IList<string> GroupAdd { get; set; } [DataMember(Name = "IpcMode", EmitDefaultValue = false)] public string IpcMode { get; set; } [DataMember(Name = "Cgroup", EmitDefaultValue = false)] public string Cgroup { get; set; } [DataMember(Name = "Links", EmitDefaultValue = false)] public IList<string> Links { get; set; } [DataMember(Name = "OomScoreAdj", EmitDefaultValue = false)] public long OomScoreAdj { get; set; } [DataMember(Name = "PidMode", EmitDefaultValue = false)] public string PidMode { get; set; } [DataMember(Name = "Privileged", EmitDefaultValue = false)] public bool Privileged { get; set; } [DataMember(Name = "PublishAllPorts", EmitDefaultValue = false)] public bool PublishAllPorts { get; set; } [DataMember(Name = "ReadonlyRootfs", EmitDefaultValue = false)] public bool ReadonlyRootfs { get; set; } [DataMember(Name = "SecurityOpt", EmitDefaultValue = false)] public IList<string> SecurityOpt { get; set; } [DataMember(Name = "StorageOpt", EmitDefaultValue = false)] public IDictionary<string, string> StorageOpt { get; set; } [DataMember(Name = "Tmpfs", EmitDefaultValue = false)] public IDictionary<string, string> Tmpfs { get; set; } [DataMember(Name = "UTSMode", EmitDefaultValue = false)] public string UTSMode { get; set; } [DataMember(Name = "UsernsMode", EmitDefaultValue = false)] public string UsernsMode { get; set; } [DataMember(Name = "ShmSize", EmitDefaultValue = false)] public long ShmSize { get; set; } [DataMember(Name = "Sysctls", EmitDefaultValue = false)] public IDictionary<string, string> Sysctls { get; set; } [DataMember(Name = "Runtime", EmitDefaultValue = false)] public string Runtime { get; set; } [DataMember(Name = "ConsoleSize", EmitDefaultValue = false)] public ulong[] ConsoleSize { get; set; } [DataMember(Name = "Isolation", EmitDefaultValue = false)] public string Isolation { get; set; } [DataMember(Name = "CpuShares", EmitDefaultValue = false)] public long CPUShares { get; set; } [DataMember(Name = "Memory", EmitDefaultValue = false)] public long Memory { get; set; } [DataMember(Name = "NanoCpus", EmitDefaultValue = false)] public long NanoCPUs { get; set; } [DataMember(Name = "CgroupParent", EmitDefaultValue = false)] public string CgroupParent { get; set; } [DataMember(Name = "BlkioWeight", EmitDefaultValue = false)] public ushort BlkioWeight { get; set; } [DataMember(Name = "BlkioWeightDevice", EmitDefaultValue = false)] public IList<WeightDevice> BlkioWeightDevice { get; set; } [DataMember(Name = "BlkioDeviceReadBps", EmitDefaultValue = false)] public IList<ThrottleDevice> BlkioDeviceReadBps { get; set; } [DataMember(Name = "BlkioDeviceWriteBps", EmitDefaultValue = false)] public IList<ThrottleDevice> BlkioDeviceWriteBps { get; set; } [DataMember(Name = "BlkioDeviceReadIOps", EmitDefaultValue = false)] public IList<ThrottleDevice> BlkioDeviceReadIOps { get; set; } [DataMember(Name = "BlkioDeviceWriteIOps", EmitDefaultValue = false)] public IList<ThrottleDevice> BlkioDeviceWriteIOps { get; set; } [DataMember(Name = "CpuPeriod", EmitDefaultValue = false)] public long CPUPeriod { get; set; } [DataMember(Name = "CpuQuota", EmitDefaultValue = false)] public long CPUQuota { get; set; } [DataMember(Name = "CpuRealtimePeriod", EmitDefaultValue = false)] public long CPURealtimePeriod { get; set; } [DataMember(Name = "CpuRealtimeRuntime", EmitDefaultValue = false)] public long CPURealtimeRuntime { get; set; } [DataMember(Name = "CpusetCpus", EmitDefaultValue = false)] public string CpusetCpus { get; set; } [DataMember(Name = "CpusetMems", EmitDefaultValue = false)] public string CpusetMems { get; set; } [DataMember(Name = "Devices", EmitDefaultValue = false)] public IList<DeviceMapping> Devices { get; set; } [DataMember(Name = "DiskQuota", EmitDefaultValue = false)] public long DiskQuota { get; set; } [DataMember(Name = "KernelMemory", EmitDefaultValue = false)] public long KernelMemory { get; set; } [DataMember(Name = "MemoryReservation", EmitDefaultValue = false)] public long MemoryReservation { get; set; } [DataMember(Name = "MemorySwap", EmitDefaultValue = false)] public long MemorySwap { get; set; } [DataMember(Name = "MemorySwappiness", EmitDefaultValue = false)] public long? MemorySwappiness { get; set; } [DataMember(Name = "OomKillDisable", EmitDefaultValue = false)] public bool? OomKillDisable { get; set; } [DataMember(Name = "PidsLimit", EmitDefaultValue = false)] public long PidsLimit { get; set; } [DataMember(Name = "Ulimits", EmitDefaultValue = false)] public IList<Ulimit> Ulimits { get; set; } [DataMember(Name = "CpuCount", EmitDefaultValue = false)] public long CPUCount { get; set; } [DataMember(Name = "CpuPercent", EmitDefaultValue = false)] public long CPUPercent { get; set; } [DataMember(Name = "IOMaximumIOps", EmitDefaultValue = false)] public ulong IOMaximumIOps { get; set; } [DataMember(Name = "IOMaximumBandwidth", EmitDefaultValue = false)] public ulong IOMaximumBandwidth { get; set; } [DataMember(Name = "Mounts", EmitDefaultValue = false)] public IList<Mount> Mounts { get; set; } [DataMember(Name = "Init", EmitDefaultValue = false)] public bool? Init { get; set; } [DataMember(Name = "InitPath", EmitDefaultValue = false)] public string InitPath { get; set; } } }
// <copyright file="UserCholeskyTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // 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. // </copyright> using MathNet.Numerics.LinearAlgebra; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single.Factorization { /// <summary> /// Cholesky factorization tests for a user matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class UserCholeskyTests { /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorC = matrixI.Cholesky().Factor; Assert.AreEqual(matrixI.RowCount, factorC.RowCount); Assert.AreEqual(matrixI.ColumnCount, factorC.ColumnCount); for (var i = 0; i < factorC.RowCount; i++) { for (var j = 0; j < factorC.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, factorC[i, j]); } } } /// <summary> /// Cholesky factorization fails with diagonal a non-positive definite matrix. /// </summary> [Test] public void CholeskyFailsWithDiagonalNonPositiveDefiniteMatrix() { var matrixI = UserDefinedMatrix.Identity(10); matrixI[3, 3] = -4.0f; Assert.That(() => matrixI.Cholesky(), Throws.ArgumentException); } /// <summary> /// Cholesky factorization fails with a non-square matrix. /// </summary> [Test] public void CholeskyFailsWithNonSquareMatrix() { var matrixI = new UserDefinedMatrix(3, 2); Assert.That(() => matrixI.Cholesky(), Throws.ArgumentException); } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorC = matrixI.Cholesky(); Assert.AreEqual(1.0, factorC.Determinant); Assert.AreEqual(0.0, factorC.DeterminantLn); } /// <summary> /// Can factorize a random square matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanFactorizeRandomMatrix(int order) { var matrixX = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(order, 1).ToArray()); var chol = matrixX.Cholesky(); var factorC = chol.Factor; // Make sure the Cholesky factor has the right dimensions. Assert.AreEqual(order, factorC.RowCount); Assert.AreEqual(order, factorC.ColumnCount); // Make sure the Cholesky factor is lower triangular. for (var i = 0; i < factorC.RowCount; i++) { for (var j = i + 1; j < factorC.ColumnCount; j++) { Assert.AreEqual(0.0, factorC[i, j]); } } // Make sure the cholesky factor times it's transpose is the original matrix. var matrixXfromC = factorC * factorC.Transpose(); for (var i = 0; i < matrixXfromC.RowCount; i++) { for (var j = 0; j < matrixXfromC.ColumnCount; j++) { Assert.AreEqual(matrixX[i, j], matrixXfromC[i, j], 1e-3); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var chol = matrixA.Cholesky(); var b = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray()); var x = chol.Solve(b); Assert.AreEqual(b.Count, x.Count); var matrixBReconstruct = matrixA * x; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(b[i], matrixBReconstruct[i], 0.5); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="col">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 4)] [TestCase(5, 8)] [TestCase(10, 3)] [TestCase(50, 10)] [TestCase(100, 100)] public void CanSolveForRandomMatrix(int row, int col) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(row, 1).ToArray()); var matrixACopy = matrixA.Clone(); var chol = matrixA.Cholesky(); var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(row, col, 1).ToArray()); var matrixX = chol.Solve(matrixB); Assert.AreEqual(matrixB.RowCount, matrixX.RowCount); Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var chol = matrixA.Cholesky(); var b = new UserDefinedVector(Vector<float>.Build.Random(order, 1).ToArray()); var matrixBCopy = b.Clone(); var x = new UserDefinedVector(order); chol.Solve(b, x); Assert.AreEqual(b.Count, x.Count); var matrixBReconstruct = matrixA * x; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(b[i], matrixBReconstruct[i], 0.5); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < order; i++) { Assert.AreEqual(matrixBCopy[i], b[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="col">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 4)] [TestCase(5, 8)] [TestCase(10, 3)] [TestCase(50, 10)] [TestCase(100, 100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int row, int col) { var matrixA = new UserDefinedMatrix(Matrix<float>.Build.RandomPositiveDefinite(row, 1).ToArray()); var matrixACopy = matrixA.Clone(); var chol = matrixA.Cholesky(); var matrixB = new UserDefinedMatrix(Matrix<float>.Build.Random(row, col, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(row, col); chol.Solve(matrixB, matrixX); Assert.AreEqual(matrixB.RowCount, matrixX.RowCount); Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers.Text; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Numerics; using System.Runtime.CompilerServices; using System.Text; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { internal sealed partial class HttpRequestHeaders : HttpHeaders { private EnumeratorCache? _enumeratorCache; private long _previousBits; public bool ReuseHeaderValues { get; set; } public Func<string, Encoding?> EncodingSelector { get; set; } public HttpRequestHeaders(bool reuseHeaderValues = true, Func<string, Encoding?>? encodingSelector = null) { ReuseHeaderValues = reuseHeaderValues; EncodingSelector = encodingSelector ?? KestrelServerOptions.DefaultHeaderEncodingSelector; } public void OnHeadersComplete() { var newHeaderFlags = _bits; var previousHeaderFlags = _previousBits; _previousBits = 0; var headersToClear = (~newHeaderFlags) & previousHeaderFlags; if (headersToClear == 0) { // All headers were resued. return; } // Some previous headers were not reused or overwritten. // While they cannot be accessed by the current request (as they were not supplied by it) // there is no point in holding on to them, so clear them now, // to allow them to get collected by the GC. Clear(headersToClear); } protected override void ClearFast() { if (!ReuseHeaderValues) { // If we aren't reusing headers clear them all Clear(_bits); } else { // If we are reusing headers, store the currently set headers for comparison later _previousBits = _bits; } // Mark no headers as currently in use _bits = 0; // Clear ContentLength and any unknown headers as we will never reuse them _contentLength = null; MaybeUnknown?.Clear(); _enumeratorCache?.Reset(); } private static long ParseContentLength(string value) { if (!HeaderUtilities.TryParseNonNegativeInt64(value, out var parsed)) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidContentLength, value); } return parsed; } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendContentLength(ReadOnlySpan<byte> value) { if (_contentLength.HasValue) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.MultipleContentLengths); } if (!Utf8Parser.TryParse(value, out long parsed, out var consumed) || parsed < 0 || consumed != value.Length) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidContentLength, value.GetRequestHeaderString(HeaderNames.ContentLength, EncodingSelector, checkForNewlineChars : false)); } _contentLength = parsed; } [MethodImpl(MethodImplOptions.NoInlining)] [SkipLocalsInit] private void AppendContentLengthCustomEncoding(ReadOnlySpan<byte> value, Encoding customEncoding) { if (_contentLength.HasValue) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.MultipleContentLengths); } // long.MaxValue = 9223372036854775807 (19 chars) Span<char> decodedChars = stackalloc char[20]; var numChars = customEncoding.GetChars(value, decodedChars); long parsed = -1; if (numChars > 19 || !long.TryParse(decodedChars.Slice(0, numChars), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsed) || parsed < 0) { KestrelBadHttpRequestException.Throw(RequestRejectionReason.InvalidContentLength, value.GetRequestHeaderString(HeaderNames.ContentLength, EncodingSelector, checkForNewlineChars : false)); } _contentLength = parsed; } [MethodImpl(MethodImplOptions.NoInlining)] private void SetValueUnknown(string key, StringValues value) { Unknown[GetInternedHeaderName(key)] = value; } [MethodImpl(MethodImplOptions.NoInlining)] private bool AddValueUnknown(string key, StringValues value) { Unknown.Add(GetInternedHeaderName(key), value); // Return true, above will throw and exit for false return true; } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe void AppendUnknownHeaders(string name, string valueString) { name = GetInternedHeaderName(name); Unknown.TryGetValue(name, out var existing); Unknown[name] = AppendValue(existing, valueString); } public Enumerator GetEnumerator() { return new Enumerator(this); } protected override IEnumerator<KeyValuePair<string, StringValues>> GetEnumeratorFast() { // Get or create the cache. var cache = _enumeratorCache ??= new(); EnumeratorBox enumerator; if (cache.CachedEnumerator is not null) { // Previous enumerator, reuse that one. enumerator = cache.InUseEnumerator = cache.CachedEnumerator; // Set previous to null so if there is a second enumerator call // during the same request it doesn't get the same one. cache.CachedEnumerator = null; } else { // Create new enumerator box and store as in use. enumerator = cache.InUseEnumerator = new(); } // Set the underlying struct enumerator to a new one. enumerator.Enumerator = new Enumerator(this); return enumerator; } private class EnumeratorCache { /// <summary> /// Enumerator created from previous request /// </summary> public EnumeratorBox? CachedEnumerator { get; set; } /// <summary> /// Enumerator used on this request /// </summary> public EnumeratorBox? InUseEnumerator { get; set; } /// <summary> /// Moves InUseEnumerator to CachedEnumerator /// </summary> public void Reset() { var enumerator = InUseEnumerator; if (enumerator is not null) { InUseEnumerator = null; enumerator.Enumerator = default; CachedEnumerator = enumerator; } } } /// <summary> /// Strong box enumerator for the IEnumerator interface to cache and amortizate the /// IEnumerator allocations across requests if the header collection is commonly /// enumerated for forwarding in a reverse-proxy type situation. /// </summary> private class EnumeratorBox : IEnumerator<KeyValuePair<string, StringValues>> { public Enumerator Enumerator; public KeyValuePair<string, StringValues> Current => Enumerator.Current; public bool MoveNext() => Enumerator.MoveNext(); object IEnumerator.Current => Current; public void Dispose() { } public void Reset() => throw new NotSupportedException(); } public partial struct Enumerator : IEnumerator<KeyValuePair<string, StringValues>> { private readonly HttpRequestHeaders _collection; private long _currentBits; private int _next; private KeyValuePair<string, StringValues> _current; private readonly bool _hasUnknown; private Dictionary<string, StringValues>.Enumerator _unknownEnumerator; internal Enumerator(HttpRequestHeaders collection) { _collection = collection; _currentBits = collection._bits; _next = _currentBits != 0 ? BitOperations.TrailingZeroCount(_currentBits) : -1; _current = default; _hasUnknown = collection.MaybeUnknown != null; _unknownEnumerator = _hasUnknown ? collection.MaybeUnknown!.GetEnumerator() : default; } public KeyValuePair<string, StringValues> Current => _current; object IEnumerator.Current => _current; public void Dispose() { } public void Reset() { _currentBits = _collection._bits; _next = _currentBits != 0 ? BitOperations.TrailingZeroCount(_currentBits) : -1; } } } }
using ClosedXML.Excel.Drawings; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using Vml = DocumentFormat.OpenXml.Vml; using Xdr = DocumentFormat.OpenXml.Drawing.Spreadsheet; namespace ClosedXML.Excel { internal static class EnumConverter { #region To OpenXml public static UnderlineValues ToOpenXml(this XLFontUnderlineValues value) { switch (value) { case XLFontUnderlineValues.Double: return UnderlineValues.Double; case XLFontUnderlineValues.DoubleAccounting: return UnderlineValues.DoubleAccounting; case XLFontUnderlineValues.None: return UnderlineValues.None; case XLFontUnderlineValues.Single: return UnderlineValues.Single; case XLFontUnderlineValues.SingleAccounting: return UnderlineValues.SingleAccounting; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static OrientationValues ToOpenXml(this XLPageOrientation value) { switch (value) { case XLPageOrientation.Default: return OrientationValues.Default; case XLPageOrientation.Landscape: return OrientationValues.Landscape; case XLPageOrientation.Portrait: return OrientationValues.Portrait; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static VerticalAlignmentRunValues ToOpenXml(this XLFontVerticalTextAlignmentValues value) { switch (value) { case XLFontVerticalTextAlignmentValues.Baseline: return VerticalAlignmentRunValues.Baseline; case XLFontVerticalTextAlignmentValues.Subscript: return VerticalAlignmentRunValues.Subscript; case XLFontVerticalTextAlignmentValues.Superscript: return VerticalAlignmentRunValues.Superscript; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static PatternValues ToOpenXml(this XLFillPatternValues value) { switch (value) { case XLFillPatternValues.DarkDown: return PatternValues.DarkDown; case XLFillPatternValues.DarkGray: return PatternValues.DarkGray; case XLFillPatternValues.DarkGrid: return PatternValues.DarkGrid; case XLFillPatternValues.DarkHorizontal: return PatternValues.DarkHorizontal; case XLFillPatternValues.DarkTrellis: return PatternValues.DarkTrellis; case XLFillPatternValues.DarkUp: return PatternValues.DarkUp; case XLFillPatternValues.DarkVertical: return PatternValues.DarkVertical; case XLFillPatternValues.Gray0625: return PatternValues.Gray0625; case XLFillPatternValues.Gray125: return PatternValues.Gray125; case XLFillPatternValues.LightDown: return PatternValues.LightDown; case XLFillPatternValues.LightGray: return PatternValues.LightGray; case XLFillPatternValues.LightGrid: return PatternValues.LightGrid; case XLFillPatternValues.LightHorizontal: return PatternValues.LightHorizontal; case XLFillPatternValues.LightTrellis: return PatternValues.LightTrellis; case XLFillPatternValues.LightUp: return PatternValues.LightUp; case XLFillPatternValues.LightVertical: return PatternValues.LightVertical; case XLFillPatternValues.MediumGray: return PatternValues.MediumGray; case XLFillPatternValues.None: return PatternValues.None; case XLFillPatternValues.Solid: return PatternValues.Solid; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static BorderStyleValues ToOpenXml(this XLBorderStyleValues value) { switch (value) { case XLBorderStyleValues.DashDot: return BorderStyleValues.DashDot; case XLBorderStyleValues.DashDotDot: return BorderStyleValues.DashDotDot; case XLBorderStyleValues.Dashed: return BorderStyleValues.Dashed; case XLBorderStyleValues.Dotted: return BorderStyleValues.Dotted; case XLBorderStyleValues.Double: return BorderStyleValues.Double; case XLBorderStyleValues.Hair: return BorderStyleValues.Hair; case XLBorderStyleValues.Medium: return BorderStyleValues.Medium; case XLBorderStyleValues.MediumDashDot: return BorderStyleValues.MediumDashDot; case XLBorderStyleValues.MediumDashDotDot: return BorderStyleValues.MediumDashDotDot; case XLBorderStyleValues.MediumDashed: return BorderStyleValues.MediumDashed; case XLBorderStyleValues.None: return BorderStyleValues.None; case XLBorderStyleValues.SlantDashDot: return BorderStyleValues.SlantDashDot; case XLBorderStyleValues.Thick: return BorderStyleValues.Thick; case XLBorderStyleValues.Thin: return BorderStyleValues.Thin; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static HorizontalAlignmentValues ToOpenXml(this XLAlignmentHorizontalValues value) { switch (value) { case XLAlignmentHorizontalValues.Center: return HorizontalAlignmentValues.Center; case XLAlignmentHorizontalValues.CenterContinuous: return HorizontalAlignmentValues.CenterContinuous; case XLAlignmentHorizontalValues.Distributed: return HorizontalAlignmentValues.Distributed; case XLAlignmentHorizontalValues.Fill: return HorizontalAlignmentValues.Fill; case XLAlignmentHorizontalValues.General: return HorizontalAlignmentValues.General; case XLAlignmentHorizontalValues.Justify: return HorizontalAlignmentValues.Justify; case XLAlignmentHorizontalValues.Left: return HorizontalAlignmentValues.Left; case XLAlignmentHorizontalValues.Right: return HorizontalAlignmentValues.Right; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static VerticalAlignmentValues ToOpenXml(this XLAlignmentVerticalValues value) { switch (value) { case XLAlignmentVerticalValues.Bottom: return VerticalAlignmentValues.Bottom; case XLAlignmentVerticalValues.Center: return VerticalAlignmentValues.Center; case XLAlignmentVerticalValues.Distributed: return VerticalAlignmentValues.Distributed; case XLAlignmentVerticalValues.Justify: return VerticalAlignmentValues.Justify; case XLAlignmentVerticalValues.Top: return VerticalAlignmentValues.Top; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static PageOrderValues ToOpenXml(this XLPageOrderValues value) { switch (value) { case XLPageOrderValues.DownThenOver: return PageOrderValues.DownThenOver; case XLPageOrderValues.OverThenDown: return PageOrderValues.OverThenDown; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static CellCommentsValues ToOpenXml(this XLShowCommentsValues value) { switch (value) { case XLShowCommentsValues.AsDisplayed: return CellCommentsValues.AsDisplayed; case XLShowCommentsValues.AtEnd: return CellCommentsValues.AtEnd; case XLShowCommentsValues.None: return CellCommentsValues.None; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static PrintErrorValues ToOpenXml(this XLPrintErrorValues value) { switch (value) { case XLPrintErrorValues.Blank: return PrintErrorValues.Blank; case XLPrintErrorValues.Dash: return PrintErrorValues.Dash; case XLPrintErrorValues.Displayed: return PrintErrorValues.Displayed; case XLPrintErrorValues.NA: return PrintErrorValues.NA; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static CalculateModeValues ToOpenXml(this XLCalculateMode value) { switch (value) { case XLCalculateMode.Auto: return CalculateModeValues.Auto; case XLCalculateMode.AutoNoTable: return CalculateModeValues.AutoNoTable; case XLCalculateMode.Manual: return CalculateModeValues.Manual; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static ReferenceModeValues ToOpenXml(this XLReferenceStyle value) { switch (value) { case XLReferenceStyle.R1C1: return ReferenceModeValues.R1C1; case XLReferenceStyle.A1: return ReferenceModeValues.A1; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static uint ToOpenXml(this XLAlignmentReadingOrderValues value) { switch (value) { case XLAlignmentReadingOrderValues.ContextDependent: return 0; case XLAlignmentReadingOrderValues.LeftToRight: return 1; case XLAlignmentReadingOrderValues.RightToLeft: return 2; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static TotalsRowFunctionValues ToOpenXml(this XLTotalsRowFunction value) { switch (value) { case XLTotalsRowFunction.None: return TotalsRowFunctionValues.None; case XLTotalsRowFunction.Sum: return TotalsRowFunctionValues.Sum; case XLTotalsRowFunction.Minimum: return TotalsRowFunctionValues.Minimum; case XLTotalsRowFunction.Maximum: return TotalsRowFunctionValues.Maximum; case XLTotalsRowFunction.Average: return TotalsRowFunctionValues.Average; case XLTotalsRowFunction.Count: return TotalsRowFunctionValues.Count; case XLTotalsRowFunction.CountNumbers: return TotalsRowFunctionValues.CountNumbers; case XLTotalsRowFunction.StandardDeviation: return TotalsRowFunctionValues.StandardDeviation; case XLTotalsRowFunction.Variance: return TotalsRowFunctionValues.Variance; case XLTotalsRowFunction.Custom: return TotalsRowFunctionValues.Custom; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static DataValidationValues ToOpenXml(this XLAllowedValues value) { switch (value) { case XLAllowedValues.AnyValue: return DataValidationValues.None; case XLAllowedValues.Custom: return DataValidationValues.Custom; case XLAllowedValues.Date: return DataValidationValues.Date; case XLAllowedValues.Decimal: return DataValidationValues.Decimal; case XLAllowedValues.List: return DataValidationValues.List; case XLAllowedValues.TextLength: return DataValidationValues.TextLength; case XLAllowedValues.Time: return DataValidationValues.Time; case XLAllowedValues.WholeNumber: return DataValidationValues.Whole; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static DataValidationErrorStyleValues ToOpenXml(this XLErrorStyle value) { switch (value) { case XLErrorStyle.Information: return DataValidationErrorStyleValues.Information; case XLErrorStyle.Warning: return DataValidationErrorStyleValues.Warning; case XLErrorStyle.Stop: return DataValidationErrorStyleValues.Stop; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static DataValidationOperatorValues ToOpenXml(this XLOperator value) { switch (value) { case XLOperator.Between: return DataValidationOperatorValues.Between; case XLOperator.EqualOrGreaterThan: return DataValidationOperatorValues.GreaterThanOrEqual; case XLOperator.EqualOrLessThan: return DataValidationOperatorValues.LessThanOrEqual; case XLOperator.EqualTo: return DataValidationOperatorValues.Equal; case XLOperator.GreaterThan: return DataValidationOperatorValues.GreaterThan; case XLOperator.LessThan: return DataValidationOperatorValues.LessThan; case XLOperator.NotBetween: return DataValidationOperatorValues.NotBetween; case XLOperator.NotEqualTo: return DataValidationOperatorValues.NotEqual; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static SheetStateValues ToOpenXml(this XLWorksheetVisibility value) { switch (value) { case XLWorksheetVisibility.Visible: return SheetStateValues.Visible; case XLWorksheetVisibility.Hidden: return SheetStateValues.Hidden; case XLWorksheetVisibility.VeryHidden: return SheetStateValues.VeryHidden; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static PhoneticAlignmentValues ToOpenXml(this XLPhoneticAlignment value) { switch (value) { case XLPhoneticAlignment.Center: return PhoneticAlignmentValues.Center; case XLPhoneticAlignment.Distributed: return PhoneticAlignmentValues.Distributed; case XLPhoneticAlignment.Left: return PhoneticAlignmentValues.Left; case XLPhoneticAlignment.NoControl: return PhoneticAlignmentValues.NoControl; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static PhoneticValues ToOpenXml(this XLPhoneticType value) { switch (value) { case XLPhoneticType.FullWidthKatakana: return PhoneticValues.FullWidthKatakana; case XLPhoneticType.HalfWidthKatakana: return PhoneticValues.HalfWidthKatakana; case XLPhoneticType.Hiragana: return PhoneticValues.Hiragana; case XLPhoneticType.NoConversion: return PhoneticValues.NoConversion; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static DataConsolidateFunctionValues ToOpenXml(this XLPivotSummary value) { switch (value) { case XLPivotSummary.Sum: return DataConsolidateFunctionValues.Sum; case XLPivotSummary.Count: return DataConsolidateFunctionValues.Count; case XLPivotSummary.Average: return DataConsolidateFunctionValues.Average; case XLPivotSummary.Minimum: return DataConsolidateFunctionValues.Minimum; case XLPivotSummary.Maximum: return DataConsolidateFunctionValues.Maximum; case XLPivotSummary.Product: return DataConsolidateFunctionValues.Product; case XLPivotSummary.CountNumbers: return DataConsolidateFunctionValues.CountNumbers; case XLPivotSummary.StandardDeviation: return DataConsolidateFunctionValues.StandardDeviation; case XLPivotSummary.PopulationStandardDeviation: return DataConsolidateFunctionValues.StandardDeviationP; case XLPivotSummary.Variance: return DataConsolidateFunctionValues.Variance; case XLPivotSummary.PopulationVariance: return DataConsolidateFunctionValues.VarianceP; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static ShowDataAsValues ToOpenXml(this XLPivotCalculation value) { switch (value) { case XLPivotCalculation.Normal: return ShowDataAsValues.Normal; case XLPivotCalculation.DifferenceFrom: return ShowDataAsValues.Difference; case XLPivotCalculation.PercentageOf: return ShowDataAsValues.Percent; case XLPivotCalculation.PercentageDifferenceFrom: return ShowDataAsValues.PercentageDifference; case XLPivotCalculation.RunningTotal: return ShowDataAsValues.RunTotal; case XLPivotCalculation.PercentageOfRow: return ShowDataAsValues.PercentOfRaw; // There's a typo in the OpenXML SDK =) case XLPivotCalculation.PercentageOfColumn: return ShowDataAsValues.PercentOfColumn; case XLPivotCalculation.PercentageOfTotal: return ShowDataAsValues.PercentOfTotal; case XLPivotCalculation.Index: return ShowDataAsValues.Index; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static FilterOperatorValues ToOpenXml(this XLFilterOperator value) { switch (value) { case XLFilterOperator.Equal: return FilterOperatorValues.Equal; case XLFilterOperator.NotEqual: return FilterOperatorValues.NotEqual; case XLFilterOperator.GreaterThan: return FilterOperatorValues.GreaterThan; case XLFilterOperator.EqualOrGreaterThan: return FilterOperatorValues.GreaterThanOrEqual; case XLFilterOperator.LessThan: return FilterOperatorValues.LessThan; case XLFilterOperator.EqualOrLessThan: return FilterOperatorValues.LessThanOrEqual; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static DynamicFilterValues ToOpenXml(this XLFilterDynamicType value) { switch (value) { case XLFilterDynamicType.AboveAverage: return DynamicFilterValues.AboveAverage; case XLFilterDynamicType.BelowAverage: return DynamicFilterValues.BelowAverage; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static SheetViewValues ToOpenXml(this XLSheetViewOptions value) { switch (value) { case XLSheetViewOptions.Normal: return SheetViewValues.Normal; case XLSheetViewOptions.PageBreakPreview: return SheetViewValues.PageBreakPreview; case XLSheetViewOptions.PageLayout: return SheetViewValues.PageLayout; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static Vml.StrokeLineStyleValues ToOpenXml(this XLLineStyle value) { switch (value) { case XLLineStyle.Single: return Vml.StrokeLineStyleValues.Single; case XLLineStyle.ThickBetweenThin: return Vml.StrokeLineStyleValues.ThickBetweenThin; case XLLineStyle.ThickThin: return Vml.StrokeLineStyleValues.ThickThin; case XLLineStyle.ThinThick: return Vml.StrokeLineStyleValues.ThinThick; case XLLineStyle.ThinThin: return Vml.StrokeLineStyleValues.ThinThin; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static ConditionalFormatValues ToOpenXml(this XLConditionalFormatType value) { switch (value) { case XLConditionalFormatType.Expression: return ConditionalFormatValues.Expression; case XLConditionalFormatType.CellIs: return ConditionalFormatValues.CellIs; case XLConditionalFormatType.ColorScale: return ConditionalFormatValues.ColorScale; case XLConditionalFormatType.DataBar: return ConditionalFormatValues.DataBar; case XLConditionalFormatType.IconSet: return ConditionalFormatValues.IconSet; case XLConditionalFormatType.Top10: return ConditionalFormatValues.Top10; case XLConditionalFormatType.IsUnique: return ConditionalFormatValues.UniqueValues; case XLConditionalFormatType.IsDuplicate: return ConditionalFormatValues.DuplicateValues; case XLConditionalFormatType.ContainsText: return ConditionalFormatValues.ContainsText; case XLConditionalFormatType.NotContainsText: return ConditionalFormatValues.NotContainsText; case XLConditionalFormatType.StartsWith: return ConditionalFormatValues.BeginsWith; case XLConditionalFormatType.EndsWith: return ConditionalFormatValues.EndsWith; case XLConditionalFormatType.IsBlank: return ConditionalFormatValues.ContainsBlanks; case XLConditionalFormatType.NotBlank: return ConditionalFormatValues.NotContainsBlanks; case XLConditionalFormatType.IsError: return ConditionalFormatValues.ContainsErrors; case XLConditionalFormatType.NotError: return ConditionalFormatValues.NotContainsErrors; case XLConditionalFormatType.TimePeriod: return ConditionalFormatValues.TimePeriod; case XLConditionalFormatType.AboveAverage: return ConditionalFormatValues.AboveAverage; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static ConditionalFormatValueObjectValues ToOpenXml(this XLCFContentType value) { switch (value) { case XLCFContentType.Number: return ConditionalFormatValueObjectValues.Number; case XLCFContentType.Percent: return ConditionalFormatValueObjectValues.Percent; case XLCFContentType.Maximum: return ConditionalFormatValueObjectValues.Max; case XLCFContentType.Minimum: return ConditionalFormatValueObjectValues.Min; case XLCFContentType.Formula: return ConditionalFormatValueObjectValues.Formula; case XLCFContentType.Percentile: return ConditionalFormatValueObjectValues.Percentile; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static ConditionalFormattingOperatorValues ToOpenXml(this XLCFOperator value) { switch (value) { case XLCFOperator.LessThan: return ConditionalFormattingOperatorValues.LessThan; case XLCFOperator.EqualOrLessThan: return ConditionalFormattingOperatorValues.LessThanOrEqual; case XLCFOperator.Equal: return ConditionalFormattingOperatorValues.Equal; case XLCFOperator.NotEqual: return ConditionalFormattingOperatorValues.NotEqual; case XLCFOperator.EqualOrGreaterThan: return ConditionalFormattingOperatorValues.GreaterThanOrEqual; case XLCFOperator.GreaterThan: return ConditionalFormattingOperatorValues.GreaterThan; case XLCFOperator.Between: return ConditionalFormattingOperatorValues.Between; case XLCFOperator.NotBetween: return ConditionalFormattingOperatorValues.NotBetween; case XLCFOperator.Contains: return ConditionalFormattingOperatorValues.ContainsText; case XLCFOperator.NotContains: return ConditionalFormattingOperatorValues.NotContains; case XLCFOperator.StartsWith: return ConditionalFormattingOperatorValues.BeginsWith; case XLCFOperator.EndsWith: return ConditionalFormattingOperatorValues.EndsWith; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static IconSetValues ToOpenXml(this XLIconSetStyle value) { switch (value) { case XLIconSetStyle.ThreeArrows: return IconSetValues.ThreeArrows; case XLIconSetStyle.ThreeArrowsGray: return IconSetValues.ThreeArrowsGray; case XLIconSetStyle.ThreeFlags: return IconSetValues.ThreeFlags; case XLIconSetStyle.ThreeTrafficLights1: return IconSetValues.ThreeTrafficLights1; case XLIconSetStyle.ThreeTrafficLights2: return IconSetValues.ThreeTrafficLights2; case XLIconSetStyle.ThreeSigns: return IconSetValues.ThreeSigns; case XLIconSetStyle.ThreeSymbols: return IconSetValues.ThreeSymbols; case XLIconSetStyle.ThreeSymbols2: return IconSetValues.ThreeSymbols2; case XLIconSetStyle.FourArrows: return IconSetValues.FourArrows; case XLIconSetStyle.FourArrowsGray: return IconSetValues.FourArrowsGray; case XLIconSetStyle.FourRedToBlack: return IconSetValues.FourRedToBlack; case XLIconSetStyle.FourRating: return IconSetValues.FourRating; case XLIconSetStyle.FourTrafficLights: return IconSetValues.FourTrafficLights; case XLIconSetStyle.FiveArrows: return IconSetValues.FiveArrows; case XLIconSetStyle.FiveArrowsGray: return IconSetValues.FiveArrowsGray; case XLIconSetStyle.FiveRating: return IconSetValues.FiveRating; case XLIconSetStyle.FiveQuarters: return IconSetValues.FiveQuarters; #region default default: throw new ArgumentOutOfRangeException("Not implemented value!"); #endregion default } } public static ImagePartType ToOpenXml(this XLPictureFormat value) { return Enum.Parse(typeof(ImagePartType), value.ToString()).CastTo<ImagePartType>(); } public static Xdr.EditAsValues ToOpenXml(this XLPicturePlacement value) { switch (value) { case XLPicturePlacement.FreeFloating: return Xdr.EditAsValues.Absolute; case XLPicturePlacement.Move: return Xdr.EditAsValues.OneCell; case XLPicturePlacement.MoveAndSize: return Xdr.EditAsValues.TwoCell; default: throw new ArgumentOutOfRangeException("Not implemented value!"); } } #endregion To OpenXml #region To ClosedXml public static XLFontUnderlineValues ToClosedXml(this UnderlineValues value) { switch (value) { case UnderlineValues.Double: return XLFontUnderlineValues.Double; case UnderlineValues.DoubleAccounting: return XLFontUnderlineValues.DoubleAccounting; case UnderlineValues.None: return XLFontUnderlineValues.None; case UnderlineValues.Single: return XLFontUnderlineValues.Single; case UnderlineValues.SingleAccounting: return XLFontUnderlineValues.SingleAccounting; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPageOrientation ToClosedXml(this OrientationValues value) { switch (value) { case OrientationValues.Default: return XLPageOrientation.Default; case OrientationValues.Landscape: return XLPageOrientation.Landscape; case OrientationValues.Portrait: return XLPageOrientation.Portrait; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLFontVerticalTextAlignmentValues ToClosedXml(this VerticalAlignmentRunValues value) { switch (value) { case VerticalAlignmentRunValues.Baseline: return XLFontVerticalTextAlignmentValues.Baseline; case VerticalAlignmentRunValues.Subscript: return XLFontVerticalTextAlignmentValues.Subscript; case VerticalAlignmentRunValues.Superscript: return XLFontVerticalTextAlignmentValues.Superscript; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLFillPatternValues ToClosedXml(this PatternValues value) { switch (value) { case PatternValues.DarkDown: return XLFillPatternValues.DarkDown; case PatternValues.DarkGray: return XLFillPatternValues.DarkGray; case PatternValues.DarkGrid: return XLFillPatternValues.DarkGrid; case PatternValues.DarkHorizontal: return XLFillPatternValues.DarkHorizontal; case PatternValues.DarkTrellis: return XLFillPatternValues.DarkTrellis; case PatternValues.DarkUp: return XLFillPatternValues.DarkUp; case PatternValues.DarkVertical: return XLFillPatternValues.DarkVertical; case PatternValues.Gray0625: return XLFillPatternValues.Gray0625; case PatternValues.Gray125: return XLFillPatternValues.Gray125; case PatternValues.LightDown: return XLFillPatternValues.LightDown; case PatternValues.LightGray: return XLFillPatternValues.LightGray; case PatternValues.LightGrid: return XLFillPatternValues.LightGrid; case PatternValues.LightHorizontal: return XLFillPatternValues.LightHorizontal; case PatternValues.LightTrellis: return XLFillPatternValues.LightTrellis; case PatternValues.LightUp: return XLFillPatternValues.LightUp; case PatternValues.LightVertical: return XLFillPatternValues.LightVertical; case PatternValues.MediumGray: return XLFillPatternValues.MediumGray; case PatternValues.None: return XLFillPatternValues.None; case PatternValues.Solid: return XLFillPatternValues.Solid; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLBorderStyleValues ToClosedXml(this BorderStyleValues value) { switch (value) { case BorderStyleValues.DashDot: return XLBorderStyleValues.DashDot; case BorderStyleValues.DashDotDot: return XLBorderStyleValues.DashDotDot; case BorderStyleValues.Dashed: return XLBorderStyleValues.Dashed; case BorderStyleValues.Dotted: return XLBorderStyleValues.Dotted; case BorderStyleValues.Double: return XLBorderStyleValues.Double; case BorderStyleValues.Hair: return XLBorderStyleValues.Hair; case BorderStyleValues.Medium: return XLBorderStyleValues.Medium; case BorderStyleValues.MediumDashDot: return XLBorderStyleValues.MediumDashDot; case BorderStyleValues.MediumDashDotDot: return XLBorderStyleValues.MediumDashDotDot; case BorderStyleValues.MediumDashed: return XLBorderStyleValues.MediumDashed; case BorderStyleValues.None: return XLBorderStyleValues.None; case BorderStyleValues.SlantDashDot: return XLBorderStyleValues.SlantDashDot; case BorderStyleValues.Thick: return XLBorderStyleValues.Thick; case BorderStyleValues.Thin: return XLBorderStyleValues.Thin; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLAlignmentHorizontalValues ToClosedXml(this HorizontalAlignmentValues value) { switch (value) { case HorizontalAlignmentValues.Center: return XLAlignmentHorizontalValues.Center; case HorizontalAlignmentValues.CenterContinuous: return XLAlignmentHorizontalValues.CenterContinuous; case HorizontalAlignmentValues.Distributed: return XLAlignmentHorizontalValues.Distributed; case HorizontalAlignmentValues.Fill: return XLAlignmentHorizontalValues.Fill; case HorizontalAlignmentValues.General: return XLAlignmentHorizontalValues.General; case HorizontalAlignmentValues.Justify: return XLAlignmentHorizontalValues.Justify; case HorizontalAlignmentValues.Left: return XLAlignmentHorizontalValues.Left; case HorizontalAlignmentValues.Right: return XLAlignmentHorizontalValues.Right; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLAlignmentVerticalValues ToClosedXml(this VerticalAlignmentValues value) { switch (value) { case VerticalAlignmentValues.Bottom: return XLAlignmentVerticalValues.Bottom; case VerticalAlignmentValues.Center: return XLAlignmentVerticalValues.Center; case VerticalAlignmentValues.Distributed: return XLAlignmentVerticalValues.Distributed; case VerticalAlignmentValues.Justify: return XLAlignmentVerticalValues.Justify; case VerticalAlignmentValues.Top: return XLAlignmentVerticalValues.Top; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPageOrderValues ToClosedXml(this PageOrderValues value) { switch (value) { case PageOrderValues.DownThenOver: return XLPageOrderValues.DownThenOver; case PageOrderValues.OverThenDown: return XLPageOrderValues.OverThenDown; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLShowCommentsValues ToClosedXml(this CellCommentsValues value) { switch (value) { case CellCommentsValues.AsDisplayed: return XLShowCommentsValues.AsDisplayed; case CellCommentsValues.AtEnd: return XLShowCommentsValues.AtEnd; case CellCommentsValues.None: return XLShowCommentsValues.None; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPrintErrorValues ToClosedXml(this PrintErrorValues value) { switch (value) { case PrintErrorValues.Blank: return XLPrintErrorValues.Blank; case PrintErrorValues.Dash: return XLPrintErrorValues.Dash; case PrintErrorValues.Displayed: return XLPrintErrorValues.Displayed; case PrintErrorValues.NA: return XLPrintErrorValues.NA; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLCalculateMode ToClosedXml(this CalculateModeValues value) { switch (value) { case CalculateModeValues.Auto: return XLCalculateMode.Auto; case CalculateModeValues.AutoNoTable: return XLCalculateMode.AutoNoTable; case CalculateModeValues.Manual: return XLCalculateMode.Manual; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLReferenceStyle ToClosedXml(this ReferenceModeValues value) { switch (value) { case ReferenceModeValues.R1C1: return XLReferenceStyle.R1C1; case ReferenceModeValues.A1: return XLReferenceStyle.A1; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLAlignmentReadingOrderValues ToClosedXml(this uint value) { switch (value) { case 0: return XLAlignmentReadingOrderValues.ContextDependent; case 1: return XLAlignmentReadingOrderValues.LeftToRight; case 2: return XLAlignmentReadingOrderValues.RightToLeft; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLTotalsRowFunction ToClosedXml(this TotalsRowFunctionValues value) { switch (value) { case TotalsRowFunctionValues.None: return XLTotalsRowFunction.None; case TotalsRowFunctionValues.Sum: return XLTotalsRowFunction.Sum; case TotalsRowFunctionValues.Minimum: return XLTotalsRowFunction.Minimum; case TotalsRowFunctionValues.Maximum: return XLTotalsRowFunction.Maximum; case TotalsRowFunctionValues.Average: return XLTotalsRowFunction.Average; case TotalsRowFunctionValues.Count: return XLTotalsRowFunction.Count; case TotalsRowFunctionValues.CountNumbers: return XLTotalsRowFunction.CountNumbers; case TotalsRowFunctionValues.StandardDeviation: return XLTotalsRowFunction.StandardDeviation; case TotalsRowFunctionValues.Variance: return XLTotalsRowFunction.Variance; case TotalsRowFunctionValues.Custom: return XLTotalsRowFunction.Custom; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLAllowedValues ToClosedXml(this DataValidationValues value) { switch (value) { case DataValidationValues.None: return XLAllowedValues.AnyValue; case DataValidationValues.Custom: return XLAllowedValues.Custom; case DataValidationValues.Date: return XLAllowedValues.Date; case DataValidationValues.Decimal: return XLAllowedValues.Decimal; case DataValidationValues.List: return XLAllowedValues.List; case DataValidationValues.TextLength: return XLAllowedValues.TextLength; case DataValidationValues.Time: return XLAllowedValues.Time; case DataValidationValues.Whole: return XLAllowedValues.WholeNumber; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLErrorStyle ToClosedXml(this DataValidationErrorStyleValues value) { switch (value) { case DataValidationErrorStyleValues.Information: return XLErrorStyle.Information; case DataValidationErrorStyleValues.Warning: return XLErrorStyle.Warning; case DataValidationErrorStyleValues.Stop: return XLErrorStyle.Stop; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLOperator ToClosedXml(this DataValidationOperatorValues value) { switch (value) { case DataValidationOperatorValues.Between: return XLOperator.Between; case DataValidationOperatorValues.GreaterThanOrEqual: return XLOperator.EqualOrGreaterThan; case DataValidationOperatorValues.LessThanOrEqual: return XLOperator.EqualOrLessThan; case DataValidationOperatorValues.Equal: return XLOperator.EqualTo; case DataValidationOperatorValues.GreaterThan: return XLOperator.GreaterThan; case DataValidationOperatorValues.LessThan: return XLOperator.LessThan; case DataValidationOperatorValues.NotBetween: return XLOperator.NotBetween; case DataValidationOperatorValues.NotEqual: return XLOperator.NotEqualTo; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLWorksheetVisibility ToClosedXml(this SheetStateValues value) { switch (value) { case SheetStateValues.Visible: return XLWorksheetVisibility.Visible; case SheetStateValues.Hidden: return XLWorksheetVisibility.Hidden; case SheetStateValues.VeryHidden: return XLWorksheetVisibility.VeryHidden; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPhoneticAlignment ToClosedXml(this PhoneticAlignmentValues value) { switch (value) { case PhoneticAlignmentValues.Center: return XLPhoneticAlignment.Center; case PhoneticAlignmentValues.Distributed: return XLPhoneticAlignment.Distributed; case PhoneticAlignmentValues.Left: return XLPhoneticAlignment.Left; case PhoneticAlignmentValues.NoControl: return XLPhoneticAlignment.NoControl; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPhoneticType ToClosedXml(this PhoneticValues value) { switch (value) { case PhoneticValues.FullWidthKatakana: return XLPhoneticType.FullWidthKatakana; case PhoneticValues.HalfWidthKatakana: return XLPhoneticType.HalfWidthKatakana; case PhoneticValues.Hiragana: return XLPhoneticType.Hiragana; case PhoneticValues.NoConversion: return XLPhoneticType.NoConversion; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPivotSummary ToClosedXml(this DataConsolidateFunctionValues value) { switch (value) { case DataConsolidateFunctionValues.Sum: return XLPivotSummary.Sum; case DataConsolidateFunctionValues.Count: return XLPivotSummary.Count; case DataConsolidateFunctionValues.Average: return XLPivotSummary.Average; case DataConsolidateFunctionValues.Minimum: return XLPivotSummary.Minimum; case DataConsolidateFunctionValues.Maximum: return XLPivotSummary.Maximum; case DataConsolidateFunctionValues.Product: return XLPivotSummary.Product; case DataConsolidateFunctionValues.CountNumbers: return XLPivotSummary.CountNumbers; case DataConsolidateFunctionValues.StandardDeviation: return XLPivotSummary.StandardDeviation; case DataConsolidateFunctionValues.StandardDeviationP: return XLPivotSummary.PopulationStandardDeviation; case DataConsolidateFunctionValues.Variance: return XLPivotSummary.Variance; case DataConsolidateFunctionValues.VarianceP: return XLPivotSummary.PopulationVariance; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPivotCalculation ToClosedXml(this ShowDataAsValues value) { switch (value) { case ShowDataAsValues.Normal: return XLPivotCalculation.Normal; case ShowDataAsValues.Difference: return XLPivotCalculation.DifferenceFrom; case ShowDataAsValues.Percent: return XLPivotCalculation.PercentageOf; case ShowDataAsValues.PercentageDifference: return XLPivotCalculation.PercentageDifferenceFrom; case ShowDataAsValues.RunTotal: return XLPivotCalculation.RunningTotal; case ShowDataAsValues.PercentOfRaw: return XLPivotCalculation.PercentageOfRow; // There's a typo in the OpenXML SDK =) case ShowDataAsValues.PercentOfColumn: return XLPivotCalculation.PercentageOfColumn; case ShowDataAsValues.PercentOfTotal: return XLPivotCalculation.PercentageOfTotal; case ShowDataAsValues.Index: return XLPivotCalculation.Index; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLFilterOperator ToClosedXml(this FilterOperatorValues value) { switch (value) { case FilterOperatorValues.Equal: return XLFilterOperator.Equal; case FilterOperatorValues.NotEqual: return XLFilterOperator.NotEqual; case FilterOperatorValues.GreaterThan: return XLFilterOperator.GreaterThan; case FilterOperatorValues.LessThan: return XLFilterOperator.LessThan; case FilterOperatorValues.GreaterThanOrEqual: return XLFilterOperator.EqualOrGreaterThan; case FilterOperatorValues.LessThanOrEqual: return XLFilterOperator.EqualOrLessThan; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLFilterDynamicType ToClosedXml(this DynamicFilterValues value) { switch (value) { case DynamicFilterValues.AboveAverage: return XLFilterDynamicType.AboveAverage; case DynamicFilterValues.BelowAverage: return XLFilterDynamicType.BelowAverage; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLSheetViewOptions ToClosedXml(this SheetViewValues value) { switch (value) { case SheetViewValues.Normal: return XLSheetViewOptions.Normal; case SheetViewValues.PageBreakPreview: return XLSheetViewOptions.PageBreakPreview; case SheetViewValues.PageLayout: return XLSheetViewOptions.PageLayout; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLLineStyle ToClosedXml(this Vml.StrokeLineStyleValues value) { switch (value) { case Vml.StrokeLineStyleValues.Single: return XLLineStyle.Single; case Vml.StrokeLineStyleValues.ThickBetweenThin: return XLLineStyle.ThickBetweenThin; case Vml.StrokeLineStyleValues.ThickThin: return XLLineStyle.ThickThin; case Vml.StrokeLineStyleValues.ThinThick: return XLLineStyle.ThinThick; case Vml.StrokeLineStyleValues.ThinThin: return XLLineStyle.ThinThin; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLConditionalFormatType ToClosedXml(this ConditionalFormatValues value) { switch (value) { case ConditionalFormatValues.Expression: return XLConditionalFormatType.Expression; case ConditionalFormatValues.CellIs: return XLConditionalFormatType.CellIs; case ConditionalFormatValues.ColorScale: return XLConditionalFormatType.ColorScale; case ConditionalFormatValues.DataBar: return XLConditionalFormatType.DataBar; case ConditionalFormatValues.IconSet: return XLConditionalFormatType.IconSet; case ConditionalFormatValues.Top10: return XLConditionalFormatType.Top10; case ConditionalFormatValues.UniqueValues: return XLConditionalFormatType.IsUnique; case ConditionalFormatValues.DuplicateValues: return XLConditionalFormatType.IsDuplicate; case ConditionalFormatValues.ContainsText: return XLConditionalFormatType.ContainsText; case ConditionalFormatValues.NotContainsText: return XLConditionalFormatType.NotContainsText; case ConditionalFormatValues.BeginsWith: return XLConditionalFormatType.StartsWith; case ConditionalFormatValues.EndsWith: return XLConditionalFormatType.EndsWith; case ConditionalFormatValues.ContainsBlanks: return XLConditionalFormatType.IsBlank; case ConditionalFormatValues.NotContainsBlanks: return XLConditionalFormatType.NotBlank; case ConditionalFormatValues.ContainsErrors: return XLConditionalFormatType.IsError; case ConditionalFormatValues.NotContainsErrors: return XLConditionalFormatType.NotError; case ConditionalFormatValues.TimePeriod: return XLConditionalFormatType.TimePeriod; case ConditionalFormatValues.AboveAverage: return XLConditionalFormatType.AboveAverage; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLCFContentType ToClosedXml(this ConditionalFormatValueObjectValues value) { switch (value) { case ConditionalFormatValueObjectValues.Number: return XLCFContentType.Number; case ConditionalFormatValueObjectValues.Percent: return XLCFContentType.Percent; case ConditionalFormatValueObjectValues.Max: return XLCFContentType.Maximum; case ConditionalFormatValueObjectValues.Min: return XLCFContentType.Minimum; case ConditionalFormatValueObjectValues.Formula: return XLCFContentType.Formula; case ConditionalFormatValueObjectValues.Percentile: return XLCFContentType.Percentile; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLCFOperator ToClosedXml(this ConditionalFormattingOperatorValues value) { switch (value) { case ConditionalFormattingOperatorValues.LessThan: return XLCFOperator.LessThan; case ConditionalFormattingOperatorValues.LessThanOrEqual: return XLCFOperator.EqualOrLessThan; case ConditionalFormattingOperatorValues.Equal: return XLCFOperator.Equal; case ConditionalFormattingOperatorValues.NotEqual: return XLCFOperator.NotEqual; case ConditionalFormattingOperatorValues.GreaterThanOrEqual: return XLCFOperator.EqualOrGreaterThan; case ConditionalFormattingOperatorValues.GreaterThan: return XLCFOperator.GreaterThan; case ConditionalFormattingOperatorValues.Between: return XLCFOperator.Between; case ConditionalFormattingOperatorValues.NotBetween: return XLCFOperator.NotBetween; case ConditionalFormattingOperatorValues.ContainsText: return XLCFOperator.Contains; case ConditionalFormattingOperatorValues.NotContains: return XLCFOperator.NotContains; case ConditionalFormattingOperatorValues.BeginsWith: return XLCFOperator.StartsWith; case ConditionalFormattingOperatorValues.EndsWith: return XLCFOperator.EndsWith; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLIconSetStyle ToClosedXml(this IconSetValues value) { switch (value) { case IconSetValues.ThreeArrows: return XLIconSetStyle.ThreeArrows; case IconSetValues.ThreeArrowsGray: return XLIconSetStyle.ThreeArrowsGray; case IconSetValues.ThreeFlags: return XLIconSetStyle.ThreeFlags; case IconSetValues.ThreeTrafficLights1: return XLIconSetStyle.ThreeTrafficLights1; case IconSetValues.ThreeTrafficLights2: return XLIconSetStyle.ThreeTrafficLights2; case IconSetValues.ThreeSigns: return XLIconSetStyle.ThreeSigns; case IconSetValues.ThreeSymbols: return XLIconSetStyle.ThreeSymbols; case IconSetValues.ThreeSymbols2: return XLIconSetStyle.ThreeSymbols2; case IconSetValues.FourArrows: return XLIconSetStyle.FourArrows; case IconSetValues.FourArrowsGray: return XLIconSetStyle.FourArrowsGray; case IconSetValues.FourRedToBlack: return XLIconSetStyle.FourRedToBlack; case IconSetValues.FourRating: return XLIconSetStyle.FourRating; case IconSetValues.FourTrafficLights: return XLIconSetStyle.FourTrafficLights; case IconSetValues.FiveArrows: return XLIconSetStyle.FiveArrows; case IconSetValues.FiveArrowsGray: return XLIconSetStyle.FiveArrowsGray; case IconSetValues.FiveRating: return XLIconSetStyle.FiveRating; case IconSetValues.FiveQuarters: return XLIconSetStyle.FiveQuarters; #region default default: throw new ApplicationException("Not implemented value!"); #endregion default } } public static XLPictureFormat ToClosedXml(this ImagePartType value) { return Enum.Parse(typeof(XLPictureFormat), value.ToString()).CastTo<XLPictureFormat>(); } public static XLPicturePlacement ToClosedXml(this Xdr.EditAsValues value) { switch (value) { case Xdr.EditAsValues.Absolute: return XLPicturePlacement.FreeFloating; case Xdr.EditAsValues.OneCell: return XLPicturePlacement.Move; case Xdr.EditAsValues.TwoCell: return XLPicturePlacement.MoveAndSize; default: throw new ArgumentOutOfRangeException(); } } #endregion To ClosedXml } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the DataSource class. /// </summary> [Serializable] public partial class DataSourceCollection : ActiveList<DataSource, DataSourceCollection> { public DataSourceCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>DataSourceCollection</returns> public DataSourceCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { DataSource 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 DataSource table. /// </summary> [Serializable] public partial class DataSource : ActiveRecord<DataSource>, IActiveRecord { #region .ctors and Default Settings public DataSource() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public DataSource(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public DataSource(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public DataSource(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("DataSource", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarCode = new TableSchema.TableColumn(schema); colvarCode.ColumnName = "Code"; colvarCode.DataType = DbType.AnsiString; colvarCode.MaxLength = 50; colvarCode.AutoIncrement = false; colvarCode.IsNullable = false; colvarCode.IsPrimaryKey = false; colvarCode.IsForeignKey = false; colvarCode.IsReadOnly = false; colvarCode.DefaultSetting = @""; colvarCode.ForeignKeyTableName = ""; schema.Columns.Add(colvarCode); TableSchema.TableColumn colvarName = new TableSchema.TableColumn(schema); colvarName.ColumnName = "Name"; colvarName.DataType = DbType.AnsiString; colvarName.MaxLength = 150; colvarName.AutoIncrement = false; colvarName.IsNullable = false; colvarName.IsPrimaryKey = false; colvarName.IsForeignKey = false; colvarName.IsReadOnly = false; colvarName.DefaultSetting = @""; colvarName.ForeignKeyTableName = ""; schema.Columns.Add(colvarName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.AnsiString; colvarDescription.MaxLength = 5000; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; colvarDescription.DefaultSetting = @""; colvarDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarUrl = new TableSchema.TableColumn(schema); colvarUrl.ColumnName = "Url"; colvarUrl.DataType = DbType.AnsiString; colvarUrl.MaxLength = 250; colvarUrl.AutoIncrement = false; colvarUrl.IsNullable = true; colvarUrl.IsPrimaryKey = false; colvarUrl.IsForeignKey = false; colvarUrl.IsReadOnly = false; colvarUrl.DefaultSetting = @""; colvarUrl.ForeignKeyTableName = ""; schema.Columns.Add(colvarUrl); TableSchema.TableColumn colvarDefaultNullValue = new TableSchema.TableColumn(schema); colvarDefaultNullValue.ColumnName = "DefaultNullValue"; colvarDefaultNullValue.DataType = DbType.Double; colvarDefaultNullValue.MaxLength = 0; colvarDefaultNullValue.AutoIncrement = false; colvarDefaultNullValue.IsNullable = true; colvarDefaultNullValue.IsPrimaryKey = false; colvarDefaultNullValue.IsForeignKey = false; colvarDefaultNullValue.IsReadOnly = false; colvarDefaultNullValue.DefaultSetting = @""; colvarDefaultNullValue.ForeignKeyTableName = ""; schema.Columns.Add(colvarDefaultNullValue); TableSchema.TableColumn colvarErrorEstimate = new TableSchema.TableColumn(schema); colvarErrorEstimate.ColumnName = "ErrorEstimate"; colvarErrorEstimate.DataType = DbType.Double; colvarErrorEstimate.MaxLength = 0; colvarErrorEstimate.AutoIncrement = false; colvarErrorEstimate.IsNullable = true; colvarErrorEstimate.IsPrimaryKey = false; colvarErrorEstimate.IsForeignKey = false; colvarErrorEstimate.IsReadOnly = false; colvarErrorEstimate.DefaultSetting = @""; colvarErrorEstimate.ForeignKeyTableName = ""; schema.Columns.Add(colvarErrorEstimate); TableSchema.TableColumn colvarUpdateFreq = new TableSchema.TableColumn(schema); colvarUpdateFreq.ColumnName = "UpdateFreq"; colvarUpdateFreq.DataType = DbType.Int32; colvarUpdateFreq.MaxLength = 0; colvarUpdateFreq.AutoIncrement = false; colvarUpdateFreq.IsNullable = false; colvarUpdateFreq.IsPrimaryKey = false; colvarUpdateFreq.IsForeignKey = false; colvarUpdateFreq.IsReadOnly = false; colvarUpdateFreq.DefaultSetting = @""; colvarUpdateFreq.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdateFreq); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; colvarStartDate.DefaultSetting = @""; colvarStartDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; colvarEndDate.DefaultSetting = @""; colvarEndDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarLastUpdate = new TableSchema.TableColumn(schema); colvarLastUpdate.ColumnName = "LastUpdate"; colvarLastUpdate.DataType = DbType.DateTime; colvarLastUpdate.MaxLength = 0; colvarLastUpdate.AutoIncrement = false; colvarLastUpdate.IsNullable = false; colvarLastUpdate.IsPrimaryKey = false; colvarLastUpdate.IsForeignKey = false; colvarLastUpdate.IsReadOnly = false; colvarLastUpdate.DefaultSetting = @""; colvarLastUpdate.ForeignKeyTableName = ""; schema.Columns.Add(colvarLastUpdate); TableSchema.TableColumn colvarDataSchemaID = new TableSchema.TableColumn(schema); colvarDataSchemaID.ColumnName = "DataSchemaID"; colvarDataSchemaID.DataType = DbType.Guid; colvarDataSchemaID.MaxLength = 0; colvarDataSchemaID.AutoIncrement = false; colvarDataSchemaID.IsNullable = true; colvarDataSchemaID.IsPrimaryKey = false; colvarDataSchemaID.IsForeignKey = true; colvarDataSchemaID.IsReadOnly = false; colvarDataSchemaID.DefaultSetting = @""; colvarDataSchemaID.ForeignKeyTableName = "DataSchema"; schema.Columns.Add(colvarDataSchemaID); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; colvarAddedAt.DefaultSetting = @"(getdate())"; colvarAddedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; colvarUpdatedAt.DefaultSetting = @"(getdate())"; colvarUpdatedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; colvarRowVersion.DefaultSetting = @""; colvarRowVersion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRowVersion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("DataSource",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Code")] [Bindable(true)] public string Code { get { return GetColumnValue<string>(Columns.Code); } set { SetColumnValue(Columns.Code, value); } } [XmlAttribute("Name")] [Bindable(true)] public string Name { get { return GetColumnValue<string>(Columns.Name); } set { SetColumnValue(Columns.Name, value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>(Columns.Description); } set { SetColumnValue(Columns.Description, value); } } [XmlAttribute("Url")] [Bindable(true)] public string Url { get { return GetColumnValue<string>(Columns.Url); } set { SetColumnValue(Columns.Url, value); } } [XmlAttribute("DefaultNullValue")] [Bindable(true)] public double? DefaultNullValue { get { return GetColumnValue<double?>(Columns.DefaultNullValue); } set { SetColumnValue(Columns.DefaultNullValue, value); } } [XmlAttribute("ErrorEstimate")] [Bindable(true)] public double? ErrorEstimate { get { return GetColumnValue<double?>(Columns.ErrorEstimate); } set { SetColumnValue(Columns.ErrorEstimate, value); } } [XmlAttribute("UpdateFreq")] [Bindable(true)] public int UpdateFreq { get { return GetColumnValue<int>(Columns.UpdateFreq); } set { SetColumnValue(Columns.UpdateFreq, value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>(Columns.StartDate); } set { SetColumnValue(Columns.StartDate, value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>(Columns.EndDate); } set { SetColumnValue(Columns.EndDate, value); } } [XmlAttribute("LastUpdate")] [Bindable(true)] public DateTime LastUpdate { get { return GetColumnValue<DateTime>(Columns.LastUpdate); } set { SetColumnValue(Columns.LastUpdate, value); } } [XmlAttribute("DataSchemaID")] [Bindable(true)] public Guid? DataSchemaID { get { return GetColumnValue<Guid?>(Columns.DataSchemaID); } set { SetColumnValue(Columns.DataSchemaID, value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>(Columns.AddedAt); } set { SetColumnValue(Columns.AddedAt, value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); } set { SetColumnValue(Columns.UpdatedAt, value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>(Columns.RowVersion); } set { SetColumnValue(Columns.RowVersion, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public SAEON.Observations.Data.DataSourceTransformationCollection DataSourceTransformationRecords() { return new SAEON.Observations.Data.DataSourceTransformationCollection().Where(DataSourceTransformation.Columns.DataSourceID, Id).Load(); } public SAEON.Observations.Data.ImportBatchCollection ImportBatchRecords() { return new SAEON.Observations.Data.ImportBatchCollection().Where(ImportBatch.Columns.DataSourceID, Id).Load(); } public SAEON.Observations.Data.SensorCollection SensorRecords() { return new SAEON.Observations.Data.SensorCollection().Where(Sensor.Columns.DataSourceID, Id).Load(); } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this DataSource /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } private SAEON.Observations.Data.DataSchema _DataSchema = null; /// <summary> /// Returns a DataSchema ActiveRecord object related to this DataSource /// /// </summary> public SAEON.Observations.Data.DataSchema DataSchema { // get { return SAEON.Observations.Data.DataSchema.FetchByID(this.DataSchemaID); } get { return _DataSchema ?? (_DataSchema = SAEON.Observations.Data.DataSchema.FetchByID(this.DataSchemaID)); } set { SetColumnValue("DataSchemaID", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,string varCode,string varName,string varDescription,string varUrl,double? varDefaultNullValue,double? varErrorEstimate,int varUpdateFreq,DateTime? varStartDate,DateTime? varEndDate,DateTime varLastUpdate,Guid? varDataSchemaID,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { DataSource item = new DataSource(); item.Id = varId; item.Code = varCode; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.DefaultNullValue = varDefaultNullValue; item.ErrorEstimate = varErrorEstimate; item.UpdateFreq = varUpdateFreq; item.StartDate = varStartDate; item.EndDate = varEndDate; item.LastUpdate = varLastUpdate; item.DataSchemaID = varDataSchemaID; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; 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(Guid varId,string varCode,string varName,string varDescription,string varUrl,double? varDefaultNullValue,double? varErrorEstimate,int varUpdateFreq,DateTime? varStartDate,DateTime? varEndDate,DateTime varLastUpdate,Guid? varDataSchemaID,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { DataSource item = new DataSource(); item.Id = varId; item.Code = varCode; item.Name = varName; item.Description = varDescription; item.Url = varUrl; item.DefaultNullValue = varDefaultNullValue; item.ErrorEstimate = varErrorEstimate; item.UpdateFreq = varUpdateFreq; item.StartDate = varStartDate; item.EndDate = varEndDate; item.LastUpdate = varLastUpdate; item.DataSchemaID = varDataSchemaID; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; 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 IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CodeColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn NameColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn DescriptionColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn UrlColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn DefaultNullValueColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn ErrorEstimateColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn UpdateFreqColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn StartDateColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn EndDateColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn LastUpdateColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn DataSchemaIDColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn AddedAtColumn { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn UpdatedAtColumn { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn RowVersionColumn { get { return Schema.Columns[15]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string Code = @"Code"; public static string Name = @"Name"; public static string Description = @"Description"; public static string Url = @"Url"; public static string DefaultNullValue = @"DefaultNullValue"; public static string ErrorEstimate = @"ErrorEstimate"; public static string UpdateFreq = @"UpdateFreq"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string LastUpdate = @"LastUpdate"; public static string DataSchemaID = @"DataSchemaID"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
// SharpMath - C# Mathematical Library // Copyright (c) 2014 Morten Bakkedal // This code is published under the MIT License. using System; using System.Diagnostics; namespace SharpMath.LinearAlgebra { [Serializable] [DebuggerStepThrough] [DebuggerDisplay("{DebuggerDisplay}")] public sealed class ComplexVector { private ComplexMatrix inner; internal ComplexVector(ComplexMatrix inner) { if (inner.Columns != 1) { throw new ArgumentException(); } this.inner = inner; } public ComplexVector(Complex[] entries) { int n = entries.Length; Complex[,] a = new Complex[n, 1]; for (int i = 0; i < n; i++) { a[i, 0] = entries[i]; } inner = new ComplexMatrix(a); } public ComplexVector SetValue(int index, Complex t) { return new ComplexVector(inner.SetEntry(index, 0, t)); } public ComplexVector SetVector(int index, ComplexVector a) { return new ComplexVector(inner.SetMatrix(index, 0, a.inner)); } public ComplexVector GetVector(int index, int length) { return new ComplexVector(inner.GetMatrix(index, 0, length, 1)); } public Complex[] ToArray() { return inner.ToLinearArray(); } public override string ToString() { return ToString(null); } public string ToString(string format) { //string s = ComplexMatrix.Transpose(inner).ToString(format); //return s.Substring(1, s.Length - 2); return inner.ToString(format); } public static ComplexVector Zero(int length) { return new ComplexVector(ComplexMatrix.Zero(length, 1)); } public static ComplexVector Basis(int length, int index) { return new ComplexVector(ComplexMatrix.Basis(length, 1, index, 0)); } public static Complex Dot(ComplexVector a, ComplexVector b) { int n = a.Length; if (n != b.Length) { throw new ArgumentException("Dot product undefined. Size mismatch."); } Complex s = 0.0; for (int i = 0; i < n; i++) { s += a[i] * b[i]; } return s; } public static implicit operator ComplexMatrix(ComplexVector a) { return a.inner; } public static explicit operator ComplexVector(ComplexMatrix a) { if (a.Columns == 1) { return new ComplexVector(a); } if (a.Rows == 1) { // Some copying overhead here. return new ComplexVector(ComplexMatrix.Transpose(a)); } throw new InvalidCastException("The matrix has no vector representation."); } public static implicit operator ComplexVector(Vector vector) { return new ComplexVector((ComplexMatrix)(Matrix)vector); } public static ComplexVector operator +(ComplexVector a, ComplexVector b) { return new ComplexVector(a.inner + b.inner); } public static ComplexVector operator +(ComplexVector a, Complex t) { return new ComplexVector(a.inner + t); } public static ComplexVector operator +(Complex t, ComplexVector a) { return a + t; } public static ComplexVector operator -(ComplexVector a) { return a * -1.0; } public static ComplexVector operator -(ComplexVector a, ComplexVector b) { return new ComplexVector(a.inner - b.inner); } public static ComplexVector operator -(ComplexVector a, Complex t) { return a + (-t); } public static ComplexVector operator -(Complex t, ComplexVector a) { return new ComplexVector(t - a.inner); } public static ComplexVector operator *(ComplexMatrix a, ComplexVector b) { return new ComplexVector(a * b.inner); } public static ComplexVector operator *(Matrix a, ComplexVector b) { return new ComplexVector(a * b.inner); } public static ComplexVector operator *(ComplexVector a, Complex t) { return new ComplexVector(a.inner * t); } public static ComplexVector operator *(Complex t, ComplexVector a) { return a * t; } public static ComplexVector operator /(ComplexVector a, Complex t) { return a * (1.0 / t); } public Complex this[int index] { get { return inner[index, 0]; } } public int Length { get { return inner.Rows; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebuggerDisplay { get { return ToString(); } } } }
// Gardens Point Parser Generator // Copyright (c) Wayne Kelly, QUT 2005 // (see accompanying GPPGcopyright.rtf) using System; using System.Collections.Generic; using System.IO; namespace gpcc { public class LR0Generator { protected List<State> states = new List<State>(); protected Grammar grammar; private Dictionary<Symbol, List<State>> accessedBy = new Dictionary<Symbol, List<State>>(); public LR0Generator(Grammar grammar) { this.grammar = grammar; } public List<State> BuildStates() { // create state for root production and expand recursively ExpandState(grammar.rootProduction.lhs, new State(grammar.rootProduction)); return states; } private void ExpandState(Symbol sym, State newState) { newState.accessedBy = sym; states.Add(newState); if (!accessedBy.ContainsKey(sym)) accessedBy[sym] = new List<State>(); accessedBy[sym].Add(newState); newState.AddClosure(); ComputeGoto(newState); } private void ComputeGoto(State state) { foreach (ProductionItem item in state.all_items) if (!item.expanded && !item.isReduction()) { item.expanded = true; Symbol s1 = item.production.rhs[item.pos]; // Create itemset for new state ... List<ProductionItem> itemSet = new List<ProductionItem>(); itemSet.Add(new ProductionItem(item.production, item.pos + 1)); foreach (ProductionItem item2 in state.all_items) if (!item2.expanded && !item2.isReduction()) { Symbol s2 = item2.production.rhs[item2.pos]; if (s1 == s2) { item2.expanded = true; itemSet.Add(new ProductionItem(item2.production, item2.pos + 1)); } } State existingState = FindExistingState(s1, itemSet); if (existingState == null) { State newState = new State(itemSet); state.AddGoto(s1, newState); ExpandState(s1, newState); } else state.AddGoto(s1, existingState); } } private State FindExistingState(Symbol sym, List<ProductionItem> itemSet) { if (accessedBy.ContainsKey(sym)) foreach (State state in accessedBy[sym]) if (ProductionItem.SameProductions(state.kernal_items, itemSet)) return state; return null; } public void BuildParseTable() { foreach (State state in states) { // Add shift actions ... foreach (Terminal t in state.terminalTransitions) { state.parseTable[t] = new Shift(state.Goto[t]); } // Add reduce actions ... foreach (ProductionItem item in state.all_items) { if (item.isReduction()) { // Accept on everything if (item.production == grammar.rootProduction) foreach (Terminal t in grammar.terminals.Values) state.parseTable[t] = new Reduce(item); foreach (Terminal t in item.LA) { // possible conflict with existing action if (state.parseTable.ContainsKey(t)) { ParserAction other = state.parseTable[t]; if (state.conflictTable.ContainsKey(t)) { continue; } if (other is Reduce) { Console.Error.WriteLine("Reduce/Reduce conflict, state {0}: {1} vs {2} on {3}", state.num, item.production.num, ((Reduce)other).item.production.num, t); // choose in favour of production listed first in the grammar// (changed to handle conflict parsing) if (((Reduce)other).item.production.num > item.production.num) { state.conflictTable[t] = state.parseTable[t]; state.parseTable[t] = new Reduce(item); //state.conflictTable[t] = (Reduce)other; } else { state.conflictTable[t] = new Reduce(item); } } else { if (item.production.prec != null && t.prec != null) { if (item.production.prec.prec > t.prec.prec || (item.production.prec.prec == t.prec.prec && item.production.prec.type == PrecType.left)) { // resolve in favour of reduce (without error) //state.conflictTable[t] = state.parseTable[t]; state.parseTable[t] = new Reduce(item); } else { // resolve in favour of shift (without error) state.conflictTable[t] = new Reduce(item); } } else { Console.Error.WriteLine("Shift/Reduce conflict, state {0} on {1}", state.num, t); state.conflictTable[t] = new Reduce(item); // choose in favour of the shift } } } else state.parseTable[t] = new Reduce(item); } } } } } public void Report(string filename) { using (TextWriter w = File.CreateText(filename + ".report")) { w.WriteLine("Grammar"); NonTerminal lhs = null; foreach (Production production in grammar.productions) { if (production.lhs != lhs) { lhs = production.lhs; w.WriteLine(); w.Write("{0,5} {1}: ", production.num, lhs); } else w.Write("{0,5} {1}| ", production.num, new string(' ', lhs.ToString().Length)); for (int i = 0; i < production.rhs.Count - 1; i++) w.Write("{0} ", production.rhs[i].ToString()); if (production.rhs.Count > 0) w.WriteLine("{0}", production.rhs[production.rhs.Count - 1]); else w.WriteLine("/* empty */"); } w.WriteLine(); foreach (State state in states) w.WriteLine(state.ToString()); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.History { using System.Collections.Generic; using System.Data.Common; using System.Data.Entity.Core; using System.Data.Entity.Core.Common; using System.Data.Entity.Core.Common.CommandTrees; using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Infrastructure; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.Internal; using System.Data.Entity.Migrations.Edm; using System.Data.Entity.Migrations.Infrastructure; using System.Data.Entity.Migrations.Model; using System.Data.Entity.ModelConfiguration.Edm; using System.Data.Entity.Resources; using System.Data.Entity.Utilities; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Transactions; using System.Xml.Linq; internal class HistoryRepository : RepositoryBase { private static readonly string _productVersion = typeof(HistoryRepository).Assembly().GetInformationalVersion(); public static readonly PropertyInfo MigrationIdProperty = typeof(HistoryRow).GetDeclaredProperty("MigrationId"); public static readonly PropertyInfo ContextKeyProperty = typeof(HistoryRow).GetDeclaredProperty("ContextKey"); private readonly string _contextKey; private readonly int? _commandTimeout; private readonly IEnumerable<string> _schemas; private readonly Func<DbConnection, string, HistoryContext> _historyContextFactory; private readonly DbContext _contextForInterception; private readonly int _contextKeyMaxLength; private readonly int _migrationIdMaxLength; private readonly DatabaseExistenceState _initialExistence; private readonly DbTransaction _existingTransaction; private string _currentSchema; private bool? _exists; private bool _contextKeyColumnExists; public HistoryRepository( InternalContext usersContext, string connectionString, DbProviderFactory providerFactory, string contextKey, int? commandTimeout, Func<DbConnection, string, HistoryContext> historyContextFactory, IEnumerable<string> schemas = null, DbContext contextForInterception = null, DatabaseExistenceState initialExistence = DatabaseExistenceState.Unknown) : base(usersContext, connectionString, providerFactory) { DebugCheck.NotEmpty(contextKey); DebugCheck.NotNull(historyContextFactory); _initialExistence = initialExistence; _commandTimeout = commandTimeout; _existingTransaction = usersContext.TryGetCurrentStoreTransaction(); _schemas = new[] { EdmModelExtensions.DefaultSchema } .Concat(schemas ?? Enumerable.Empty<string>()) .Distinct(); _contextForInterception = contextForInterception; _historyContextFactory = historyContextFactory; DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var historyRowEntity = ((IObjectContextAdapter)context).ObjectContext .MetadataWorkspace .GetItems<EntityType>(DataSpace.CSpace) .Single(et => et.GetClrType() == typeof(HistoryRow)); var maxLength = historyRowEntity .Properties .Single(p => p.GetClrPropertyInfo().IsSameAs(MigrationIdProperty)) .MaxLength; _migrationIdMaxLength = maxLength.HasValue ? maxLength.Value : HistoryContext.MigrationIdMaxLength; maxLength = historyRowEntity .Properties .Single(p => p.GetClrPropertyInfo().IsSameAs(ContextKeyProperty)) .MaxLength; _contextKeyMaxLength = maxLength.HasValue ? maxLength.Value : HistoryContext.ContextKeyMaxLength; } } finally { DisposeConnection(connection); } _contextKey = contextKey.RestrictTo(_contextKeyMaxLength); } public virtual MigrationOperation CreateInsertOperation(string migrationId, XDocument model) { DebugCheck.NotEmpty(migrationId); DebugCheck.NotNull(model); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { context.History.Add( new HistoryRow { MigrationId = migrationId.RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(versionedModel.Model), ProductVersion = _productVersion }); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); return new HistoryOperation( commandTracer.CommandTrees.OfType<DbModificationCommandTree>().ToList()); } } } finally { DisposeConnection(connection); } } public int ContextKeyMaxLength { get { return _contextKeyMaxLength; } } public int MigrationIdMaxLength { get { return _migrationIdMaxLength; } } public string CurrentSchema { get { return _currentSchema; } set { DebugCheck.NotEmpty(value); _currentSchema = value; } } public virtual XDocument GetLastModel(out string migrationId, out string productVersion, string contextKey = null) { using (var context = CreateContext(connection)) { context.Database.ExecuteSqlCommand( ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript()); context.History.Add( new HistoryRow { MigrationId = MigrationAssembly .CreateMigrationId(Strings.InitialCreate) .RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(versionedModel.Model), ProductVersion = _productVersion }); context.SaveChanges(); } migrationId = null; productVersion = null; if (!Exists(contextKey)) { return null; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { using (new TransactionScope(TransactionScopeOption.Suppress)) { var baseQuery = CreateHistoryQuery(context, contextKey) .OrderByDescending(h => h.MigrationId); var lastModel = baseQuery .Select( s => new { s.MigrationId, s.Model, s.ProductVersion }) .FirstOrDefault(); if (lastModel == null) { return null; } migrationId = lastModel.MigrationId; productVersion = lastModel.ProductVersion; return new ModelCompressor().Decompress(lastModel.Model); } } } finally { DisposeConnection(connection); } } public virtual XDocument GetModel(string migrationId, out string productVersion) { DebugCheck.NotEmpty(migrationId); productVersion = null; if (!Exists()) { return null; } migrationId = migrationId.RestrictTo(_migrationIdMaxLength); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var baseQuery = CreateHistoryQuery(context) .Where(h => h.MigrationId == migrationId); var model = baseQuery .Select( h => new { h.Model, h.ProductVersion }) .SingleOrDefault(); if (model == null) { return null; } productVersion = model.ProductVersion; return new ModelCompressor().Decompress(model.Model); } } finally { DisposeConnection(connection); } } public virtual IEnumerable<string> GetPendingMigrations(IEnumerable<string> localMigrations) { DebugCheck.NotNull(localMigrations); if (!Exists()) { return localMigrations; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { List<string> databaseMigrations; using (new TransactionScope(TransactionScopeOption.Suppress)) { databaseMigrations = CreateHistoryQuery(context) .Select(h => h.MigrationId) .ToList(); } localMigrations = localMigrations .Select(m => m.RestrictTo(_migrationIdMaxLength)) .ToArray(); var pendingMigrations = localMigrations.Except(databaseMigrations); var firstDatabaseMigration = databaseMigrations.FirstOrDefault(); var firstLocalMigration = localMigrations.FirstOrDefault(); // If the first database migration and the first local migration don't match, // but both are named InitialCreate then treat it as already applied. This can // happen when trying to migrate a database that was created using initializers if (firstDatabaseMigration != firstLocalMigration && firstDatabaseMigration != null && firstDatabaseMigration.MigrationName() == Strings.InitialCreate && firstLocalMigration != null && firstLocalMigration.MigrationName() == Strings.InitialCreate) { Debug.Assert(pendingMigrations.First() == firstLocalMigration); pendingMigrations = pendingMigrations.Skip(1); } return pendingMigrations.ToList(); } } finally { DisposeConnection(connection); } } public virtual IEnumerable<string> GetMigrationsSince(string migrationId) { DebugCheck.NotEmpty(migrationId); var exists = Exists(); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var query = CreateHistoryQuery(context); migrationId = migrationId.RestrictTo(_migrationIdMaxLength); if (migrationId != DbMigrator.InitialDatabase) { if (!exists || !query.Any(h => h.MigrationId == migrationId)) { throw Error.MigrationNotFound(migrationId); } query = query.Where(h => string.Compare(h.MigrationId, migrationId, StringComparison.Ordinal) > 0); } else if (!exists) { return Enumerable.Empty<string>(); } return query .OrderByDescending(h => h.MigrationId) .Select(h => h.MigrationId) .ToList(); } } finally { DisposeConnection(connection); } } public virtual string GetMigrationId(string migrationName) { DebugCheck.NotEmpty(migrationName); if (!Exists()) { return null; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var migrationIds = CreateHistoryQuery(context) .Select(h => h.MigrationId) .Where(m => m.Substring(16) == migrationName) .ToList(); if (!migrationIds.Any()) { return null; } if (migrationIds.Count() == 1) { return migrationIds.Single(); } throw Error.AmbiguousMigrationName(migrationName); } } finally { DisposeConnection(connection); } } private IQueryable<HistoryRow> CreateHistoryQuery(HistoryContext context, string contextKey = null) { IQueryable<HistoryRow> q = context.History; contextKey = !string.IsNullOrWhiteSpace(contextKey) ? contextKey.RestrictTo(_contextKeyMaxLength) : _contextKey; if (_contextKeyColumnExists) { q = q.Where(h => h.ContextKey == contextKey); } return q; } public virtual bool IsShared() { if (!Exists() || !_contextKeyColumnExists) { return false; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { return context.History.Any(hr => hr.ContextKey != _contextKey); } } finally { DisposeConnection(connection); } } public virtual bool HasMigrations() { if (!Exists()) { return false; } if (!_contextKeyColumnExists) { return true; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { return context.History.Count(hr => hr.ContextKey == _contextKey) > 0; } } finally { DisposeConnection(connection); } } public virtual bool Exists(string contextKey = null) { if (_exists == null) { _exists = QueryExists(contextKey ?? _contextKey); } return _exists.Value; } private bool QueryExists(string contextKey) { DebugCheck.NotNull(contextKey); if (_initialExistence == DatabaseExistenceState.DoesNotExist) { return false; } DbConnection connection = null; try { connection = CreateConnection(); if (_initialExistence == DatabaseExistenceState.Unknown) { using (var context = CreateContext(connection)) { if (!context.Database.Exists()) { return false; } } } foreach (var schema in _schemas.Reverse()) { using (var context = CreateContext(connection, schema)) { _currentSchema = schema; _contextKeyColumnExists = true; // Do the context-key specific query first, since if it succeeds we can avoid // doing the more general query. try { using (new TransactionScope(TransactionScopeOption.Suppress)) { contextKey = contextKey.RestrictTo(_contextKeyMaxLength); if (context.History.Count(hr => hr.ContextKey == contextKey) > 0) { return true; } } } catch (EntityException) { _contextKeyColumnExists = false; } // If the context-key specific query failed, then try the general query to see // if there is a history table in this schema at all if (!_contextKeyColumnExists) { try { using (new TransactionScope(TransactionScopeOption.Suppress)) { context.History.Count(); } } catch (EntityException) { _currentSchema = null; } } } } } finally { DisposeConnection(connection); } return !string.IsNullOrWhiteSpace(_currentSchema); } public virtual void ResetExists() { _exists = null; } public virtual IEnumerable<MigrationOperation> GetUpgradeOperations() { if (!Exists()) { yield break; } DbConnection connection = null; try { connection = CreateConnection(); var tableName = "dbo." + HistoryContext.DefaultTableName; DbProviderManifest providerManifest; if (connection.GetProviderInfo(out providerManifest).IsSqlCe()) { tableName = HistoryContext.DefaultTableName; } using (var context = new LegacyHistoryContext(connection)) { var createdOnExists = false; try { InjectInterceptionContext(context); using (new TransactionScope(TransactionScopeOption.Suppress)) { context.History .Select(h => h.CreatedOn) .FirstOrDefault(); } createdOnExists = true; } catch (EntityException) { } if (createdOnExists) { yield return new DropColumnOperation(tableName, "CreatedOn"); } } using (var context = CreateContext(connection)) { if (!_contextKeyColumnExists) { if (_historyContextFactory != HistoryContext.DefaultFactory) { throw Error.UnableToUpgradeHistoryWhenCustomFactory(); } yield return new AddColumnOperation( tableName, new ColumnModel(PrimitiveTypeKind.String) { MaxLength = _contextKeyMaxLength, Name = "ContextKey", IsNullable = false, DefaultValue = _contextKey }); var emptyModel = new DbModelBuilder().Build(connection).GetModel(); var createTableOperation = (CreateTableOperation) new EdmModelDiffer().Diff(emptyModel, context.GetModel()).Single(); var dropPrimaryKeyOperation = new DropPrimaryKeyOperation { Table = tableName, CreateTableOperation = createTableOperation }; dropPrimaryKeyOperation.Columns.Add("MigrationId"); yield return dropPrimaryKeyOperation; yield return new AlterColumnOperation( tableName, new ColumnModel(PrimitiveTypeKind.String) { MaxLength = _migrationIdMaxLength, Name = "MigrationId", IsNullable = false }, isDestructiveChange: false); var addPrimaryKeyOperation = new AddPrimaryKeyOperation { Table = tableName }; addPrimaryKeyOperation.Columns.Add("MigrationId"); addPrimaryKeyOperation.Columns.Add("ContextKey"); yield return addPrimaryKeyOperation; } } } finally { DisposeConnection(connection); } } public virtual MigrationOperation CreateDeleteOperation(string migrationId) { DebugCheck.NotEmpty(migrationId); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var historyRow = new HistoryRow { MigrationId = migrationId.RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey }; context.History.Attach(historyRow); context.History.Remove(historyRow); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); return new HistoryOperation( commandTracer.CommandTrees.OfType<DbModificationCommandTree>().ToList()); } } } finally { DisposeConnection(connection); } } public virtual IEnumerable<DbQueryCommandTree> CreateDiscoveryQueryTrees() { DbConnection connection = null; try { connection = CreateConnection(); foreach (var schema in _schemas) { using (var context = CreateContext(connection, schema)) { var query = context.History .Where(h => h.ContextKey == _contextKey) .Select(s => s.MigrationId) .OrderByDescending(s => s); var dbQuery = query as DbQuery<string>; if (dbQuery != null) { dbQuery.InternalQuery.ObjectQuery.EnablePlanCaching = false; } using (var commandTracer = new CommandTracer(context)) { query.First(); var queryTree = commandTracer .CommandTrees .OfType<DbQueryCommandTree>() .Single(t => t.DataSpace == DataSpace.SSpace); yield return new DbQueryCommandTree( queryTree.MetadataWorkspace, queryTree.DataSpace, queryTree.Query.Accept( new ParameterInliner( commandTracer.DbCommands.Single().Parameters))); } } } } finally { DisposeConnection(connection); } } private class ParameterInliner : DefaultExpressionVisitor { private readonly DbParameterCollection _parameters; public ParameterInliner(DbParameterCollection parameters) { DebugCheck.NotNull(parameters); _parameters = parameters; } public override DbExpression Visit(DbParameterReferenceExpression expression) { // Inline parameters return DbExpressionBuilder.Constant(_parameters[expression.ParameterName].Value); } // Removes null parameter checks public override DbExpression Visit(DbOrExpression expression) { return expression.Left.Accept(this); } public override DbExpression Visit(DbAndExpression expression) { if (expression.Right is DbNotExpression) { return expression.Left.Accept(this); } return base.Visit(expression); } } public virtual void BootstrapUsingEFProviderDdl(XDocument model) { DebugCheck.NotNull(model); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { context.Database.ExecuteSqlCommand( ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript()); context.History.Add( new HistoryRow { MigrationId = MigrationAssembly .CreateMigrationId(Strings.InitialCreate) .RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); context.SaveChanges(); } } finally { DisposeConnection(connection); } } public HistoryContext CreateContext(DbConnection connection, string schema = null) { DebugCheck.NotNull(connection); var context = _historyContextFactory(connection, schema ?? CurrentSchema); context.Database.CommandTimeout = _commandTimeout; if (_existingTransaction != null) { Debug.Assert(_existingTransaction.Connection == connection); if (_existingTransaction.Connection == connection) { context.Database.UseTransaction(_existingTransaction); } } InjectInterceptionContext(context); return context; } private void InjectInterceptionContext(DbContext context) { if (_contextForInterception != null) { var objectContext = context.InternalContext.ObjectContext; objectContext.InterceptionContext = objectContext.InterceptionContext.WithDbContext(_contextForInterception); } } } }
using System; using System.Collections.Generic; using System.Linq; using SharpGEDParser; using SharpGEDParser.Model; // 20161225 01\00005.ged is an example of inconsistancy between the INDI.FAMC // and the FAM.CHIL linkages. From my reading, the INDI.FAMC links are the // "master". The first version of this code was working from the FAM.CHIL links. // 201701?? BuildTree2() is a variant where the FAM.CHIL links are the "master". // 20170108 Handle "child in more than one family" by replacing child hash with a MultiMap. The FamilyUnit // connections to "Dad's family" and "Mom's family" are now a problem because there could be more than one link. namespace BuildTree { public class FamilyTreeBuild { private int _CHILErrorsCount; private int errorsCount; private Dictionary<string, IndiWrap> _indiHash; // INDI ident -> INDI record private Dictionary<string, FamilyUnit> _famHash; // FAM ident -> FAM record private MultiMap<string, FamilyUnit> _childsIn; // INDI ident -> multi FAM private List<Issue> _issues; private string _firstPerson; // "First" person in tree - default initial person public IEnumerable<string> IndiIds { get { return _indiHash.Keys; } } private IndiWrap MakeFillerIndi(string ident, out IndiRecord hack) { // There is a reference to an individual who doesn't exist in // the GEDCOM. Create a placeholder. IndiWrap hack0 = new IndiWrap(); // TODO need a library method to do this!!! hack = new IndiRecord(null, ident, null); var hack2 = new NameRec(); hack2.Surname = "Missing"; hack.Names.Add(hack2); hack0.Indi = hack; hack0.Ahnen = -1; return hack0; } private void MakeError(Issue.IssueCode code, params object[] evidence) { Issue err = new Issue(code, evidence); _issues.Add(err); } private void Pass1(IEnumerable<GEDCommon> gedRecs) { // Wrap INDI and FAM records, collect into hashes _indiHash = new Dictionary<string, IndiWrap>(); _famHash = new Dictionary<string, FamilyUnit>(); _childsIn = new MultiMap<string, FamilyUnit>(); _issues = new List<Issue>(); foreach (var gedCommon in gedRecs) // TODO really need 'INDI', 'FAM' accessors { if (gedCommon is IndiRecord) { var ident = (gedCommon as IndiRecord).Ident; if (_indiHash.ContainsKey(ident)) { MakeError(Issue.IssueCode.DUPL_INDI, ident); } else { IndiWrap iw = new IndiWrap(); iw.Indi = gedCommon as IndiRecord; iw.Ahnen = 0; _indiHash.Add(ident, iw); if (_firstPerson == null) _firstPerson = ident; } } // TODO GEDCOM_Amssoms.ged has a duplicate family "X0". Needs to be caught by validate, flag as error, and not reach here. if (gedCommon is FamRecord) { var fam = gedCommon as FamRecord; var ident = fam.Ident; if (string.IsNullOrEmpty(ident)) { MakeError(Issue.IssueCode.MISS_FAMID, fam.BegLine); continue; } if (!_famHash.ContainsKey(ident)) _famHash.Add(ident, new FamilyUnit(fam)); else { MakeError(Issue.IssueCode.DUPL_FAM, ident); } } } } private void Pass3() { // Try to determine each spouse's family [the family they were born into] // TODO currently of dubious value because dad/mom may be adopted and currently keeping only the 'first' family connection // Also check if HUSB/WIFE links are to valid people // Also check if CHIL links are valid (exist and matched) foreach (var familyUnit in _famHash.Values) { var famIdent = familyUnit.FamRec.Ident; if (familyUnit.Husband != null) { var dadFams = _childsIn[familyUnit.DadId]; if (dadFams != null && dadFams.Count > 0) { familyUnit.DadFam = dadFams[0]; if (dadFams.Count > 1) { MakeError(Issue.IssueCode.AMB_CONN, "dad", famIdent); } } } if (familyUnit.Wife != null) { var momFams = _childsIn[familyUnit.MomId]; if (momFams != null && momFams.Count > 0) { familyUnit.MomFam = momFams[0]; if (momFams.Count > 1) { MakeError(Issue.IssueCode.AMB_CONN, "mom", famIdent); } } } // TODO what happens in parse if more than one HUSB/WIFE specified? var husbId = familyUnit.FamRec.Dad; if (husbId != null && !_indiHash.ContainsKey(husbId)) { MakeError(Issue.IssueCode.SPOUSE_CONN2, famIdent, husbId, "HUSB"); } var wifeId = familyUnit.FamRec.Mom; if (wifeId != null && !_indiHash.ContainsKey(wifeId)) { MakeError(Issue.IssueCode.SPOUSE_CONN2, famIdent, wifeId, "WIFE"); } foreach (var childId in familyUnit.FamRec.Childs) { if (childId == null) continue; IndiWrap indi; if (!_indiHash.TryGetValue(childId, out indi)) { MakeError(Issue.IssueCode.CHIL_MISS, famIdent, childId); } else { // TODO need a simple FAMC link accessor bool found = false; foreach (var link in indi.Indi.Links) { if (link.Tag == "FAMC" && link.Xref == famIdent) found = true; } if (!found) MakeError(Issue.IssueCode.CHIL_NOTMATCH, famIdent, childId); } } } } public void BuildTree(IEnumerable<GEDCommon> gedRecs, bool showErrors, bool checkCHIL) { // an indi has a FAMS or FAMC // a FAM has HUSB WIFE CHIL but the CHIL are being ignored Pass1(gedRecs); // Iterate through the indi records. // For each FAMS, identify the husb/wife relation // For each FAMC, add to childhash foreach (var indiWrap in _indiHash.Values) { var indiId = indiWrap.Indi.Ident; foreach (var indiLink in indiWrap.Indi.Links) // TODO wow this is awkward { FamilyUnit fu; var id = indiLink.Xref; if (string.IsNullOrEmpty(id)) { MakeError(Issue.IssueCode.MISS_XREFID, indiId, indiLink.Tag); continue; } switch (indiLink.Tag) { case "FAMS": if (_famHash.TryGetValue(id, out fu)) { indiWrap.SpouseIn.Add(fu); if (fu.FamRec.Dad == indiId) fu.Husband = indiWrap; else if (fu.FamRec.Mom == indiId) fu.Wife = indiWrap; else { MakeError(Issue.IssueCode.SPOUSE_CONN, indiLink.Xref, indiId); } } else { MakeError(Issue.IssueCode.FAMS_MISSING, indiId, id); } break; case "FAMC": if (_famHash.TryGetValue(id, out fu)) { _childsIn.Add(indiId, fu); fu.Childs.Add(indiWrap); indiWrap.ChildIn.Add(fu); } else { MakeError(Issue.IssueCode.FAMC_MISSING, indiId, id); } break; } } } Pass3(); errorsCount = 0; foreach (var issue in _issues) { var msg = issue.Message(); if (msg.StartsWith("Error:")) // TODO unit testing errorsCount++; if (showErrors) Console.WriteLine(msg); } // verify if FAM.CHIL have matching INDI.FAMC if (checkCHIL) { _CHILErrorsCount = 0; foreach (var fam in _famHash.Values) { foreach (var child in fam.FamRec.Childs) { var id = child; if (_indiHash.ContainsKey(id)) { var indi = _indiHash[id]; bool found = false; foreach (var link in indi.Indi.Links) { if (link.Tag == "FAMC") { if (link.Xref == fam.FamRec.Ident) found = true; } } if (!found) { // TODO duplicated in Pass3 //if (showErrors) // Console.WriteLine("Error: FAM {0} with CHIL link to {1} and no matching FAMC", fam.FamRec.Ident, id); //_CHILErrorsCount += 1; } } else { // TODO duplicated in Pass3 //if (showErrors) // Console.WriteLine("Error: FAM {0} has CHIL link {1} to non-existing INDI", fam.FamRec.Ident, id); } } } } } public int ChilErrorsCount { get { return _CHILErrorsCount; } } public int ErrorsCount { get { return errorsCount; } } public IndiWrap IndiFromId(string indiId) { return _indiHash[indiId]; } public List<FamilyUnit> FamFromIndi(string ident) { return _childsIn[ident]; } public void BuildTree2(IEnumerable<GEDCommon> gedRecs, bool showErrors, bool checkCHIL) { // an indi has a FAMS or FAMC // a FAM has HUSB WIFE CHIL // This variant of BuildTree believes the CHIL links are correct Pass1(gedRecs); errorsCount = 0; // TODO how, if at all, is the tree check impacted? // Iterate through the family records // For each HUSB/WIFE, connect to INDI // For each CHIL, connect to INDI foreach (var familyUnit in _famHash.Values) { var famId = familyUnit.FamRec.Ident; var dadId = familyUnit.FamRec.Dad; if (dadId != null) // TODO mark as error? { IndiWrap dadWrap; if (_indiHash.TryGetValue(dadId, out dadWrap)) { dadWrap.SpouseIn.Add(familyUnit); // TODO verify dadWrap has matching FAMS familyUnit.Husband = dadWrap; } else { // TODO duplicated in Pass3 //if (showErrors) // Console.WriteLine("Error: family {0} has HUSB link {1} to non-existing INDI", famId, dadId); //errorsCount += 1; } } var momId = familyUnit.FamRec.Mom; if (momId != null) // TODO mark as error? { IndiWrap momWrap; if (_indiHash.TryGetValue(momId, out momWrap)) { momWrap.SpouseIn.Add(familyUnit); // TODO verify momWrap has matching FAMS familyUnit.Wife = momWrap; } else { // TODO duplicated in Pass3 //if (showErrors) // Console.WriteLine("Error: family {0} has WIFE link {1} to non-existing INDI", famId, momId); //errorsCount += 1; } } foreach (var childId in familyUnit.FamRec.Childs) { // does childId exist in _indiHash: if yes, add to familyUnit.Childs // if no, error IndiWrap childWrap; if (_indiHash.TryGetValue(childId, out childWrap)) { childWrap.ChildIn.Add(familyUnit); familyUnit.Childs.Add(childWrap); // TODO shouldn't this be IndiWrap? _childsIn.Add(childId, familyUnit); } else { // TODO now duplicate in Pass3 //if (showErrors) // Console.WriteLine("Error: family {0} has CHIL link {1} to non-existing INDI", famId, childId); //errorsCount += 1; } } } Pass3(); foreach (var issue in _issues) { var msg = issue.Message(); if (msg.StartsWith("Error:")) // TODO unit testing errorsCount ++; if (showErrors) Console.WriteLine(msg); } // verify if INDI.FAMC have matching FAM.CHIL if (checkCHIL) { _CHILErrorsCount = 0; foreach (var indi in _indiHash.Values) { foreach (var link in indi.Indi.Links) { if (link.Tag == "FAMC") { bool found = indi.ChildIn.Any(familyUnit => link.Xref == familyUnit.FamRec.Ident); if (!found) { if (showErrors) Console.WriteLine("Error: INDI {0} with FAMC link to {1} and no matching CHIL", indi.Indi.Ident, link.Xref); _CHILErrorsCount += 1; } } if (link.Tag == "FAMS") // TODO inaccurate to check INDI.FAMS inside "child check" { bool found = indi.SpouseIn.Any(familyUnit => link.Xref == familyUnit.FamRec.Ident); if (!found) { if (showErrors) Console.WriteLine("Error: INDI {0} has FAMS link {1} to non-existing family", indi.Indi.Ident, link.Xref); errorsCount += 1; // NOTE: not CHIL error! } } } } // TODO are FAMC links to non-existing FAM being skipped? } } } }
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using Fluent.Extensions; using Fluent.Helpers; using Fluent.Internal.KnownBoxes; using WindowChrome = ControlzEx.Windows.Shell.WindowChrome; /// <summary> /// Represents title bar /// </summary> [StyleTypedProperty(Property = nameof(ItemContainerStyle), StyleTargetType = typeof(RibbonContextualTabGroup))] [TemplatePart(Name = "PART_QuickAccessToolbarHolder", Type = typeof(FrameworkElement))] [TemplatePart(Name = "PART_HeaderHolder", Type = typeof(FrameworkElement))] [TemplatePart(Name = "PART_ItemsContainer", Type = typeof(Panel))] public class RibbonTitleBar : HeaderedItemsControl { #region Fields // Quick access toolbar holder private FrameworkElement quickAccessToolbarHolder; // Header holder private FrameworkElement headerHolder; // Items container private Panel itemsContainer; // Quick access toolbar rect private Rect quickAccessToolbarRect; // Header rect private Rect headerRect; // Items rect private Rect itemsRect; #endregion #region Properties /// <summary> /// Gets or sets quick access toolbar /// </summary> public FrameworkElement QuickAccessToolBar { get { return (FrameworkElement)this.GetValue(QuickAccessToolBarProperty); } set { this.SetValue(QuickAccessToolBarProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for QuickAccessToolBar. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty QuickAccessToolBarProperty = DependencyProperty.Register(nameof(QuickAccessToolBar), typeof(FrameworkElement), typeof(RibbonTitleBar), new PropertyMetadata(OnQuickAccessToolbarChanged)); // Handles QuickAccessToolBar property chages private static void OnQuickAccessToolbarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var titleBar = (RibbonTitleBar)d; titleBar.ForceMeasureAndArrange(); } /// <summary> /// Gets or sets header alignment /// </summary> public HorizontalAlignment HeaderAlignment { get { return (HorizontalAlignment)this.GetValue(HeaderAlignmentProperty); } set { this.SetValue(HeaderAlignmentProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for HeaderAlignment. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty HeaderAlignmentProperty = DependencyProperty.Register(nameof(HeaderAlignment), typeof(HorizontalAlignment), typeof(RibbonTitleBar), new PropertyMetadata(HorizontalAlignment.Center)); /// <summary> /// Defines whether title bar is collapsed /// </summary> public bool IsCollapsed { get { return (bool)this.GetValue(IsCollapsedProperty); } set { this.SetValue(IsCollapsedProperty, value); } } /// <summary> /// DependencyProperty for <see cref="IsCollapsed"/> /// </summary> public static readonly DependencyProperty IsCollapsedProperty = DependencyProperty.Register(nameof(IsCollapsed), typeof(bool), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); private bool isAtLeastOneRequiredControlPresent; /// <summary> /// Using a DependencyProperty as the backing store for HideContextTabs. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty HideContextTabsProperty = DependencyProperty.Register(nameof(HideContextTabs), typeof(bool), typeof(RibbonTitleBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); /// <summary> /// Gets or sets whether context tabs are hidden. /// </summary> public bool HideContextTabs { get { return (bool)this.GetValue(HideContextTabsProperty); } set { this.SetValue(HideContextTabsProperty, value); } } #endregion #region Initialize /// <summary> /// Static constructor /// </summary> static RibbonTitleBar() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RibbonTitleBar), new FrameworkPropertyMetadata(typeof(RibbonTitleBar))); HeaderProperty.OverrideMetadata(typeof(RibbonTitleBar), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); } /// <summary> /// Creates a new instance. /// </summary> public RibbonTitleBar() { WindowChrome.SetIsHitTestVisibleInChrome(this, true); } #endregion #region Overrides /// <inheritdoc /> protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters) { var baseResult = base.HitTestCore(hitTestParameters); if (baseResult == null) { return new PointHitTestResult(this, hitTestParameters.HitPoint); } return baseResult; } /// <inheritdoc /> protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) { base.OnMouseRightButtonUp(e); if (e.Handled || this.IsMouseDirectlyOver == false) { return; } WindowSteeringHelper.ShowSystemMenu(this, e); } /// <inheritdoc /> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); if (e.Handled) { return; } // Contextual groups shall handle mouse events if (e.Source is RibbonContextualGroupsContainer || e.Source is RibbonContextualTabGroup) { return; } WindowSteeringHelper.HandleMouseLeftButtonDown(e, true, true); } /// <inheritdoc /> protected override DependencyObject GetContainerForItemOverride() { return new RibbonContextualTabGroup(); } /// <inheritdoc /> protected override bool IsItemItsOwnContainerOverride(object item) { return item is RibbonContextualTabGroup; } /// <inheritdoc /> public override void OnApplyTemplate() { base.OnApplyTemplate(); this.quickAccessToolbarHolder = this.GetTemplateChild("PART_QuickAccessToolbarHolder") as FrameworkElement; this.headerHolder = this.GetTemplateChild("PART_HeaderHolder") as FrameworkElement; this.itemsContainer = this.GetTemplateChild("PART_ItemsContainer") as Panel; this.isAtLeastOneRequiredControlPresent = this.quickAccessToolbarHolder != null || this.headerHolder != null || this.itemsContainer != null; if (this.quickAccessToolbarHolder != null) { WindowChrome.SetIsHitTestVisibleInChrome(this.quickAccessToolbarHolder, true); } } /// <inheritdoc /> protected override Size MeasureOverride(Size constraint) { if (this.isAtLeastOneRequiredControlPresent == false) { return base.MeasureOverride(constraint); } var resultSize = constraint; if (double.IsPositiveInfinity(resultSize.Width) || double.IsPositiveInfinity(resultSize.Height)) { resultSize = base.MeasureOverride(resultSize); } this.Update(resultSize); this.itemsContainer.Measure(this.itemsRect.Size); this.headerHolder.Measure(this.headerRect.Size); this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); var maxHeight = Math.Max(Math.Max(this.itemsRect.Height, this.headerRect.Height), this.quickAccessToolbarRect.Height); var width = this.itemsRect.Width + this.headerRect.Width + this.quickAccessToolbarRect.Width; return new Size(width, maxHeight); } /// <inheritdoc /> protected override Size ArrangeOverride(Size arrangeBounds) { if (this.isAtLeastOneRequiredControlPresent == false) { return base.ArrangeOverride(arrangeBounds); } this.itemsContainer.Arrange(this.itemsRect); this.headerHolder.Arrange(this.headerRect); this.quickAccessToolbarHolder.Arrange(this.quickAccessToolbarRect); this.EnsureCorrectLayoutAfterArrange(); return arrangeBounds; } #endregion #region Private methods /// <summary> /// Sometimes the relative position only changes after the arrange phase. /// To compensate such sitiations we issue a second layout pass by invalidating our measure. /// This situation can occur if, for example, the icon of a ribbon window has it's visibility changed. /// </summary> private void EnsureCorrectLayoutAfterArrange() { var currentRelativePosition = this.GetCurrentRelativePosition(); this.RunInDispatcherAsync(() => this.CheckPosition(currentRelativePosition, this.GetCurrentRelativePosition())); } private void CheckPosition(Point previousRelativePosition, Point currentRelativePositon) { if (previousRelativePosition != currentRelativePositon) { this.InvalidateMeasure(); } } private Point GetCurrentRelativePosition() { var parentUIElement = this.Parent as UIElement; if (parentUIElement == null) { return default(Point); } return this.TranslatePoint(default(Point), parentUIElement); } // Update items size and positions private void Update(Size constraint) { var visibleGroups = this.Items.OfType<RibbonContextualTabGroup>() .Where(group => group.InnerVisibility == Visibility.Visible && group.Items.Count > 0) .ToList(); var infinity = new Size(double.PositiveInfinity, double.PositiveInfinity); var canRibbonTabControlScroll = false; // Defensively try to find out if the RibbonTabControl can scroll if (visibleGroups.Count > 0) { var firstVisibleItem = visibleGroups.First().FirstVisibleItem; if (firstVisibleItem?.Parent != null) { canRibbonTabControlScroll = ((RibbonTabControl)firstVisibleItem.Parent).CanScroll; } } if (this.IsCollapsed) { // Collapse QuickAccessToolbar this.quickAccessToolbarRect = new Rect(0, 0, 0, 0); // Collapse itemRect this.itemsRect = new Rect(0, 0, 0, 0); this.headerHolder.Measure(new Size(constraint.Width, constraint.Height)); this.headerRect = new Rect(0, 0, this.headerHolder.DesiredSize.Width, constraint.Height); } else if (visibleGroups.Count == 0 || canRibbonTabControlScroll) { // Collapse itemRect this.itemsRect = new Rect(0, 0, 0, 0); // Set quick launch toolbar and header position and size this.quickAccessToolbarHolder.Measure(infinity); if (constraint.Width <= this.quickAccessToolbarHolder.DesiredSize.Width + 50) { this.quickAccessToolbarRect = new Rect(0, 0, Math.Max(0, constraint.Width - 50), this.quickAccessToolbarHolder.DesiredSize.Height); this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); } if (constraint.Width > this.quickAccessToolbarHolder.DesiredSize.Width + 50) { this.quickAccessToolbarRect = new Rect(0, 0, this.quickAccessToolbarHolder.DesiredSize.Width, this.quickAccessToolbarHolder.DesiredSize.Height); this.headerHolder.Measure(infinity); var allTextWidth = constraint.Width - this.quickAccessToolbarHolder.DesiredSize.Width; if (this.HeaderAlignment == HorizontalAlignment.Left) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width, 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else if (this.HeaderAlignment == HorizontalAlignment.Center) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, (allTextWidth / 2) - (this.headerHolder.DesiredSize.Width / 2)), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else if (this.HeaderAlignment == HorizontalAlignment.Right) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth - this.headerHolder.DesiredSize.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else if (this.HeaderAlignment == HorizontalAlignment.Stretch) { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width, 0, allTextWidth, constraint.Height); } } else { this.headerRect = new Rect(Math.Max(0, constraint.Width - 50), 0, 50, constraint.Height); } } else { var pointZero = default(Point); // get initial StartX value var startX = visibleGroups.First().FirstVisibleItem.TranslatePoint(pointZero, this).X; var endX = 0D; //Get minimum x point (workaround) foreach (var group in visibleGroups) { var currentStartX = group.FirstVisibleItem.TranslatePoint(pointZero, this).X; if (currentStartX < startX) { startX = currentStartX; } var lastItem = group.LastVisibleItem; var currentEndX = lastItem.TranslatePoint(new Point(lastItem.DesiredSize.Width, 0), this).X; if (currentEndX > endX) { endX = currentEndX; } } // Ensure that startX and endX are never negative startX = Math.Max(0, startX); endX = Math.Max(0, endX); // Ensure that startX respect min width of QuickAccessToolBar startX = Math.Max(startX, this.QuickAccessToolBar?.MinWidth ?? 0); // Set contextual groups position and size this.itemsContainer.Measure(infinity); var itemsRectWidth = Math.Min(this.itemsContainer.DesiredSize.Width, Math.Max(0, Math.Min(endX, constraint.Width) - startX)); this.itemsRect = new Rect(startX, 0, itemsRectWidth, constraint.Height); // Set quick launch toolbar position and size this.quickAccessToolbarHolder.Measure(infinity); var quickAccessToolbarWidth = this.quickAccessToolbarHolder.DesiredSize.Width; this.quickAccessToolbarRect = new Rect(0, 0, Math.Min(quickAccessToolbarWidth, startX), this.quickAccessToolbarHolder.DesiredSize.Height); if (quickAccessToolbarWidth > startX) { this.quickAccessToolbarHolder.Measure(this.quickAccessToolbarRect.Size); this.quickAccessToolbarRect = new Rect(0, 0, this.quickAccessToolbarHolder.DesiredSize.Width, this.quickAccessToolbarHolder.DesiredSize.Height); quickAccessToolbarWidth = this.quickAccessToolbarHolder.DesiredSize.Width; } // Set header this.headerHolder.Measure(infinity); switch (this.HeaderAlignment) { case HorizontalAlignment.Left: { if (startX - quickAccessToolbarWidth > 150) { var allTextWidth = startX - quickAccessToolbarWidth; this.headerRect = new Rect(this.quickAccessToolbarRect.Width, 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else { var allTextWidth = Math.Max(0, constraint.Width - endX); this.headerRect = new Rect(Math.Min(endX, constraint.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } } break; case HorizontalAlignment.Center: { var allTextWidthRight = Math.Max(0, constraint.Width - endX); var allTextWidthLeft = Math.Max(0, startX - quickAccessToolbarWidth); var fitsRightButNotLeft = allTextWidthRight >= this.headerHolder.DesiredSize.Width && allTextWidthLeft < this.headerHolder.DesiredSize.Width; if (((startX - quickAccessToolbarWidth < 150 || fitsRightButNotLeft) && (startX - quickAccessToolbarWidth > 0) && (startX - quickAccessToolbarWidth < constraint.Width - endX)) || (endX < constraint.Width / 2)) { this.headerRect = new Rect(Math.Min(Math.Max(endX, (constraint.Width / 2) - (this.headerHolder.DesiredSize.Width / 2)), constraint.Width), 0, Math.Min(allTextWidthRight, this.headerHolder.DesiredSize.Width), constraint.Height); } else { this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, (allTextWidthLeft / 2) - (this.headerHolder.DesiredSize.Width / 2)), 0, Math.Min(allTextWidthLeft, this.headerHolder.DesiredSize.Width), constraint.Height); } } break; case HorizontalAlignment.Right: { if (startX - quickAccessToolbarWidth > 150) { var allTextWidth = Math.Max(0, startX - quickAccessToolbarWidth); this.headerRect = new Rect(this.quickAccessToolbarHolder.DesiredSize.Width + Math.Max(0, allTextWidth - this.headerHolder.DesiredSize.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } else { var allTextWidth = Math.Max(0, constraint.Width - endX); this.headerRect = new Rect(Math.Min(Math.Max(endX, constraint.Width - this.headerHolder.DesiredSize.Width), constraint.Width), 0, Math.Min(allTextWidth, this.headerHolder.DesiredSize.Width), constraint.Height); } } break; case HorizontalAlignment.Stretch: { if (startX - quickAccessToolbarWidth > 150) { var allTextWidth = startX - quickAccessToolbarWidth; this.headerRect = new Rect(this.quickAccessToolbarRect.Width, 0, allTextWidth, constraint.Height); } else { var allTextWidth = Math.Max(0, constraint.Width - endX); this.headerRect = new Rect(Math.Min(endX, constraint.Width), 0, allTextWidth, constraint.Height); } } break; } } this.headerRect.Width = this.headerRect.Width + 2; } #endregion } }
// $Id$ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using Org.Apache.Etch.Bindings.Csharp.Support; using Org.Apache.Etch.Bindings.Csharp.Util; using NUnit.Framework; using org.apache.etch.tests; using org.apache.etch.tests.types.Inheritance; namespace etch.tests { [TestFixture] public class TestInheritance { private static RemoteInheritanceServer server; private static ServerFactory listener; [TestFixtureSetUp] public void Setup() { String uri = "tcp://localhost:4003"; MainInheritanceListener implFactory = new MainInheritanceListener(); listener = InheritanceHelper.NewListener(uri, null, implFactory); listener.TransportControl(TransportConsts.START_AND_WAIT_UP, 4000); MainInheritanceClient client = new MainInheritanceClient(); server = InheritanceHelper.NewServer(uri, null, client); // server._TransportControl(Etch.Transport.TransportConsts.START_AND_WAIT_UP, 4000); server._StartAndWaitUp(4000); } [Test] public void types() { Assert.AreEqual(true,typeof(S1).IsAssignableFrom(typeof(S1))); Assert.AreEqual(true,typeof(S1).IsAssignableFrom(typeof(S2))); Assert.AreEqual(true,typeof(S1).IsAssignableFrom(typeof(S3))); Assert.AreEqual(false,typeof(S2).IsAssignableFrom(typeof(S1))); Assert.AreEqual(true,typeof(S2).IsAssignableFrom(typeof(S2))); Assert.AreEqual(true,typeof(S2).IsAssignableFrom(typeof(S3))); Assert.AreEqual(false,typeof(S3).IsAssignableFrom(typeof(S1))); Assert.AreEqual(false,typeof(S3).IsAssignableFrom(typeof(S2))); Assert.AreEqual(true,typeof(S3).IsAssignableFrom(typeof(S3))); Assert.AreEqual(true,typeof(E1).IsAssignableFrom(typeof(E1))); Assert.AreEqual(true,typeof(E1).IsAssignableFrom(typeof(E2))); Assert.AreEqual(true,typeof(E1).IsAssignableFrom(typeof(E3))); Assert.AreEqual(true,typeof(Exception).IsAssignableFrom(typeof(E1))); Assert.AreEqual(true,typeof(Exception).IsAssignableFrom(typeof(E2))); Assert.AreEqual(true,typeof(Exception).IsAssignableFrom(typeof(E3))); Assert.AreEqual(false,typeof(E2).IsAssignableFrom(typeof(E1))); Assert.AreEqual(true,typeof(E2).IsAssignableFrom(typeof(E2))); Assert.AreEqual(true,typeof(E2).IsAssignableFrom(typeof(E3))); Assert.AreEqual(false,typeof(E3).IsAssignableFrom(typeof(E1))); Assert.AreEqual(false,typeof(E3).IsAssignableFrom(typeof(E2))); Assert.AreEqual(true,typeof(E3).IsAssignableFrom(typeof(E3))); } [Test] public void Construct_S1() { check_s1( new S1(), null, null ); check_s1( new S1( null, null ), null, null ); check_s1( new S1( 1, 2 ), 1, 2 ); } [Test] public void construct_s2() { check_s2( new S2(), null, null, null, null ); check_s2( new S2( null, null, null, null ), null, null, null, null ); check_s2( new S2( 1, 2, 3, 4 ), 1, 2, 3, 4 ); } [Test] public void construct_s3() { check_s3( new S3(), null, null, null, null, null, null ); check_s3( new S3( null, null, null, null, null, null ), null, null, null, null, null, null ); check_s3( new S3( 1, 2, 3, 4, 5, 6 ), 1, 2, 3, 4, 5, 6 ); } [Test] public void construct_e1() { check_e1( new E1(), null, null ); check_e1( new E1( null, null ), null, null ); check_e1( new E1( 1, 2 ), 1, 2 ); } [Test] public void construct_e2() { check_e2( new E2(), null, null, null, null ); check_e2( new E2( null, null, null, null ), null, null, null, null ); check_e2( new E2( 1, 2, 3, 4 ), 1, 2, 3, 4 ); } [Test] public void construct_e3() { check_e3( new E3(), null, null, null, null, null, null ); check_e3( new E3( null, null, null, null, null, null ), null, null, null, null, null, null ); check_e3( new E3( 1, 2, 3, 4, 5, 6 ), 1, 2, 3, 4, 5, 6 ); } [Test] public void assign_s1() { S1 v = new S1( 1, 2 ); check_s1( v, 1, 2 ); v.a = null; check_s1( v, null, 2 ); v.a = 3; check_s1( v, 3, 2 ); v.SetA( null ); check_s1( v, null, 2 ); v.SetA( 4 ); check_s1( v, 4, 2 ); v.b = null; check_s1( v, 4, null ); v.b = 5; check_s1( v, 4, 5 ); v.SetB( null ); check_s1( v, 4, null ); v.SetB( 6 ); check_s1( v, 4, 6 ); } [Test] public void assign_s2() { S2 v = new S2( 1, 2, 3, 4 ); check_s2( v, 1, 2, 3, 4 ); v.a = null; check_s2( v, null, 2, 3, 4 ); v.a = 5; check_s2( v, 5, 2, 3, 4 ); v.SetA( null ); check_s2( v, null, 2, 3, 4 ); v.SetA( 6 ); check_s2( v, 6, 2, 3, 4 ); v.b = null; check_s2( v, 6, null, 3, 4 ); v.b = 7; check_s2( v, 6, 7, 3, 4 ); v.SetB( null ); check_s2( v, 6, null, 3, 4 ); v.SetB( 8 ); check_s2( v, 6, 8, 3, 4 ); v.c = null; check_s2( v, 6, 8, null, 4 ); v.c = 9; check_s2( v, 6, 8, 9, 4 ); v.SetC( null ); check_s2( v, 6, 8, null, 4 ); v.SetC( 10 ); check_s2( v, 6, 8, 10, 4 ); v.d = null; check_s2( v, 6, 8, 10, null ); v.d = 11; check_s2( v, 6, 8, 10, 11 ); v.SetD( null ); check_s2( v, 6, 8, 10, null ); v.SetD( 12 ); check_s2( v, 6, 8, 10, 12 ); } [Test] public void assign_s3() { S3 v = new S3( 1, 2, 3, 4, 5, 6 ); check_s3( v, 1, 2, 3, 4, 5, 6 ); v.a = null; check_s3( v, null, 2, 3, 4, 5, 6 ); v.a = 7; check_s3( v, 7, 2, 3, 4, 5, 6 ); v.SetA( null ); check_s3( v, null, 2, 3, 4, 5, 6 ); v.SetA( 8 ); check_s3( v, 8, 2, 3, 4, 5, 6 ); v.b = null; check_s3( v, 8, null, 3, 4, 5, 6 ); v.b = 9; check_s3( v, 8, 9, 3, 4, 5, 6 ); v.SetB( null ); check_s3( v, 8, null, 3, 4, 5, 6 ); v.SetB( 10 ); check_s3( v, 8, 10, 3, 4, 5, 6 ); v.c = null; check_s3( v, 8, 10, null, 4, 5, 6 ); v.c = 11; check_s3( v, 8, 10, 11, 4, 5, 6 ); v.SetC( null ); check_s3( v, 8, 10, null, 4, 5, 6 ); v.SetC( 12 ); check_s3( v, 8, 10, 12, 4, 5, 6 ); v.d = null; check_s3( v, 8, 10, 12, null, 5, 6 ); v.d = 13; check_s3( v, 8, 10, 12, 13, 5, 6 ); v.SetD( null ); check_s3( v, 8, 10, 12, null, 5, 6 ); v.SetD( 14 ); check_s3( v, 8, 10, 12, 14, 5, 6 ); v.e = null; check_s3( v, 8, 10, 12, 14, null, 6 ); v.e = 15; check_s3( v, 8, 10, 12, 14, 15, 6 ); v.SetE( null ); check_s3( v, 8, 10, 12, 14, null, 6 ); v.SetE( 16 ); check_s3( v, 8, 10, 12, 14, 16, 6 ); v.f = null; check_s3( v, 8, 10, 12, 14, 16, null ); v.f = 17; check_s3( v, 8, 10, 12, 14, 16, 17 ); v.SetF( null ); check_s3( v, 8, 10, 12, 14, 16, null ); v.SetF( 18 ); check_s3( v, 8, 10, 12, 14, 16, 18 ); } [Test] public void tostring() { Assert.AreEqual( "S1(a=1; b=2)", new S1( 1, 2 ).ToString() ); Assert.AreEqual( "S2(S1(a=1; b=2); c=3; d=4)", new S2( 1, 2, 3, 4 ).ToString() ); Assert.AreEqual( "S3(S2(S1(a=1; b=2); c=3; d=4); e=5; f=6)", new S3( 1, 2, 3, 4, 5, 6 ).ToString() ); Assert.AreEqual( "a=1; b=2", new E1( 1, 2 ).GetMessage() ); Assert.AreEqual( "a=1; b=2; c=3; d=4", new E2( 1, 2, 3, 4 ).GetMessage() ); Assert.AreEqual( "a=1; b=2; c=3; d=4; e=5; f=6", new E3( 1, 2, 3, 4, 5, 6 ).GetMessage() ); } private void check_s1( S1 v, int? a, int? b ) { Assert.AreEqual( a, v.a ); Assert.AreEqual( a, v.GetA() ); Assert.AreEqual( b, v.b ); Assert.AreEqual( b, v.GetB() ); } private void check_s2( S2 v, int? a, int? b, int? c, int? d ) { check_s1( v, a, b ); Assert.AreEqual( c, v.c ); Assert.AreEqual( c, v.GetC() ); Assert.AreEqual( d, v.d ); Assert.AreEqual( d, v.GetD() ); } private void check_s3( S3 v, int? a, int? b, int? c, int? d, int? e, int? f ) { check_s2( v, a, b, c, d ); Assert.AreEqual( e, v.e ); Assert.AreEqual( e, v.GetE() ); Assert.AreEqual( f, v.f ); Assert.AreEqual( f, v.GetF() ); } private void check_e1( E1 v, int? a, int? b ) { Assert.AreEqual( a, v.a ); Assert.AreEqual( a, v.GetA() ); Assert.AreEqual( b, v.b ); Assert.AreEqual( b, v.GetB() ); } private void check_e2( E2 v, int? a, int? b, int? c, int? d ) { check_e1( v, a, b ); Assert.AreEqual( c, v.c ); Assert.AreEqual( c, v.GetC() ); Assert.AreEqual( d, v.d ); Assert.AreEqual( d, v.GetD() ); } private void check_e3( E3 v, int? a, int? b, int? c, int? d, int? e, int? f ) { check_e2( v, a, b, c, d ); Assert.AreEqual( e, v.e ); Assert.AreEqual( e, v.GetE() ); Assert.AreEqual( f, v.f ); Assert.AreEqual( f, v.GetF() ); } [Test] public void test_s1() { do_s1( new S1( 1, 2 ), new S1Compare() ); do_s1( new S1( 9, 8 ), new S1Compare() ); } [Test] public void test_s2() { do_s2( new S2( 1, 2, 3, 4 ), new S2Compare() ); do_s2( new S2( 9, 8, 7, 6 ), new S2Compare() ); } [Test] public void test_s3() { do_s3( new S3( 1, 2, 3, 4, 5, 6 ), new S3Compare() ); do_s3( new S3( 9, 8, 7, 6, 5, 4 ), new S3Compare() ); } interface CompareObj<T> { void compare( T a, T b ); } /** * Class to compare one S2 to another. */ class S2Compare : CompareObj<object> { public void compare( object a, object b ) { Assert.AreEqual(typeof(S2), a.GetType()); Assert.AreEqual( typeof(S2), b.GetType() ); S2 a1 = (S2)a; S2 b1 = (S2)b; Assert.AreEqual( a1.a, b1.a ); Assert.AreEqual( a1.b, b1.b ); Assert.AreEqual( a1.c, b1.c ); Assert.AreEqual( a1.d, b1.d ); } } /** * Class to compare one S3 to another. */ class S3Compare : CompareObj<object> { public void compare( object a, object b ) { Assert.AreEqual( typeof(S3), a.GetType() ); Assert.AreEqual( typeof(S3), b.GetType() ); S3 a1 = (S3)a; S3 b1 = (S3)b; Assert.AreEqual( a1.a, b1.a ); Assert.AreEqual( a1.b, b1.b ); Assert.AreEqual( a1.c, b1.c ); Assert.AreEqual( a1.d, b1.d ); Assert.AreEqual( a1.e, b1.e ); Assert.AreEqual( a1.f, b1.f ); } } class AS2Compare : CompareObj<object[]> { public AS2Compare( CompareObj<object> cmp ) { this.cmp = cmp; } private CompareObj<object> cmp; public void compare( object[] a, object[] b ) { S2[] a1 = (S2[])a; S2[] b1 = (S2[])b; Assert.AreEqual( a1.Length, b1.Length ); for (int i = 0; i < a.Length; i++) cmp.compare( a1[i], b1[i] ); } } class AS3Compare : CompareObj<object[]> { public AS3Compare( CompareObj<object> cmp ) { this.cmp = cmp; } private CompareObj<object> cmp; public void compare( object[] a, object[] b ) { Assert.AreEqual( a.Length, b.Length ); for (int i = 0; i < a.Length; i++) cmp.compare( a[i], b[i] ); } } ///////////// // HELPERS // ///////////// private void do_obj(object v, CompareObj<object> cmp) { // test an object both by itself and as an array. cmp.compare( v,server.f1( v ) ); object[] a = { v }; CompareObj<object[]> acmp = new AObjectCompare( cmp ); acmp.compare( a, server.f5( a ) ); } private void do_s1( S1 v, CompareObj<object> cmp ) { // test an S1 both by itself and as an array. // also test each of those as an object. cmp.compare( v, server.f2( v ) ); do_obj( v, cmp ); S1[] a = { v }; CompareObj<object[]> acmp = new AS1Compare(cmp); acmp.compare( a, server.f6( a ) ); // do_obj( a, acmp ); } /** * Class to compare one S1 to another. */ class S1Compare : CompareObj<object> { public void compare(object a, object b) { Assert.AreEqual(typeof(S1), a.GetType()); Assert.AreEqual(typeof(S1), b.GetType()); S1 a1 = (S1)a; S1 b1 = (S1)b; Assert.AreEqual(a1.a, b1.a); Assert.AreEqual(a1.b, b1.b); } } class AObjectCompare : CompareObj<Object[]> { public AObjectCompare(CompareObj<Object> cmp) { this.cmp = cmp; } private CompareObj<Object> cmp; public void compare(Object[] a, Object[] b) { Assert.AreEqual(a.Length, b.Length); for (int i = 0; i < a.Length; i++) cmp.compare(a[i], b[i]); } } class AS1Compare : CompareObj<object[]> { public AS1Compare(CompareObj<object> cmp) { this.cmp = cmp; } private CompareObj<object> cmp; public void compare(object[] a, object[] b) { S1[] a1 = (S1[])a; S1[] b1 = (S1[])b; Assert.AreEqual(a1.Length, b1.Length); for (int i = 0; i < a1.Length; i++) cmp.compare(a1[i], b1[i]); } } private void do_s2( S2 v, CompareObj<object> cmp ) { // test an S2 both by itself and as an array. // also test the S2 as an S1, and the S2 array // as an object. cmp.compare( v, server.f3( v ) ); do_s1( v, cmp ); S2[] a = { v }; CompareObj<object[]> acmp = new AS2Compare( cmp ); acmp.compare( a, server.f7( a ) ); // do_obj( a, acmp ); } private void do_s3( S3 v, CompareObj<object> cmp ) { // test an S3 both by itself and as an array. // also test the S3 as an S2, and the S3 array // as an object. cmp.compare( v, server.f4( v ) ); do_s2( v, cmp ); S3[] a = { v }; CompareObj<object[]> acmp = new AS3Compare( cmp ); acmp.compare( a, server.f8( a ) ); // do_obj( a, acmp ); } [TestFixtureTearDown] public void Dispose() { if (server != null) server._StopAndWaitDown( 4000 ); if (listener != null) listener.TransportControl(TransportConsts.STOP_AND_WAIT_DOWN, 4000); } } }
using System; using System.Collections.Generic; using Zenject; using NUnit.Framework; using System.Linq; using ModestTree; using Assert=ModestTree.Assert; namespace Zenject.Tests { [TestFixture] public class TestSingleton : TestWithContainer { private interface IFoo { int ReturnValue(); } private class Foo : IFoo, ITickable, IInitializable { public int ReturnValue() { return 5; } public void Initialize() { } public void Tick() { } } [Test] public void TestClassRegistration() { Container.Bind<Foo>().ToSingle(); Assert.That(Container.ValidateResolve<Foo>().IsEmpty()); Assert.That(Container.Resolve<Foo>().ReturnValue() == 5); } [Test] public void TestSingletonOneInstance() { Container.Bind<Foo>().ToSingle(); Assert.That(Container.ValidateResolve<Foo>().IsEmpty()); var test1 = Container.Resolve<Foo>(); Assert.That(Container.ValidateResolve<Foo>().IsEmpty()); var test2 = Container.Resolve<Foo>(); Assert.That(test1 != null && test2 != null); Assert.That(ReferenceEquals(test1, test2)); } [Test] public void TestSingletonOneInstanceUntyped() { Container.Bind(typeof(Foo)).ToSingle(); Assert.That(Container.ValidateResolve<Foo>().IsEmpty()); var test1 = Container.Resolve<Foo>(); Assert.That(Container.ValidateResolve<Foo>().IsEmpty()); var test2 = Container.Resolve<Foo>(); Assert.That(test1 != null && test2 != null); Assert.That(ReferenceEquals(test1, test2)); } [Test] public void TestInterfaceBoundToImplementationRegistration() { Container.Bind<IFoo>().ToSingle<Foo>(); Assert.That(Container.ValidateResolve<IFoo>().IsEmpty()); Assert.That(Container.Resolve<IFoo>().ReturnValue() == 5); } [Test] public void TestInterfaceBoundToImplementationRegistrationUntyped() { Container.Bind(typeof(IFoo)).ToSingle(typeof(Foo)); Assert.That(Container.ValidateResolve<IFoo>().IsEmpty()); Assert.That(Container.Resolve<IFoo>().ReturnValue() == 5); } [Test] public void TestInterfaceBoundToInstanceRegistration() { IFoo instance = new Foo(); Container.Bind<IFoo>().ToInstance(instance); Assert.That(Container.ValidateResolve<IFoo>().IsEmpty()); var builtInstance = Container.Resolve<IFoo>(); Assert.That(ReferenceEquals(builtInstance, instance)); Assert.That(builtInstance.ReturnValue() == 5); } [Test] public void TestInterfaceBoundToInstanceRegistrationUntyped() { IFoo instance = new Foo(); Container.Bind(typeof(IFoo)).ToInstance(instance); Assert.That(Container.ValidateResolve<IFoo>().IsEmpty()); var builtInstance = Container.Resolve<IFoo>(); Assert.That(ReferenceEquals(builtInstance, instance)); Assert.That(builtInstance.ReturnValue() == 5); } [Test] public void TestDuplicateBindings() { // Note: does not error out until a request for Foo is made Container.Bind<Foo>().ToSingle(); Container.Bind<Foo>().ToSingle(); } [Test] public void TestDuplicateBindingsFail() { Container.Bind<Foo>().ToSingle(); Container.Bind<Foo>().ToSingle(); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Foo>(); }); Assert.That(Container.ValidateResolve<Foo>().Any()); } [Test] public void TestDuplicateBindingsFailUntyped() { Container.Bind(typeof(Foo)).ToSingle(); Container.Bind(typeof(Foo)).ToSingle(); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Foo>(); }); Assert.That(Container.ValidateResolve<Foo>().Any()); } [Test] public void TestDuplicateInstanceBindingsFail() { var instance = new Foo(); Container.Bind<Foo>().ToInstance(instance); Container.Bind<Foo>().ToInstance(instance); Assert.That(Container.ValidateResolve<Foo>().Any()); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Foo>(); }); } [Test] public void TestDuplicateInstanceBindingsFailUntyped() { var instance = new Foo(); Container.Bind(typeof(Foo)).ToInstance(instance); Container.Bind(typeof(Foo)).ToInstance(instance); Assert.That(Container.ValidateResolve<Foo>().Any()); Assert.Throws<ZenjectResolveException>( delegate { Container.Resolve<Foo>(); }); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleWithInstance() { Container.Bind<Foo>().ToSingleInstance(new Foo()); Container.Bind<Foo>().ToSingleInstance(new Foo()); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleWithInstanceUntyped() { Container.Bind(typeof(Foo)).ToSingleInstance(new Foo()); Container.Bind(typeof(Foo)).ToSingleInstance(new Foo()); } [Test] public void TestToSingleWithInstance2() { var foo = new Foo(); Container.Bind<Foo>().ToInstance(foo); Container.Bind<IFoo>().ToSingle<Foo>(); Assert.That( !ReferenceEquals(Container.Resolve<IFoo>(), Container.Resolve<Foo>())); } [Test] public void TestToSingleWithInstance2Untyped() { var foo = new Foo(); Container.Bind(typeof(Foo)).ToInstance(foo); Container.Bind(typeof(IFoo)).ToSingle<Foo>(); Assert.That( !ReferenceEquals(Container.Resolve<IFoo>(), Container.Resolve<Foo>())); } [Test] public void TestToSingleMethod() { var foo = new Foo(); Container.Bind(typeof(Foo)).ToSingleMethod((container) => foo); Assert.That(ReferenceEquals(Container.Resolve<Foo>(), foo)); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleMethod1() { var foo = new Foo(); Container.Bind(typeof(Foo)).ToSingleMethod((container) => foo); Container.Bind(typeof(IFoo)).ToSingle<Foo>(); Assert.That(ReferenceEquals(Container.Resolve<Foo>(), foo)); Assert.That(ReferenceEquals(Container.Resolve<Foo>(), Container.Resolve<IFoo>())); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleMethod3() { Container.Bind<Foo>().ToSingle(); Container.Bind(typeof(IFoo)).ToSingleMethod((container) => new Foo()); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleMethod4() { // Cannot bind different singleton providers Container.Bind<Foo>().ToSingleMethod((container) => new Foo()); Container.Bind<Foo>().ToSingle(); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleMethod5() { Container.Bind<Foo>().ToSingleMethod((container) => new Foo()); Container.Bind<Foo>().ToSingleMethod((container) => new Foo()); } [Test] public void TestToSingleMethod6() { Func<InjectContext, Foo> method = (ctx) => new Foo(); Container.Bind<Foo>().ToSingleMethod(method); Container.Bind<Foo>().ToSingleMethod(method); var foos = Container.ResolveAll<Foo>(); Assert.IsEqual(foos[0], foos[1]); } [Test] public void TestToSingleFactory() { Container.Bind<Foo>().ToSingleFactory<FooFactory>(); Container.Bind<IFoo>().ToSingleFactory<FooFactory, Foo>(); FooFactory.WasCalled = false; var foo = Container.Resolve<Foo>(); Assert.That(FooFactory.WasCalled); FooFactory.WasCalled = false; var ifoo = Container.Resolve<IFoo>(); Assert.That(!FooFactory.WasCalled); var foo2 = Container.Resolve<Foo>(); Assert.That(!FooFactory.WasCalled); Assert.IsEqual(foo, foo2); Assert.IsEqual(ifoo, foo2); } [Test] [ExpectedException(typeof(ZenjectBindException))] public void TestToSingleFactory2() { // Cannot bind different singleton providers Container.Bind<Foo>().ToSingleFactory<FooFactory>(); Container.Bind<Foo>().ToSingle(); } class FooFactory : IFactory<Foo> { public static bool WasCalled; public Foo Create() { WasCalled = true; return new Foo(); } } } }
/* Copyright (c) 2006 Tomas Matousek and Ladislav Prosek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Diagnostics; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Reflection.Emit; using System.Collections; using PHP.Core.AST; using PHP.Core.Emit; using PHP.Core.Parsers; namespace PHP.Core.Reflection { #region DConstantDesc public sealed class DConstantDesc : DMemberDesc { /// <summary> /// Written-up by the analyzer if the value is evaluable (literals only). /// </summary> public object LiteralValue { get { Debug.Assert(!ValueIsDeferred, "This constant's literal value cannot be accessed directly. You have to read its realField in runtime after you initialize static fields."); return literalValue; } internal /* friend DConstant */ set { Debug.Assert(value is int || value is string || value == null || value is bool || value is double || value is long); this.literalValue = value; this.ValueIsDeferred = false; } } private object literalValue; public GlobalConstant GlobalConstant { get { return (GlobalConstant)Member; } } public ClassConstant ClassConstant { get { return (ClassConstant)Member; } } #region Construction /// <summary> /// Used by compiler for global constants. /// </summary> public DConstantDesc(DModule/*!*/ declaringModule, PhpMemberAttributes memberAttributes, object literalValue) : base(declaringModule.GlobalType.TypeDesc, memberAttributes | PhpMemberAttributes.Static) { Debug.Assert(declaringModule != null); this.literalValue = literalValue; } /// <summary> /// Used by compiler for class constants. /// </summary> public DConstantDesc(DTypeDesc/*!*/ declaringType, PhpMemberAttributes memberAttributes, object literalValue) : base(declaringType, memberAttributes | PhpMemberAttributes.Static) { Debug.Assert(declaringType != null); this.literalValue = literalValue; } #endregion public override string MakeFullName() { Debug.Fail("Not Supported"); return null; } public override string MakeFullGenericName() { Debug.Fail("Not Supported"); return null; } #region Run-Time Operations /// <summary> /// <c>True</c> if value of this constant is deferred to runtime; hence it must be read from corresponding static field every time. /// </summary> internal bool ValueIsDeferred { get; set; } /// <summary> /// Read value of this constant. /// </summary> /// <param name="context"></param> /// <returns></returns> public object GetValue(ScriptContext/*!*/ context) { if (ValueIsDeferred) { if (Member.GetType() == typeof(ClassConstant) && DeclaringType.GetType() == typeof(PhpTypeDesc)) { ((PhpTypeDesc)DeclaringType).EnsureThreadStaticFieldsInitialized(context); return ((ClassConstant)Member).GetValue(); } if (memberAttributes.GetType() == typeof(GlobalConstant)) { // TODO: initialize deferred global constant return ((ClassConstant)Member).GetValue(); } Debug.Fail("Uncaught constant type."); } // return this.LiteralValue; } #endregion } #endregion #region DConstant public abstract class DConstant : DMember { public sealed override bool IsDefinite { get { return IsIdentityDefinite; } } public DConstantDesc/*!*/ ConstantDesc { get { return (DConstantDesc)memberDesc; } } /// <summary> /// Whether the value of the constant is known and stored in the constant-desc. /// </summary> public abstract bool HasValue { get; } /// <summary> /// Constant value. Valid only if <see cref="HasValue"/> is <B>true</B>. /// </summary> public object Value { get { return ConstantDesc.LiteralValue; } } #region Construction /// <summary> /// Used by known constant subclasses. /// </summary> public DConstant(DConstantDesc/*!*/ constantDesc) : base(constantDesc) { Debug.Assert(constantDesc != null); } /// <summary> /// Used by unknown constants subclasses. /// </summary> public DConstant(string/*!*/ fullName) : base(null, fullName) { Debug.Assert(IsUnknown); } #endregion internal virtual void ReportCircularDefinition(ErrorSink/*!*/ errors) { Debug.Fail(null); } internal abstract PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType, bool runtimeVisibilityCheck, string fallbackName); } #endregion #region UnknownClassConstant, UnknownGlobalConstant public sealed class UnknownClassConstant : DConstant { public override bool IsUnknown { get { return true; } } public override bool IsIdentityDefinite { get { return false; } } public override bool HasValue { get { return false; } } public override DType/*!*/ DeclaringType { get { return declaringType; } } private readonly DType/*!*/ declaringType; public UnknownClassConstant(DType/*!*/ declaringType, string/*!*/ fullName) : base(fullName) { Debug.Assert(fullName != null); this.declaringType = declaringType; } public override string GetFullName() { return FullName; } internal override PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType, bool runtimeVisibilityCheck, string fallbackName) { Debug.Assert(fallbackName == null); codeGenerator.EmitGetConstantValueOperator(declaringType, this.FullName, null); return PhpTypeCode.Object; } } public sealed class UnknownGlobalConstant : DConstant { public override bool IsUnknown { get { return true; } } public override bool IsIdentityDefinite { get { return false; } } public override bool HasValue { get { return false; } } public UnknownGlobalConstant(string/*!*/ fullName) : base(fullName) { Debug.Assert(fullName != null); } public override string GetFullName() { return FullName; } internal override PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType, bool runtimeVisibilityCheck, string fallbackName) { codeGenerator.EmitGetConstantValueOperator(null, this.FullName, fallbackName); return PhpTypeCode.Object; } } #endregion #region KnownConstant public abstract class KnownConstant : DConstant, IPhpMember { public sealed override bool IsUnknown { get { return false; } } /// <summary> /// Whether the value of the constant is known and stored in the constant-desc. /// </summary> public sealed override bool HasValue { get { return node == null && !ConstantDesc.ValueIsDeferred; } } /// <summary> /// Real storage of the constant (a field). /// </summary> public FieldInfo RealField { get { return realField; } } public FieldBuilder RealFieldBuilder { get { return (FieldBuilder)realField; } } protected FieldInfo realField; private Func<object>/*!*/GetterStub { get { if (getterStub == null) GenerateGetterStub(); return getterStub; } } private Func<object>/*!*/getterStub = null; /// <summary> /// AST node representing the constant. Used for evaluation only. /// </summary> internal AST.ConstantDecl Node { get { return node; } } private AST.ConstantDecl node; public abstract Text.Span Span { get; } public abstract SourceUnit SourceUnit { get; } internal ExportAttribute ExportInfo { get { return exportInfo; } set { exportInfo = value; } } internal /* protected */ ExportAttribute exportInfo; /// <summary> /// Gets whether the constant is exported. /// </summary> internal abstract bool IsExported { get; } public KnownConstant(DConstantDesc/*!*/ constantDesc) : base(constantDesc) { Debug.Assert(constantDesc != null); this.node = null; } internal void SetValue(object value) { this.ConstantDesc.LiteralValue = value; this.node = null; } internal void SetNode(AST.ConstantDecl/*!*/ node) { this.ConstantDesc.LiteralValue = null; this.node = node; } private void GenerateGetterStub() { Debug.Assert(this.realField != null); Debug.Assert(this.realField.FieldType == typeof(object)); DynamicMethod stub = new DynamicMethod("<^GetterStub>", this.realField.FieldType, Type.EmptyTypes, true); ILEmitter il = new ILEmitter(stub); il.Emit(OpCodes.Ldsfld, this.realField); il.Emit(OpCodes.Ret); this.getterStub = (Func<object>)stub.CreateDelegate(typeof(Func<object>)); } #region Emission internal override PhpTypeCode EmitGet(CodeGenerator/*!*/ codeGenerator, ConstructedType constructedType, bool runtimeVisibilityCheck, string fallbackName) { ILEmitter il = codeGenerator.IL; if (HasValue) { il.LoadLiteral(Value); return PhpTypeCodeEnum.FromObject(Value); } else { Debug.Assert(realField != null); il.Emit(OpCodes.Ldsfld, DType.MakeConstructed(realField, constructedType)); return PhpTypeCodeEnum.FromType(realField.FieldType); } } #endregion #region Run-Time Operations internal object GetValue() { Debug.Assert(realField != null); return GetterStub(); } #endregion } #endregion #region GlobalConstant /// <summary> /// Pure mode global constants, namespace constants, CLR constants, library constants. /// </summary> public sealed class GlobalConstant : KnownConstant, IDeclaree { #region Statics public static readonly GlobalConstant Null; public static readonly GlobalConstant False; public static readonly GlobalConstant True; public static readonly GlobalConstant PhpIntSize; public static readonly GlobalConstant PhpIntMax; static GlobalConstant() { if (UnknownModule.RuntimeModule == null) UnknownModule.RuntimeModule = new UnknownModule(); Null = new GlobalConstant(QualifiedName.Null, Fields.PhpVariable_LiteralNull); Null.SetValue(null); False = new GlobalConstant(QualifiedName.False, Fields.PhpVariable_LiteralFalse); False.SetValue(false); True = new GlobalConstant(QualifiedName.True, Fields.PhpVariable_LiteralTrue); True.SetValue(true); PhpIntSize = new GlobalConstant(new QualifiedName(new Name("PHP_INT_SIZE")), typeof(PhpVariable).GetField("LiteralIntSize")); PhpIntSize.SetValue(PhpVariable.LiteralIntSize); PhpIntMax = new GlobalConstant(new QualifiedName(new Name("PHP_INT_MAX")), typeof(int).GetField("MaxValue")); PhpIntMax.SetValue(int.MaxValue); } #endregion #region Properties public override bool IsIdentityDefinite { get { return declaration == null || !declaration.IsConditional; } } public IPhpModuleBuilder DeclaringModuleBuilder { get { return (IPhpModuleBuilder)DeclaringModule; } } /// <summary> /// Note: the base name is case-sensitive. /// </summary> public QualifiedName QualifiedName { get { return qualifiedName; } } private readonly QualifiedName qualifiedName; public Declaration Declaration { get { return declaration; } } private Declaration declaration; public VersionInfo Version { get { return version; } set { version = value; } } private VersionInfo version; public override Text.Span Span { get { return declaration.Span; } } public override SourceUnit SourceUnit { get { return declaration.SourceUnit; } } /// <summary> /// If constant defined within &lt;script&gt; type, remember its builder to define constant field there. /// In case of pure or transient module, this is null. If this is null, the constant is declared in as CLR global. /// </summary> private TypeBuilder scriptTypeBuilder = null; /// <summary> /// Name of the extension where this global constant was defined. /// </summary> public string Extension { get { PhpLibraryModule libraryModule = DeclaringModule as PhpLibraryModule; if (libraryModule != null) return libraryModule.GetImplementedExtension(realField.DeclaringType); else return null; } } internal override bool IsExported { get { return exportInfo != null; } } #endregion #region Construction /// <summary> /// Used for constants created by run-time, but with known declaring module /// </summary> internal GlobalConstant(DModule/*!*/ declaringModule, QualifiedName qualifiedName, FieldInfo info) : base(new DConstantDesc(declaringModule, PhpMemberAttributes.None, null)) { this.realField = info; this.qualifiedName = qualifiedName; } /// <summary> /// Used for constants created by run-time. /// </summary> internal GlobalConstant(QualifiedName qualifiedName, FieldInfo info) : base(new DConstantDesc(UnknownModule.RuntimeModule, PhpMemberAttributes.None, null)) { this.realField = info; this.qualifiedName = qualifiedName; } /// <summary> /// Used by compiler. /// </summary> public GlobalConstant(QualifiedName qualifiedName, PhpMemberAttributes memberAttributes, CompilationSourceUnit/*!*/ sourceUnit, bool isConditional, Scope scope, Text.Span position) : base(new DConstantDesc(sourceUnit.CompilationUnit.Module, memberAttributes, null)) { Debug.Assert(sourceUnit != null); this.qualifiedName = qualifiedName; this.declaration = new Declaration(sourceUnit, this, false, isConditional, scope, position); //this.origin = origin; if (sourceUnit.CompilationUnit is ScriptCompilationUnit) // J: place the constant into <script> type so it can be reflected properly scriptTypeBuilder = ((ScriptCompilationUnit)sourceUnit.CompilationUnit).ScriptBuilder.ScriptTypeBuilder; } #endregion public override string GetFullName() { return qualifiedName.ToString(); } internal override void ReportCircularDefinition(ErrorSink/*!*/ errors) { errors.Add(Errors.CircularConstantDefinitionGlobal, SourceUnit, Span, FullName); } public void ReportRedeclaration(ErrorSink/*!*/ errors) { errors.Add(FatalErrors.ConstantRedeclared, SourceUnit, Span, FullName); } internal void DefineBuilders() { if (realField == null) { // resolve attributes FieldAttributes field_attrs = Enums.ToFieldAttributes(memberDesc.MemberAttributes); field_attrs |= FieldAttributes.Literal; Debug.Assert((field_attrs & FieldAttributes.Static) != 0); // convert name to CLR notation: var clrName = qualifiedName.ToClrNotation(0, 0); // type Type type = Types.Object[0]; if (this.HasValue && this.Value != null) type = this.Value.GetType(); // define public static const field: if (scriptTypeBuilder != null) // const in SSA or MSA { realField = scriptTypeBuilder.DefineField(clrName, type, field_attrs); } else // const in Pure or Transient { ModuleBuilder module_builder = this.DeclaringModuleBuilder.AssemblyBuilder.RealModuleBuilder; // represent the class constant as a static initonly field realField = ReflectionUtils.DefineGlobalField(module_builder, clrName, type, field_attrs); } Debug.Assert(realField != null); // set value if (this.HasValue) ((FieldBuilder)realField).SetConstant(this.Value); } } internal DConstantDesc Bake() { // TODO: rereflection return this.ConstantDesc; } } #endregion #region ClassConstant public sealed class ClassConstant : KnownConstant { public override bool IsIdentityDefinite { get { return true; } } public VariableName Name { get { return name; } } private readonly VariableName name; /// <summary> /// Error reporting. /// <see cref="ShortPosition.Invalid"/> for reflected PHP methods. /// </summary> public override Text.Span Span { get { return span; } } private readonly Text.Span span; /// <summary> /// Error reporting (for partial classes). /// <B>null</B> for reflected PHP methods. /// </summary> public override SourceUnit SourceUnit { get { return sourceUnit; } } private SourceUnit sourceUnit; internal override bool IsExported { get { return exportInfo != null || this.DeclaringPhpType.IsExported; } } #region Construction /// <summary> /// Used by compiler. /// </summary> public ClassConstant(VariableName name, DTypeDesc/*!*/ declaringType, PhpMemberAttributes memberAttributes, SourceUnit/*!*/ sourceUnit, Text.Span position) : base(new DConstantDesc(declaringType, memberAttributes, null)) { Debug.Assert(declaringType != null); this.name = name; this.span = position; this.sourceUnit = sourceUnit; } /// <summary> /// Used by full-reflect (CLR). /// </summary> public ClassConstant(VariableName name, DTypeDesc/*!*/ declaringType, PhpMemberAttributes memberAttributes) : base(new DConstantDesc(declaringType, memberAttributes, null)) { Debug.Assert(declaringType != null); this.name = name; } /// <summary> /// Used by full-reflect (PHP). /// </summary> public ClassConstant(VariableName name, DConstantDesc/*!*/ constantDesc, FieldInfo/*!*/ fieldInfo) : base(constantDesc) { this.name = name; this.realField = fieldInfo; } #endregion public override string GetFullName() { return name.Value; } internal override void ReportCircularDefinition(ErrorSink/*!*/ errors) { errors.Add(Errors.CircularConstantDefinitionClass, SourceUnit, Span, DeclaringType.FullName, FullName); } /// <summary> /// Checks whether a specified name is valid constant name. /// </summary> /// <param name="name">The constant name.</param> /// <seealso cref="PhpVariable.IsValidName"/> public static bool IsValidName(string name) { return PhpVariable.IsValidName(name); } public void Validate(ErrorSink/*!*/ errors) { // nop } internal void DefineBuilders() { if (realField == null) { TypeBuilder type_builder = this.DeclaringPhpType.RealTypeBuilder; // represent the class constant as a static initonly field FieldAttributes field_attrs = Enums.ToFieldAttributes(memberDesc.MemberAttributes); Type field_type = Types.Object[0]; if (this.HasValue) { var value = this.Value; if (value == null || value is int || value is double || value is string || value is long || value is bool) { if (value != null) field_type = value.GetType(); field_attrs |= FieldAttributes.Literal; } else { field_attrs |= FieldAttributes.InitOnly; } } string name = FullName; if (IsExported) name += "#"; FieldBuilder fb = type_builder.DefineField(name, field_type, field_attrs); // [EditorBrowsable(Never)] for user convenience - not on silverlight // [ThreadStatic] for deferred constants #if !SILVERLIGHT if (IsExported) fb.SetCustomAttribute(AttributeBuilders.EditorBrowsableNever); if (!this.HasValue) // constant initialized for every request separatelly (same as static PHP field) fb.SetCustomAttribute(AttributeBuilders.ThreadStatic); #endif realField = fb; } } #region Emission internal override PhpTypeCode EmitGet(CodeGenerator codeGenerator, ConstructedType constructedType, bool runtimeVisibilityCheck, string fallbackName) { if (!HasValue) { // __InitializeStaticFields to ensure, this deferred constant has been initialized (same as thread static field): DeclaringPhpType.EmitThreadStaticInit(codeGenerator, constructedType); } return base.EmitGet(codeGenerator, constructedType, runtimeVisibilityCheck, fallbackName); } #endregion } #endregion }
// Copyright 2021 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Reflection; namespace Falken { /// <summary> /// <c>PositionVector</c> defines the location of an object in 3D Space. /// </summary> [Serializable] public sealed class PositionVector { /// <summary> /// X component of the position vector. /// </summary> public float X { get; set; } /// <summary> /// Y component of the position vector. /// </summary> public float Y { get; set; } /// <summary> /// Z component of the position vector. /// </summary> public float Z { get; set; } /// <summary> /// Default constructor. Set every component to 0.0f. /// </summary> public PositionVector() { } /// <summary> /// Initialize every component to the same value. /// </summary> public PositionVector(float initializationValue) { X = initializationValue; Y = initializationValue; Z = initializationValue; } #if UNITY_5_3_OR_NEWER /// <summary> /// Initialize the position vector using a Unity's vector. /// </summary> public PositionVector(UnityEngine.Vector3 unityVector) { X = unityVector.x; Y = unityVector.y; Z = unityVector.z; } #endif // UNITY_5_3_OR_NEWER /// <summary> /// Construct a PositionVector with the given component values. /// </summary> public PositionVector(float newX, float newY, float newZ) { X = newX; Y = newY; Z = newZ; } /// <summary> /// Initialize the position with the internal Falken position class. /// </summary> internal PositionVector(FalkenInternal.falken.Position position) { X = position.x; Y = position.y; Z = position.z; } /// <summary> /// Modify a falken internal position with the instance's attributes. /// </summary> internal FalkenInternal.falken.Position ToInternalPosition( FalkenInternal.falken.Position position) { position.x = X; position.y = Y; position.z = Z; return position; } #if UNITY_5_3_OR_NEWER /// <summary> /// Convert a PositionVector to a UnityEngine.Vector3. /// </summary> public static implicit operator UnityEngine.Vector3(PositionVector value) => new UnityEngine.Vector3(value.X, value.Y, value.Z); /// <summary> /// Convert a UnityEngine.Vector3 to a PositionVector. /// </summary> public static implicit operator PositionVector(UnityEngine.Vector3 value) => new PositionVector(value); #endif // UNITY_5_3_OR_NEWER } /// <summary> /// <c>Position</c> Establishes a connection with a Falken's PositionAttribute. /// A position attribute is embedded in Entity's class and there's no /// support for more than position attribute. /// </summary> public sealed class Position : Falken.AttributeBase { /// <summary> /// Verify that the given object can be converted/assigned /// to a PositionVector. /// </summary> static private bool CanConvertToPositionVectorType(object obj) { return CanConvertToGivenType(typeof(PositionVector), obj); } #if UNITY_5_3_OR_NEWER /// <summary> /// Verify that the given object can be converted/assigned /// to a UnityEngine.Vector3 /// </summary> static private bool CanConvertToUnityVectorType(object obj) { return CanConvertToGivenType(typeof(UnityEngine.Vector3), obj); } #endif // UNITY_5_3_OR_NEWER /// <summary> /// Verify that the given object can be converted/assigned /// to any supported position type. /// </summary> static internal bool CanConvertToPositionType(object obj) { bool canConvert = CanConvertToPositionVectorType(obj); #if UNITY_5_3_OR_NEWER canConvert |= CanConvertToUnityVectorType(obj); #endif // UNITY_5_3_OR_NEWER return canConvert; } // Type of the position field. // Useful to distinguish between UnityEngine.Vector3 and Falken's // PositionVector private Type _positionType = typeof(Falken.PositionVector); /// <summary> /// Get Falken's position attribute value. /// <exception> AttributeNotBoundException if attribute is /// not bound. </exception> /// <returns> Value stored in Falken's attribute. </returns> /// </summary> public PositionVector Value { get { if (Bound) { Read(); return new PositionVector(_attribute.position()); } throw new AttributeNotBoundException( "Can't retrieve the value if the attribute is not bound."); } set { if (Bound) { _attribute.set_position(CastTo<PositionVector>(value).ToInternalPosition( _attribute.position())); Write(); return; } throw new AttributeNotBoundException( "Can't set value if the attribute is not bound."); } } /// <summary> /// Establish a connection between a C# attribute and a Falken's attribute. /// </summary> /// <param name="fieldInfo">Metadata information of the field this is being bound /// to.</param> /// <param name="fieldContainer">Object that contains the value of the field.</param> /// <param name="container">Internal container to add the attribute to.</param> /// <exception>AlreadyBoundException thrown when trying to bind the attribute when it was /// bound already.</exception> internal override void BindAttribute(FieldInfo fieldInfo, object fieldContainer, FalkenInternal.falken.AttributeContainer container) { ThrowIfBound(fieldInfo); SetNameToFieldName(fieldInfo, fieldContainer); if (fieldInfo != null && fieldContainer != null) { object value = fieldInfo.GetValue(fieldContainer); if (value != this) { // Attribute represents a field with non-Falken value. #if UNITY_5_3_OR_NEWER if (CanConvertToUnityVectorType(value)) { _positionType = typeof(UnityEngine.Vector3); } #endif // UNITY_5_3_OR_NEWER if (_positionType == null || CanConvertToPositionVectorType(value)) { _positionType = typeof(Falken.PositionVector); } if (_positionType == null) { ClearBindings(); throw new UnsupportedFalkenTypeException( $"Field '{fieldInfo.Name}' is not a Falken.PositionVector" + " or a UnityEngine.Vector3 or it does not have the" + " necessary implicit conversions to support it."); } } } else { _name = "position"; ClearBindings(); } FalkenInternal.falken.AttributeBase attributeBase; if (fieldInfo == null || System.Attribute.GetCustomAttribute( fieldInfo, typeof(FalkenInheritedAttribute)) == null) { attributeBase = new FalkenInternal.falken.AttributeBase( container, _name, FalkenInternal.falken.AttributeBase.Type.kTypePosition); } else { attributeBase = container.attribute(_name); if (attributeBase == null) { ClearBindings(); throw new InheritedAttributeNotFoundException( $"Inherited field '{_name}' was not found in the container."); } else if (attributeBase.type() != FalkenInternal.falken.AttributeBase.Type.kTypePosition) { ClearBindings(); throw new InheritedAttributeNotFoundException( $"Inherited field '{_name}' has a position type but the " + $"attribute type is '{attributeBase.type()}'"); } } SetFalkenInternalAttribute(attributeBase, fieldInfo, fieldContainer); Read(); InvalidateNonFalkenFieldValue(); } /// <summary> /// Clear all field and attribute bindings. /// </summary> protected override void ClearBindings() { base.ClearBindings(); _positionType = typeof(Falken.PositionVector); } /// <summary> /// Read a field and check if the value is valid. /// </summary> /// <returns> /// Object boxed version of the attribute value. /// or null if invalid or unable to readValue stored in Falken's attribute. /// </returns> internal override object ReadFieldIfValid() { object value = base.ReadField(); PositionVector position = null; if (value != null) { if (_positionType == typeof(PositionVector)) { position = CastTo<PositionVector>(value); } #if UNITY_5_3_OR_NEWER if (_positionType == typeof(UnityEngine.Vector3)) { position = CastTo<UnityEngine.Vector3>(value); } #endif // UNITY_5_3_OR_NEWER if (Single.IsNaN(position.X) || Single.IsNaN(position.Y) || Single.IsNaN(position.Z)) { return null; } } return position; } /// <summary> /// Update Falken's attribute value to reflect C# field's value. /// </summary> internal override void Read() { var value = ReadFieldIfValid(); if (value != null) { _attribute.set_position( ((PositionVector)value).ToInternalPosition(_attribute.position())); } } /// <summary> /// Update C# field's value to match Falken's attribute value. /// </summary> internal override void Write() { if (Bound && HasForeignFieldValue) { WriteField(CastFrom<PositionVector>(new PositionVector(_attribute.position()))); } } /// <summary> /// Invalidates the value of any non-Falken field represented by this attribute. /// </summary> internal override void InvalidateNonFalkenFieldValue() { if (HasForeignFieldValue) { PositionVector pos = new PositionVector { X = Single.NaN, Y = Single.NaN, Z = Single.NaN }; WriteField(CastFrom<PositionVector>(pos)); } } } }
using Machine.Specifications; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace BellRichM.TestRunner { public class EmbeddedRunner { private Type _testType; private Assembly _assembly; private Type _test; private Type[] testAssemblyTypes; private List<ContextAssembly> contextAssemblies; private int testcount; public EmbeddedRunner(Type testType, string testName) { if (testType == null) { throw new ArgumentNullException(nameof(testType)); } _testType = testType; var assembly = Assembly.GetAssembly(_testType); _test = assembly.GetType(_testType.FullName + "+" + testName); // The test is not a nested class, try as a baseclass if (_test == null) { var testNamespace = _testType.Namespace; _test = assembly.GetType(testNamespace + "." + testName); } if (_test == null) { throw new ArgumentException("Could not find test: " + testName); } testAssemblyTypes = assembly.GetTypes(); contextAssemblies = new List<ContextAssembly>(); testcount = 0; } public EmbeddedRunner(Type testType) { _testType = testType; var assembly = Assembly.GetAssembly(_testType); testAssemblyTypes = assembly.GetTypes(); contextAssemblies = new List<ContextAssembly>(); testcount = 0; } public EmbeddedRunner(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } _assembly = assembly; _testType = null; testAssemblyTypes = assembly.GetTypes(); contextAssemblies = new List<ContextAssembly>(); testcount = 0; } public void RunTests() { OnAssemblyStart(); if (_test != null) { RunTestCase(_test); } else if (_testType != null) { RunTest(_testType); } else { var interfaceType = typeof(IAssemblyContext); var testTypes = _assembly.GetTypes() .Where(t => t.FullName.StartsWith("BellRichM", StringComparison.InvariantCulture) && t.BaseType == Type.GetType("System.Object") && !t.IsNested && t.Name != "Program" && !t.GetInterfaces().Contains(interfaceType)); foreach (var testType in testTypes) { _testType = testType; // ToDo - fix hack RunTest(testType); } } OnAssemblyComplete(); Console.WriteLine(testcount); } public void RunTest(Type testType) { if (testType == null) { throw new ArgumentNullException(nameof(testType)); } // var subclasses2 = testAssemblyTypes.Where(t => t.BaseType == _testType); var tests = testAssemblyTypes.Where(t => t.IsSubclassOf(testType)); if (!tests.Any()) { tests = testType.GetNestedTypes(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(t => t.GetCustomAttribute<System.Runtime.CompilerServices.CompilerGeneratedAttribute>() == null); } if (!tests.Any()) { tests = testAssemblyTypes.Where(t => t == testType); } Console.WriteLine("Running " + testType.Name); foreach (var test in tests) { RunTestCase(test); } } public void RunTestCase(Type test) { if (test == null) { throw new ArgumentNullException(nameof(test)); } if (System.Attribute.IsDefined(test, typeof(IgnoreAttribute))) { return; } Console.WriteLine(" " + test.Name); var testInstance = Activator.CreateInstance(test); var testCase = GetTestCase(test, testInstance); SetupTestCase(testCase); try { CheckTestCaseResults(testCase); CheckTestCaseBehaviors(testCase, testInstance); } catch (System.Reflection.TargetInvocationException ex) when (ex.InnerException is Machine.Specifications.SpecificationException) { Console.WriteLine(ex.InnerException.Message); Console.WriteLine(ex.InnerException.StackTrace); } } public void OnAssemblyStart() { var interfaceType = typeof(IAssemblyContext); var implementations = testAssemblyTypes.Where(t => t.GetInterfaces().Contains(interfaceType)); foreach (Type type in implementations) { var method = type.GetMethod("OnAssemblyStart", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); var instance = Activator.CreateInstance(type); method.Invoke(instance, null); contextAssemblies.Add(new ContextAssembly { ImplementationType = type, ImplementationInstance = instance }); } } public void OnAssemblyComplete() { foreach (var contextAssembly in contextAssemblies) { var method = contextAssembly.ImplementationType.GetMethod("OnAssemblyComplete", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); method.Invoke(contextAssembly.ImplementationInstance, null); } } private static void SetupTestCase(TestCase testCase) { foreach (var establishDelegate in testCase.EstablishDelegates) { establishDelegate.Method.Invoke(establishDelegate.Target, null); } testCase.BecauseDelegate.Method.Invoke(testCase.BecauseDelegate.Target, null); } private void CheckTestCaseResults(TestCase testCase) { foreach (var itDelegateDetail in testCase.ItDelegatesDetail) { Console.WriteLine(" " + itDelegateDetail.Name); itDelegateDetail.DelegateField.Method.Invoke(itDelegateDetail.DelegateField.Target, null); testcount++; } } private void CheckTestCaseBehaviors(TestCase testCase, object testInstance) { foreach (var loggingBehavior in testCase.LoggingBehaviors) { var loggingBehaviorType = loggingBehavior.GetType(); var testInstanceType = testInstance.GetType(); Console.WriteLine(" checking " + loggingBehaviorType.Name); var loggerMockValue = testInstanceType .GetField("loggerMock", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) .GetValue(testInstance); loggingBehaviorType .GetField("loggerMock", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) .SetValue(loggingBehavior, loggerMockValue); var loggingDataValue = testInstanceType .GetField("loggingData", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) .GetValue(testInstance); loggingBehaviorType .GetField("loggingData", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) .SetValue(loggingBehavior, loggingDataValue); var loggingBehaviorFieldInfos = loggingBehaviorType.GetFields(BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); foreach (var loggingBehaviorFieldInfo in loggingBehaviorFieldInfos) { if (loggingBehaviorFieldInfo.FieldType == typeof(Machine.Specifications.It)) { var loggingBehaviorCheck = loggingBehaviorFieldInfo.GetValue(loggingBehavior) as Delegate; loggingBehaviorCheck.Method.Invoke(loggingBehaviorCheck.Target, null); testcount++; } } } } private TestCase GetTestCase(Type test, object testInstance) { var testCase = new TestCase(); var establishFieldInfo = _testType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance) .Where(t => t.FieldType == typeof(Machine.Specifications.Establish)).FirstOrDefault(); if (establishFieldInfo != null) { // another hack if (_testType.IsAbstract) { testCase.EstablishDelegates.Add(establishFieldInfo.GetValue(testInstance) as Delegate); } else { var instance = Activator.CreateInstance(_testType); testCase.EstablishDelegates.Add(establishFieldInfo.GetValue(instance) as Delegate); } } var fieldInfos = test.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); foreach (var fieldInfo in fieldInfos) { var fieldType = fieldInfo.FieldType; if (fieldType == typeof(Machine.Specifications.Establish)) { testCase.EstablishDelegates.Add(fieldInfo.GetValue(testInstance) as Delegate); } if (fieldType == typeof(Machine.Specifications.Because)) { testCase.BecauseDelegate = fieldInfo.GetValue(testInstance) as Delegate; } if (fieldType == typeof(Machine.Specifications.It)) { testCase.ItDelegatesDetail.Add( new DelegateDetail { Name = fieldInfo.Name, DelegateField = fieldInfo.GetValue(testInstance) as Delegate }); } if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Machine.Specifications.Behaves_like<>)) { var behavior = fieldType.GenericTypeArguments[0]; if (behavior.IsGenericType && behavior.GetGenericTypeDefinition() == typeof(BellRichM.Logging.LoggingBehaviors<>)) { var loggingBehavior = behavior.GetGenericTypeDefinition(); testCase.LoggingBehaviors.Add(Activator.CreateInstance(loggingBehavior.MakeGenericType(behavior.GenericTypeArguments))); } } } return testCase; } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Microsoft.CSharp; namespace Manos.Tool { public class BuildCommand { public static readonly string COMPILED_TEMPLATES = "Templates.dll"; private string output_name; private string[] ref_asm; private string[] sources; public BuildCommand(Environment env) { Environment = env; } public Environment Environment { get; private set; } public string[] Sources { get { if (sources == null) sources = CreateSourcesList(); return sources; } set { if (value == null) throw new ArgumentNullException("value"); sources = value; } } public string OutputAssembly { get { if (output_name == null) return Path.GetFileName(Directory.GetCurrentDirectory()) + ".dll"; return output_name; } set { if (value == null) throw new ArgumentNullException("value"); output_name = value; } } public string[] ReferencedAssemblies { get { if (ref_asm == null) ref_asm = CreateReferencesList(); return ref_asm; } set { ref_asm = value; } } public void Run() { ManosConfig.Load(); if (RunXBuild()) return; if (RunMake()) return; CompileCS(); } public bool RunXBuild() { string[] slns = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.sln"); if (slns.Length < 1) return false; foreach (string sln in slns) { Process p = Process.Start("xbuild", sln); p.WaitForExit(); } return true; } public bool RunMake() { if (!File.Exists("Makefile") && !File.Exists("makefile")) return false; Process p = Process.Start("make"); p.WaitForExit(); return true; } public void CompileCS() { var provider = new CSharpCodeProvider(); var options = new CompilerParameters(ReferencedAssemblies, OutputAssembly, true); CompilerResults results = provider.CompileAssemblyFromFile(options, Sources); if (results.Errors.Count > 0) { foreach (object e in results.Errors) { Console.WriteLine(e); } } } private string[] CreateSourcesList() { var sources = new List<string>(); FindCSFilesRecurse(Environment.WorkingDirectory, sources); return sources.ToArray(); } private void FindCSFilesRecurse(string dir, List<string> sources) { sources.AddRange(Directory.GetFiles(dir, "*.cs")); foreach (string subdir in Directory.GetDirectories(dir)) { if (dir == Environment.WorkingDirectory) { if (subdir == "Content" || subdir == "Templates") continue; } if (subdir.EndsWith(".exclude")) continue; FindCSFilesRecurse(subdir, sources); } } private string[] CreateReferencesList() { var libs = new List<string>(); AddDefaultReferences(libs); // Find any additional dlls in project file foreach (string lib in Directory.GetFiles(Directory.GetCurrentDirectory())) { if (!lib.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase)) continue; if (Path.GetFileName(lib) == OutputAssembly) continue; libs.Add(lib); } // Read additional referenced assemblies from manos.config in project folder: // eg: // // [manos] // ReferencedAssemblies=System.Core.dll Microsoft.CSharp.dll Manos.Mvc.dll // if (ManosConfig.Main != null) { string strReferencedAssemblies = ManosConfig.GetExpanded("ReferencedAssemblies"); if (strReferencedAssemblies != null) { string[] referencedAssemblies = strReferencedAssemblies.Split(' ', ','); foreach (string a in referencedAssemblies) { string ManosFile = Path.Combine(Environment.ManosDirectory, a); if (File.Exists(ManosFile)) { libs.Add(ManosFile); } else { libs.Add(a); } } } } return libs.ToArray(); } private void AddDefaultReferences(List<string> libs) { string manosdll = Path.Combine(Environment.ManosDirectory, "Manos.dll"); libs.Add(manosdll); string manosiodll = Path.Combine(Environment.ManosDirectory, "Manos.IO.dll"); libs.Add(manosiodll); string ninidll = Path.Combine(Environment.ManosDirectory, "Nini.dll"); libs.Add(ninidll); } } }
#pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony { public class Tools : global::haxe.lang.HxObject { public Tools(global::haxe.lang.EmptyObject empty) { unchecked { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public Tools() { unchecked { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::pony.Tools.__hx_ctor_pony_Tools(this); } #line default } public static void __hx_ctor_pony_Tools(global::pony.Tools __temp_me103) { unchecked { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public static bool equal(object a, object b, global::haxe.lang.Null<int> maxDepth) { unchecked { #line 59 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int __temp_maxDepth100 = ( (global::haxe.lang.Runtime.eq((maxDepth).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (1) )) : (maxDepth.@value) ); if (global::haxe.lang.Runtime.eq(a, b)) { #line 60 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return true; } if (( __temp_maxDepth100 == 0 )) { #line 61 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 63 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::ValueType type = global::Type.@typeof(a); #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" switch (global::Type.enumIndex(type)) { case 1:case 2:case 3:case 0: { return false; } case 5: { #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" try { #line 69 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return global::Reflect.compareMethods(a, b); } catch (global::System.Exception __temp_catchallException485) { #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object __temp_catchall486 = __temp_catchallException485; #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( __temp_catchall486 is global::haxe.lang.HaxeException )) { #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" __temp_catchall486 = ((global::haxe.lang.HaxeException) (__temp_catchallException485) ).obj; } #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object _ = __temp_catchall486; #line 71 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } } } case 7: { #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::System.Type t = ((global::System.Type) (type.@params[0]) ); #line 73 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { if ( ! (global::haxe.lang.Runtime.typeEq(t, global::Type.getEnum(b))) ) { #line 74 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( global::Type.enumIndex(a) != global::Type.enumIndex(b) )) { #line 76 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 78 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::Array a1 = global::Type.enumParameters(a); global::Array b1 = global::Type.enumParameters(b); #line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( ((int) (global::haxe.lang.Runtime.getField_f(a1, "length", 520590566, true)) ) != ((int) (global::haxe.lang.Runtime.getField_f(b1, "length", 520590566, true)) ) )) { #line 81 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } { #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g1 = 0; #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g = ((int) (global::haxe.lang.Runtime.getField_f(a1, "length", 520590566, true)) ); #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g1 < _g )) { #line 82 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int i = _g1++; if ( ! (global::pony.Tools.equal(a1[i], b1[i], new global::haxe.lang.Null<int>(( __temp_maxDepth100 - 1 ), true))) ) { #line 83 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } } } return true; } } case 4: { #line 86 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( a is global::System.Type )) { #line 86 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 86 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } case 8: { { } #line 87 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } case 6: { #line 65 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::System.Type t1 = ((global::System.Type) (type.@params[0]) ); #line 90 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (global::haxe.lang.Runtime.refEq(t1, typeof(global::Array))) { if ( ! (( b is global::Array )) ) { #line 91 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( ! (global::haxe.lang.Runtime.eq(global::haxe.lang.Runtime.getField(a, "length", 520590566, true), global::haxe.lang.Runtime.getField(b, "length", 520590566, true))) )) { #line 93 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } { #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g11 = 0; #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g2 = ((int) (global::haxe.lang.Runtime.toInt(global::haxe.lang.Runtime.getField(a, "length", 520590566, true))) ); #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g11 < _g2 )) { #line 94 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int i1 = _g11++; if ( ! (global::pony.Tools.equal(((object) (global::haxe.lang.Runtime.callField(a, "__get", 1915412854, new global::Array<object>(new object[]{i1}))) ), ((object) (global::haxe.lang.Runtime.callField(b, "__get", 1915412854, new global::Array<object>(new object[]{i1}))) ), new global::haxe.lang.Null<int>(( __temp_maxDepth100 - 1 ), true))) ) { #line 95 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } } } return true; } #line 88 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } } #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::ValueType _g3 = global::Type.@typeof(b); #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" switch (global::Type.enumIndex(_g3)) { case 1:case 2:case 3:case 5:case 7:case 0: { return false; } case 4: { if (( b is global::System.Type )) { #line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 103 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } case 6: { #line 101 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::System.Type t2 = ((global::System.Type) (_g3.@params[0]) ); #line 104 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (global::haxe.lang.Runtime.refEq(t2, typeof(global::Array))) { #line 104 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line 104 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } case 8: { { } #line 105 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } } } #line 108 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::Array<object> fields = global::Reflect.fields(a); #line 111 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( fields.length == global::Reflect.fields(b).length )) { if (( fields.length == 0 )) { #line 112 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return true; } { #line 113 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g4 = 0; #line 113 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g4 < fields.length )) { #line 113 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string f = global::haxe.lang.Runtime.toString(fields[_g4]); #line 113 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g4; if (( ! (global::Reflect.hasField(b, f)) || ! (global::pony.Tools.equal(global::Reflect.field(a, f), global::Reflect.field(b, f), new global::haxe.lang.Null<int>(( __temp_maxDepth100 - 1 ), true))) )) { return false; } } } return true; } #line 118 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return false; } #line default } public static int superIndexOf<T>(object it, T v, global::haxe.lang.Null<int> maxDepth) { unchecked { #line 121 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int __temp_maxDepth101 = ( (global::haxe.lang.Runtime.eq((maxDepth).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (1) )) : (maxDepth.@value) ); int i = 0; { #line 123 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object __temp_iterator195 = ((object) (global::haxe.lang.Runtime.callField(it, "iterator", 328878574, default(global::Array))) ); #line 123 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator195, "hasNext", 407283053, default(global::Array))) )) { #line 123 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" T e = global::haxe.lang.Runtime.genericCast<T>(global::haxe.lang.Runtime.callField(__temp_iterator195, "next", 1224901875, default(global::Array))); if (global::pony.Tools.equal(e, v, new global::haxe.lang.Null<int>(__temp_maxDepth101, true))) { #line 124 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return i; } i++; } } #line 127 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return -1; } #line default } public static int superMultyIndexOf<T>(object it, global::Array<T> av, global::haxe.lang.Null<int> maxDepth) { unchecked { #line 130 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int __temp_maxDepth102 = ( (global::haxe.lang.Runtime.eq((maxDepth).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (1) )) : (maxDepth.@value) ); int i = 0; { #line 132 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object __temp_iterator196 = ((object) (global::haxe.lang.Runtime.callField(it, "iterator", 328878574, default(global::Array))) ); #line 132 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator196, "hasNext", 407283053, default(global::Array))) )) { #line 132 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" T e = global::haxe.lang.Runtime.genericCast<T>(global::haxe.lang.Runtime.callField(__temp_iterator196, "next", 1224901875, default(global::Array))); { #line 133 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g = 0; #line 133 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g < av.length )) { #line 133 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" T v = av[_g]; #line 133 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g; #line 133 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (global::pony.Tools.equal(e, v, new global::haxe.lang.Null<int>(__temp_maxDepth102, true))) { #line 133 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return i; } } } i++; } } #line 136 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return -1; } #line default } public static int multyIndexOf<T>(object it, global::Array<T> av) { unchecked { #line 140 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int i = 0; { #line 141 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object __temp_iterator197 = ((object) (global::haxe.lang.Runtime.callField(it, "iterator", 328878574, default(global::Array))) ); #line 141 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator197, "hasNext", 407283053, default(global::Array))) )) { #line 141 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" T e = global::haxe.lang.Runtime.genericCast<T>(global::haxe.lang.Runtime.callField(__temp_iterator197, "next", 1224901875, default(global::Array))); { #line 142 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g = 0; #line 142 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g < av.length )) { #line 142 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" T v = av[_g]; #line 142 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g; #line 142 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (global::haxe.lang.Runtime.eq(e, v)) { #line 142 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return i; } } } i++; } } #line 145 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return -1; } #line default } public static double percentCalc(double p, double min, double max) { unchecked { #line 148 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( ( (( max - min )) * p ) + min ); } #line default } public static global::haxe.io.BytesInput cut(global::haxe.io.BytesInput inp) { unchecked { #line 156 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::haxe.io.BytesOutput @out = new global::haxe.io.BytesOutput(); int cntNull = 0; bool flagNull = true; int cur = -99; while (true) { #line 163 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" try { #line 163 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" cur = inp.readByte(); } catch (global::System.Exception __temp_catchallException487) { #line 165 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object __temp_catchall488 = __temp_catchallException487; #line 165 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( __temp_catchall488 is global::haxe.lang.HaxeException )) { #line 165 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" __temp_catchall488 = ((global::haxe.lang.HaxeException) (__temp_catchallException487) ).obj; } #line 165 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 165 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object _ = __temp_catchall488; #line 165 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" break; } } #line 167 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( cur == 0 )) { #line 169 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if ( ! (flagNull) ) { flagNull = true; } cntNull++; } else { #line 175 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (flagNull) { while (( cntNull-- > 0 )) { @out.writeByte(0); } } flagNull = false; @out.writeByte(cur); } } #line 182 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" @out.close(); return new global::haxe.io.BytesInput(((global::haxe.io.Bytes) (@out.getBytes()) ), ((global::haxe.lang.Null<int>) (default(global::haxe.lang.Null<int>)) ), ((global::haxe.lang.Null<int>) (default(global::haxe.lang.Null<int>)) )); } #line default } public static new object __hx_createEmpty() { unchecked { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.Tools(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 43 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.Tools(); } #line default } } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony { public class ArrayTools : global::haxe.lang.HxObject { public ArrayTools(global::haxe.lang.EmptyObject empty) { unchecked { #line 202 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public ArrayTools() { unchecked { #line 202 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::pony.ArrayTools.__hx_ctor_pony_ArrayTools(this); } #line default } public static void __hx_ctor_pony_ArrayTools(global::pony.ArrayTools __temp_me104) { unchecked { #line 202 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public static bool thereIs<T>(object a, global::Array<T> b) { unchecked { #line 205 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 205 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" object __temp_iterator198 = ((object) (global::haxe.lang.Runtime.callField(a, "iterator", 328878574, default(global::Array))) ); #line 205 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (((bool) (global::haxe.lang.Runtime.callField(__temp_iterator198, "hasNext", 407283053, default(global::Array))) )) { #line 205 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::Array<T> e = ((global::Array<T>) (global::Array<object>.__hx_cast<T>(((global::Array) (global::haxe.lang.Runtime.callField(__temp_iterator198, "next", 1224901875, default(global::Array))) ))) ); #line 205 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (global::pony.Tools.equal(e, b, default(global::haxe.lang.Null<int>))) { #line 205 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return true; } } } return false; } #line default } public static double arithmeticMean(global::Array<double> a) { unchecked { #line 210 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" double s = ((double) (0) ); { #line 211 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g = 0; #line 211 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g < a.length )) { #line 211 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" double e = a[_g]; #line 211 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g; #line 211 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" s += e; } } return ( s / a.length ); } #line default } public static new object __hx_createEmpty() { unchecked { #line 202 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.ArrayTools(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 202 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.ArrayTools(); } #line default } } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony { public class FloatTools : global::haxe.lang.HxObject { public FloatTools(global::haxe.lang.EmptyObject empty) { unchecked { #line 217 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public FloatTools() { unchecked { #line 217 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::pony.FloatTools.__hx_ctor_pony_FloatTools(this); } #line default } public static void __hx_ctor_pony_FloatTools(global::pony.FloatTools __temp_me107) { unchecked { #line 217 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public static string _toFixed(double v, int n, global::haxe.lang.Null<int> begin, string d, string beginS, string endS) { unchecked { #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (string.Equals(endS, default(string))) { #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" endS = "0"; } #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (string.Equals(beginS, default(string))) { #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" beginS = "0"; } #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (string.Equals(d, default(string))) { #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" d = "."; } #line 233 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int __temp_begin105 = ( (global::haxe.lang.Runtime.eq((begin).toDynamic(), (default(global::haxe.lang.Null<int>)).toDynamic())) ? (((int) (0) )) : (begin.@value) ); if (( __temp_begin105 != 0 )) { string s = global::pony.FloatTools._toFixed(v, n, new global::haxe.lang.Null<int>(0, true), d, beginS, endS); global::Array<object> a = global::haxe.lang.StringExt.split(s, d); int d1 = ( __temp_begin105 - global::haxe.lang.Runtime.toString(a[0]).Length ); return global::haxe.lang.Runtime.concat(global::pony.StringTls.repeat(beginS, d1), s); } #line 241 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( n == 0 )) { #line 241 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return global::Std.@string(((int) (v) )); } double p = global::System.Math.Pow(((double) (10) ), ((double) (n) )); int __temp_stmt489 = default(int); #line 243 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 243 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" double x = global::System.Math.Floor(((double) (( v * p )) )); #line 243 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" __temp_stmt489 = ((int) (x) ); } #line 243 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" v = ( __temp_stmt489 / p ); string s1 = global::Std.@string(v); global::Array<object> a1 = global::haxe.lang.StringExt.split(s1, "."); if (( a1.length <= 1 )) { return global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(s1, d), global::pony.StringTls.repeat(endS, n)); } else { #line 249 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.concat(global::haxe.lang.Runtime.toString(a1[0]), d), global::haxe.lang.Runtime.toString(a1[1])), global::pony.StringTls.repeat(endS, ( n - global::haxe.lang.Runtime.toString(a1[1]).Length ))); } } #line default } public static bool inRange(double v, double min, double max) { unchecked { #line 252 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( ( min <= v ) && ( v <= max ) ); } #line default } public static bool approximately(double a, double b, global::haxe.lang.Null<double> range) { unchecked { #line 254 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" double __temp_range106 = ( (global::haxe.lang.Runtime.eq((range).toDynamic(), (default(global::haxe.lang.Null<double>)).toDynamic())) ? (((double) (1) )) : (range.@value) ); #line 254 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( ( ( b - __temp_range106 ) <= a ) && ( a <= ( b + __temp_range106 ) ) ); } #line default } public static double limit(double v, double min, double max) { unchecked { #line 257 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( v < min )) { #line 257 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return min; } else { if (( v > max )) { #line 258 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return max; } else { return v; } } } #line default } public static double cultureAdd(double a, double b, double max) { unchecked { #line 264 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( ( a + b ) >= max )) { return max; } else { #line 267 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( a + b ); } } #line default } public static double cultureSub(double a, double b, double min) { unchecked { #line 271 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( ( a - b ) <= min )) { #line 271 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return min; } else { return ( a - b ); } } #line default } public static double cultureTarget(double a, double b, double step) { unchecked { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( a > b )) { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( ( a - step ) <= b )) { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return b; } else { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( a - step ); } } else { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( ( a + step ) >= b )) { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return b; } else { #line 276 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( a + step ); } } } #line default } public static double midValue(double a, double b, double aCount, double bCount) { unchecked { #line 280 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return ( (( ( aCount * a ) + ( bCount * b ) )) / (( aCount + bCount )) ); } #line default } public static new object __hx_createEmpty() { unchecked { #line 217 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.FloatTools(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 217 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.FloatTools(); } #line default } } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony { public class StringTls : global::haxe.lang.HxObject { public StringTls(global::haxe.lang.EmptyObject empty) { unchecked { #line 284 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public StringTls() { unchecked { #line 284 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::pony.StringTls.__hx_ctor_pony_StringTls(this); } #line default } public static void __hx_ctor_pony_StringTls(global::pony.StringTls __temp_me108) { unchecked { #line 284 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public static string repeat(string s, int count) { unchecked { #line 287 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string r = ""; while (( count-- > 0 )) { #line 288 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" r = global::haxe.lang.Runtime.concat(r, s); } return r; } #line default } public static bool isTrue(string s) { unchecked { #line 292 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string __temp_stmt490 = default(string); #line 292 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 292 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string s1 = s.ToLower(); #line 292 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" __temp_stmt490 = s1.Trim(); } #line 292 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return string.Equals(__temp_stmt490, "true"); } #line default } public static global::Array<object> explode(string s, global::Array<object> delimiters) { unchecked { #line 295 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::Array<object> r = new global::Array<object>(new object[]{s}); { #line 296 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g = 0; #line 296 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g < delimiters.length )) { #line 296 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string d = global::haxe.lang.Runtime.toString(delimiters[_g]); #line 296 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g; global::Array<object> sr = new global::Array<object>(new object[]{}); { #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g1 = 0; #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g1 < r.length )) { #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string e = global::haxe.lang.Runtime.toString(r[_g1]); #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g1; #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" int _g2 = 0; #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::Array<object> _g3 = global::haxe.lang.StringExt.split(e, d); #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" while (( _g2 < _g3.length )) { #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string se = global::haxe.lang.Runtime.toString(_g3[_g2]); #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" ++ _g2; #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if ( ! (string.Equals(se, "")) ) { #line 298 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" sr.push(se); } } } } r = sr; } } #line 301 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return r; } #line default } public static double parsePercent(string s) { unchecked { #line 311 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (( global::haxe.lang.StringExt.indexOf(s, "%", default(global::haxe.lang.Null<int>)) != -1 )) { return ( global::Std.parseFloat(global::haxe.lang.StringExt.substr(s, 0, new global::haxe.lang.Null<int>(( s.Length - 1 ), true))) / 100 ); } else { #line 314 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return global::Std.parseFloat(s); } } #line default } public static new object __hx_createEmpty() { unchecked { #line 284 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.StringTls(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 284 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.StringTls(); } #line default } } } #pragma warning disable 109, 114, 219, 429, 168, 162 namespace pony { public class XmlTools : global::haxe.lang.HxObject { public XmlTools(global::haxe.lang.EmptyObject empty) { unchecked { #line 318 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public XmlTools() { unchecked { #line 318 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" global::pony.XmlTools.__hx_ctor_pony_XmlTools(this); } #line default } public static void __hx_ctor_pony_XmlTools(global::pony.XmlTools __temp_me109) { unchecked { #line 318 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { } } #line default } public static bool isTrue(global::haxe.xml.Fast x, string name) { unchecked { #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" bool __temp_boolv493 = x.has.resolve(name); #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" bool __temp_boolv492 = false; #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" if (__temp_boolv493) { #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string s = x.att.resolve(name); #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string __temp_stmt494 = default(string); #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" { #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" string s1 = s.ToLower(); #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" __temp_stmt494 = s1.Trim(); } #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" __temp_boolv492 = string.Equals(__temp_stmt494, "true"); } } #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" bool __temp_stmt491 = ( __temp_boolv493 && __temp_boolv492 ); #line 319 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return __temp_stmt491; } #line default } public static global::haxe.xml.Fast fast(string text) { unchecked { #line 320 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::haxe.xml.Fast(((global::Xml) (global::Xml.parse(text)) )); } #line default } public static new object __hx_createEmpty() { unchecked { #line 318 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.XmlTools(((global::haxe.lang.EmptyObject) (global::haxe.lang.EmptyObject.EMPTY) )); } #line default } public static new object __hx_create(global::Array arr) { unchecked { #line 318 "C:\\HaxeToolkit\\haxe\\lib\\pony/git/pony/Tools.hx" return new global::pony.XmlTools(); } #line default } } }
using System; using System.Collections.Generic; using xsc = DotNetXmlSwfChart; namespace testWeb.tests { public class Column3DTwo : ChartTestBase { #region ChartInclude public override xsc.ChartHTML ChartInclude { get { xsc.ChartHTML chartHtml = new xsc.ChartHTML(); chartHtml.height = 300; chartHtml.bgColor = "888888"; chartHtml.flashFile = "charts/charts.swf"; chartHtml.libraryPath = "charts/charts_library"; chartHtml.xmlSource = "xmlData.aspx"; return chartHtml; } } #endregion #region Chart public override xsc.Chart Chart { get { xsc.Chart c = new xsc.Chart(); c.AddChartType(xsc.XmlSwfChartType.Column3d); c.AxisCategory = SetAxisCategory(c.ChartType[0]); c.AxisTicks = SetAxisTicks(); c.AxisValue = SetAxisValue(); c.ChartBorder = SetChartBorder(); c.Data = SetChartData(); c.ChartGridH = SetChartGrid(xsc.ChartGridType.Horizontal); c.ChartGridV = SetChartGrid(xsc.ChartGridType.Vertical); c.ChartRectangle = SetChartRectangle(); c.ChartPreferences = SetChartPreferences(c.ChartType[0]); c.ChartTransition = SetChartTransition(); c.ChartValue = SetChartValue(); c.LegendLabel = SetLegendLabel(); c.LegendRectangle = SetLegendRectangle(); c.LegendTransition = SetLegendTransition(); c.AddSeriesColor("ff8800"); c.AddSeriesColor("88ff00"); c.SeriesGap = SetSeriesGap(); return c; } } #endregion #region Helpers #region SetSeriesGap() private xsc.SeriesGap SetSeriesGap() { xsc.SeriesGap sg = new xsc.SeriesGap(); sg.BarGap = 0; sg.SetGap = 20; return sg; } #endregion #region SetLegendTransition() private xsc.LegendTransition SetLegendTransition() { xsc.LegendTransition lt = new xsc.LegendTransition(); lt.Type = xsc.TransitionType.dissolve; lt.Delay = 0; lt.Duration = 1; return lt; } #endregion #region SetLegendRectangle() private xsc.LegendRectangle SetLegendRectangle() { xsc.LegendRectangle lr = new xsc.LegendRectangle(); lr.X = 25; lr.Y = 250; lr.Width = 350; lr.Height = 50; lr.Margin = 20; lr.FillColor = "000000"; lr.FillAlpha = 7; lr.LineAlpha = 0; lr.LineThickness = 0; return lr; } #endregion #region SetLegendLabel() private xsc.LegendLabel SetLegendLabel() { xsc.LegendLabel ll = new xsc.LegendLabel(); ll.Layout = xsc.LegendLabelLayout.horizontal; ll.Font = "Arial"; ll.Bold = true; ll.Size = 12; ll.Color = "000000"; ll.Alpha = 50; return ll; } #endregion #region SetChartValue() private xsc.ChartValue SetChartValue() { xsc.ChartValue cv = new xsc.ChartValue(); cv.HideZero = true; cv.Color = "000000"; cv.Alpha = 80; cv.Size = 12; cv.Position = "cursor"; cv.Prefix = ""; cv.Suffix = ""; cv.Decimals = 0; cv.Separator = ""; cv.AsPercentage = true; return cv; } #endregion #region SetChartTransition() private xsc.ChartTransition SetChartTransition() { xsc.ChartTransition ct = new xsc.ChartTransition(); ct.TransitionType = xsc.TransitionType.slide_left; ct.Delay = 0; ct.Duration = 1; ct.Order = xsc.TransitionOrder.series; return ct; } #endregion #region SetChartPreferences(xsc.XmlSwfChartType type) private xsc.ChartPreferences SetChartPreferences(xsc.XmlSwfChartType type) { xsc.ChartPreferences cp = new xsc.ChartPreferences(type); cp.RotationX = 20; cp.RotationY = 50; return cp; } #endregion #region SetChartRectangle() private xsc.ChartRectangle SetChartRectangle() { xsc.ChartRectangle cr = new xsc.ChartRectangle(); cr.X = -70; cr.Y = -35; cr.Width = 500; cr.Height = 250; cr.PositiveAlpha = 0; return cr; } #endregion #region SetChartGrid(xsc.ChartGridType type) private xsc.ChartGrid SetChartGrid(xsc.ChartGridType type) { xsc.ChartGrid cg = new xsc.ChartGrid(type); cg.Thickness = 0; return cg; } #endregion #region SetChartData() private xsc.ChartData SetChartData() { xsc.ChartData cd = new xsc.ChartData(); cd.AddDataPoint("Region 1", "Su", 70); cd.AddDataPoint("Region 1", "M", 60); cd.AddDataPoint("Region 1", "Tu", 11); cd.AddDataPoint("Region 1", "W", 15); cd.AddDataPoint("Region 1", "Th", 20); cd.AddDataPoint("Region 1", "F", 22); cd.AddDataPoint("Region 1", "Sa", 11); cd.AddDataPoint("Region 2", "Su", 30); cd.AddDataPoint("Region 2", "M", 32); cd.AddDataPoint("Region 2", "Tu", 35); cd.AddDataPoint("Region 2", "W", 80); cd.AddDataPoint("Region 2", "Th", 84); cd.AddDataPoint("Region 2", "F", 70); cd.AddDataPoint("Region 2", "Sa", 36); return cd; } #endregion #region SetChartBorder() private xsc.ChartBorder SetChartBorder() { xsc.ChartBorder cb = new xsc.ChartBorder(); cb.TopThickness = 0; cb.BottomThickness = 0; cb.LeftThickness = 0; cb.RightThickness = 0; return cb; } #endregion #region SetAxisValue() private xsc.AxisValue SetAxisValue() { xsc.AxisValue av = new xsc.AxisValue(); av.Alpha = 0; return av; } #endregion #region SetAxisTicks() private xsc.AxisTicks SetAxisTicks() { xsc.AxisTicks at = new xsc.AxisTicks(); at.ValueTicks = false; at.CategoryTicks = false; return at; } #endregion #region SetAxisCategory(xsc.XmlSwfChartType type) private xsc.AxisCategory SetAxisCategory(xsc.XmlSwfChartType type) { xsc.AxisCategory ac = new xsc.AxisCategory(type); ac.Size = 10; ac.Color = "ffffff"; ac.Alpha = 75; ac.Skip = 0; ac.Orientation = "diagonal_up"; return ac; } #endregion #endregion } }
/* * [The "BSD license"] * Copyright (c) 2011 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2011 Sam Harwell, Tunnel Vision Laboratories, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime { using Antlr.Runtime.Tree; using ArgumentException = System.ArgumentException; using ArgumentNullException = System.ArgumentNullException; using Exception = System.Exception; using SerializationInfo = System.Runtime.Serialization.SerializationInfo; using StreamingContext = System.Runtime.Serialization.StreamingContext; /** <summary>The root of the ANTLR exception hierarchy.</summary> * * <remarks> * To avoid English-only error messages and to generally make things * as flexible as possible, these exceptions are not created with strings, * but rather the information necessary to generate an error. Then * the various reporting methods in Parser and Lexer can be overridden * to generate a localized error message. For example, MismatchedToken * exceptions are built with the expected token type. * So, don't expect getMessage() to return anything. * * Note that as of Java 1.4, you can access the stack trace, which means * that you can compute the complete trace of rules from the start symbol. * This gives you considerable context information with which to generate * useful error messages. * * ANTLR generates code that throws exceptions upon recognition error and * also generates code to catch these exceptions in each rule. If you * want to quit upon first error, you can turn off the automatic error * handling mechanism using rulecatch action, but you still need to * override methods mismatch and recoverFromMismatchSet. * * In general, the recognition exceptions can track where in a grammar a * problem occurred and/or what was the expected input. While the parser * knows its state (such as current input symbol and line info) that * state can change before the exception is reported so current token index * is computed and stored at exception time. From this info, you can * perhaps print an entire line of input not just a single token, for example. * Better to just say the recognizer had a problem and then let the parser * figure out a fancy report. * </remarks> */ [System.Serializable] public class RecognitionException : Exception { /** <summary>What input stream did the error occur in?</summary> */ private IIntStream _input; /// <summary> /// What was the lookahead index when this exception was thrown? /// </summary> private int _k; /** <summary>What is index of token/char were we looking at when the error occurred?</summary> */ private int _index; /** <summary> * The current Token when an error occurred. Since not all streams * can retrieve the ith Token, we have to track the Token object. * For parsers. Even when it's a tree parser, token might be set. * </summary> */ private IToken _token; /** <summary> * If this is a tree parser exception, node is set to the node with * the problem. * </summary> */ private object _node; /** <summary>The current char when an error occurred. For lexers.</summary> */ private int _c; /** <summary> * Track the line (1-based) at which the error occurred in case this is * generated from a lexer. We need to track this since the * unexpected char doesn't carry the line info. * </summary> */ private int _line; /// <summary> /// The 0-based index into the line where the error occurred. /// </summary> private int _charPositionInLine; /** <summary> * If you are parsing a tree node stream, you will encounter som * imaginary nodes w/o line/col info. We now search backwards looking * for most recent token with line/col info, but notify getErrorHeader() * that info is approximate. * </summary> */ private bool _approximateLineInfo; /** <summary>Used for remote debugger deserialization</summary> */ public RecognitionException() : this("A recognition error occurred.", null, null) { } public RecognitionException(IIntStream input) : this("A recognition error occurred.", input, 1, null) { } public RecognitionException(IIntStream input, int k) : this("A recognition error occurred.", input, k, null) { } public RecognitionException(string message) : this(message, null, null) { } public RecognitionException(string message, IIntStream input) : this(message, input, 1, null) { } public RecognitionException(string message, IIntStream input, int k) : this(message, input, k, null) { } public RecognitionException(string message, Exception innerException) : this(message, null, innerException) { } public RecognitionException(string message, IIntStream input, Exception innerException) : this(message, input, 1, innerException) { } public RecognitionException(string message, IIntStream input, int k, Exception innerException) : base(message, innerException) { this._input = input; this._k = k; if (input != null) { this._index = input.Index + k - 1; if (input is ITokenStream) { this._token = ((ITokenStream)input).LT(k); this._line = _token.Line; this._charPositionInLine = _token.CharPositionInLine; } ITreeNodeStream tns = input as ITreeNodeStream; if (tns != null) { ExtractInformationFromTreeNodeStream(tns, k); } else { ICharStream charStream = input as ICharStream; if (charStream != null) { int mark = input.Mark(); try { for (int i = 0; i < k - 1; i++) input.Consume(); this._c = input.LA(1); this._line = ((ICharStream)input).Line; this._charPositionInLine = ((ICharStream)input).CharPositionInLine; } finally { input.Rewind(mark); } } else { this._c = input.LA(k); } } } } protected RecognitionException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) throw new ArgumentNullException("info"); _index = info.GetInt32("Index"); _c = info.GetInt32("C"); _line = info.GetInt32("Line"); _charPositionInLine = info.GetInt32("CharPositionInLine"); _approximateLineInfo = info.GetBoolean("ApproximateLineInfo"); } /** <summary>Return the token type or char of the unexpected input element</summary> */ public virtual int UnexpectedType { get { if ( _input is ITokenStream ) { return _token.Type; } ITreeNodeStream treeNodeStream = _input as ITreeNodeStream; if ( treeNodeStream != null ) { ITreeAdaptor adaptor = treeNodeStream.TreeAdaptor; return adaptor.GetType( _node ); } return _c; } } public bool ApproximateLineInfo { get { return _approximateLineInfo; } protected set { _approximateLineInfo = value; } } public IIntStream Input { get { return _input; } protected set { _input = value; } } public int Lookahead { get { return _k; } } public IToken Token { get { return _token; } set { _token = value; } } public object Node { get { return _node; } protected set { _node = value; } } public int Character { get { return _c; } protected set { _c = value; } } public int Index { get { return _index; } protected set { _index = value; } } public int Line { get { return _line; } set { _line = value; } } public int CharPositionInLine { get { return _charPositionInLine; } set { _charPositionInLine = value; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); base.GetObjectData(info, context); info.AddValue("Index", _index); info.AddValue("C", _c); info.AddValue("Line", _line); info.AddValue("CharPositionInLine", _charPositionInLine); info.AddValue("ApproximateLineInfo", _approximateLineInfo); } protected virtual void ExtractInformationFromTreeNodeStream(ITreeNodeStream input) { this._node = input.LT(1); ITokenStreamInformation streamInformation = input as ITokenStreamInformation; if (streamInformation != null) { IToken lastToken = streamInformation.LastToken; IToken lastRealToken = streamInformation.LastRealToken; if (lastRealToken != null) { this._token = lastRealToken; this._line = lastRealToken.Line; this._charPositionInLine = lastRealToken.CharPositionInLine; this._approximateLineInfo = lastRealToken.Equals(lastToken); } } else { ITreeAdaptor adaptor = input.TreeAdaptor; IToken payload = adaptor.GetToken(_node); if (payload != null) { this._token = payload; if (payload.Line <= 0) { // imaginary node; no line/pos info; scan backwards int i = -1; object priorNode = input.LT(i); while (priorNode != null) { IToken priorPayload = adaptor.GetToken(priorNode); if (priorPayload != null && priorPayload.Line > 0) { // we found the most recent real line / pos info this._line = priorPayload.Line; this._charPositionInLine = priorPayload.CharPositionInLine; this._approximateLineInfo = true; break; } --i; try { priorNode = input.LT(i); } catch (ArgumentException) { priorNode = null; } } } else { // node created from real token this._line = payload.Line; this._charPositionInLine = payload.CharPositionInLine; } } else if (this._node is Tree.ITree) { this._line = ((Tree.ITree)this._node).Line; this._charPositionInLine = ((Tree.ITree)this._node).CharPositionInLine; if (this._node is CommonTree) { this._token = ((CommonTree)this._node).Token; } } else { int type = adaptor.GetType(this._node); string text = adaptor.GetText(this._node); this._token = new CommonToken(type, text); } } } protected virtual void ExtractInformationFromTreeNodeStream(ITreeNodeStream input, int k) { int mark = input.Mark(); try { for (int i = 0; i < k - 1; i++) input.Consume(); ExtractInformationFromTreeNodeStream(input); } finally { input.Rewind(mark); } } } }
// ReSharper disable ParameterOnlyUsedForPreconditionCheck.Local namespace BigGustave.Tests { using Xunit; using System; using System.Collections.Generic; using System.IO; using BigGustave; public class PngTests { private static readonly Pixel Tr = new Pixel(0, 0, 0, 0, false); [Fact] public void FourByFourGrayscale() { var values = new List<byte[]> { new byte[] {176, 255, 255, 176}, new byte[] {255, 0, 0, 255}, new byte[] {133, 255, 255, 133}, new byte[] {255, 176, 176, 255} }; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", "4by4grayscale.png"); using (var stream = File.OpenRead(path)) { var img = Png.Open(stream); for (var row = 0; row < values.Count; row++) { var expectedRow = values[row]; for (var col = 0; col < expectedRow.Length; col++) { var pixel = img.GetPixel(col, row); Assert.Equal(values[row][col], pixel.R); Assert.True(pixel.IsGrayscale); } } Assert.Equal(4, img.Width); Assert.Equal(4 ,img.Height); Assert.False(img.HasAlphaChannel); } } [Fact] public void TenByTenRgbAWithAdam7() { var yellow = P(255, 255, 0); var green = P(0, 255, 6); var pink = P(255, 75, 240); var red = P(255, 0, 0); var blue = P(31, 57, 255); var values = new List<Pixel[]> { new [] { Tr, Tr, yellow, yellow, yellow, yellow, yellow, yellow, yellow, yellow }, new [] { Tr, Tr, yellow, green, green, green, green, pink, yellow, yellow }, new [] { Tr, Tr, yellow, yellow, yellow, pink, red, pink, yellow, yellow }, new [] { Tr, Tr, yellow, yellow, yellow, pink, yellow, pink, yellow, yellow }, new [] { Tr, Tr, yellow, blue, pink, pink, red, pink, yellow, yellow }, new [] { Tr, Tr, yellow, blue, green, green, green, green, pink, yellow }, new [] { Tr, Tr, yellow, blue, pink, yellow, yellow, yellow, yellow, yellow }, new [] { Tr, Tr, yellow, yellow, yellow, yellow, yellow, yellow, yellow, yellow }, new [] { Tr, Tr, Tr, Tr, Tr, Tr, Tr, Tr, Tr, Tr }, new [] { Tr, Tr, Tr, Tr, Tr, Tr, Tr, Tr, Tr, Tr } }; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", "10by10rgbaadam7.png"); using (var stream = File.OpenRead(path)) { var img = Png.Open(stream); Assert.Equal(10, img.Width); Assert.Equal(10, img.Height); Assert.True(img.HasAlphaChannel); for (var row = 0; row < values.Count; row++) { var expectedRow = values[row]; for (var col = 0; col < expectedRow.Length; col++) { var pixel = img.GetPixel(col, row); Assert.True(pixel.Equals(expectedRow[col]), $"Expected {expectedRow[col]} but got {pixel}."); } } } } [Fact] public void TwelveBySevenRgbWithAdam7() { var green = P(0, 201, 52); var yellowGreen = P(81, 184, 50); var darkGreen = P(12, 140, 45); var nostrilGreen = P(54, 71, 52); var red = P(255, 37, 37); var blue = P(37, 83, 255); var white = P(255, 255, 255); var black = P(0, 0, 0); var values = new List<Pixel[]> { new [] { blue, blue, blue, blue, blue, blue, blue, blue, red, red, red, red }, new [] { blue, blue, blue, yellowGreen, green, green, blue, blue, red, red, red, red }, new [] { blue, blue, green, white, yellowGreen, white, green, blue, blue, blue, blue, blue }, new [] { blue, blue, green, black, green, black, green, green, blue, blue, blue, blue }, new [] { blue, blue, green, green, yellowGreen, green, yellowGreen, green, green, green, blue, blue }, new [] { blue, blue, darkGreen, darkGreen, darkGreen, green, green, nostrilGreen, green, nostrilGreen, blue, blue }, new [] { blue, blue, blue, blue, darkGreen, darkGreen, yellowGreen, green, green, green, blue, blue } }; var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", "12by7rgbadam7.png"); using (var stream = File.OpenRead(path)) { var img = Png.Open(stream); Assert.Equal(12, img.Width); Assert.Equal(7, img.Height); Assert.False(img.HasAlphaChannel); for (var row = 0; row < values.Count; row++) { var expectedRow = values[row]; for (var col = 0; col < expectedRow.Length; col++) { var pixel = img.GetPixel(col, row); Assert.True(pixel.Equals(expectedRow[col]), $"Expected {expectedRow[col]} but got {pixel}."); } } } } [Fact] public void LargerImage() { CheckFile("piggies", 676, 573, true); } [Fact] public void PdfPigLogo() { CheckFile("pdfpig", 294, 294, true); } [Fact] public void FinnishOpinionPollGraph() { // https://commons.wikimedia.org/wiki/File:Finnish_Opinion_Polling,_30_Day_Moving_Average,_2015-2019.png CheckFile("finnish-opinion-polling", 1181, 500, true); } [Fact] public void TwoFiveSixByTwoFiveSixPalette() { CheckFile("256by2568bppwithplte", 256, 256, false); } [Fact] public void SevenTwentyByFiveSixtySixteenBitPerChannelRgb() { CheckFile("720by560spookycave", 720, 560, false); } [Fact] public void SixteenBySixteenGrayAlphaSixteenBitPerChannel() { CheckFile("16by16graya16bit", 16, 16, true, true); } [Fact] public void SixteenBySixteenGraySixteenBitPerChannel() { CheckFile("16by16gray16bit", 16, 16, false, true); } [Fact] public void TwelveByTwentyFourRgbaSixteenBitPerChannel() { CheckFile("12by24rgba16bit", 12, 24, true); } [Fact] public void TenByNinePixelsWithPaletteSameAsNonPalette() { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", $"10by9pixelscompressedrgb8bpp.png"); var pathRaw = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", $"10by9pixelsrgb8bpp.png"); var png = Png.Open(File.ReadAllBytes(path)); var pngRaw = Png.Open(File.ReadAllBytes(pathRaw)); for (int y = 0; y < png.Height; y++) { for (int x = 0; x < png.Width; x++) { var pix = png.GetPixel(x, y); var pixRaw = pngRaw.GetPixel(x, y); Assert.Equal(pix, pixRaw); } } } [Fact] public void TenByNinePixelsWithPaletteAdditionalColorsSameAsNonPalette() { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", $"10by9pixelscompressedrgbadditionalcolors.png"); var pathRaw = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", $"10by9pixelsrgbadditionalcolors.png"); var png = Png.Open(File.ReadAllBytes(path)); var pngRaw = Png.Open(File.ReadAllBytes(pathRaw)); for (int y = 0; y < png.Height; y++) { for (int x = 0; x < png.Width; x++) { var pix = png.GetPixel(x, y); var pixRaw = pngRaw.GetPixel(x, y); Assert.Equal(pix, pixRaw); } } } private static void CheckFile(string imageName, int width, int height, bool hasAlpha, bool grayscale = false) { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", $"{imageName}.png"); using (var stream = File.OpenRead(path)) { var img = Png.Open(stream); Assert.Equal(width, img.Width); Assert.Equal(height, img.Height); Assert.Equal(hasAlpha, img.HasAlphaChannel); var data = GetImageData(imageName, grayscale); foreach (var (x, y, pixel) in data) { Assert.Equal(pixel, img.GetPixel(x, y)); } } } private static Pixel P(byte r, byte g, byte b) { return new Pixel(r, g, b, 255, false); } private static IEnumerable<(int x, int y, Pixel pixel)> GetImageData(string filename, bool grayscale) { var file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data", $"{filename}.txt"); foreach (var line in File.ReadLines(file)) { var parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries); var x = int.Parse(parts[0]); var y = int.Parse(parts[1]); var r = byte.Parse(parts[2]); var g = byte.Parse(parts[3]); var b = byte.Parse(parts[4]); var a = byte.Parse(parts[5]); yield return (x, y, new Pixel(r, g, b, a, grayscale)); } } } }
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2011 Jon Skeet // // 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 using System; using System.Globalization; using System.Text; using NodaTime.Fields; using NodaTime.Utility; namespace NodaTime.ZoneInfoCompiler.Tzdb { /// <summary> /// Contains the parsed information from one zone line of the TZDB zone database. /// </summary> /// <remarks> /// Immutable, thread-safe /// </remarks> internal class Zone : IEquatable<Zone> { private readonly int dayOfMonth; private readonly string format; private readonly int monthOfYear; private readonly string name; private readonly Offset offset; private readonly string rules; private readonly Offset tickOfDay; private readonly int year; private readonly char zoneCharacter; /// <summary> /// Initializes a new instance of the <see cref="Zone" /> class. /// </summary> public Zone(string name, Offset offset, string rules, string format, int year, int monthOfYear, int dayOfMonth, Offset tickOfDay, char zoneCharacter) { FieldUtils.VerifyFieldValue(CalendarSystem.Iso.Fields.MonthOfYear, "monthOfYear", monthOfYear); FieldUtils.VerifyFieldValue(CalendarSystem.Iso.Fields.DayOfMonth, "dayOfMonth", dayOfMonth); FieldUtils.VerifyFieldValue(CalendarSystem.Iso.Fields.TickOfDay, "tickOfDay", tickOfDay.TotalTicks); this.name = name; this.offset = offset; this.rules = rules; this.format = format; this.year = year; this.monthOfYear = monthOfYear; this.dayOfMonth = dayOfMonth; this.tickOfDay = tickOfDay; this.zoneCharacter = zoneCharacter; } internal Zone(string name, Offset offset, string rules, string format) : this(name, offset, rules, format, Int32.MaxValue, 1, 1, Offset.Zero, (char)0) { } /// <summary> /// Gets or sets the until day if defined. /// </summary> /// <value>The day number or 0.</value> internal int DayOfMonth { get { return dayOfMonth; } } /// <summary> /// Gets or sets the format for generating the label for this time zone. /// </summary> /// <value>The format string.</value> internal string Format { get { return format; } } /// <summary> /// Gets or sets the until month if defined. /// </summary> /// <value>The month or 0.</value> internal int MonthOfYear { get { return monthOfYear; } } /// <summary> /// Gets or sets the name of the time zone /// </summary> /// <value>The time zone name.</value> internal string Name { get { return name; } } /// <summary> /// Gets or sets the offset to add to UTC for this time zone. /// </summary> /// <value>The offset from UTC.</value> internal Offset Offset { get { return offset; } } /// <summary> /// Gets or sets the daylight savings rules name applicable to this zone line. /// </summary> /// <value>The rules name.</value> internal string Rules { get { return rules; } } /// <summary> /// Gets or sets the until offset time of the day if defined. /// </summary> /// <value>The offset or Offset.MinValue.</value> internal Offset TickOfDay { get { return tickOfDay; } } /// <summary> /// Gets or sets the until year if defined. /// </summary> /// <value>The until year or 0.</value> internal int Year { get { return year; } } /// <summary> /// Gets or sets the until zone character if defined. /// </summary> /// <value>The zone character or NUL.</value> internal char ZoneCharacter { get { return zoneCharacter; } } #region IEquatable<Zone> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name = "other" /> parameter; /// otherwise, false. /// </returns> public bool Equals(Zone other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } var result = Name == other.Name && Offset == other.Offset && Rules == other.Rules && Format == other.Format && Year == other.Year; if (Year != Int32.MaxValue) { result = result && MonthOfYear == other.MonthOfYear && DayOfMonth == other.DayOfMonth && TickOfDay == other.TickOfDay && ZoneCharacter == other.ZoneCharacter; } return result; } #endregion /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; /// otherwise, <c>false</c>. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name = "obj" /> parameter is null. /// </exception> public override bool Equals(object obj) { return Equals(obj as Zone); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data /// structures like a hash table. /// </returns> public override int GetHashCode() { int hash = HashCodeHelper.Initialize(); hash = HashCodeHelper.Hash(hash, Name); hash = HashCodeHelper.Hash(hash, Offset); hash = HashCodeHelper.Hash(hash, Rules); hash = HashCodeHelper.Hash(hash, Format); hash = HashCodeHelper.Hash(hash, Year); if (Year != Int32.MaxValue) { hash = HashCodeHelper.Hash(hash, MonthOfYear); hash = HashCodeHelper.Hash(hash, DayOfMonth); hash = HashCodeHelper.Hash(hash, TickOfDay); hash = HashCodeHelper.Hash(hash, ZoneCharacter); } return hash; } /// <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 builder = new StringBuilder(); builder.Append(Name).Append(" "); builder.Append(Offset.ToString()).Append(" "); builder.Append(ParserHelper.FormatOptional(Rules)).Append(" "); builder.Append(Format); if (Year != Int32.MaxValue) { builder.Append(" ").Append(Year.ToString("D4", CultureInfo.InvariantCulture)).Append(" "); if (MonthOfYear > 0) { builder.Append(" ").Append(TzdbZoneInfoParser.Months[MonthOfYear]); if (DayOfMonth > 0) { builder.Append(" ").Append(DayOfMonth.ToString("D", CultureInfo.InvariantCulture)).Append(" "); if (TickOfDay > Offset.Zero) { builder.Append(" ").Append(TickOfDay.ToString()); if (ZoneCharacter != 0) { builder.Append(ZoneCharacter); } } } } } return builder.ToString(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TimeZone ** ** ** Purpose: ** This class is used to represent a TimeZone. It ** has methods for converting a DateTime to UTC from local time ** and to local time from UTC and methods for getting the ** standard name and daylight name of the time zone. ** ** The only TimeZone that we support in version 1 is the ** CurrentTimeZone as determined by the system timezone. ** ** ============================================================*/ #if !FEATURE_CORECLR namespace System { using System; using System.Text; using System.Threading; using System.Collections; using System.Globalization; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_CORECLR [Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")] #endif public abstract class TimeZone { private static volatile TimeZone currentTimeZone = null; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } protected TimeZone() { } public static TimeZone CurrentTimeZone { get { //Grabbing the cached value is required at the top of this function so that //we don't incur a race condition with the ResetTimeZone method below. TimeZone tz = currentTimeZone; if (tz == null) { lock(InternalSyncObject) { if (currentTimeZone == null) { currentTimeZone = new CurrentSystemTimeZone(); } tz = currentTimeZone; } } return (tz); } } //This method is called by CultureInfo.ClearCachedData in response to control panel //change events. It must be synchronized because otherwise there is a race condition //with the CurrentTimeZone property above. internal static void ResetTimeZone() { if (currentTimeZone!=null) { lock(InternalSyncObject) { currentTimeZone = null; } } } public abstract String StandardName { get; } public abstract String DaylightName { get; } public abstract TimeSpan GetUtcOffset(DateTime time); // // Converts the specified datatime to the Universal time base on the current timezone // public virtual DateTime ToUniversalTime(DateTime time) { if (time.Kind == DateTimeKind.Utc) { return time; } long tickCount = time.Ticks - GetUtcOffset(time).Ticks; if (tickCount>DateTime.MaxTicks) { return new DateTime(DateTime.MaxTicks, DateTimeKind.Utc); } if (tickCount<DateTime.MinTicks) { return new DateTime(DateTime.MinTicks, DateTimeKind.Utc); } return new DateTime(tickCount, DateTimeKind.Utc); } // // Convert the specified datetime value from UTC to the local time based on the time zone. // public virtual DateTime ToLocalTime(DateTime time) { if (time.Kind == DateTimeKind.Local) { return time; } Boolean isAmbiguousLocalDst = false; Int64 offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); return new DateTime(time.Ticks + offset, DateTimeKind.Local, isAmbiguousLocalDst); } // Return an array of DaylightTime which reflects the daylight saving periods in a particular year. // We currently only support having one DaylightSavingTime per year. // If daylight saving time is not used in this timezone, null will be returned. public abstract DaylightTime GetDaylightChanges(int year); public virtual bool IsDaylightSavingTime(DateTime time) { return (IsDaylightSavingTime(time, GetDaylightChanges(time.Year))); } // Check if the specified time is in a daylight saving time. Allows the user to // specify the array of Daylight Saving Times. public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) { return CalculateUtcOffset(time, daylightTimes)!=TimeSpan.Zero; } // // NOTENOTE: Implementation detail // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 03:00) 10:00 -8:00 [This time doesn't actually exist, but it can be created from DateTime] // 03:00 10:00 -7:00 // 04:00 11:00 -7:00 // 05:00 12:00 -7:00 // // So from 02:00 - 02:59:59, we should return the standard offset, instead of the daylight saving offset. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 08:00 -7:00 // 02:00 (=> 01:00) 09:00 -8:00 // 02:00 10:00 -8:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // But note that there are two 01:00 in the local time. // // And imagine if the daylight saving offset is negative (although this does not exist in real life) // In the transition from standard time to daylight saving time, // if we convert local time to Universal time, we can have the // following (take PST as an example, but the daylight saving offset is -01:00): // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 09:00 -8:00 // 02:00 (=> 01:00) 10:00 -9:00 // 02:00 11:00 -9:00 // 03:00 12:00 -9:00 // 04:00 13:00 -9:00 // 05:00 14:00 -9:00 // // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this. // // In the transition from daylight saving time to standard time, // if we convert local time to Universal time, we can have the // following (take PST as an example, daylight saving offset is -01:00): // // Local Universal UTC Offset // ----- --------- ---------- // 01:00AM 10:00 -9:00 // 02:00 (=> 03:00) 11:00 -9:00 // 03:00 11:00 -8:00 // 04:00 12:00 -8:00 // 05:00 13:00 -8:00 // 06:00 14:00 -8:00 // // So from 02:00 - 02:59:59, we should return the daylight saving offset, instead of the standard offset. // internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { if (daylightTimes==null) { return TimeSpan.Zero; } DateTimeKind kind = time.Kind; if (kind == DateTimeKind.Utc) { return TimeSpan.Zero; } DateTime startTime; DateTime endTime; // startTime and endTime represent the period from either the start of DST to the end and includes the // potentially overlapped times startTime = daylightTimes.Start + daylightTimes.Delta; endTime = daylightTimes.End; // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the // clock back. It is theoretically possible to have a positive delta, (which would really be daylight // reduction time), where you would have to wind the clock back in the begnning. DateTime ambiguousStart; DateTime ambiguousEnd; if (daylightTimes.Delta.Ticks > 0) { ambiguousStart = endTime - daylightTimes.Delta; ambiguousEnd = endTime; } else { ambiguousStart = startTime; ambiguousEnd = startTime - daylightTimes.Delta; } Boolean isDst = false; if (startTime > endTime) { // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year. // Note, the summer in the southern hemisphere begins late in the year. if (time >= startTime || time < endTime) { isDst = true; } } else if (time>=startTime && time < endTime) { // In northern hemisphere, the daylight saving time starts in the middle of the year. isDst = true; } // If this date was previously converted from a UTC date and we were able to detect that the local // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity. if (isDst && time >= ambiguousStart && time < ambiguousEnd) { isDst = time.IsAmbiguousDaylightSavingTime(); } if (isDst) { return daylightTimes.Delta; } return TimeSpan.Zero; } } } #endif // FEATURE_CORECLR
// 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.Generic; using Scriban.Parsing; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Functions { /// <summary> /// The include function available through the function 'include' in scriban. /// </summary> public sealed partial class IncludeFunction : IScriptCustomFunction { public IncludeFunction() { } public object Invoke(TemplateContext context, ScriptNode callerContext, ScriptArray arguments, ScriptBlockStatement blockStatement) { if (arguments.Count == 0) { throw new ScriptRuntimeException(callerContext.Span, "Expecting at least the name of the template to include for the <include> function"); } var templateName = context.ObjectToString(arguments[0]); // If template name is empty, throw an exception if (string.IsNullOrEmpty(templateName)) { // In a liquid template context, we let an include to continue without failing if (context is LiquidTemplateContext) { return null; } throw new ScriptRuntimeException(callerContext.Span, $"Include template name cannot be null or empty"); } var templateLoader = context.TemplateLoader; if (templateLoader == null) { throw new ScriptRuntimeException(callerContext.Span, $"Unable to include <{templateName}>. No TemplateLoader registered in TemplateContext.TemplateLoader"); } string templatePath; try { templatePath = templateLoader.GetPath(context, callerContext.Span, templateName); } catch (Exception ex) when (!(ex is ScriptRuntimeException)) { throw new ScriptRuntimeException(callerContext.Span, $"Unexpected exception while getting the path for the include name `{templateName}`", ex); } // If template path is empty (probably because template doesn't exist), throw an exception if (templatePath == null) { throw new ScriptRuntimeException(callerContext.Span, $"Include template path is null for `{templateName}"); } string indent = null; // Handle indent if (context.IndentWithInclude) { // Find the statement for the include var current = callerContext.Parent; while (current != null && !(current is ScriptStatement)) { current = current.Parent; } // Find the RawStatement preceding this include ScriptNode childNode = null; bool shouldContinue = true; while (shouldContinue && current != null) { if (current is ScriptList<ScriptStatement> statementList && childNode is ScriptStatement childStatement) { var indexOf = statementList.IndexOf(childStatement); // Case for first indent, if it is not the first statement in the doc // it's not a valid indent if (indent != null && indexOf > 0) { indent = null; break; } for (int i = indexOf - 1; i >= 0; i--) { var previousStatement = statementList[i]; if (previousStatement is ScriptEscapeStatement escapeStatement && escapeStatement.IsEntering) { if (i > 0 && statementList[i - 1] is ScriptRawStatement rawStatement) { var text = rawStatement.Text; for (int j = text.Length - 1; j >= 0; j--) { var c = text[j]; if (c == '\n') { shouldContinue = false; indent = text.Substring(j + 1); break; } if (!char.IsWhiteSpace(c)) { shouldContinue = false; break; } if (j == 0) { // We have a raw statement that has only white spaces // It could be the first raw statement of the document // so we continue but we handle it later indent = text.ToString(); } } } else { shouldContinue = false; } break; } } } childNode = current; current = childNode.Parent; } if (string.IsNullOrEmpty(indent)) { indent = null; } } Template template; if (!context.CachedTemplates.TryGetValue(templatePath, out template)) { string templateText; try { templateText = templateLoader.Load(context, callerContext.Span, templatePath); } catch (Exception ex) when (!(ex is ScriptRuntimeException)) { throw new ScriptRuntimeException(callerContext.Span, $"Unexpected exception while loading the include `{templateName}` from path `{templatePath}`", ex); } if (templateText == null) { throw new ScriptRuntimeException(callerContext.Span, $"The result of including `{templateName}->{templatePath}` cannot be null"); } // Clone parser options var parserOptions = context.TemplateLoaderParserOptions; var lexerOptions = context.TemplateLoaderLexerOptions; template = Template.Parse(templateText, templatePath, parserOptions, lexerOptions); // If the template has any errors, throw an exception if (template.HasErrors) { throw new ScriptParserRuntimeException(callerContext.Span, $"Error while parsing template `{templateName}` from `{templatePath}`", template.Messages); } context.CachedTemplates.Add(templatePath, template); } // Make sure that we cannot recursively include a template object result = null; context.EnterRecursive(callerContext); var previousIndent = context.CurrentIndent; context.CurrentIndent = indent; context.PushOutput(); context.PushLocal(); try { context.SetValue(ScriptVariable.Arguments, arguments, true); if (indent != null) { // We reset before and after the fact that we have a new line context.ResetPreviousNewLine(); } result = template.Render(context); if (indent != null) { context.ResetPreviousNewLine(); } } finally { context.PopLocal(); context.PopOutput(); context.CurrentIndent = previousIndent; context.ExitRecursive(callerContext); } return result; } public int RequiredParameterCount => 1; public int ParameterCount => 1; public ScriptVarParamKind VarParamKind => ScriptVarParamKind.Direct; public Type ReturnType => typeof(object); public ScriptParameterInfo GetParameterInfo(int index) { if (index == 0) return new ScriptParameterInfo(typeof(string), "template_name"); return new ScriptParameterInfo(typeof(object), "value"); } public int GetParameterIndexByName(string name) { throw new NotImplementedException(); } } }
/* * Copyright (c) 2018 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Algolia.Search.Clients; using Algolia.Search.Exceptions; using Algolia.Search.Models.Common; using Algolia.Search.Models.Search; using Algolia.Search.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; namespace Algolia.Search.Test.EndToEnd.Index { [TestFixture] [Parallelizable] public class IndexingTest { private SearchIndex _index; private string _indexName; private SearchIndex _indexDeleteBy; private string _indexDeleteByName; private SearchIndex _indexDelete; private string _indexDeleteName; private SearchIndex _indexMove; private string _indexMoveName; private SearchIndex _indexClear; private string _indexClearName; private SearchIndex _indexWithJObject; private string _indexWithJObjectName; [OneTimeSetUp] public void Init() { _indexName = TestHelper.GetTestIndexName("indexing"); _index = BaseTest.SearchClient.InitIndex(_indexName); _indexDeleteByName = TestHelper.GetTestIndexName("delete_by"); _indexDeleteBy = BaseTest.SearchClient.InitIndex(_indexDeleteByName); _indexDeleteName = TestHelper.GetTestIndexName("delete"); _indexDelete = BaseTest.SearchClient.InitIndex(_indexDeleteName); _indexMoveName = TestHelper.GetTestIndexName("move_test_source"); _indexMove = BaseTest.SearchClient.InitIndex(_indexMoveName); _indexClearName = TestHelper.GetTestIndexName("clear_objects"); _indexClear = BaseTest.SearchClient.InitIndex(_indexClearName); _indexWithJObjectName = TestHelper.GetTestIndexName("indexing_with_JObject"); _indexWithJObject = BaseTest.SearchClient.InitIndex(_indexWithJObjectName); } [Test] [Parallelizable] public async Task IndexOperationsAsyncTest() { // AddObject with ID var objectOne = new AlgoliaStub { ObjectId = "one" }; var addObject = _index.SaveObjectAsync(objectOne); // AddObject without ID var objectWoId = new AlgoliaStub(); var addObjectWoId = _index.SaveObjectAsync(objectWoId, autoGenerateObjectId: true); // Save two objects with objectID var objectsWithIds = new List<AlgoliaStub> { new AlgoliaStub { ObjectId = "two" }, new AlgoliaStub { ObjectId = "three" } }; var addObjects = _index.SaveObjectsAsync(objectsWithIds); // Save two objects w/o objectIDs var objectsWoId = new List<AlgoliaStub> { new AlgoliaStub { Property = "addObjectsWoId" }, new AlgoliaStub { Property = "addObjectsWoId" } }; var addObjectsWoId = _index.SaveObjectsAsync(objectsWoId, autoGenerateObjectId: true); // Batch 1000 objects var objectsToBatch = new List<AlgoliaStub>(); var ids = new List<string>(); for (int i = 0; i < 1000; i++) { var id = (i + 1).ToString(); objectsToBatch.Add(new AlgoliaStub { ObjectId = id, Property = $"Property{id}" }); ids.Add(id); } var batch = _index.SaveObjectsAsync(objectsToBatch); // Wait for all http call to finish var responses = await Task.WhenAll(new[] { addObject, addObjectWoId, addObjects, addObjectsWoId, batch }) .ConfigureAwait(false); // Wait for Algolia's task to finish (indexing) responses.Wait(); // Six first records var generatedId = addObjectWoId.Result.Responses[0].ObjectIDs.ToList(); objectWoId.ObjectId = generatedId.ElementAt(0); var generatedIDs = addObjectsWoId.Result.Responses[0].ObjectIDs.ToList(); objectsWoId[0].ObjectId = generatedIDs.ElementAt(0); objectsWoId[1].ObjectId = generatedIDs.ElementAt(1); var settedIds = new List<string> { "one", "two", "three" }; var sixFirstRecordsIds = settedIds.Concat(generatedId).Concat(generatedIDs).ToList(); var sixFirstRecords = (await _index.GetObjectsAsync<AlgoliaStub>(sixFirstRecordsIds)).ToList(); Assert.That(sixFirstRecords, Has.Exactly(6).Items); var objectsToCompare = new List<AlgoliaStub> { objectOne }.Concat(objectsWithIds) .Concat(new List<AlgoliaStub> { objectWoId }) .Concat(objectsWoId) .ToList(); // Check retrieved objects againt original content Parallel.For(0, sixFirstRecords.Count, i => { Assert.True(TestHelper.AreObjectsEqual(sixFirstRecords[i], objectsToCompare[i])); }); // 1000 records var batchResponse = (await _index.GetObjectsAsync<AlgoliaStub>(ids)).ToList(); Assert.That(batchResponse, Has.Exactly(1000).Items); // Check retrieved objects againt original content Parallel.For(0, batchResponse.Count, i => { Assert.True(TestHelper.AreObjectsEqual(objectsToBatch[i], batchResponse[i])); }); // Browse all index to assert that we have 1006 objects var objectsBrowsed = new List<AlgoliaStub>(); foreach (var item in _index.Browse<AlgoliaStub>(new BrowseIndexQuery())) objectsBrowsed.Add(item); Assert.That(objectsBrowsed, Has.Exactly(1006).Items); // Update one object var objectToPartialUpdate = objectsToBatch.ElementAt(0); objectToPartialUpdate.Property = "PartialUpdated"; var partialUpdateObject = await _index.PartialUpdateObjectAsync(objectToPartialUpdate); partialUpdateObject.Wait(); var getUpdatedObject = await _index.GetObjectAsync<AlgoliaStub>(objectToPartialUpdate.ObjectId); Assert.That(getUpdatedObject.Property, Is.EqualTo(objectToPartialUpdate.Property)); // Update two objects var objectToPartialUpdate1 = objectsToBatch.ElementAt(1); objectToPartialUpdate1.Property = "PartialUpdated1"; var objectToPartialUpdate2 = objectsToBatch.ElementAt(2); objectToPartialUpdate2.Property = "PartialUpdated2"; var partialUpdateObjects = await _index.PartialUpdateObjectsAsync(new List<AlgoliaStub> { objectToPartialUpdate1, objectToPartialUpdate2 }); partialUpdateObjects.Wait(); var getUpdatedObjects = (await _index.GetObjectsAsync<AlgoliaStub>(new List<string> { objectToPartialUpdate1.ObjectId, objectToPartialUpdate2.ObjectId })).ToList(); Assert.That(getUpdatedObjects.ElementAt(0).Property, Is.EqualTo(objectToPartialUpdate1.Property)); Assert.That(getUpdatedObjects.ElementAt(1).Property, Is.EqualTo(objectToPartialUpdate2.Property)); // Add 1 record with saveObject with an objectID and a tag algolia and wait for the task to finish AlgoliaStub taggedRecord = new AlgoliaStub { ObjectId = "taggedObject", Tags = new List<string> { "algolia" } }; var saveTaggedObject = await _index.SaveObjectAsync(taggedRecord); saveTaggedObject.Wait(); // Delete the record containing the tag algolia with deleteBy and the tagFilters option var deleteByTaggedObject = await _index.DeleteByAsync(new Query { Filters = "algolia" }); deleteByTaggedObject.Wait(); // Delete six first objects var deleteObjects = await _index.DeleteObjectsAsync(sixFirstRecordsIds); // Assert that the objects were deleted var objectsBrowsedAfterDelete = new List<AlgoliaStub>(); deleteObjects.Wait(); foreach (var item in _index.Browse<AlgoliaStub>(new BrowseIndexQuery())) objectsBrowsedAfterDelete.Add(item); Assert.That(objectsBrowsedAfterDelete, Has.Exactly(1000).Items); // Delete remaining objects var deleteRemainingObjects = await _index.DeleteObjectsAsync(ids); deleteRemainingObjects.Wait(); // Assert that all objects were deleted var search = await _index.SearchAsync<AlgoliaStub>(new Query("")); Assert.That(search.Hits, Is.Empty); } [Test] [Parallelizable] public async Task DeleteByTest() { List<AlgoliaStub> objectsToBatch = new List<AlgoliaStub>(); List<string> ids = new List<string>(); for (int i = 0; i < 10; i++) { var id = (i + 1).ToString(); objectsToBatch.Add(new AlgoliaStub { ObjectId = id, Tags = new List<string> { "car" } }); ids.Add(id); } var batch = await _indexDeleteBy.SaveObjectsAsync(objectsToBatch); batch.Wait(); var delete = await _indexDeleteBy.DeleteObjectAsync("1"); delete.Wait(); var searchAfterDelete = await _indexDeleteBy.SearchAsync<AlgoliaStub>(new Query("")); Assert.That(searchAfterDelete.Hits, Has.Exactly(9).Items); var resp = await _indexDeleteBy.DeleteByAsync(new Query { TagFilters = new List<List<string>> { new List<string> { "car" } } }); resp.Wait(); var search = await _indexDeleteBy.SearchAsync<AlgoliaStub>(new Query("")); Assert.That(search.Hits, Is.Empty); } [Test] [Parallelizable] public async Task DeleteTest() { List<AlgoliaStub> objectsToBatch = new List<AlgoliaStub>(); List<string> ids = new List<string>(); for (int i = 0; i < 10; i++) { var id = (i + 1).ToString(); objectsToBatch.Add(new AlgoliaStub { ObjectId = id, Tags = new List<string> { "car" } }); ids.Add(id); } var batch = await _indexDelete.SaveObjectsAsync(objectsToBatch); batch.Wait(); var response = await _indexDelete.DeleteAsync(); response.Wait(); AlgoliaApiException ex = Assert.Throws<AlgoliaApiException>(() => _indexDelete.Search<AlgoliaStub>(new Query(""))); Assert.That(ex.Message.Contains("does not exist")); } [Test] [Parallelizable] public async Task ClearObjects() { List<AlgoliaStub> objectsToBatch = new List<AlgoliaStub>(); List<string> ids = new List<string>(); for (int i = 0; i < 10; i++) { var id = (i + 1).ToString(); objectsToBatch.Add(new AlgoliaStub { ObjectId = id, Tags = new List<string> { "car" } }); ids.Add(id); } var batch = await _indexClear.SaveObjectsAsync(objectsToBatch); batch.Wait(); var clear = await _indexClear.ClearObjectsAsync(); clear.Wait(); var search = await _indexClear.SearchAsync<AlgoliaStub>(new Query("")); Assert.That(search.Hits, Is.Empty); } [Test] [Parallelizable] public async Task MoveIndexTest() { var objectOne = new JObject { { "objectID", "one" } }; var addObject = await _indexMove.SaveObjectAsync(objectOne); addObject.Wait(); var indexDestName = TestHelper.GetTestIndexName("move_test_dest"); var move = await BaseTest.SearchClient.MoveIndexAsync(_indexMoveName, indexDestName); move.Wait(); var listIndices = await BaseTest.SearchClient.ListIndicesAsync(); Assert.True(listIndices.Items.Exists(x => x.Name.Equals(indexDestName))); Assert.False(listIndices.Items.Exists(x => x.Name.Equals(_indexMoveName))); } [Test] [Parallelizable] public async Task IndexOperationsAsyncWithJObjectTest() { //Add JObject with ID var objectOne = new JObject { { "objectID", "one" }, { "title", "Foo" } }; var addObject = await _indexWithJObject.SaveObjectAsync(objectOne); addObject.Wait(); //Add JObject without ID with autoGenerateObjectId var objectOneWoId = new JObject { { "title", "Bar" } }; var addObjectWoId = await _indexWithJObject.SaveObjectAsync(objectOneWoId, autoGenerateObjectId: true); addObjectWoId.Wait(); //Add JObject without ID without autoGenerateObjectId Assert.ThrowsAsync<AlgoliaApiException>(() => _indexWithJObject.SaveObjectAsync(objectOneWoId, autoGenerateObjectId: false)); //Update record with JObject var objectTwo = new JObject { { "objectID", "one" }, { "title", "Baz" } }; var updateObject = await _indexWithJObject.PartialUpdateObjectAsync(objectTwo); updateObject.Wait(); //Update record with JObject without ID var objectTwoWoId = new JObject { { "title", "Bam" } }; Assert.ThrowsAsync<AlgoliaException>(() => _indexWithJObject.PartialUpdateObjectAsync(objectTwoWoId)); // Clear the index var clear = await _indexWithJObject.ClearObjectsAsync(); clear.Wait(); //Check if index is empty var search = await _indexClear.SearchAsync<AlgoliaStub>(new Query("")); Assert.That(search.Hits, Is.Empty); } } public class AlgoliaObject { [JsonProperty(PropertyName = "objectID")] public string ObjectId { get; set; } } public class AlgoliaStub : AlgoliaObject { public string Property { get; set; } = "Default"; [JsonProperty(PropertyName = "_tags")] public List<string> Tags { get; set; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class NetworkInterfacesOperationsExtensions { /// <summary> /// The delete netwokInterface operation deletes the specified netwokInterface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static void Delete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).DeleteAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete netwokInterface operation deletes the specified netwokInterface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The delete netwokInterface operation deletes the specified netwokInterface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> public static void BeginDelete(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName) { Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).BeginDeleteAsync(resourceGroupName, networkInterfaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The delete netwokInterface operation deletes the specified netwokInterface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// expand references resources. /// </param> public static NetworkInterface Get(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string)) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).GetAsync(resourceGroupName, networkInterfaceName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> GetAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkInterface> result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put NetworkInterface operation creates/updates a networkInterface /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update NetworkInterface operation /// </param> public static NetworkInterface CreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).CreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkInterface operation creates/updates a networkInterface /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update NetworkInterface operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> CreateOrUpdateAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkInterface> result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Put NetworkInterface operation creates/updates a networkInterface /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update NetworkInterface operation /// </param> public static NetworkInterface BeginCreateOrUpdate(this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, networkInterfaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkInterface operation creates/updates a networkInterface /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update NetworkInterface operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> BeginCreateOrUpdateAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string networkInterfaceName, NetworkInterface parameters, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkInterface> result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkInterfaceName, parameters, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine from a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetVMNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine from a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfaces(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetNetworkInterfacesAsync(resourceGroupName, virtualMachineScaleSetName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListVirtualMachineScaleSetNetworkInterfacesWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// expand references resources. /// </param> public static NetworkInterface GetVirtualMachineScaleSetNetworkInterface(this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string)) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).GetVirtualMachineScaleSetNetworkInterfaceAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get ntework interface operation retreives information about the /// specified network interface in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualMachineScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='virtualmachineIndex'> /// The virtual machine index. /// </param> /// <param name='networkInterfaceName'> /// The name of the network interface. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkInterface> GetVirtualMachineScaleSetNetworkInterfaceAsync( this INetworkInterfacesOperations operations, string resourceGroupName, string virtualMachineScaleSetName, string virtualmachineIndex, string networkInterfaceName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<NetworkInterface> result = await operations.GetVirtualMachineScaleSetNetworkInterfaceWithHttpMessagesAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NetworkInterface> ListAll(this INetworkInterfacesOperations operations) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListAllAsync( this INetworkInterfacesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> public static IPage<NetworkInterface> List(this INetworkInterfacesOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListAsync( this INetworkInterfacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine from a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetVMNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine from a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetVMNetworkInterfacesNextAsync( this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListVirtualMachineScaleSetVMNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListVirtualMachineScaleSetNetworkInterfacesNext(this INetworkInterfacesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListVirtualMachineScaleSetNetworkInterfacesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list network interface operation retrieves information about all /// network interfaces in a virtual machine scale set. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListVirtualMachineScaleSetNetworkInterfacesNextAsync( this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListVirtualMachineScaleSetNetworkInterfacesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListAllNext(this INetworkInterfacesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListAllNextAsync( this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NetworkInterface> ListNext(this INetworkInterfacesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkInterfacesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The List networkInterfaces opertion retrieves all the networkInterfaces in /// a resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NetworkInterface>> ListNextAsync( this INetworkInterfacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<NetworkInterface>> result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// FolderItem /// </summary> [DataContract] public partial class FolderItem : IEquatable<FolderItem>, IValidatableObject { public FolderItem() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="FolderItem" /> class. /// </summary> /// <param name="CompletedDateTime">Specifies the date and time this item was completed..</param> /// <param name="CreatedDateTime">Indicates the date and time the item was created..</param> /// <param name="CustomFields">An optional array of strings that allows the sender to provide custom data about the recipient. This information is returned in the envelope status but otherwise not used by DocuSign. Each customField string can be a maximum of 100 characters..</param> /// <param name="Description">.</param> /// <param name="EnvelopeId">The envelope ID of the envelope status that failed to post..</param> /// <param name="EnvelopeUri">Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes..</param> /// <param name="Is21CFRPart11">When set to **true**, indicates that this module is enabled on the account..</param> /// <param name="IsSignatureProviderEnvelope">.</param> /// <param name="LastModified">.</param> /// <param name="Name">.</param> /// <param name="OwnerName">Name of the envelope owner..</param> /// <param name="PageCount">.</param> /// <param name="Password">.</param> /// <param name="SenderEmail">.</param> /// <param name="SenderName">Name of the envelope sender..</param> /// <param name="SentDateTime">The date and time the envelope was sent..</param> /// <param name="Shared">When set to **true**, this custom tab is shared..</param> /// <param name="Status">Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later..</param> /// <param name="Subject">.</param> /// <param name="TemplateId">The unique identifier of the template. If this is not provided, DocuSign will generate a value. .</param> /// <param name="Uri">.</param> public FolderItem(string CompletedDateTime = default(string), string CreatedDateTime = default(string), List<CustomFieldV2> CustomFields = default(List<CustomFieldV2>), string Description = default(string), string EnvelopeId = default(string), string EnvelopeUri = default(string), string Is21CFRPart11 = default(string), string IsSignatureProviderEnvelope = default(string), string LastModified = default(string), string Name = default(string), string OwnerName = default(string), int? PageCount = default(int?), string Password = default(string), string SenderEmail = default(string), string SenderName = default(string), string SentDateTime = default(string), string Shared = default(string), string Status = default(string), string Subject = default(string), string TemplateId = default(string), string Uri = default(string)) { this.CompletedDateTime = CompletedDateTime; this.CreatedDateTime = CreatedDateTime; this.CustomFields = CustomFields; this.Description = Description; this.EnvelopeId = EnvelopeId; this.EnvelopeUri = EnvelopeUri; this.Is21CFRPart11 = Is21CFRPart11; this.IsSignatureProviderEnvelope = IsSignatureProviderEnvelope; this.LastModified = LastModified; this.Name = Name; this.OwnerName = OwnerName; this.PageCount = PageCount; this.Password = Password; this.SenderEmail = SenderEmail; this.SenderName = SenderName; this.SentDateTime = SentDateTime; this.Shared = Shared; this.Status = Status; this.Subject = Subject; this.TemplateId = TemplateId; this.Uri = Uri; } /// <summary> /// Specifies the date and time this item was completed. /// </summary> /// <value>Specifies the date and time this item was completed.</value> [DataMember(Name="completedDateTime", EmitDefaultValue=false)] public string CompletedDateTime { get; set; } /// <summary> /// Indicates the date and time the item was created. /// </summary> /// <value>Indicates the date and time the item was created.</value> [DataMember(Name="createdDateTime", EmitDefaultValue=false)] public string CreatedDateTime { get; set; } /// <summary> /// An optional array of strings that allows the sender to provide custom data about the recipient. This information is returned in the envelope status but otherwise not used by DocuSign. Each customField string can be a maximum of 100 characters. /// </summary> /// <value>An optional array of strings that allows the sender to provide custom data about the recipient. This information is returned in the envelope status but otherwise not used by DocuSign. Each customField string can be a maximum of 100 characters.</value> [DataMember(Name="customFields", EmitDefaultValue=false)] public List<CustomFieldV2> CustomFields { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// The envelope ID of the envelope status that failed to post. /// </summary> /// <value>The envelope ID of the envelope status that failed to post.</value> [DataMember(Name="envelopeId", EmitDefaultValue=false)] public string EnvelopeId { get; set; } /// <summary> /// Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes. /// </summary> /// <value>Contains a URI for an endpoint that you can use to retrieve the envelope or envelopes.</value> [DataMember(Name="envelopeUri", EmitDefaultValue=false)] public string EnvelopeUri { get; set; } /// <summary> /// When set to **true**, indicates that this module is enabled on the account. /// </summary> /// <value>When set to **true**, indicates that this module is enabled on the account.</value> [DataMember(Name="is21CFRPart11", EmitDefaultValue=false)] public string Is21CFRPart11 { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="isSignatureProviderEnvelope", EmitDefaultValue=false)] public string IsSignatureProviderEnvelope { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="lastModified", EmitDefaultValue=false)] public string LastModified { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Name of the envelope owner. /// </summary> /// <value>Name of the envelope owner.</value> [DataMember(Name="ownerName", EmitDefaultValue=false)] public string OwnerName { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="pageCount", EmitDefaultValue=false)] public int? PageCount { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="password", EmitDefaultValue=false)] public string Password { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="senderEmail", EmitDefaultValue=false)] public string SenderEmail { get; set; } /// <summary> /// Name of the envelope sender. /// </summary> /// <value>Name of the envelope sender.</value> [DataMember(Name="senderName", EmitDefaultValue=false)] public string SenderName { get; set; } /// <summary> /// The date and time the envelope was sent. /// </summary> /// <value>The date and time the envelope was sent.</value> [DataMember(Name="sentDateTime", EmitDefaultValue=false)] public string SentDateTime { get; set; } /// <summary> /// When set to **true**, this custom tab is shared. /// </summary> /// <value>When set to **true**, this custom tab is shared.</value> [DataMember(Name="shared", EmitDefaultValue=false)] public string Shared { get; set; } /// <summary> /// Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later. /// </summary> /// <value>Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later.</value> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="subject", EmitDefaultValue=false)] public string Subject { get; set; } /// <summary> /// The unique identifier of the template. If this is not provided, DocuSign will generate a value. /// </summary> /// <value>The unique identifier of the template. If this is not provided, DocuSign will generate a value. </value> [DataMember(Name="templateId", EmitDefaultValue=false)] public string TemplateId { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="uri", EmitDefaultValue=false)] public string Uri { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class FolderItem {\n"); sb.Append(" CompletedDateTime: ").Append(CompletedDateTime).Append("\n"); sb.Append(" CreatedDateTime: ").Append(CreatedDateTime).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" EnvelopeId: ").Append(EnvelopeId).Append("\n"); sb.Append(" EnvelopeUri: ").Append(EnvelopeUri).Append("\n"); sb.Append(" Is21CFRPart11: ").Append(Is21CFRPart11).Append("\n"); sb.Append(" IsSignatureProviderEnvelope: ").Append(IsSignatureProviderEnvelope).Append("\n"); sb.Append(" LastModified: ").Append(LastModified).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" OwnerName: ").Append(OwnerName).Append("\n"); sb.Append(" PageCount: ").Append(PageCount).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" SenderEmail: ").Append(SenderEmail).Append("\n"); sb.Append(" SenderName: ").Append(SenderName).Append("\n"); sb.Append(" SentDateTime: ").Append(SentDateTime).Append("\n"); sb.Append(" Shared: ").Append(Shared).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Subject: ").Append(Subject).Append("\n"); sb.Append(" TemplateId: ").Append(TemplateId).Append("\n"); sb.Append(" Uri: ").Append(Uri).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as FolderItem); } /// <summary> /// Returns true if FolderItem instances are equal /// </summary> /// <param name="other">Instance of FolderItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(FolderItem other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CompletedDateTime == other.CompletedDateTime || this.CompletedDateTime != null && this.CompletedDateTime.Equals(other.CompletedDateTime) ) && ( this.CreatedDateTime == other.CreatedDateTime || this.CreatedDateTime != null && this.CreatedDateTime.Equals(other.CreatedDateTime) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ) && ( this.EnvelopeId == other.EnvelopeId || this.EnvelopeId != null && this.EnvelopeId.Equals(other.EnvelopeId) ) && ( this.EnvelopeUri == other.EnvelopeUri || this.EnvelopeUri != null && this.EnvelopeUri.Equals(other.EnvelopeUri) ) && ( this.Is21CFRPart11 == other.Is21CFRPart11 || this.Is21CFRPart11 != null && this.Is21CFRPart11.Equals(other.Is21CFRPart11) ) && ( this.IsSignatureProviderEnvelope == other.IsSignatureProviderEnvelope || this.IsSignatureProviderEnvelope != null && this.IsSignatureProviderEnvelope.Equals(other.IsSignatureProviderEnvelope) ) && ( this.LastModified == other.LastModified || this.LastModified != null && this.LastModified.Equals(other.LastModified) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.OwnerName == other.OwnerName || this.OwnerName != null && this.OwnerName.Equals(other.OwnerName) ) && ( this.PageCount == other.PageCount || this.PageCount != null && this.PageCount.Equals(other.PageCount) ) && ( this.Password == other.Password || this.Password != null && this.Password.Equals(other.Password) ) && ( this.SenderEmail == other.SenderEmail || this.SenderEmail != null && this.SenderEmail.Equals(other.SenderEmail) ) && ( this.SenderName == other.SenderName || this.SenderName != null && this.SenderName.Equals(other.SenderName) ) && ( this.SentDateTime == other.SentDateTime || this.SentDateTime != null && this.SentDateTime.Equals(other.SentDateTime) ) && ( this.Shared == other.Shared || this.Shared != null && this.Shared.Equals(other.Shared) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ) && ( this.Subject == other.Subject || this.Subject != null && this.Subject.Equals(other.Subject) ) && ( this.TemplateId == other.TemplateId || this.TemplateId != null && this.TemplateId.Equals(other.TemplateId) ) && ( this.Uri == other.Uri || this.Uri != null && this.Uri.Equals(other.Uri) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.CompletedDateTime != null) hash = hash * 59 + this.CompletedDateTime.GetHashCode(); if (this.CreatedDateTime != null) hash = hash * 59 + this.CreatedDateTime.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); if (this.Description != null) hash = hash * 59 + this.Description.GetHashCode(); if (this.EnvelopeId != null) hash = hash * 59 + this.EnvelopeId.GetHashCode(); if (this.EnvelopeUri != null) hash = hash * 59 + this.EnvelopeUri.GetHashCode(); if (this.Is21CFRPart11 != null) hash = hash * 59 + this.Is21CFRPart11.GetHashCode(); if (this.IsSignatureProviderEnvelope != null) hash = hash * 59 + this.IsSignatureProviderEnvelope.GetHashCode(); if (this.LastModified != null) hash = hash * 59 + this.LastModified.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.OwnerName != null) hash = hash * 59 + this.OwnerName.GetHashCode(); if (this.PageCount != null) hash = hash * 59 + this.PageCount.GetHashCode(); if (this.Password != null) hash = hash * 59 + this.Password.GetHashCode(); if (this.SenderEmail != null) hash = hash * 59 + this.SenderEmail.GetHashCode(); if (this.SenderName != null) hash = hash * 59 + this.SenderName.GetHashCode(); if (this.SentDateTime != null) hash = hash * 59 + this.SentDateTime.GetHashCode(); if (this.Shared != null) hash = hash * 59 + this.Shared.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); if (this.Subject != null) hash = hash * 59 + this.Subject.GetHashCode(); if (this.TemplateId != null) hash = hash * 59 + this.TemplateId.GetHashCode(); if (this.Uri != null) hash = hash * 59 + this.Uri.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2015-10-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Container for the parameters to the RunInstances operation. /// Launches the specified number of instances using an AMI for which you have permissions. /// /// /// <para> /// When you launch an instance, it enters the <code>pending</code> state. After the instance /// is ready for you, it enters the <code>running</code> state. To check the state of /// your instance, call <a>DescribeInstances</a>. /// </para> /// /// <para> /// If you don't specify a security group when launching an instance, Amazon EC2 uses /// the default security group. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Security /// Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// [EC2-VPC only accounts] If you don't specify a subnet in the request, we choose a /// default subnet from your default VPC for you. /// </para> /// /// <para> /// [EC2-Classic accounts] If you're launching into EC2-Classic and you don't specify /// an Availability Zone, we choose one for you. /// </para> /// /// <para> /// Linux instances have access to the public key of the key pair at boot. You can use /// this key to provide secure access to the instance. Amazon EC2 public images use this /// feature to provide secure access without passwords. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Key /// Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// You can provide optional user data when launching an instance. For more information, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html">Instance /// Metadata</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// If any of the AMIs have a product code attached for which the user has not subscribed, /// <code>RunInstances</code> fails. /// </para> /// /// <para> /// T2 instance types can only be launched into a VPC. If you do not have a default VPC, /// or if you do not specify a subnet ID in the request, <code>RunInstances</code> fails. /// </para> /// /// <para> /// For more information about troubleshooting, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_InstanceStraightToTerminated.html">What /// To Do If An Instance Immediately Terminates</a>, and <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html">Troubleshooting /// Connecting to Your Instance</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public partial class RunInstancesRequest : AmazonEC2Request { private string _additionalInfo; private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>(); private string _clientToken; private bool? _disableApiTermination; private bool? _ebsOptimized; private IamInstanceProfileSpecification _iamInstanceProfile; private string _imageId; private ShutdownBehavior _instanceInitiatedShutdownBehavior; private InstanceType _instanceType; private string _kernelId; private string _keyName; private int? _maxCount; private int? _minCount; private bool? _monitoring; private List<InstanceNetworkInterfaceSpecification> _networkInterfaces = new List<InstanceNetworkInterfaceSpecification>(); private Placement _placement; private string _privateIpAddress; private string _ramdiskId; private List<string> _securityGroupIds = new List<string>(); private List<string> _securityGroups = new List<string>(); private string _subnetId; private string _userData; /// <summary> /// Empty constructor used to set properties independently even when a simple constructor is available /// </summary> public RunInstancesRequest() { } /// <summary> /// Instantiates RunInstancesRequest with the parameterized properties /// </summary> /// <param name="imageId">The ID of the AMI, which you can get by calling <a>DescribeImages</a>.</param> /// <param name="minCount">The minimum number of instances to launch. If you specify a minimum that is more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no instances. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ.</param> /// <param name="maxCount">The maximum number of instances to launch. If you specify more instances than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible number of instances above <code>MinCount</code>. Constraints: Between 1 and the maximum number you're allowed for the specified instance type. For more information about the default limits, and how to request an increase, see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ.</param> public RunInstancesRequest(string imageId, int minCount, int maxCount) { _imageId = imageId; _minCount = minCount; _maxCount = maxCount; } /// <summary> /// Gets and sets the property AdditionalInfo. /// <para> /// Reserved. /// </para> /// </summary> public string AdditionalInfo { get { return this._additionalInfo; } set { this._additionalInfo = value; } } // Check to see if AdditionalInfo property is set internal bool IsSetAdditionalInfo() { return this._additionalInfo != null; } /// <summary> /// Gets and sets the property BlockDeviceMappings. /// <para> /// The block device mapping. /// </para> /// </summary> public List<BlockDeviceMapping> BlockDeviceMappings { get { return this._blockDeviceMappings; } set { this._blockDeviceMappings = value; } } // Check to see if BlockDeviceMappings property is set internal bool IsSetBlockDeviceMappings() { return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0; } /// <summary> /// Gets and sets the property ClientToken. /// <para> /// Unique, case-sensitive identifier you provide to ensure the idempotency of the request. /// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/Run_Instance_Idempotency.html">Ensuring /// Idempotency</a>. /// </para> /// /// <para> /// Constraints: Maximum 64 ASCII characters /// </para> /// </summary> public string ClientToken { get { return this._clientToken; } set { this._clientToken = value; } } // Check to see if ClientToken property is set internal bool IsSetClientToken() { return this._clientToken != null; } /// <summary> /// Gets and sets the property DisableApiTermination. /// <para> /// If you set this parameter to <code>true</code>, you can't terminate the instance using /// the Amazon EC2 console, CLI, or API; otherwise, you can. If you set this parameter /// to <code>true</code> and then later want to be able to terminate the instance, you /// must first change the value of the <code>disableApiTermination</code> attribute to /// <code>false</code> using <a>ModifyInstanceAttribute</a>. Alternatively, if you set /// <code>InstanceInitiatedShutdownBehavior</code> to <code>terminate</code>, you can /// terminate the instance by running the shutdown command from the instance. /// </para> /// /// <para> /// Default: <code>false</code> /// </para> /// </summary> public bool DisableApiTermination { get { return this._disableApiTermination.GetValueOrDefault(); } set { this._disableApiTermination = value; } } // Check to see if DisableApiTermination property is set internal bool IsSetDisableApiTermination() { return this._disableApiTermination.HasValue; } /// <summary> /// Gets and sets the property EbsOptimized. /// <para> /// Indicates whether the instance is optimized for EBS I/O. This optimization provides /// dedicated throughput to Amazon EBS and an optimized configuration stack to provide /// optimal EBS I/O performance. This optimization isn't available with all instance types. /// Additional usage charges apply when using an EBS-optimized instance. /// </para> /// /// <para> /// Default: <code>false</code> /// </para> /// </summary> public bool EbsOptimized { get { return this._ebsOptimized.GetValueOrDefault(); } set { this._ebsOptimized = value; } } // Check to see if EbsOptimized property is set internal bool IsSetEbsOptimized() { return this._ebsOptimized.HasValue; } /// <summary> /// Gets and sets the property IamInstanceProfile. /// <para> /// The IAM instance profile. /// </para> /// </summary> public IamInstanceProfileSpecification IamInstanceProfile { get { return this._iamInstanceProfile; } set { this._iamInstanceProfile = value; } } // Check to see if IamInstanceProfile property is set internal bool IsSetIamInstanceProfile() { return this._iamInstanceProfile != null; } /// <summary> /// Gets and sets the property ImageId. /// <para> /// The ID of the AMI, which you can get by calling <a>DescribeImages</a>. /// </para> /// </summary> public string ImageId { get { return this._imageId; } set { this._imageId = value; } } // Check to see if ImageId property is set internal bool IsSetImageId() { return this._imageId != null; } /// <summary> /// Gets and sets the property InstanceInitiatedShutdownBehavior. /// <para> /// Indicates whether an instance stops or terminates when you initiate shutdown from /// the instance (using the operating system command for system shutdown). /// </para> /// /// <para> /// Default: <code>stop</code> /// </para> /// </summary> public ShutdownBehavior InstanceInitiatedShutdownBehavior { get { return this._instanceInitiatedShutdownBehavior; } set { this._instanceInitiatedShutdownBehavior = value; } } // Check to see if InstanceInitiatedShutdownBehavior property is set internal bool IsSetInstanceInitiatedShutdownBehavior() { return this._instanceInitiatedShutdownBehavior != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance /// Types</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// Default: <code>m1.small</code> /// </para> /// </summary> public InstanceType InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property KernelId. /// <para> /// The ID of the kernel. /// </para> /// <important> /// <para> /// We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html"> /// PV-GRUB</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </important> /// </summary> public string KernelId { get { return this._kernelId; } set { this._kernelId = value; } } // Check to see if KernelId property is set internal bool IsSetKernelId() { return this._kernelId != null; } /// <summary> /// Gets and sets the property KeyName. /// <para> /// The name of the key pair. You can create a key pair using <a>CreateKeyPair</a> or /// <a>ImportKeyPair</a>. /// </para> /// <important> /// <para> /// If you do not specify a key pair, you can't connect to the instance unless you choose /// an AMI that is configured to allow users another way to log in. /// </para> /// </important> /// </summary> public string KeyName { get { return this._keyName; } set { this._keyName = value; } } // Check to see if KeyName property is set internal bool IsSetKeyName() { return this._keyName != null; } /// <summary> /// Gets and sets the property MaxCount. /// <para> /// The maximum number of instances to launch. If you specify more instances than Amazon /// EC2 can launch in the target Availability Zone, Amazon EC2 launches the largest possible /// number of instances above <code>MinCount</code>. /// </para> /// /// <para> /// Constraints: Between 1 and the maximum number you're allowed for the specified instance /// type. For more information about the default limits, and how to request an increase, /// see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How /// many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ. /// </para> /// </summary> public int MaxCount { get { return this._maxCount.GetValueOrDefault(); } set { this._maxCount = value; } } // Check to see if MaxCount property is set internal bool IsSetMaxCount() { return this._maxCount.HasValue; } /// <summary> /// Gets and sets the property MinCount. /// <para> /// The minimum number of instances to launch. If you specify a minimum that is more instances /// than Amazon EC2 can launch in the target Availability Zone, Amazon EC2 launches no /// instances. /// </para> /// /// <para> /// Constraints: Between 1 and the maximum number you're allowed for the specified instance /// type. For more information about the default limits, and how to request an increase, /// see <a href="http://aws.amazon.com/ec2/faqs/#How_many_instances_can_I_run_in_Amazon_EC2">How /// many instances can I run in Amazon EC2</a> in the Amazon EC2 General FAQ. /// </para> /// </summary> public int MinCount { get { return this._minCount.GetValueOrDefault(); } set { this._minCount = value; } } // Check to see if MinCount property is set internal bool IsSetMinCount() { return this._minCount.HasValue; } /// <summary> /// Gets and sets the property Monitoring. /// <para> /// The monitoring for the instance. /// </para> /// </summary> public bool Monitoring { get { return this._monitoring.GetValueOrDefault(); } set { this._monitoring = value; } } // Check to see if Monitoring property is set internal bool IsSetMonitoring() { return this._monitoring.HasValue; } /// <summary> /// Gets and sets the property NetworkInterfaces. /// <para> /// One or more network interfaces. /// </para> /// </summary> public List<InstanceNetworkInterfaceSpecification> NetworkInterfaces { get { return this._networkInterfaces; } set { this._networkInterfaces = value; } } // Check to see if NetworkInterfaces property is set internal bool IsSetNetworkInterfaces() { return this._networkInterfaces != null && this._networkInterfaces.Count > 0; } /// <summary> /// Gets and sets the property Placement. /// <para> /// The placement for the instance. /// </para> /// </summary> public Placement Placement { get { return this._placement; } set { this._placement = value; } } // Check to see if Placement property is set internal bool IsSetPlacement() { return this._placement != null; } /// <summary> /// Gets and sets the property PrivateIpAddress. /// <para> /// [EC2-VPC] The primary IP address. You must specify a value from the IP address range /// of the subnet. /// </para> /// /// <para> /// Only one private IP address can be designated as primary. Therefore, you can't specify /// this parameter if <code>PrivateIpAddresses.n.Primary</code> is set to <code>true</code> /// and <code>PrivateIpAddresses.n.PrivateIpAddress</code> is set to an IP address. /// </para> /// /// <para> /// Default: We select an IP address from the IP address range of the subnet. /// </para> /// </summary> public string PrivateIpAddress { get { return this._privateIpAddress; } set { this._privateIpAddress = value; } } // Check to see if PrivateIpAddress property is set internal bool IsSetPrivateIpAddress() { return this._privateIpAddress != null; } /// <summary> /// Gets and sets the property RamdiskId. /// <para> /// The ID of the RAM disk. /// </para> /// <important> /// <para> /// We recommend that you use PV-GRUB instead of kernels and RAM disks. For more information, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/UserProvidedkernels.html"> /// PV-GRUB</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </important> /// </summary> public string RamdiskId { get { return this._ramdiskId; } set { this._ramdiskId = value; } } // Check to see if RamdiskId property is set internal bool IsSetRamdiskId() { return this._ramdiskId != null; } /// <summary> /// Gets and sets the property SecurityGroupIds. /// <para> /// One or more security group IDs. You can create a security group using <a>CreateSecurityGroup</a>. /// </para> /// /// <para> /// Default: Amazon EC2 uses the default security group. /// </para> /// </summary> public List<string> SecurityGroupIds { get { return this._securityGroupIds; } set { this._securityGroupIds = value; } } // Check to see if SecurityGroupIds property is set internal bool IsSetSecurityGroupIds() { return this._securityGroupIds != null && this._securityGroupIds.Count > 0; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// [EC2-Classic, default VPC] One or more security group names. For a nondefault VPC, /// you must use security group IDs instead. /// </para> /// /// <para> /// Default: Amazon EC2 uses the default security group. /// </para> /// </summary> public List<string> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property SubnetId. /// <para> /// [EC2-VPC] The ID of the subnet to launch the instance into. /// </para> /// </summary> public string SubnetId { get { return this._subnetId; } set { this._subnetId = value; } } // Check to see if SubnetId property is set internal bool IsSetSubnetId() { return this._subnetId != null; } /// <summary> /// Gets and sets the property UserData. /// <para> /// The Base64-encoded MIME user data for the instances. /// </para> /// </summary> public string UserData { get { return this._userData; } set { this._userData = value; } } // Check to see if UserData property is set internal bool IsSetUserData() { return this._userData != null; } } }
//#define ProfileAstar using UnityEngine; using System.Text; namespace Pathfinding { [AddComponentMenu("Pathfinding/Pathfinding Debugger")] [ExecuteInEditMode] /** Debugger for the A* Pathfinding Project. * This class can be used to profile different parts of the pathfinding system * and the whole game as well to some extent. * * Clarification of the labels shown when enabled. * All memory related things profiles <b>the whole game</b> not just the A* Pathfinding System.\n * - Currently allocated: memory the GC (garbage collector) says the application has allocated right now. * - Peak allocated: maximum measured value of the above. * - Last collect peak: the last peak of 'currently allocated'. * - Allocation rate: how much the 'currently allocated' value increases per second. This value is not as reliable as you can think * it is often very random probably depending on how the GC thinks this application is using memory. * - Collection frequency: how often the GC is called. Again, the GC might decide it is better with many small collections * or with a few large collections. So you cannot really trust this variable much. * - Last collect fps: FPS during the last garbage collection, the GC will lower the fps a lot. * * - FPS: current FPS (not updated every frame for readability) * - Lowest FPS (last x): As the label says, the lowest fps of the last x frames. * * - Size: Size of the path pool. * - Total created: Number of paths of that type which has been created. Pooled paths are not counted twice. * If this value just keeps on growing and growing without an apparent stop, you are are either not pooling any paths * or you have missed to pool some path somewhere in your code. * * \see pooling * * \todo Add field showing how many graph updates are being done right now */ [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_astar_debugger.php")] public class AstarDebugger : VersionedMonoBehaviour { public int yOffset = 5; public bool show = true; public bool showInEditor = false; public bool showFPS = false; public bool showPathProfile = false; public bool showMemProfile = false; public bool showGraph = false; public int graphBufferSize = 200; /** Font to use. * A monospaced font is the best */ public Font font = null; public int fontSize = 12; StringBuilder text = new StringBuilder(); string cachedText; float lastUpdate = -999; private GraphPoint[] graph; struct GraphPoint { public float fps, memory; public bool collectEvent; } private float delayedDeltaTime = 1; private float lastCollect = 0; private float lastCollectNum = 0; private float delta = 0; private float lastDeltaTime = 0; private int allocRate = 0; private int lastAllocMemory = 0; private float lastAllocSet = -9999; private int allocMem = 0; private int collectAlloc = 0; private int peakAlloc = 0; private int fpsDropCounterSize = 200; private float[] fpsDrops; private Rect boxRect; private GUIStyle style; private Camera cam; float graphWidth = 100; float graphHeight = 100; float graphOffset = 50; public void Start () { useGUILayout = false; fpsDrops = new float[fpsDropCounterSize]; cam = GetComponent<Camera>(); if (cam == null) { cam = Camera.main; } graph = new GraphPoint[graphBufferSize]; if (Time.unscaledDeltaTime > 0) { for (int i = 0; i < fpsDrops.Length; i++) { fpsDrops[i] = 1F / Time.unscaledDeltaTime; } } } int maxVecPool = 0; int maxNodePool = 0; PathTypeDebug[] debugTypes = new PathTypeDebug[] { new PathTypeDebug("ABPath", () => PathPool.GetSize(typeof(ABPath)), () => PathPool.GetTotalCreated(typeof(ABPath))) , new PathTypeDebug("MultiTargetPath", () => PathPool.GetSize(typeof(MultiTargetPath)), () => PathPool.GetTotalCreated(typeof(MultiTargetPath))), new PathTypeDebug("RandomPath", () => PathPool.GetSize(typeof(RandomPath)), () => PathPool.GetTotalCreated(typeof(RandomPath))), new PathTypeDebug("FleePath", () => PathPool.GetSize(typeof(FleePath)), () => PathPool.GetTotalCreated(typeof(FleePath))), new PathTypeDebug("ConstantPath", () => PathPool.GetSize(typeof(ConstantPath)), () => PathPool.GetTotalCreated(typeof(ConstantPath))), new PathTypeDebug("FloodPath", () => PathPool.GetSize(typeof(FloodPath)), () => PathPool.GetTotalCreated(typeof(FloodPath))), new PathTypeDebug("FloodPathTracer", () => PathPool.GetSize(typeof(FloodPathTracer)), () => PathPool.GetTotalCreated(typeof(FloodPathTracer))) }; struct PathTypeDebug { string name; System.Func<int> getSize; System.Func<int> getTotalCreated; public PathTypeDebug (string name, System.Func<int> getSize, System.Func<int> getTotalCreated) { this.name = name; this.getSize = getSize; this.getTotalCreated = getTotalCreated; } public void Print (StringBuilder text) { int totCreated = getTotalCreated(); if (totCreated > 0) { text.Append("\n").Append((" " + name).PadRight(25)).Append(getSize()).Append("/").Append(totCreated); } } } public void LateUpdate () { if (!show || (!Application.isPlaying && !showInEditor)) return; if (Time.unscaledDeltaTime <= 0.0001f) return; int collCount = System.GC.CollectionCount(0); if (lastCollectNum != collCount) { lastCollectNum = collCount; delta = Time.realtimeSinceStartup-lastCollect; lastCollect = Time.realtimeSinceStartup; lastDeltaTime = Time.unscaledDeltaTime; collectAlloc = allocMem; } allocMem = (int)System.GC.GetTotalMemory(false); bool collectEvent = allocMem < peakAlloc; peakAlloc = !collectEvent ? allocMem : peakAlloc; if (Time.realtimeSinceStartup - lastAllocSet > 0.3F || !Application.isPlaying) { int diff = allocMem - lastAllocMemory; lastAllocMemory = allocMem; lastAllocSet = Time.realtimeSinceStartup; delayedDeltaTime = Time.unscaledDeltaTime; if (diff >= 0) { allocRate = diff; } } if (Application.isPlaying) { fpsDrops[Time.frameCount % fpsDrops.Length] = Time.unscaledDeltaTime > 0.00001f ? 1F / Time.unscaledDeltaTime : 0; int graphIndex = Time.frameCount % graph.Length; graph[graphIndex].fps = Time.unscaledDeltaTime < 0.00001f ? 1F / Time.unscaledDeltaTime : 0; graph[graphIndex].collectEvent = collectEvent; graph[graphIndex].memory = allocMem; } if (Application.isPlaying && cam != null && showGraph) { graphWidth = cam.pixelWidth*0.8f; float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0; for (int i = 0; i < graph.Length; i++) { minMem = Mathf.Min(graph[i].memory, minMem); maxMem = Mathf.Max(graph[i].memory, maxMem); minFPS = Mathf.Min(graph[i].fps, minFPS); maxFPS = Mathf.Max(graph[i].fps, maxFPS); } int currentGraphIndex = Time.frameCount % graph.Length; Matrix4x4 m = Matrix4x4.TRS(new Vector3((cam.pixelWidth - graphWidth)/2f, graphOffset, 1), Quaternion.identity, new Vector3(graphWidth, graphHeight, 1)); for (int i = 0; i < graph.Length-1; i++) { if (i == currentGraphIndex) continue; DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minMem, maxMem, graph[i].memory), Mathf.InverseLerp(minMem, maxMem, graph[i+1].memory), Color.blue); DrawGraphLine(i, m, i/(float)graph.Length, (i+1)/(float)graph.Length, Mathf.InverseLerp(minFPS, maxFPS, graph[i].fps), Mathf.InverseLerp(minFPS, maxFPS, graph[i+1].fps), Color.green); } } } void DrawGraphLine (int index, Matrix4x4 m, float x1, float x2, float y1, float y2, Color color) { Debug.DrawLine(cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x1, y1))), cam.ScreenToWorldPoint(m.MultiplyPoint3x4(new Vector3(x2, y2))), color); } public void OnGUI () { if (!show || (!Application.isPlaying && !showInEditor)) return; if (style == null) { style = new GUIStyle(); style.normal.textColor = Color.white; style.padding = new RectOffset(5, 5, 5, 5); } if (Time.realtimeSinceStartup - lastUpdate > 0.5f || cachedText == null || !Application.isPlaying) { lastUpdate = Time.realtimeSinceStartup; boxRect = new Rect(5, yOffset, 310, 40); text.Length = 0; text.AppendLine("A* Pathfinding Project Debugger"); text.Append("A* Version: ").Append(AstarPath.Version.ToString()); if (showMemProfile) { boxRect.height += 200; text.AppendLine(); text.AppendLine(); text.Append("Currently allocated".PadRight(25)); text.Append((allocMem/1000000F).ToString("0.0 MB")); text.AppendLine(); text.Append("Peak allocated".PadRight(25)); text.Append((peakAlloc/1000000F).ToString("0.0 MB")).AppendLine(); text.Append("Last collect peak".PadRight(25)); text.Append((collectAlloc/1000000F).ToString("0.0 MB")).AppendLine(); text.Append("Allocation rate".PadRight(25)); text.Append((allocRate/1000000F).ToString("0.0 MB")).AppendLine(); text.Append("Collection frequency".PadRight(25)); text.Append(delta.ToString("0.00")); text.Append("s\n"); text.Append("Last collect fps".PadRight(25)); text.Append((1F/lastDeltaTime).ToString("0.0 fps")); text.Append(" ("); text.Append(lastDeltaTime.ToString("0.000 s")); text.Append(")"); } if (showFPS) { text.AppendLine(); text.AppendLine(); var delayedFPS = delayedDeltaTime > 0.00001f ? 1F/delayedDeltaTime : 0; text.Append("FPS".PadRight(25)).Append(delayedFPS.ToString("0.0 fps")); float minFps = Mathf.Infinity; for (int i = 0; i < fpsDrops.Length; i++) if (fpsDrops[i] < minFps) minFps = fpsDrops[i]; text.AppendLine(); text.Append(("Lowest fps (last " + fpsDrops.Length + ")").PadRight(25)).Append(minFps.ToString("0.0")); } if (showPathProfile) { AstarPath astar = AstarPath.active; text.AppendLine(); if (astar == null) { text.Append("\nNo AstarPath Object In The Scene"); } else { #if ProfileAstar double searchSpeed = (double)AstarPath.TotalSearchedNodes*10000 / (double)AstarPath.TotalSearchTime; text.Append("\nSearch Speed (nodes/ms) ").Append(searchSpeed.ToString("0")).Append(" ("+AstarPath.TotalSearchedNodes+" / ").Append(((double)AstarPath.TotalSearchTime/10000F).ToString("0")+")"); #endif if (Pathfinding.Util.ListPool<Vector3>.GetSize() > maxVecPool) maxVecPool = Pathfinding.Util.ListPool<Vector3>.GetSize(); if (Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize() > maxNodePool) maxNodePool = Pathfinding.Util.ListPool<Pathfinding.GraphNode>.GetSize(); text.Append("\nPool Sizes (size/total created)"); for (int i = 0; i < debugTypes.Length; i++) { debugTypes[i].Print(text); } } } cachedText = text.ToString(); } if (font != null) { style.font = font; style.fontSize = fontSize; } boxRect.height = style.CalcHeight(new GUIContent(cachedText), boxRect.width); GUI.Box(boxRect, ""); GUI.Label(boxRect, cachedText, style); if (showGraph) { float minMem = float.PositiveInfinity, maxMem = 0, minFPS = float.PositiveInfinity, maxFPS = 0; for (int i = 0; i < graph.Length; i++) { minMem = Mathf.Min(graph[i].memory, minMem); maxMem = Mathf.Max(graph[i].memory, maxMem); minFPS = Mathf.Min(graph[i].fps, minFPS); maxFPS = Mathf.Max(graph[i].fps, maxFPS); } float line; GUI.color = Color.blue; // Round to nearest x.x MB line = Mathf.RoundToInt(maxMem/(100.0f*1000)); GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB")); line = Mathf.Round(minMem/(100.0f*1000)); GUI.Label(new Rect(5, Screen.height - AstarMath.MapTo(minMem, maxMem, 0 + graphOffset, graphHeight + graphOffset, line*1000*100) - 10, 100, 20), (line/10.0f).ToString("0.0 MB")); GUI.color = Color.green; // Round to nearest x.x MB line = Mathf.Round(maxFPS); GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS")); line = Mathf.Round(minFPS); GUI.Label(new Rect(55, Screen.height - AstarMath.MapTo(minFPS, maxFPS, 0 + graphOffset, graphHeight + graphOffset, line) - 10, 100, 20), line.ToString("0 FPS")); } } } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: DocFolderColl // ObjectType: DocFolderColl // CSLAType: EditableChildCollection using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; using Csla.Rules; using Csla.Rules.CommonRules; namespace DocStore.Business { /// <summary> /// Collection of folders where this document is archived (editable child list).<br/> /// This is a generated <see cref="DocFolderColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="Doc"/> editable root object.<br/> /// The items of the collection are <see cref="DocFolder"/> objects. /// </remarks> [Serializable] #if WINFORMS public partial class DocFolderColl : BusinessBindingListBase<DocFolderColl, DocFolder> #else public partial class DocFolderColl : BusinessListBase<DocFolderColl, DocFolder> #endif { #region Collection Business Methods /// <summary> /// Adds a new <see cref="DocFolder"/> item to the collection. /// </summary> /// <param name="item">The item to add.</param> /// <exception cref="System.Security.SecurityException">if the user isn't authorized to add items to the collection.</exception> /// <exception cref="ArgumentException">if the item already exists in the collection.</exception> public new void Add(DocFolder item) { if (!CanAddObject()) throw new System.Security.SecurityException("User not authorized to create a DocFolder."); if (Contains(item.FolderID)) throw new ArgumentException("DocFolder already exists."); base.Add(item); } /// <summary> /// Removes a <see cref="DocFolder"/> item from the collection. /// </summary> /// <param name="item">The item to remove.</param> /// <returns><c>true</c> if the item was removed from the collection, otherwise <c>false</c>.</returns> /// <exception cref="System.Security.SecurityException">if the user isn't authorized to remove items from the collection.</exception> public new bool Remove(DocFolder item) { if (!CanDeleteObject()) throw new System.Security.SecurityException("User not authorized to remove a DocFolder."); return base.Remove(item); } /// <summary> /// Adds a new <see cref="DocFolder"/> item to the collection. /// </summary> /// <param name="folderID">The FolderID of the object to be added.</param> /// <returns>The new DocFolder item added to the collection.</returns> public DocFolder Add(int folderID) { var item = DocFolder.NewDocFolder(folderID); Add(item); return item; } /// <summary> /// Asynchronously adds a new <see cref="DocFolder"/> item to the collection. /// </summary> /// <param name="folderID">The FolderID of the object to be added.</param> public void BeginAdd(int folderID) { DocFolder docFolder = null; DocFolder.NewDocFolder(folderID, (o, e) => { if (e.Error != null) throw e.Error; else docFolder = e.Object; }); Add(docFolder); } /// <summary> /// Removes a <see cref="DocFolder"/> item from the collection. /// </summary> /// <param name="folderID">The FolderID of the item to be removed.</param> public void Remove(int folderID) { foreach (var docFolder in this) { if (docFolder.FolderID == folderID) { Remove(docFolder); break; } } } /// <summary> /// Determines whether a <see cref="DocFolder"/> item is in the collection. /// </summary> /// <param name="folderID">The FolderID of the item to search for.</param> /// <returns><c>true</c> if the DocFolder is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int folderID) { foreach (var docFolder in this) { if (docFolder.FolderID == folderID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="DocFolder"/> item is in the collection's DeletedList. /// </summary> /// <param name="folderID">The FolderID of the item to search for.</param> /// <returns><c>true</c> if the DocFolder is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int folderID) { foreach (var docFolder in DeletedList) { if (docFolder.FolderID == folderID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="DocFolder"/> item of the <see cref="DocFolderColl"/> collection, based on a given FolderID. /// </summary> /// <param name="folderID">The FolderID.</param> /// <returns>A <see cref="DocFolder"/> object.</returns> public DocFolder FindDocFolderByFolderID(int folderID) { for (var i = 0; i < this.Count; i++) { if (this[i].FolderID.Equals(folderID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="DocFolderColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="DocFolderColl"/> collection.</returns> internal static DocFolderColl NewDocFolderColl() { return DataPortal.CreateChild<DocFolderColl>(); } /// <summary> /// Factory method. Loads a <see cref="DocFolderColl"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="DocFolderColl"/> object.</returns> internal static DocFolderColl GetDocFolderColl(SafeDataReader dr) { if (!CanGetObject()) throw new System.Security.SecurityException("User not authorized to load a DocFolderColl."); DocFolderColl obj = new DocFolderColl(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); return obj; } /// <summary> /// Factory method. Asynchronously creates a new <see cref="DocFolderColl"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> internal static void NewDocFolderColl(EventHandler<DataPortalResult<DocFolderColl>> callback) { DataPortal.BeginCreate<DocFolderColl>(callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DocFolderColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DocFolderColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = DocFolderColl.CanAddObject(); AllowEdit = DocFolderColl.CanEditObject(); AllowRemove = DocFolderColl.CanDeleteObject(); RaiseListChangedEvents = rlce; } #endregion #region Object Authorization /// <summary> /// Adds the object authorization rules. /// </summary> protected static void AddObjectAuthorizationRules() { BusinessRules.AddRule(typeof (DocFolderColl), new IsInRole(AuthorizationActions.CreateObject, "Archivist")); BusinessRules.AddRule(typeof (DocFolderColl), new IsInRole(AuthorizationActions.GetObject, "User")); BusinessRules.AddRule(typeof (DocFolderColl), new IsInRole(AuthorizationActions.EditObject, "Author")); BusinessRules.AddRule(typeof (DocFolderColl), new IsInRole(AuthorizationActions.DeleteObject, "Admin", "Manager")); AddObjectAuthorizationRulesExtend(); } /// <summary> /// Allows the set up of custom object authorization rules. /// </summary> static partial void AddObjectAuthorizationRulesExtend(); /// <summary> /// Checks if the current user can create a new DocFolderColl object. /// </summary> /// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns> public static bool CanAddObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(DocFolderColl)); } /// <summary> /// Checks if the current user can retrieve DocFolderColl's properties. /// </summary> /// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns> public static bool CanGetObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(DocFolderColl)); } /// <summary> /// Checks if the current user can change DocFolderColl's properties. /// </summary> /// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns> public static bool CanEditObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(DocFolderColl)); } /// <summary> /// Checks if the current user can delete a DocFolderColl object. /// </summary> /// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns> public static bool CanDeleteObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(DocFolderColl)); } #endregion #region Data Access /// <summary> /// Loads all <see cref="DocFolderColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; var args = new DataPortalHookArgs(dr); OnFetchPre(args); while (dr.Read()) { Add(DocFolder.GetDocFolder(dr)); } OnFetchPost(args); RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// OrderTrackingNumberDetail /// </summary> [DataContract] public partial class OrderTrackingNumberDetail : IEquatable<OrderTrackingNumberDetail>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="OrderTrackingNumberDetail" /> class. /// </summary> /// <param name="city">city.</param> /// <param name="eventDts">ISO 8601 timestamp that the event occurred.</param> /// <param name="eventLocalDate">eventLocalDate.</param> /// <param name="eventLocalTime">eventLocalTime.</param> /// <param name="eventTimezoneId">Timezone the event occurred in. Use this in conjunction with event_dts to format a local date/time..</param> /// <param name="state">state.</param> /// <param name="subtag">subtag.</param> /// <param name="subtagMessage">subtagMessage.</param> /// <param name="tag">tag.</param> /// <param name="tagDescription">tagDescription.</param> /// <param name="tagIcon">tagIcon.</param> /// <param name="zip">zip.</param> public OrderTrackingNumberDetail(string city = default(string), string eventDts = default(string), string eventLocalDate = default(string), string eventLocalTime = default(string), string eventTimezoneId = default(string), string state = default(string), string subtag = default(string), string subtagMessage = default(string), string tag = default(string), string tagDescription = default(string), string tagIcon = default(string), string zip = default(string)) { this.City = city; this.EventDts = eventDts; this.EventLocalDate = eventLocalDate; this.EventLocalTime = eventLocalTime; this.EventTimezoneId = eventTimezoneId; this.State = state; this.Subtag = subtag; this.SubtagMessage = subtagMessage; this.Tag = tag; this.TagDescription = tagDescription; this.TagIcon = tagIcon; this.Zip = zip; } /// <summary> /// Gets or Sets City /// </summary> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// ISO 8601 timestamp that the event occurred /// </summary> /// <value>ISO 8601 timestamp that the event occurred</value> [DataMember(Name="event_dts", EmitDefaultValue=false)] public string EventDts { get; set; } /// <summary> /// Gets or Sets EventLocalDate /// </summary> [DataMember(Name="event_local_date", EmitDefaultValue=false)] public string EventLocalDate { get; set; } /// <summary> /// Gets or Sets EventLocalTime /// </summary> [DataMember(Name="event_local_time", EmitDefaultValue=false)] public string EventLocalTime { get; set; } /// <summary> /// Timezone the event occurred in. Use this in conjunction with event_dts to format a local date/time. /// </summary> /// <value>Timezone the event occurred in. Use this in conjunction with event_dts to format a local date/time.</value> [DataMember(Name="event_timezone_id", EmitDefaultValue=false)] public string EventTimezoneId { get; set; } /// <summary> /// Gets or Sets State /// </summary> [DataMember(Name="state", EmitDefaultValue=false)] public string State { get; set; } /// <summary> /// Gets or Sets Subtag /// </summary> [DataMember(Name="subtag", EmitDefaultValue=false)] public string Subtag { get; set; } /// <summary> /// Gets or Sets SubtagMessage /// </summary> [DataMember(Name="subtag_message", EmitDefaultValue=false)] public string SubtagMessage { get; set; } /// <summary> /// Gets or Sets Tag /// </summary> [DataMember(Name="tag", EmitDefaultValue=false)] public string Tag { get; set; } /// <summary> /// Gets or Sets TagDescription /// </summary> [DataMember(Name="tag_description", EmitDefaultValue=false)] public string TagDescription { get; set; } /// <summary> /// Gets or Sets TagIcon /// </summary> [DataMember(Name="tag_icon", EmitDefaultValue=false)] public string TagIcon { get; set; } /// <summary> /// Gets or Sets Zip /// </summary> [DataMember(Name="zip", EmitDefaultValue=false)] public string Zip { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderTrackingNumberDetail {\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" EventDts: ").Append(EventDts).Append("\n"); sb.Append(" EventLocalDate: ").Append(EventLocalDate).Append("\n"); sb.Append(" EventLocalTime: ").Append(EventLocalTime).Append("\n"); sb.Append(" EventTimezoneId: ").Append(EventTimezoneId).Append("\n"); sb.Append(" State: ").Append(State).Append("\n"); sb.Append(" Subtag: ").Append(Subtag).Append("\n"); sb.Append(" SubtagMessage: ").Append(SubtagMessage).Append("\n"); sb.Append(" Tag: ").Append(Tag).Append("\n"); sb.Append(" TagDescription: ").Append(TagDescription).Append("\n"); sb.Append(" TagIcon: ").Append(TagIcon).Append("\n"); sb.Append(" Zip: ").Append(Zip).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderTrackingNumberDetail); } /// <summary> /// Returns true if OrderTrackingNumberDetail instances are equal /// </summary> /// <param name="input">Instance of OrderTrackingNumberDetail to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderTrackingNumberDetail input) { if (input == null) return false; return ( this.City == input.City || (this.City != null && this.City.Equals(input.City)) ) && ( this.EventDts == input.EventDts || (this.EventDts != null && this.EventDts.Equals(input.EventDts)) ) && ( this.EventLocalDate == input.EventLocalDate || (this.EventLocalDate != null && this.EventLocalDate.Equals(input.EventLocalDate)) ) && ( this.EventLocalTime == input.EventLocalTime || (this.EventLocalTime != null && this.EventLocalTime.Equals(input.EventLocalTime)) ) && ( this.EventTimezoneId == input.EventTimezoneId || (this.EventTimezoneId != null && this.EventTimezoneId.Equals(input.EventTimezoneId)) ) && ( this.State == input.State || (this.State != null && this.State.Equals(input.State)) ) && ( this.Subtag == input.Subtag || (this.Subtag != null && this.Subtag.Equals(input.Subtag)) ) && ( this.SubtagMessage == input.SubtagMessage || (this.SubtagMessage != null && this.SubtagMessage.Equals(input.SubtagMessage)) ) && ( this.Tag == input.Tag || (this.Tag != null && this.Tag.Equals(input.Tag)) ) && ( this.TagDescription == input.TagDescription || (this.TagDescription != null && this.TagDescription.Equals(input.TagDescription)) ) && ( this.TagIcon == input.TagIcon || (this.TagIcon != null && this.TagIcon.Equals(input.TagIcon)) ) && ( this.Zip == input.Zip || (this.Zip != null && this.Zip.Equals(input.Zip)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.City != null) hashCode = hashCode * 59 + this.City.GetHashCode(); if (this.EventDts != null) hashCode = hashCode * 59 + this.EventDts.GetHashCode(); if (this.EventLocalDate != null) hashCode = hashCode * 59 + this.EventLocalDate.GetHashCode(); if (this.EventLocalTime != null) hashCode = hashCode * 59 + this.EventLocalTime.GetHashCode(); if (this.EventTimezoneId != null) hashCode = hashCode * 59 + this.EventTimezoneId.GetHashCode(); if (this.State != null) hashCode = hashCode * 59 + this.State.GetHashCode(); if (this.Subtag != null) hashCode = hashCode * 59 + this.Subtag.GetHashCode(); if (this.SubtagMessage != null) hashCode = hashCode * 59 + this.SubtagMessage.GetHashCode(); if (this.Tag != null) hashCode = hashCode * 59 + this.Tag.GetHashCode(); if (this.TagDescription != null) hashCode = hashCode * 59 + this.TagDescription.GetHashCode(); if (this.TagIcon != null) hashCode = hashCode * 59 + this.TagIcon.GetHashCode(); if (this.Zip != null) hashCode = hashCode * 59 + this.Zip.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
namespace Epi.Windows.MakeView.Dialogs.CheckCodeCommandDialogs { partial class GeocodeDialog { /// <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(GeocodeDialog)); this.btnHelp = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOk = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.cbxAddress = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.cbxLatitude = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.cbxLongitude = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.Name = "btnOk"; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // cbxAddress // this.cbxAddress.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxAddress.FormattingEnabled = true; resources.ApplyResources(this.cbxAddress, "cbxAddress"); this.cbxAddress.Name = "cbxAddress"; this.cbxAddress.SelectedIndexChanged += new System.EventHandler(this.cbxAddress_SelectedIndexChanged); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // cbxLatitude // this.cbxLatitude.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxLatitude.FormattingEnabled = true; resources.ApplyResources(this.cbxLatitude, "cbxLatitude"); this.cbxLatitude.Name = "cbxLatitude"; this.cbxLatitude.SelectedIndexChanged += new System.EventHandler(this.cbxAddress_SelectedIndexChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // cbxLongitude // this.cbxLongitude.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxLongitude.FormattingEnabled = true; resources.ApplyResources(this.cbxLongitude, "cbxLongitude"); this.cbxLongitude.Name = "cbxLongitude"; this.cbxLongitude.SelectedIndexChanged += new System.EventHandler(this.cbxAddress_SelectedIndexChanged); // // GeocodeDialog // this.AcceptButton = this.btnOk; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.cbxLongitude); this.Controls.Add(this.label3); this.Controls.Add(this.cbxLatitude); this.Controls.Add(this.label2); this.Controls.Add(this.cbxAddress); this.Controls.Add(this.label1); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "GeocodeDialog"; this.ShowInTaskbar = false; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cbxAddress; private System.Windows.Forms.Label label2; private System.Windows.Forms.ComboBox cbxLatitude; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox cbxLongitude; } }
using System; using System.Text; using NDatabase.Exceptions; using NDatabase.Tool; using NDatabase.Tool.Wrappers; namespace NDatabase.IO { /// <summary> /// Class allowing buffering for IO This class is used to give /// a transparent access to buffered file io /// </summary> internal sealed class MultiBufferedFileIO : IMultiBufferedFileIO { private const bool IsReading = true; private const bool IsWriting = false; private IMultiBuffer _buffer; private int _currentBufferIndex; private long _currentPositionWhenUsingBuffer = -1; /// <summary> /// The length of the io device /// </summary> private long _ioDeviceLength; /// <summary> /// A boolean value to check if read write are using buffer /// </summary> private readonly bool _isUsingBuffer; private int _nextBufferIndex; private INonBufferedFileIO _nonBufferedFileIO; private int[] _overlappingBuffers = new int[MultiBuffer.NumberOfBuffers]; public MultiBufferedFileIO(string fileName, int bufferSize) { _isUsingBuffer = true; _buffer = new MultiBuffer(bufferSize); _nonBufferedFileIO = new NonBufferedFileIO(fileName); try { _ioDeviceLength = _nonBufferedFileIO.Length; } catch (Exception e) { throw new OdbRuntimeException(NDatabaseError.InternalError, e); } } public MultiBufferedFileIO(int bufferSize) { _isUsingBuffer = false; _buffer = new MultiBuffer(bufferSize); _nonBufferedFileIO = new NonBufferedFileIO(); try { _ioDeviceLength = _nonBufferedFileIO.Length; } catch (Exception e) { throw new OdbRuntimeException(NDatabaseError.InternalError, e); } } #region IMultiBufferedFileIO Members public long Length { get { return _isUsingBuffer ? _ioDeviceLength : _nonBufferedFileIO.Length; } } public long CurrentPosition { get { return _isUsingBuffer ? _currentPositionWhenUsingBuffer : _nonBufferedFileIO.CurrentPositionForDirectWrite; } } public void SetCurrentWritePosition(long currentPosition) { SetCurrentPosition(currentPosition, () => { }); } public void SetCurrentReadPosition(long currentPosition) { SetCurrentPosition(currentPosition, () => ManageBufferForNewPosition(currentPosition, IsReading, 1)); } public void WriteByte(byte b) { if (!_isUsingBuffer) { _nonBufferedFileIO.WriteByte(b); return; } var bufferIndex = _buffer.GetBufferIndexForPosition(_currentPositionWhenUsingBuffer, 1); if (bufferIndex == -1) bufferIndex = ManageBufferForNewPosition(_currentPositionWhenUsingBuffer, IsWriting, 1); var positionInBuffer = (int) (_currentPositionWhenUsingBuffer - _buffer.BufferPositions[bufferIndex].Start); _buffer.SetByte(bufferIndex, positionInBuffer, b); _currentPositionWhenUsingBuffer++; if (_currentPositionWhenUsingBuffer > _ioDeviceLength) _ioDeviceLength = _currentPositionWhenUsingBuffer; } public byte[] ReadBytes(int size) { if (!_isUsingBuffer) return _nonBufferedFileIO.ReadBytes(size); var bytes = new byte[size]; // If the size to read is smaller than the buffer size if (size <= _buffer.Size) return ReadBytes(bytes, 0, size); // else the read have to use various buffers var nbBuffersNeeded = bytes.Length / _buffer.Size + 1; var currentStart = 0; var currentEnd = _buffer.Size; for (var i = 0; i < nbBuffersNeeded; i++) { ReadBytes(bytes, currentStart, currentEnd); currentStart += _buffer.Size; if (currentEnd + _buffer.Size < bytes.Length) currentEnd += _buffer.Size; else currentEnd = bytes.Length; } return bytes; } public byte ReadByte() { if (!_isUsingBuffer) return _nonBufferedFileIO.ReadByte(); var bufferIndex = ManageBufferForNewPosition(_currentPositionWhenUsingBuffer, IsReading, 1); var positionInBuffer = (int) (_currentPositionWhenUsingBuffer - _buffer.BufferPositions[bufferIndex].Start); var result = _buffer.Buffers[bufferIndex][positionInBuffer]; _currentPositionWhenUsingBuffer++; return result; } public void WriteBytes(byte[] bytes) { if (bytes.Length > _buffer.Size) { var nbBuffersNeeded = bytes.Length / _buffer.Size + 1; var currentStart = 0; var currentEnd = _buffer.Size; for (var i = 0; i < nbBuffersNeeded; i++) { WriteBytes(bytes, currentStart, currentEnd); currentStart += _buffer.Size; if (currentEnd + _buffer.Size < bytes.Length) currentEnd += _buffer.Size; else currentEnd = bytes.Length; } } else WriteBytes(bytes, 0, bytes.Length); } public void FlushAll() { for (var i = 0; i < MultiBuffer.NumberOfBuffers; i++) Flush(i); } public void Close() { Clear(); _nonBufferedFileIO.Dispose(); _nonBufferedFileIO = null; } public void Dispose() { Close(); } #endregion private void SetCurrentPosition(long currentPosition, Action additionalAction) { if (_isUsingBuffer) { if (_currentPositionWhenUsingBuffer == currentPosition) return; _currentPositionWhenUsingBuffer = currentPosition; additionalAction(); } else _nonBufferedFileIO.SetCurrentPosition(currentPosition); } private int ManageBufferForNewPosition(long newPosition, bool isReading, int size) { var bufferIndex = _buffer.GetBufferIndexForPosition(newPosition, size); if (bufferIndex != -1) return bufferIndex; // checks if there is any overlapping buffer _overlappingBuffers = GetOverlappingBuffers(newPosition, _buffer.Size); // Choose the first overlapping buffer bufferIndex = _overlappingBuffers[0]; if (_overlappingBuffers[1] != -1 && bufferIndex == _currentBufferIndex) bufferIndex = _overlappingBuffers[1]; if (bufferIndex == -1) { bufferIndex = _nextBufferIndex; _nextBufferIndex = (_nextBufferIndex + 1) % MultiBuffer.NumberOfBuffers; if (bufferIndex == _currentBufferIndex) { bufferIndex = _nextBufferIndex; _nextBufferIndex = (_nextBufferIndex + 1) % MultiBuffer.NumberOfBuffers; } Flush(bufferIndex); } _currentBufferIndex = bufferIndex; var length = Length; if (isReading && newPosition >= length) { var message = string.Concat("MultiBufferedFileIO: End Of File reached - position = ", newPosition.ToString(), " : Length = ", length.ToString()); DLogger.Error(message); throw new OdbRuntimeException( NDatabaseError.EndOfFileReached.AddParameter(newPosition).AddParameter(length)); } // The buffer must be initialized with real data, so the first thing we // must do is read data from file and puts it in the array long nread = _buffer.Size; // if new position is in the file if (newPosition < length) { // We are in the file, we are updating content. to create the // buffer, we first read the content of the file // Actually loads data from the file to the buffer nread = _nonBufferedFileIO.Read(newPosition, _buffer.Buffers[bufferIndex], _buffer.Size); _buffer.SetCreationDate(bufferIndex, OdbTime.GetCurrentTimeInTicks()); } else _nonBufferedFileIO.SetCurrentPosition(newPosition); // If we are in READ, sets the size equal to what has been read var endPosition = isReading ? newPosition + nread : newPosition + _buffer.Size; _buffer.SetPositions(bufferIndex, newPosition, endPosition); _currentPositionWhenUsingBuffer = newPosition; return bufferIndex; } private void Flush(int bufferIndex) { var buffer = _buffer.Buffers[bufferIndex]; if (buffer != null && _buffer.HasBeenUsedForWrite(bufferIndex)) { // the +1 is because the maxPositionInBuffer is a position and the // parameter is a length var bufferSizeToFlush = _buffer.MaxPositionInBuffer[bufferIndex] + 1; _nonBufferedFileIO.SetCurrentPosition(_buffer.BufferPositions[bufferIndex].Start); _nonBufferedFileIO.WriteBytes(buffer, bufferSizeToFlush); _buffer.ClearBuffer(bufferIndex); } else { _buffer.ClearBuffer(bufferIndex); } } private void Clear() { FlushAll(); _buffer.Clear(); _buffer = null; _overlappingBuffers = null; } /// <summary> /// Check if a new buffer starting at position with a size ='size' would overlap with an existing buffer /// </summary> /// <param name="position"> </param> /// <param name="size"> </param> /// <returns> @ </returns> private int[] GetOverlappingBuffers(long position, int size) { var start1 = position; var end1 = position + size; var indexes = new int[MultiBuffer.NumberOfBuffers]; var index = 0; for (var i = 0; i < MultiBuffer.NumberOfBuffers; i++) { var start2 = _buffer.BufferPositions[i].Start; var end2 = _buffer.BufferPositions[i].End; if ((start1 >= start2 && start1 < end2) || (start2 >= start1 && start2 < end1) || start2 <= start1 && end2 >= end1) { // This buffer is overlapping the buffer indexes[index++] = i; // Flushes the buffer Flush(i); } } for (var i = index; i < MultiBuffer.NumberOfBuffers; i++) indexes[i] = -1; return indexes; } private byte[] ReadBytes(byte[] bytes, int startIndex, int endIndex) { var size = endIndex - startIndex; var bufferIndex = ManageBufferForNewPosition(_currentPositionWhenUsingBuffer, IsReading, size); var start = (int) (_currentPositionWhenUsingBuffer - _buffer.BufferPositions[bufferIndex].Start); var buffer = _buffer.Buffers[bufferIndex]; Buffer.BlockCopy(buffer, start, bytes, startIndex, size); _currentPositionWhenUsingBuffer += size; return bytes; } private void WriteBytes(byte[] bytes, int startIndex, int endIndex) { if (!_isUsingBuffer) { _nonBufferedFileIO.WriteBytes(bytes, bytes.Length); return; } var lengthToCopy = endIndex - startIndex; var bufferIndex = ManageBufferForNewPosition(_currentPositionWhenUsingBuffer, IsWriting, lengthToCopy); var positionInBuffer = (int) (_currentPositionWhenUsingBuffer - _buffer.BufferPositions[bufferIndex].Start); _buffer.WriteBytes(bufferIndex, bytes, startIndex, positionInBuffer, lengthToCopy); _currentPositionWhenUsingBuffer += lengthToCopy; if (_currentPositionWhenUsingBuffer > _ioDeviceLength) _ioDeviceLength = _currentPositionWhenUsingBuffer; } public override string ToString() { var buffer = new StringBuilder(); buffer.Append("Buffers=").Append("currbuffer=").Append(_currentBufferIndex).Append(" : \n"); for (var i = 0; i < MultiBuffer.NumberOfBuffers; i++) { buffer.Append(i).Append(":[").Append(_buffer.BufferPositions[i].Start).Append(",").Append( _buffer.BufferPositions[i].End).Append("] : write=").Append(_buffer.HasBeenUsedForWrite(i)).Append( " - when=").Append(_buffer.GetCreationDate(i)); if (i + 1 < MultiBuffer.NumberOfBuffers) buffer.Append("\n"); } return buffer.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace System.Runtime.Serialization { internal static class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static XmlQualifiedName s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } private static XmlQualifiedName s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } private static Type s_typeOfObject; internal static Type TypeOfObject { get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } private static Type s_typeOfValueType; internal static Type TypeOfValueType { get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } private static Type s_typeOfArray; internal static Type TypeOfArray { get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } private static Type s_typeOfException; internal static Type TypeOfException { get { if (s_typeOfException == null) s_typeOfException = typeof(Exception); return s_typeOfException; } } private static Type s_typeOfString; internal static Type TypeOfString { get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } private static Type s_typeOfInt; internal static Type TypeOfInt { get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } private static Type s_typeOfULong; internal static Type TypeOfULong { get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } private static Type s_typeOfVoid; internal static Type TypeOfVoid { get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } private static Type s_typeOfByteArray; internal static Type TypeOfByteArray { get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } private static Type s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } private static Type s_typeOfGuid; internal static Type TypeOfGuid { get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } private static Type s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } private static Type s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } private static Type s_typeOfUri; internal static Type TypeOfUri { get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } private static Type s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } private static Type s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } private static Type s_typeOfISerializable; internal static Type TypeOfISerializable { get { if (s_typeOfISerializable == null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } } private static Type s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get { if (s_typeOfIDeserializationCallback == null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } } private static Type s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } private static Type s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } private static Type s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } private static Type s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } private static Type s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } private static Type s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } private static Type s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } private static Type s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } private static Type s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } private static Type s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get { if (s_typeOfOptionalFieldAttribute == null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return s_typeOfOptionalFieldAttribute; } } private static Type s_typeOfObjectArray; internal static Type TypeOfObjectArray { get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } private static Type s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } private static Type s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } private static Type s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } private static Type s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } private static Type s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } private static Type s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } private static Type s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } private static Type s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } private static Type s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } private static Type s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof (IExtensibleDataObject)); private static Type s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof (ExtensionDataObject)); private static Type s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } private static Type s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } private static Type s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } private static Type s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof (XmlDataNode)); #if NET_NATIVE private static Type s_typeOfSafeSerializationManager; private static bool s_typeOfSafeSerializationManagerSet; internal static Type TypeOfSafeSerializationManager { get { if (!s_typeOfSafeSerializationManagerSet) { s_typeOfSafeSerializationManager = TypeOfInt.Assembly.GetType("System.Runtime.Serialization.SafeSerializationManager"); s_typeOfSafeSerializationManagerSet = true; } return s_typeOfSafeSerializationManager; } } #endif private static Type s_typeOfNullable; internal static Type TypeOfNullable { get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } private static Type s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } private static Type s_typeOfIDictionary; internal static Type TypeOfIDictionary { get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } private static Type s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } private static Type s_typeOfIList; internal static Type TypeOfIList { get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } private static Type s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } private static Type s_typeOfICollection; internal static Type TypeOfICollection { get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } private static Type s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } private static Type s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } private static Type s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } private static Type s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } private static Type s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } private static Type s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } private static Type s_typeOfKeyValue; internal static Type TypeOfKeyValue { get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } private static Type s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } private static Type s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } private static Type s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } private static Type s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } private static Type s_typeOfHashtable; internal static Type TypeOfHashtable { get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } private static Type s_typeOfListGeneric; internal static Type TypeOfListGeneric { get { if (s_typeOfListGeneric == null) s_typeOfListGeneric = typeof(List<>); return s_typeOfListGeneric; } } private static Type s_typeOfXmlElement; internal static Type TypeOfXmlElement { get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } private static Type s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static bool s_shouldGetDBNullType = true; private static Type s_typeOfDBNull; internal static Type TypeOfDBNull { get { if (s_typeOfDBNull == null && s_shouldGetDBNullType) { s_typeOfDBNull = Type.GetType("System.DBNull, System.Data.Common, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", false); s_shouldGetDBNullType = false; } return s_typeOfDBNull; } } private static object s_valueOfDBNull; internal static object ValueOfDBNull { get { if (s_valueOfDBNull == null && TypeOfDBNull != null) { var fieldInfo = TypeOfDBNull.GetField("Value"); if (fieldInfo != null) s_valueOfDBNull = fieldInfo.GetValue(null); } return s_valueOfDBNull; } } private static Uri s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } #region Contract compliance for System.Type private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2) { if (seq1 == null || seq2 == null || seq1.Length != seq2.Length) return false; for (int i = 0; i < seq1.Length; i++) { if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i])) return false; } return true; } private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName) { if (methodBases == null || string.IsNullOrEmpty(methodName)) return null; var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName)); matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes)); return matchedMethods.FirstOrDefault(); } internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { var constructorInfos = type.GetConstructors(bindingFlags); var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor"); return constructorInfo != null ? (ConstructorInfo)constructorInfo : null; } internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) { var methodInfos = type.GetMethods(bindingFlags); var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName); return methodInfo != null ? (MethodInfo)methodInfo : null; } #endregion private static Type s_typeOfScriptObject; private static Func<object, string> s_serializeFunc; private static Func<string, object> s_deserializeFunc; internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } internal static void SetScriptObjectJsonSerializer(Type typeOfScriptObject, Func<object, string> serializeFunc, Func<string, object> deserializeFunc) { Globals.s_typeOfScriptObject = typeOfScriptObject; Globals.s_serializeFunc = serializeFunc; Globals.s_deserializeFunc = deserializeFunc; } internal static string ScriptObjectJsonSerialize(object obj) { Debug.Assert(s_serializeFunc != null); return Globals.s_serializeFunc(obj); } internal static object ScriptObjectJsonDeserialize(string json) { Debug.Assert(s_deserializeFunc != null); return Globals.s_deserializeFunc(json); } internal static bool IsDBNullValue(object o) { return o != null && ValueOfDBNull != null && ValueOfDBNull.Equals(o); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string SimpleSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*$"; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string ParseMethodName = "Parse"; public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; } }
// ---------------------------------------------------------------------------------- // // FXMaker // Created by ismoon - 2012 - ismoonto@gmail.com // // ---------------------------------------------------------------------------------- using UnityEngine; using System.Collections; // [AddComponentMenu("FXMaker/NcAutoDeactive %#F")] public class NcAutoDeactive : NcEffectBehaviour { // Attribute ------------------------------------------------------------------------ public float m_fLifeTime = 2; public float m_fSmoothDestroyTime = 0; public bool m_bDisableEmit = true; public bool m_bSmoothHide = true; public bool m_bMeshFilterOnlySmoothHide = false; protected bool m_bEndNcCurveAnimation = false; public enum CollisionType {NONE, COLLISION, WORLD_Y}; public CollisionType m_CollisionType = CollisionType.NONE; public LayerMask m_CollisionLayer = -1; public float m_fCollisionRadius = 0.3f; public float m_fDestructPosY = 0.2f; // read only protected float m_fStartTime = 0; protected float m_fStartDestroyTime; protected NcCurveAnimation m_NcCurveAnimation; // Create --------------------------------------------------------------------------- public static NcAutoDeactive CreateAutoDestruct(GameObject baseGameObject, float fLifeTime, float fDestroyTime, bool bSmoothHide, bool bMeshFilterOnlySmoothHide) { NcAutoDeactive ncAutoDeactive = baseGameObject.AddComponent<NcAutoDeactive>(); ncAutoDeactive.m_fLifeTime = fLifeTime; ncAutoDeactive.m_fSmoothDestroyTime = fDestroyTime; ncAutoDeactive.m_bSmoothHide = bSmoothHide; ncAutoDeactive.m_bMeshFilterOnlySmoothHide = bMeshFilterOnlySmoothHide; if (IsActive(baseGameObject)) { ncAutoDeactive.Start(); ncAutoDeactive.Update(); } return ncAutoDeactive; } // Property ------------------------------------------------------------------------- #if UNITY_EDITOR public override string CheckProperty() { if (1 < gameObject.GetComponents(GetType()).Length) return "SCRIPT_WARRING_DUPLICATE"; return ""; // no error } #endif // Loop Function -------------------------------------------------------------------- void Awake() { m_bEndNcCurveAnimation = false; // disable m_fStartTime = 0; m_NcCurveAnimation = null; } void OnEnable() { m_fStartTime = GetEngineTime(); } void Start() { if (m_bEndNcCurveAnimation) m_NcCurveAnimation = GetComponent<NcCurveAnimation>(); } void Update() { if (0 < m_fStartDestroyTime) { if (0 < m_fSmoothDestroyTime) { if (m_bSmoothHide) { float fAlphaRate = 1 - ((GetEngineTime() - m_fStartDestroyTime) / m_fSmoothDestroyTime); if (fAlphaRate < 0) fAlphaRate = 0; if (m_bMeshFilterOnlySmoothHide) { // Recursively MeshFilter[] meshFilters = transform.GetComponentsInChildren<MeshFilter>(true); Color color; for (int n = 0; n < meshFilters.Length; n++) { Color[] colors = meshFilters[n].mesh.colors; if (colors.Length == 0) { colors = new Color[meshFilters[n].mesh.vertices.Length]; for (int c = 0; c < colors.Length; c++) colors[c] = Color.white; } for (int c = 0; c < colors.Length; c++) { color = colors[c]; color.a = Mathf.Min(color.a, fAlphaRate); colors[c] = color; } meshFilters[n].mesh.colors = colors; } } else { // Recursively Renderer[] rens = transform.GetComponentsInChildren<Renderer>(true); for (int n = 0; n < rens.Length; n++) { Renderer ren = rens[n]; string colName = GetMaterialColorName(ren.sharedMaterial); if (colName != null) { Color col = ren.material.GetColor(colName); col.a = Mathf.Min(col.a, fAlphaRate); ren.material.SetColor(colName, col); // AddRuntimeMaterial(ren.material); } } } } if (m_fStartDestroyTime + m_fSmoothDestroyTime < GetEngineTime()) AutoDeactive(); } } else { // Time // if (0 < m_fStartTime && m_fLifeTime != 0) if (0 < m_fStartTime) { if (m_fStartTime + m_fLifeTime <= GetEngineTime()) StartDeactive(); } // event if (m_bEndNcCurveAnimation && m_NcCurveAnimation != null) if (1 <= m_NcCurveAnimation.GetElapsedRate()) StartDeactive(); } } void FixedUpdate() { if (0 < m_fStartDestroyTime) return; bool bDeactive = false; if (m_CollisionType == CollisionType.NONE) return; if (m_CollisionType == CollisionType.COLLISION) { #if UNITY_EDITOR Collider[] colls = Physics.OverlapSphere(transform.position, m_fCollisionRadius, m_CollisionLayer); foreach (Collider coll in colls) { if (coll.gameObject.GetComponent("FxmInfoIndexing") != null) continue; bDeactive = true; break; } #else if (Physics.CheckSphere(transform.position, m_fCollisionRadius, m_CollisionLayer)) bDeactive = true; #endif } else if (m_CollisionType == CollisionType.WORLD_Y && transform.position.y <= m_fDestructPosY) bDeactive = true; if (bDeactive) StartDeactive(); } // Control Function ----------------------------------------------------------------- void StartDeactive() { if (m_fSmoothDestroyTime <= 0) AutoDeactive(); else { m_fStartDestroyTime = GetEngineTime(); if (m_bDisableEmit) DisableEmit(); } } // Event Function ------------------------------------------------------------------- public override void OnUpdateEffectSpeed(float fSpeedRate, bool bRuntime) { m_fLifeTime /= fSpeedRate; m_fSmoothDestroyTime /= fSpeedRate; } public override void OnSetReplayState() { base.OnSetReplayState(); // Backup InitColor if (0 < m_fSmoothDestroyTime && m_bSmoothHide) { m_NcEffectInitBackup = new NcEffectInitBackup(); if (m_bMeshFilterOnlySmoothHide) m_NcEffectInitBackup.BackupMeshColor(gameObject, true); else m_NcEffectInitBackup.BackupMaterialColor(gameObject, true); } } public override void OnResetReplayStage(bool bClearOldParticle) { base.OnResetReplayStage(bClearOldParticle); m_fStartTime = GetEngineTime(); m_fStartDestroyTime = 0; // Restore InitColor if (0 < m_fSmoothDestroyTime && m_bSmoothHide && m_NcEffectInitBackup != null) { if (m_bMeshFilterOnlySmoothHide) m_NcEffectInitBackup.RestoreMeshColor(); else m_NcEffectInitBackup.RestoreMaterialColor(); } } void AutoDeactive() { SetActiveRecursively(gameObject, false); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Interregion { public class LocalInterregionComms : ISharedRegionModule, IInterregionCommsOut, IInterregionCommsIn { private bool m_enabled = false; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); #region Events public event ChildAgentUpdateReceived OnChildAgentUpdate; #endregion /* Events */ #region IRegionModule public void Initialise(IConfigSource config) { if (m_sceneList.Count == 0) { IConfig startupConfig = config.Configs["Communications"]; if ((startupConfig != null) && (startupConfig.GetString("InterregionComms", "RESTComms") == "LocalComms")) { m_log.Debug("[LOCAL COMMS]: Enabling InterregionComms LocalComms module"); m_enabled = true; } } } public void PostInitialise() { } public void AddRegion(Scene scene) { } public void RemoveRegion(Scene scene) { if (m_enabled) { RemoveScene(scene); } } public void RegionLoaded(Scene scene) { if (m_enabled) { Init(scene); } } public void Close() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "LocalInterregionCommsModule"; } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void RemoveScene(Scene scene) { lock (m_sceneList) { if (m_sceneList.Contains(scene)) { m_sceneList.Remove(scene); } } } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void Init(Scene scene) { if (!m_sceneList.Contains(scene)) { lock (m_sceneList) { m_sceneList.Add(scene); if (m_enabled) scene.RegisterModuleInterface<IInterregionCommsOut>(this); scene.RegisterModuleInterface<IInterregionCommsIn>(this); } } } #endregion /* IRegionModule */ #region IInterregionComms /** * Agent-related communications */ public bool SendCreateChildAgent(ulong regionHandle, AgentCircuitData aCircuit, out string reason) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { // m_log.DebugFormat("[LOCAL COMMS]: Found region {0} to send SendCreateChildAgent", regionHandle); return s.NewUserConnection(aCircuit, out reason); } } // m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for SendCreateChildAgent", regionHandle); reason = "Did not find region."; return false; } public bool SendChildAgentUpdate(ulong regionHandle, AgentData cAgentData) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { //m_log.DebugFormat( // "[LOCAL COMMS]: Found region {0} {1} to send ChildAgentUpdate", // s.RegionInfo.RegionName, regionHandle); s.IncomingChildAgentDataUpdate(cAgentData); return true; } } // m_log.DebugFormat("[LOCAL COMMS]: Did not find region {0} for ChildAgentUpdate", regionHandle); return false; } public bool SendChildAgentUpdate(ulong regionHandle, AgentPosition cAgentData) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); s.IncomingChildAgentDataUpdate(cAgentData); return true; } } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return false; } public bool SendRetrieveRootAgent(ulong regionHandle, UUID id, out IAgentData agent) { agent = null; foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); return s.IncomingRetrieveRootAgent(id, out agent); } } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return false; } public bool SendReleaseAgent(ulong regionHandle, UUID id, string uri) { //uint x, y; //Utils.LongToUInts(regionHandle, out x, out y); //x = x / Constants.RegionSize; //y = y / Constants.RegionSize; //m_log.Debug("\n >>> Local SendReleaseAgent " + x + "-" + y); foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to SendReleaseAgent"); return s.IncomingReleaseAgent(id); } } //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent"); return false; } public bool SendCloseAgent(ulong regionHandle, UUID id) { //uint x, y; //Utils.LongToUInts(regionHandle, out x, out y); //x = x / Constants.RegionSize; //y = y / Constants.RegionSize; //m_log.Debug("\n >>> Local SendCloseAgent " + x + "-" + y); foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to SendCloseAgent"); return s.IncomingCloseAgent(id); } } //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent"); return false; } /** * Object-related communications */ public bool SendCreateObject(ulong regionHandle, SceneObjectGroup sog, bool isLocalCall) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { //m_log.Debug("[LOCAL COMMS]: Found region to SendCreateObject"); if (isLocalCall) { // We need to make a local copy of the object ISceneObject sogClone = sog.CloneForNewScene(); sogClone.SetState(sog.GetStateSnapshot(), s.RegionInfo.RegionID); return s.IncomingCreateObject(sogClone); } else { // Use the object as it came through the wire return s.IncomingCreateObject(sog); } } } return false; } public bool SendCreateObject(ulong regionHandle, UUID userID, UUID itemID) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionHandle) { return s.IncomingCreateObject(userID, itemID); } } return false; } #endregion /* IInterregionComms */ #region Misc public UUID GetRegionID(ulong regionhandle) { foreach (Scene s in m_sceneList) { if (s.RegionInfo.RegionHandle == regionhandle) return s.RegionInfo.RegionID; } // ? weird. should not happen return m_sceneList[0].RegionInfo.RegionID; } public bool IsLocalRegion(ulong regionhandle) { foreach (Scene s in m_sceneList) if (s.RegionInfo.RegionHandle == regionhandle) return true; return false; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Linq; using Csla; using Csla.Data; namespace Invoices.Business { /// <summary> /// ProductTypeUpdatedByRootList (read only list).<br/> /// This is a generated <see cref="ProductTypeUpdatedByRootList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// Updated by ProductTypeEdit /// </remarks> [Serializable] #if WINFORMS public partial class ProductTypeUpdatedByRootList : ReadOnlyBindingListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #else public partial class ProductTypeUpdatedByRootList : ReadOnlyListBase<ProductTypeUpdatedByRootList, ProductTypeUpdatedByRootInfo> #endif { #region Event handler properties [NotUndoable] private static bool _singleInstanceSavedHandler = true; /// <summary> /// Gets or sets a value indicating whether only a single instance should handle the Saved event. /// </summary> /// <value> /// <c>true</c> if only a single instance should handle the Saved event; otherwise, <c>false</c>. /// </value> public static bool SingleInstanceSavedHandler { get { return _singleInstanceSavedHandler; } set { _singleInstanceSavedHandler = value; } } #endregion #region Collection Business Methods /// <summary> /// Determines whether a <see cref="ProductTypeUpdatedByRootInfo"/> item is in the collection. /// </summary> /// <param name="productTypeId">The ProductTypeId of the item to search for.</param> /// <returns><c>true</c> if the ProductTypeUpdatedByRootInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int productTypeId) { foreach (var productTypeUpdatedByRootInfo in this) { if (productTypeUpdatedByRootInfo.ProductTypeId == productTypeId) { return true; } } return false; } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <returns>A reference to the fetched <see cref="ProductTypeUpdatedByRootList"/> collection.</returns> public static ProductTypeUpdatedByRootList GetProductTypeUpdatedByRootList() { return DataPortal.Fetch<ProductTypeUpdatedByRootList>(); } /// <summary> /// Factory method. Asynchronously loads a <see cref="ProductTypeUpdatedByRootList"/> collection. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetProductTypeUpdatedByRootList(EventHandler<DataPortalResult<ProductTypeUpdatedByRootList>> callback) { DataPortal.BeginFetch<ProductTypeUpdatedByRootList>(callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="ProductTypeUpdatedByRootList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public ProductTypeUpdatedByRootList() { // Use factory methods and do not use direct creation. ProductTypeEditSaved.Register(this); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Saved Event Handler /// <summary> /// Handle Saved events of <see cref="ProductTypeEdit"/> to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> internal void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { var obj = (ProductTypeEdit)e.NewObject; if (((ProductTypeEdit)sender).IsNew) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; Add(ProductTypeUpdatedByRootInfo.LoadInfo(obj)); RaiseListChangedEvents = rlce; IsReadOnly = true; } else if (((ProductTypeEdit)sender).IsDeleted) { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = true; this.RemoveItem(index); RaiseListChangedEvents = rlce; IsReadOnly = true; break; } } } else { for (int index = 0; index < this.Count; index++) { var child = this[index]; if (child.ProductTypeId == obj.ProductTypeId) { child.UpdatePropertiesOnSaved(obj); #if !WINFORMS var notifyCollectionChangedEventArgs = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, child, child, index); OnCollectionChanged(notifyCollectionChangedEventArgs); #else var listChangedEventArgs = new ListChangedEventArgs(ListChangedType.ItemChanged, index); OnListChanged(listChangedEventArgs); #endif break; } } } } #endregion #region Data Access /// <summary> /// Loads a <see cref="ProductTypeUpdatedByRootList"/> collection from the database. /// </summary> protected void DataPortal_Fetch() { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.InvoicesConnection, false)) { using (var cmd = new SqlCommand("dbo.GetProductTypeUpdatedByRootList", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; var args = new DataPortalHookArgs(cmd); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="ProductTypeUpdatedByRootList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(DataPortal.FetchChild<ProductTypeUpdatedByRootInfo>(dr)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion #region ProductTypeEditSaved nested class // TODO: edit "ProductTypeUpdatedByRootList.cs", uncomment the "OnDeserialized" method and add the following line: // TODO: ProductTypeEditSaved.Register(this); /// <summary> /// Nested class to manage the Saved events of <see cref="ProductTypeEdit"/> /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> private static class ProductTypeEditSaved { private static List<WeakReference> _references; private static bool Found(object obj) { return _references.Any(reference => Equals(reference.Target, obj)); } /// <summary> /// Registers a ProductTypeUpdatedByRootList instance to handle Saved events. /// to update the list of <see cref="ProductTypeUpdatedByRootInfo"/> objects. /// </summary> /// <param name="obj">The ProductTypeUpdatedByRootList instance.</param> public static void Register(ProductTypeUpdatedByRootList obj) { var mustRegister = _references == null; if (mustRegister) _references = new List<WeakReference>(); if (ProductTypeUpdatedByRootList.SingleInstanceSavedHandler) _references.Clear(); if (!Found(obj)) _references.Add(new WeakReference(obj)); if (mustRegister) ProductTypeEdit.ProductTypeEditSaved += ProductTypeEditSavedHandler; } /// <summary> /// Handles Saved events of <see cref="ProductTypeEdit"/>. /// </summary> /// <param name="sender">The sender of the event.</param> /// <param name="e">The <see cref="Csla.Core.SavedEventArgs"/> instance containing the event data.</param> public static void ProductTypeEditSavedHandler(object sender, Csla.Core.SavedEventArgs e) { foreach (var reference in _references) { if (reference.IsAlive) ((ProductTypeUpdatedByRootList) reference.Target).ProductTypeEditSavedHandler(sender, e); } } /// <summary> /// Removes event handling and clears all registered ProductTypeUpdatedByRootList instances. /// </summary> public static void Unregister() { ProductTypeEdit.ProductTypeEditSaved -= ProductTypeEditSavedHandler; _references = null; } } #endregion } }
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using BitSharper.IO; using log4net; namespace BitSharper { /// <summary> /// BitCoin transactions don't specify what they do directly. Instead <a href="https://en.bitcoin.it/wiki/Script">a small binary stack language</a> /// is used to define programs that when evaluated return whether the transaction /// "accepts" or rejects the other transactions connected to it. /// </summary> /// <remarks> /// This implementation of the scripting language is incomplete. It contains enough support to run standard /// transactions generated by the official client, but non-standard transactions will fail. /// </remarks> public class Script { private static readonly ILog _log = LogManager.GetLogger(typeof (Script)); // Some constants used for decoding the scripts. public const int OpPushData1 = 76; public const int OpPushData2 = 77; public const int OpPushData4 = 78; public const int OpDup = 118; public const int OpHash160 = 169; public const int OpEqualVerify = 136; public const int OpCheckSig = 172; private byte[] _program; private int _cursor; // The program is a set of byte[]s where each element is either [opcode] or [data, data, data ...] private IList<byte[]> _chunks; private byte[] _programCopy; // TODO: remove this private readonly NetworkParameters _params; /// <summary> /// Construct a Script using the given network parameters and a range of the programBytes array. /// </summary> /// <param name="params">Network parameters.</param> /// <param name="programBytes">Array of program bytes from a transaction.</param> /// <param name="offset">How many bytes into programBytes to start reading from.</param> /// <param name="length">How many bytes to read.</param> /// <exception cref="ScriptException"/> public Script(NetworkParameters @params, byte[] programBytes, int offset, int length) { _params = @params; Parse(programBytes, offset, length); } /// <summary> /// Returns the program opcodes as a string, for example "[1234] DUP HAHS160" /// </summary> public override string ToString() { var buf = new StringBuilder(); foreach (var chunk in _chunks) { if (chunk.Length == 1) { string opName; var opcode = chunk[0]; switch (opcode) { case OpDup: opName = "DUP"; break; case OpHash160: opName = "HASH160"; break; case OpCheckSig: opName = "CHECKSIG"; break; case OpEqualVerify: opName = "EQUALVERIFY"; break; default: opName = "?(" + opcode + ")"; break; } buf.Append(opName); buf.Append(" "); } else { // Data chunk buf.Append("["); buf.Append(chunk.Length); buf.Append("]"); buf.Append(Utils.BytesToHexString(chunk)); buf.Append(" "); } } return buf.ToString(); } /// <exception cref="ScriptException"/> private byte[] GetData(int len) { try { var buf = new byte[len]; Array.Copy(_program, _cursor, buf, 0, len); _cursor += len; return buf; } catch (IndexOutOfRangeException e) { // We want running out of data in the array to be treated as a recoverable script parsing exception, // not something that abnormally terminates the app. throw new ScriptException("Failed read of " + len + " bytes", e); } } private byte ReadByte() { return _program[_cursor++]; } /// <summary> /// To run a script, first we parse it which breaks it up into chunks representing pushes of /// data or logical opcodes. Then we can run the parsed chunks. /// </summary> /// <remarks> /// The reason for this split, instead of just interpreting directly, is to make it easier /// to reach into a programs structure and pull out bits of data without having to run it. /// This is necessary to render the to/from addresses of transactions in a user interface. /// The official client does something similar. /// </remarks> /// <exception cref="ScriptException"/> private void Parse(byte[] programBytes, int offset, int length) { // TODO: this is inefficient _programCopy = new byte[length]; Array.Copy(programBytes, offset, _programCopy, 0, length); _program = _programCopy; offset = 0; _chunks = new List<byte[]>(10); // Arbitrary choice of initial size. _cursor = offset; while (_cursor < offset + length) { var opcode = (int) ReadByte(); if (opcode >= 0xF0) { // Not a single byte opcode. opcode = (opcode << 8) | ReadByte(); } if (opcode > 0 && opcode < OpPushData1) { // Read some bytes of data, where how many is the opcode value itself. _chunks.Add(GetData(opcode)); // opcode == len here. } else if (opcode == OpPushData1) { var len = ReadByte(); _chunks.Add(GetData(len)); } else if (opcode == OpPushData2) { // Read a short, then read that many bytes of data. var len = ReadByte() | (ReadByte() << 8); _chunks.Add(GetData(len)); } else if (opcode == OpPushData4) { // Read a uint32, then read that many bytes of data. _log.Error("PUSHDATA4: Unimplemented"); } else { _chunks.Add(new[] {(byte) opcode}); } } } /// <summary> /// Returns true if this transaction is of a format that means it was a direct IP to IP transaction. These /// transactions are deprecated and no longer used, support for creating them has been removed from the official /// client. /// </summary> public bool IsSentToIp { get { return _chunks.Count == 2 && (_chunks[1][0] == OpCheckSig && _chunks[0].Length > 1); } } /// <summary> /// If a program matches the standard template DUP HASH160 &lt;pubkey hash&gt; EQUALVERIFY CHECKSIG /// then this function retrieves the third element, otherwise it throws a ScriptException. /// </summary> /// <remarks> /// This is useful for fetching the destination address of a transaction. /// </remarks> /// <exception cref="ScriptException"/> public byte[] PubKeyHash { get { if (_chunks.Count != 5) throw new ScriptException("Script not of right size to be a scriptPubKey, " + "expecting 5 but got " + _chunks.Count); if (_chunks[0][0] != OpDup || _chunks[1][0] != OpHash160 || _chunks[3][0] != OpEqualVerify || _chunks[4][0] != OpCheckSig) throw new ScriptException("Script not in the standard scriptPubKey form"); // Otherwise, the third element is the hash of the public key, ie the BitCoin address. return _chunks[2]; } } /// <summary> /// If a program has two data buffers (constants) and nothing else, the second one is returned. /// For a scriptSig this should be the public key of the sender. /// </summary> /// <remarks> /// This is useful for fetching the source address of a transaction. /// </remarks> /// <exception cref="ScriptException"/> public byte[] PubKey { get { if (_chunks.Count == 1) { // Direct IP to IP transactions only have the public key in their scriptSig. return _chunks[0]; } if (_chunks.Count != 2) throw new ScriptException("Script not of right size to be a scriptSig, expecting 2" + " but got " + _chunks.Count); if (!(_chunks[0].Length > 1) && (_chunks[1].Length > 1)) throw new ScriptException("Script not in the standard scriptSig form: " + _chunks.Count + " chunks"); return _chunks[1]; } } /// <summary> /// Convenience wrapper around getPubKey. Only works for scriptSigs. /// </summary> /// <exception cref="ScriptException"/> public Address FromAddress { get { return new Address(_params, Utils.Sha256Hash160(PubKey)); } } /// <summary> /// Gets the destination address from this script, if it's in the required form (see getPubKey). /// </summary> /// <exception cref="ScriptException"/> public Address ToAddress { get { return new Address(_params, PubKeyHash); } } ////////////////////// Interface for writing scripts from scratch //////////////////////////////// /// <summary> /// Writes out the given byte buffer to the output stream with the correct opcode prefix /// </summary> /// <exception cref="IOException"/> internal static void WriteBytes(Stream os, byte[] buf) { if (buf.Length < OpPushData1) { os.Write((byte) buf.Length); os.Write(buf); } else if (buf.Length < 256) { os.Write(OpPushData1); os.Write((byte) buf.Length); os.Write(buf); } else if (buf.Length < 65536) { os.Write(OpPushData2); os.Write((byte) buf.Length); os.Write((byte) (buf.Length >> 8)); } else { throw new NotSupportedException(); } } internal static byte[] CreateOutputScript(Address to) { using (var bits = new MemoryStream()) { // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes. bits.Write(OpDup); bits.Write(OpHash160); WriteBytes(bits, to.Hash160); bits.Write(OpEqualVerify); bits.Write(OpCheckSig); return bits.ToArray(); } } /// <summary> /// Create a script that sends coins directly to the given public key (eg in a coinbase transaction). /// </summary> internal static byte[] CreateOutputScript(byte[] pubkey) { // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes. using (var bits = new MemoryStream()) { WriteBytes(bits, pubkey); bits.Write(OpCheckSig); return bits.ToArray(); } } internal static byte[] CreateInputScript(byte[] signature, byte[] pubkey) { // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes. using (var bits = new MemoryStream()) { WriteBytes(bits, signature); WriteBytes(bits, pubkey); return bits.ToArray(); } } } }
/* * Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v.. * * 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. */ #region Using using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Net; #endregion namespace PPWCode.Util.SharePoint.I { /// <summary> /// Wrapper around selected remote Sharepoint /// functionality and added functionality. /// </summary> [ContractClass(typeof(ISharePointClientContract))] public interface ISharePointClient { /// <summary> /// Property that holds the base URL of the SharePoint /// site this instance will work on. /// </summary> string SharePointSiteUrl { get; set; } /// <summary> /// Optional credentials for authentication /// </summary> ICredentials Credentials { get; set; } /// <summary> /// Ensure the folder whose name is given /// with a <paramref name="relativeUrl"/> /// exists. /// </summary> /// <remarks> /// <para>If the folder exists, nothing happens.</para> /// <para>Else, it and all intermediate missing folders, /// are created.</para> /// </remarks> /// <param name="relativeUrl">The URL of a folder in a SharePoint document library, /// relative to <see cref="SharePointSiteUrl"/>.</param> void EnsureFolder(string relativeUrl); SharePointDocument DownloadDocument(string relativeUrl); SharePointDocument DownloadSpecificVersion(string baseRelativeUrl, string version); void UploadDocument(string relativeUrl, SharePointDocument doc); string UploadDocumentReceiveVersion(string relativeUrl, SharePointDocument doc); /// <summary> /// Validate existence of specified Uri /// </summary> bool ValidateUri(Uri sharePointUri); /// <summary> /// Open specified uri in default web browser /// MUDO: Move this method to other assembly? /// </summary> void OpenUri(Uri uri); /// <summary> /// Return files found at specified url /// </summary> List<SharePointSearchResult> SearchFiles(string url); void RenameFolder(string baseRelativeUrl, string originalFolderName, string newFolderName); void RenameAllOccurrencesOfFolder(string baseRelativeUrl, string oldFolderName, string newFolderName); /// <summary> /// Create folder with given path. /// <para> /// Depending on the parameter "createFullPath", also create all intermediate missing folders, /// or otherwise, throw an exception if any of the intermediate folders is missing. /// </para> /// </summary> /// <param name="folderPath">path of folder to be created</param> /// <param name="createFullPath">create all intermediate missing folders</param> void CreateFolder(string folderPath, bool createFullPath); /// <summary> /// Delete folder with given path. /// <para> /// Depending on the parameter "deleteChildren", also delete all children if any exist, /// or otherwise, throw an exception if any children exist. /// </para> /// </summary> /// <param name="folderPath">path of folder to be deleted</param> /// <param name="deleteChildren">delete all children of folder if any exist</param> void DeleteFolder(string folderPath, bool deleteChildren); int CountAllOccurencesOfFolderInPath(string baseRelativeUrl, string folderName); bool CheckExistenceOfFolderWithExactPath(string folderPath); IOrderedEnumerable<SharePointDocumentVersion> RetrieveAllVersionsFromUrl(string baseRelativeUrl); } // ReSharper disable InconsistentNaming /// <exclude /> [ContractClassFor(typeof(ISharePointClient))] public abstract class ISharePointClientContract : ISharePointClient { #region ISharePointClient Members public string SharePointSiteUrl { get { return default(string); } set { //NOP; } } public ICredentials Credentials { get { return default(ICredentials); } set { // NOP; } } /// <summary> /// Create all folder in the given folder path, that do not yet exist in SharePoint. /// </summary> /// <param name="relativeUrl">the folder path </param> public void EnsureFolder(string relativeUrl) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(relativeUrl)); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); } public SharePointDocument DownloadDocument(string relativeUrl) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(relativeUrl)); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); return default(SharePointDocument); } public SharePointDocument DownloadSpecificVersion(string relativeUrl, string version) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(relativeUrl)); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); return default(SharePointDocument); } public void UploadDocument(string relativeUrl, SharePointDocument doc) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(relativeUrl != null); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); Contract.Requires(doc != null); } public string UploadDocumentReceiveVersion(string relativeUrl, SharePointDocument doc) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(relativeUrl != null); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); Contract.Requires(doc != null); return default(string); } public bool ValidateUri(Uri sharePointUri) { Contract.Requires(sharePointUri != null); Contract.Requires(sharePointUri.OriginalString.StartsWith(SharePointSiteUrl)); return default(bool); } public void OpenUri(Uri uri) { Contract.Requires(uri != null); } public List<SharePointSearchResult> SearchFiles(string url) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(url != null); return new List<SharePointSearchResult>(); } /// <summary> /// Rename the folder in the given base path that has the given name. /// </summary> /// <param name="baseRelativeUrl">base folder</param> /// <param name="originalFolderName">folder in base path that has to be renamed</param> /// <param name="newFolderName">new name of the folder</param> public void RenameFolder(string baseRelativeUrl, string originalFolderName, string newFolderName) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(originalFolderName)); Contract.Requires(!string.IsNullOrEmpty(newFolderName)); } /// <summary> /// Rename all folders within the given base path, that have the given name. /// </summary> /// <param name="baseRelativeUrl">base path</param> /// <param name="oldFolderName">folder that has to be renamed</param> /// <param name="newFolderName">new name of the folder</param> public void RenameAllOccurrencesOfFolder(string baseRelativeUrl, string oldFolderName, string newFolderName) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(baseRelativeUrl)); Contract.Requires(!string.IsNullOrEmpty(oldFolderName)); Contract.Requires(!string.IsNullOrEmpty(newFolderName)); } public void CreateFolder(string folderPath, bool createFullPath) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(folderPath)); } public void DeleteFolder(string folderPath, bool deleteChildren ) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(folderPath)); } /// <summary> /// Search and count the occurrences of folders with the given name in the given path. /// </summary> /// <param name="baseRelativeUrl">path to search</param> /// <param name="folderName">name of folder</param> /// <returns>number of occurrences</returns> public int CountAllOccurencesOfFolderInPath(string baseRelativeUrl, string folderName) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(baseRelativeUrl)); Contract.Requires(!string.IsNullOrEmpty(folderName)); return default(int); } /// <summary> /// Check whether the folder with the given path exists in SharePoint. /// </summary> /// <param name="folderPath">folder path</param> /// <returns></returns> public bool CheckExistenceOfFolderWithExactPath(string folderPath) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(folderPath)); return default(bool); } public IOrderedEnumerable<SharePointDocumentVersion> RetrieveAllVersionsFromUrl(string relativeUrl) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(relativeUrl)); return default(IOrderedEnumerable<SharePointDocumentVersion>); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Cache of <see cref="ValidationAttribute" />s /// </summary> /// <remarks> /// This internal class serves as a cache of validation attributes and [Display] attributes. /// It exists both to help performance as well as to abstract away the differences between /// Reflection and TypeDescriptor. /// </remarks> internal class ValidationAttributeStore { private static readonly ValidationAttributeStore _singleton = new ValidationAttributeStore(); private readonly Dictionary<Type, TypeStoreItem> _typeStoreItems = new Dictionary<Type, TypeStoreItem>(); /// <summary> /// Gets the singleton <see cref="ValidationAttributeStore" /> /// </summary> internal static ValidationAttributeStore Instance { get { return _singleton; } } /// <summary> /// Retrieves the type level validation attributes for the given type. /// </summary> /// <param name="validationContext">The context that describes the type. It cannot be null.</param> /// <returns>The collection of validation attributes. It could be empty.</returns> internal IEnumerable<ValidationAttribute> GetTypeValidationAttributes(ValidationContext validationContext) { EnsureValidationContext(validationContext); var item = GetTypeStoreItem(validationContext.ObjectType); return item.ValidationAttributes; } /// <summary> /// Retrieves the <see cref="DisplayAttribute" /> associated with the given type. It may be null. /// </summary> /// <param name="validationContext">The context that describes the type. It cannot be null.</param> /// <returns>The display attribute instance, if present.</returns> internal DisplayAttribute GetTypeDisplayAttribute(ValidationContext validationContext) { EnsureValidationContext(validationContext); var item = GetTypeStoreItem(validationContext.ObjectType); return item.DisplayAttribute; } /// <summary> /// Retrieves the set of validation attributes for the property /// </summary> /// <param name="validationContext">The context that describes the property. It cannot be null.</param> /// <returns>The collection of validation attributes. It could be empty.</returns> internal IEnumerable<ValidationAttribute> GetPropertyValidationAttributes(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); var item = typeItem.GetPropertyStoreItem(validationContext.MemberName); return item.ValidationAttributes; } /// <summary> /// Retrieves the <see cref="DisplayAttribute" /> associated with the given property /// </summary> /// <param name="validationContext">The context that describes the property. It cannot be null.</param> /// <returns>The display attribute instance, if present.</returns> internal DisplayAttribute GetPropertyDisplayAttribute(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); var item = typeItem.GetPropertyStoreItem(validationContext.MemberName); return item.DisplayAttribute; } /// <summary> /// Retrieves the Type of the given property. /// </summary> /// <param name="validationContext">The context that describes the property. It cannot be null.</param> /// <returns>The type of the specified property</returns> internal Type GetPropertyType(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); var item = typeItem.GetPropertyStoreItem(validationContext.MemberName); return item.PropertyType; } /// <summary> /// Determines whether or not a given <see cref="ValidationContext" />'s /// <see cref="ValidationContext.MemberName" /> references a property on /// the <see cref="ValidationContext.ObjectType" />. /// </summary> /// <param name="validationContext">The <see cref="ValidationContext" /> to check.</param> /// <returns><c>true</c> when the <paramref name="validationContext" /> represents a property, <c>false</c> otherwise.</returns> internal bool IsPropertyContext(ValidationContext validationContext) { EnsureValidationContext(validationContext); var typeItem = GetTypeStoreItem(validationContext.ObjectType); PropertyStoreItem item; return typeItem.TryGetPropertyStoreItem(validationContext.MemberName, out item); } /// <summary> /// Retrieves or creates the store item for the given type /// </summary> /// <param name="type">The type whose store item is needed. It cannot be null</param> /// <returns>The type store item. It will not be null.</returns> private TypeStoreItem GetTypeStoreItem(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } lock (_typeStoreItems) { TypeStoreItem item = null; if (!_typeStoreItems.TryGetValue(type, out item)) { // use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones var attributes = CustomAttributeExtensions.GetCustomAttributes(type.GetTypeInfo(), true); item = new TypeStoreItem(type, attributes); _typeStoreItems[type] = item; } return item; } } /// <summary> /// Throws an ArgumentException of the validation context is null /// </summary> /// <param name="validationContext">The context to check</param> private static void EnsureValidationContext(ValidationContext validationContext) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } } internal static bool IsPublic(PropertyInfo p) { return (p.GetMethod != null && p.GetMethod.IsPublic) || (p.SetMethod != null && p.SetMethod.IsPublic); } internal static bool IsStatic(PropertyInfo p) { return (p.GetMethod != null && p.GetMethod.IsStatic) || (p.SetMethod != null && p.SetMethod.IsStatic); } /// <summary> /// Private abstract class for all store items /// </summary> private abstract class StoreItem { private readonly IEnumerable<ValidationAttribute> _validationAttributes; internal StoreItem(IEnumerable<Attribute> attributes) { _validationAttributes = attributes.OfType<ValidationAttribute>(); DisplayAttribute = attributes.OfType<DisplayAttribute>().SingleOrDefault(); } internal IEnumerable<ValidationAttribute> ValidationAttributes { get { return _validationAttributes; } } internal DisplayAttribute DisplayAttribute { get; set; } } /// <summary> /// Private class to store data associated with a type /// </summary> private class TypeStoreItem : StoreItem { private readonly object _syncRoot = new object(); private readonly Type _type; private Dictionary<string, PropertyStoreItem> _propertyStoreItems; internal TypeStoreItem(Type type, IEnumerable<Attribute> attributes) : base(attributes) { _type = type; } internal PropertyStoreItem GetPropertyStoreItem(string propertyName) { PropertyStoreItem item = null; if (!TryGetPropertyStoreItem(propertyName, out item)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.AttributeStore_Unknown_Property, _type.Name, propertyName), nameof(propertyName)); } return item; } internal bool TryGetPropertyStoreItem(string propertyName, out PropertyStoreItem item) { if (string.IsNullOrEmpty(propertyName)) { throw new ArgumentNullException(nameof(propertyName)); } if (_propertyStoreItems == null) { lock (_syncRoot) { if (_propertyStoreItems == null) { _propertyStoreItems = CreatePropertyStoreItems(); } } } return _propertyStoreItems.TryGetValue(propertyName, out item); } private Dictionary<string, PropertyStoreItem> CreatePropertyStoreItems() { var propertyStoreItems = new Dictionary<string, PropertyStoreItem>(); // exclude index properties to match old TypeDescriptor functionality var properties = _type.GetRuntimeProperties() .Where(prop => IsPublic(prop) && !prop.GetIndexParameters().Any()); foreach (PropertyInfo property in properties) { // use CustomAttributeExtensions.GetCustomAttributes() to get inherited attributes as well as direct ones var item = new PropertyStoreItem(property.PropertyType, CustomAttributeExtensions.GetCustomAttributes(property, true)); propertyStoreItems[property.Name] = item; } return propertyStoreItems; } } /// <summary> /// Private class to store data associated with a property /// </summary> private class PropertyStoreItem : StoreItem { private readonly Type _propertyType; internal PropertyStoreItem(Type propertyType, IEnumerable<Attribute> attributes) : base(attributes) { _propertyType = propertyType; } internal Type PropertyType { get { return _propertyType; } } } } }
// 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 ShiftRightLogicalInt6464() { var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ShiftRightLogicalInt6464 { private struct TestStruct { public Vector128<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt6464 testClass) { var result = Sse2.ShiftRightLogical(_fld, 64); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalInt6464() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public ImmUnaryOpTest__ShiftRightLogicalInt6464() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[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.ShiftRightLogical( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftRightLogical( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftRightLogical( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftRightLogical( _clsVar, 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalInt6464(); var result = Sse2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftRightLogical(_fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftRightLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(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<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int64>(Vector128<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using InControl; //#if UNITY_EDITOR //using UnityEditor; //#endif /** * WARNING: This is NOT an example of how to use InControl. * It is intended for testing and troubleshooting the library. * It can also be used for create new device profiles as it will * show the default Unity mappings for unknown devices. **/ namespace InControl { public class TestInputManager : MonoBehaviour { public Font font; GUIStyle style = new GUIStyle(); List<LogMessage> logMessages = new List<LogMessage>(); bool isPaused; void OnEnable() { isPaused = false; Time.timeScale = 1.0f; Logger.OnLogMessage += logMessage => logMessages.Add( logMessage ); // InputManager.HideDevicesWithProfile( typeof( Xbox360MacProfile ) ); InputManager.OnDeviceAttached += inputDevice => Debug.Log( "Attached: " + inputDevice.Name ); InputManager.OnDeviceDetached += inputDevice => Debug.Log( "Detached: " + inputDevice.Name ); InputManager.OnActiveDeviceChanged += inputDevice => Debug.Log( "Active device changed to: " + inputDevice.Name ); TestInputMappings(); // Debug.Log( "Unity Version: " + InputManager.UnityVersion ); } void FixedUpdate() { CheckForPauseButton(); // var inputDevice = InputManager.ActiveDevice; // if (inputDevice.Direction.Left.WasPressed) // { // Debug.Log( "Left.WasPressed" ); // } // if (inputDevice.Direction.Left.WasReleased) // { // Debug.Log( "Left.WasReleased" ); // } } void Update() { if (isPaused) { CheckForPauseButton(); } if (Input.GetKeyDown( KeyCode.R )) { Application.LoadLevel( "TestInputManager" ); } } void CheckForPauseButton() { if (Input.GetKeyDown( KeyCode.P ) || InputManager.MenuWasPressed) { Time.timeScale = isPaused ? 1.0f : 0.0f; isPaused = !isPaused; } } void SetColor( Color color ) { style.normal.textColor = color; } void OnGUI() { var w = 300; var x = 10; var y = 10; var lineHeight = 15; GUI.skin.font = font; SetColor( Color.white ); string info = "Devices:"; info += " (Platform: " + InputManager.Platform + ")"; // info += " (Joysticks " + InputManager.JoystickHash + ")"; info += " " + InputManager.ActiveDevice.Direction.Vector; // #if UNITY_EDITOR // if (EditorWindow.focusedWindow != null) // { // info += " " + EditorWindow.focusedWindow.ToString(); // } // #endif if (isPaused) { SetColor( Color.red ); info = "+++ PAUSED +++"; } GUI.Label( new Rect( x, y, x + w, y + 10 ), info, style ); SetColor( Color.white ); foreach (var inputDevice in InputManager.Devices) { bool active = InputManager.ActiveDevice == inputDevice; Color color = active ? Color.yellow : Color.white; y = 35; SetColor( color ); GUI.Label( new Rect( x, y, x + w, y + 10 ), inputDevice.Name, style ); y += lineHeight; GUI.Label( new Rect( x, y, x + w, y + 10 ), "SortOrder: " + inputDevice.SortOrder, style ); y += lineHeight; GUI.Label( new Rect( x, y, x + w, y + 10 ), "LastChangeTick: " + inputDevice.LastChangeTick, style ); y += lineHeight; foreach (var control in inputDevice.Controls) { if (control != null) { string controlName; if (inputDevice.IsKnown) { controlName = string.Format( "{0} ({1})", control.Target, control.Handle ); } else { controlName = control.Handle; } SetColor( control.State ? Color.green : color ); var label = string.Format( "{0} {1}", controlName, control.State ? "= " + control.Value : "" ); GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style ); y += lineHeight; } } SetColor( Color.cyan ); var anyButton = inputDevice.AnyButton; if (anyButton) { GUI.Label( new Rect( x, y, x + w, y + 10 ), "AnyButton = " + anyButton.Handle, style ); } x += 200; } Color[] logColors = { Color.gray, Color.yellow, Color.white }; SetColor( Color.white ); x = 10; y = Screen.height - (10 + lineHeight); for (int i = logMessages.Count - 1; i >= 0; i--) { var logMessage = logMessages[i]; SetColor( logColors[(int) logMessage.type] ); foreach (var line in logMessage.text.Split('\n')) { GUI.Label( new Rect( x, y, Screen.width, y + 10 ), line, style ); y -= lineHeight; } } } void OnDrawGizmos() { Vector3 delta = InputManager.ActiveDevice.Direction.Vector * 4.0f; Gizmos.color = Color.yellow; Gizmos.DrawSphere( delta, 1 ); } void TestInputMappings() { var complete = InputControlMapping.Range.Complete; var positive = InputControlMapping.Range.Positive; var negative = InputControlMapping.Range.Negative; var noInvert = false; var doInvert = true; TestInputMapping( complete, complete, noInvert, -1.0f, 0.0f, 1.0f ); TestInputMapping( complete, negative, noInvert, -1.0f, -0.5f, 0.0f ); TestInputMapping( complete, positive, noInvert, 0.0f, 0.5f, 1.0f ); TestInputMapping( negative, complete, noInvert, -1.0f, 1.0f, 0.0f ); TestInputMapping( negative, negative, noInvert, -1.0f, 0.0f, 0.0f ); TestInputMapping( negative, positive, noInvert, 0.0f, 1.0f, 0.0f ); TestInputMapping( positive, complete, noInvert, 0.0f, -1.0f, 1.0f ); TestInputMapping( positive, negative, noInvert, 0.0f, -1.0f, 0.0f ); TestInputMapping( positive, positive, noInvert, 0.0f, 0.0f, 1.0f ); TestInputMapping( complete, complete, doInvert, 1.0f, 0.0f, -1.0f ); TestInputMapping( complete, negative, doInvert, 1.0f, 0.5f, 0.0f ); TestInputMapping( complete, positive, doInvert, 0.0f, -0.5f, -1.0f ); TestInputMapping( negative, complete, doInvert, 1.0f, -1.0f, 0.0f ); TestInputMapping( negative, negative, doInvert, 1.0f, 0.0f, 0.0f ); TestInputMapping( negative, positive, doInvert, 0.0f, -1.0f, 0.0f ); TestInputMapping( positive, complete, doInvert, 0.0f, 1.0f, -1.0f ); TestInputMapping( positive, negative, doInvert, 0.0f, 1.0f, 0.0f ); TestInputMapping( positive, positive, doInvert, 0.0f, 0.0f, -1.0f ); } void TestInputMapping( InputControlMapping.Range sourceRange, InputControlMapping.Range targetRange, bool invert, float expectA, float expectB, float expectC ) { var mapping = new InputControlMapping() { SourceRange = sourceRange, TargetRange = targetRange, Invert = invert }; float input; float value; string sr = "Complete"; if (sourceRange == InputControlMapping.Range.Negative) sr = "Negative"; else if (sourceRange == InputControlMapping.Range.Positive) sr = "Positive"; string tr = "Complete"; if (targetRange == InputControlMapping.Range.Negative) tr = "Negative"; else if (targetRange == InputControlMapping.Range.Positive) tr = "Positive"; input = -1.0f; value = mapping.MapValue( input ); if (Mathf.Abs( value - expectA ) > Single.Epsilon) { Debug.LogError( "Input of " + input + " got value of " + value + " instead of " + expectA + " (SR = " + sr + ", TR = " + tr + ")" ); } input = 0.0f; value = mapping.MapValue( input ); if (Mathf.Abs( value - expectB ) > Single.Epsilon) { Debug.LogError( "Input of " + input + " got value of " + value + " instead of " + expectB + " (SR = " + sr + ", TR = " + tr + ")" ); } input = 1.0f; value = mapping.MapValue( input ); if (Mathf.Abs( value - expectC ) > Single.Epsilon) { Debug.LogError( "Input of " + input + " got value of " + value + " instead of " + expectC + " (SR = " + sr + ", TR = " + tr + ")" ); } } } }
using System; using System.Threading.Tasks; using Demo.SmartCache.GrainInterfaces; using Demo.SmartCache.GrainInterfaces.State; using Orleans.Providers; using Patterns.StateMachine.Implementation; namespace Demo.SmartCache.GrainImplementations { using TProcessorFunc = Func<BankAccountStateMachineGrainState, BankAccountStateMachineMessage, Task<BankAccountStateMachineGrainState>> ; [StorageProvider(ProviderName = "EventStore")] public partial class BankAccountStateMachineGrain : StateMachineGrain <BankAccountStateMachineGrainState, BankAccountStateMachineData, BankAccountStateMachineState, BankAccountStateMachineMessage>, IBankAccountStateMachineGrain { public Task<BankAccountStateMachineData> GetBalance() { return Task.FromResult(State.StateMachineData); } public async Task<BankAccountStateMachineData> Deposit(BankAccountStateMachineAmount amount) => await ProcessMessage(BankAccountStateMachineMessage.NewDepositMessage(amount)); public async Task<BankAccountStateMachineData> Withdraw(BankAccountStateMachineAmount amount) => await ProcessMessage(BankAccountStateMachineMessage.NewWithdrawMessage(amount)); public async Task<BankAccountStateMachineData> Close() => await ProcessMessage(BankAccountStateMachineMessage.CloseMessage); protected override TProcessorFunc GetProcessorFunc(BankAccountStateMachineState state) { return state.Match<TProcessorFunc>( () => ZeroBalanceStateProcessor, () => ActiveStateProcessor, () => OverdrawnStateProcessor, () => ClosedStateProcessor); } } #region ZeroBalanceState public partial class BankAccountStateMachineGrain { private static async Task<BankAccountStateMachineGrainState> ZeroBalanceStateProcessor( BankAccountStateMachineGrainState state, BankAccountStateMachineMessage message) => await message.Match( ZeroBalanceStateMessageDelegator.HandleZeroBalanceStateCloseMessage(state), ZeroBalanceStateMessageDelegator.HandleZeroBalanceStateDepositMessage(state), HandleInvalidMessage); private static class ZeroBalanceStateMessageDelegator { private static readonly IZeroBalanceStateMessageHandler Handler = new ZeroBalanceStateMessageHandler(); public static Func<Task<BankAccountStateMachineGrainState>> HandleZeroBalanceStateCloseMessage( BankAccountStateMachineGrainState state) { return async () => { var result = await Handler.Close(state); return (BankAccountStateMachineGrainState) result; }; } public static Func<BankAccountStateMachineAmount, Task<BankAccountStateMachineGrainState>> HandleZeroBalanceStateDepositMessage(BankAccountStateMachineGrainState state) { return async _ => { var result = await Handler.Deposit(state, _); return (BankAccountStateMachineGrainState) result; }; } } private interface IZeroBalanceStateMessageHandler { Task<ZeroBalanceStateMessageHandler.ZeroBalanceCloseResult> Close(BankAccountStateMachineGrainState state); Task<ZeroBalanceStateMessageHandler.ZeroBalanceDepositResult> Deposit( BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount); } private partial class ZeroBalanceStateMessageHandler : IZeroBalanceStateMessageHandler { internal abstract class ZeroBalanceDepositResultState { public static readonly ZeroBalanceDepositResultState ActiveState = new ChoiceTypes.ActiveState(); private readonly BankAccountStateMachineState _bankAccountState; private ZeroBalanceDepositResultState(BankAccountStateMachineState bankAccountStateMachineState) { _bankAccountState = bankAccountStateMachineState; } public static explicit operator BankAccountStateMachineState(ZeroBalanceDepositResultState _) => _._bankAccountState; private static class ChoiceTypes { // ReSharper disable MemberHidesStaticFromOuterClass public class ActiveState : ZeroBalanceDepositResultState { public ActiveState() : base(BankAccountStateMachineState.ActiveStateMachineState) { } } // ReSharper restore MemberHidesStaticFromOuterClass } } public class ZeroBalanceDepositResult : StateMachineGrainState<BankAccountStateMachineData, BankAccountStateMachineState>.StateTransitionResult <ZeroBalanceDepositResultState> { public ZeroBalanceDepositResult(BankAccountStateMachineData stateMachineData, ZeroBalanceDepositResultState stateMachineState) : base(stateMachineData, stateMachineState) { } public static explicit operator BankAccountStateMachineGrainState(ZeroBalanceDepositResult result) => new BankAccountStateMachineGrainState(result.StateMachineData, (BankAccountStateMachineState) result.StateMachineState); } internal abstract class ZeroBalanceCloseResultState { public static readonly ZeroBalanceCloseResultState ClosedState = new ChoiceTypes.ClosedState(); private readonly BankAccountStateMachineState _bankAccountState; private ZeroBalanceCloseResultState(BankAccountStateMachineState bankAccountStateMachineState) { _bankAccountState = bankAccountStateMachineState; } public static explicit operator BankAccountStateMachineState(ZeroBalanceCloseResultState _) => _._bankAccountState; private static class ChoiceTypes { // ReSharper disable MemberHidesStaticFromOuterClass public class ClosedState : ZeroBalanceCloseResultState { public ClosedState() : base(BankAccountStateMachineState.ClosedStateMachineState) { } } // ReSharper restore MemberHidesStaticFromOuterClass } } public class ZeroBalanceCloseResult : StateMachineGrainState<BankAccountStateMachineData, BankAccountStateMachineState>.StateTransitionResult <ZeroBalanceCloseResultState> { public ZeroBalanceCloseResult(BankAccountStateMachineData stateMachineData, ZeroBalanceCloseResultState stateMachineState) : base(stateMachineData, stateMachineState) { } public static explicit operator BankAccountStateMachineGrainState(ZeroBalanceCloseResult result) => new BankAccountStateMachineGrainState(result.StateMachineData, (BankAccountStateMachineState) result.StateMachineState); } } } public partial class BankAccountStateMachineGrain { private partial class ZeroBalanceStateMessageHandler { public Task<ZeroBalanceDepositResult> Deposit(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount) { var newBalance = state.StateMachineData.Balance.Deposit(amount); var stateMachineData = BankAccountStateMachineData.NewBalance(newBalance); var stateMachineState = ZeroBalanceDepositResultState.ActiveState; return Task.FromResult(new ZeroBalanceDepositResult(stateMachineData, stateMachineState)); } public Task<ZeroBalanceCloseResult> Close(BankAccountStateMachineGrainState state) { var stateMachineData = BankAccountStateMachineData.NewBalance( BankAccountStateMachineBalance.ZeroBankAccountStateMachineBalance); var stateMachineState = ZeroBalanceCloseResultState.ClosedState; return Task.FromResult(new ZeroBalanceCloseResult(stateMachineData, stateMachineState)); } } } #endregion #region ActiveState public partial class BankAccountStateMachineGrain { private static async Task<BankAccountStateMachineGrainState> ActiveStateProcessor( BankAccountStateMachineGrainState state, BankAccountStateMachineMessage message) => await message.Match( HandleInvalidMessage, ActiveStateMessageDelegator.HandleActiveStateDepositMessage(state), ActiveStateMessageDelegator.HandleActiveStateWithdrawMessage(state)); private static class ActiveStateMessageDelegator { private static readonly IActiveStateMessageHandler Handler = new ActiveStateMessageHandler(); public static Func<BankAccountStateMachineAmount, Task<BankAccountStateMachineGrainState>> HandleActiveStateDepositMessage(BankAccountStateMachineGrainState state) { return async _ => { var result = await Handler.Deposit(state, _); return (BankAccountStateMachineGrainState) result; }; } public static Func<BankAccountStateMachineAmount, Task<BankAccountStateMachineGrainState>> HandleActiveStateWithdrawMessage(BankAccountStateMachineGrainState state) { return async _ => { var result = await Handler.Withdraw(state, _); return (BankAccountStateMachineGrainState) result; }; } } private interface IActiveStateMessageHandler { Task<ActiveStateMessageHandler.ActiveDepositResult> Deposit(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount); Task<ActiveStateMessageHandler.ActiveWithdrawResult> Withdraw(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount); } private partial class ActiveStateMessageHandler : IActiveStateMessageHandler { internal abstract class ActiveDepositResultState { public static readonly ActiveDepositResultState ActiveState = new ChoiceTypes.ActiveState(); private readonly BankAccountStateMachineState _bankAccountState; private ActiveDepositResultState(BankAccountStateMachineState bankAccountStateMachineState) { _bankAccountState = bankAccountStateMachineState; } public static explicit operator BankAccountStateMachineState(ActiveDepositResultState _) => _._bankAccountState; private static class ChoiceTypes { // ReSharper disable MemberHidesStaticFromOuterClass public class ActiveState : ActiveDepositResultState { public ActiveState() : base(BankAccountStateMachineState.ActiveStateMachineState) { } } // ReSharper restore MemberHidesStaticFromOuterClass } } public class ActiveDepositResult : StateMachineGrainState<BankAccountStateMachineData, BankAccountStateMachineState>.StateTransitionResult <ActiveDepositResultState> { public ActiveDepositResult(BankAccountStateMachineData stateMachineData, ActiveDepositResultState stateMachineState) : base(stateMachineData, stateMachineState) { } public static explicit operator BankAccountStateMachineGrainState(ActiveDepositResult result) => new BankAccountStateMachineGrainState(result.StateMachineData, (BankAccountStateMachineState) result.StateMachineState); } internal abstract class ActiveWithdrawResultState { public static readonly ActiveWithdrawResultState ActiveState = new ChoiceTypes.ActiveState(); public static readonly ActiveWithdrawResultState OverdrawnState = new ChoiceTypes.OverdrawnState(); public static readonly ActiveWithdrawResultState ZeroBalanceState = new ChoiceTypes.ZeroBalanceState(); private readonly BankAccountStateMachineState _bankAccountState; private ActiveWithdrawResultState(BankAccountStateMachineState bankAccountStateMachineState) { _bankAccountState = bankAccountStateMachineState; } public static explicit operator BankAccountStateMachineState(ActiveWithdrawResultState _) => _._bankAccountState; private static class ChoiceTypes { // ReSharper disable MemberHidesStaticFromOuterClass public class ActiveState : ActiveWithdrawResultState { public ActiveState() : base(BankAccountStateMachineState.ActiveStateMachineState) { } } public class OverdrawnState : ActiveWithdrawResultState { public OverdrawnState() : base(BankAccountStateMachineState.OverdrawnStateMachineState) { } } public class ZeroBalanceState : ActiveWithdrawResultState { public ZeroBalanceState() : base(BankAccountStateMachineState.ZeroBalanceStateMachineState) { } } // ReSharper restore MemberHidesStaticFromOuterClass } } public class ActiveWithdrawResult : StateMachineGrainState<BankAccountStateMachineData, BankAccountStateMachineState>.StateTransitionResult <ActiveWithdrawResultState> { public ActiveWithdrawResult( BankAccountStateMachineData stateMachineData, ActiveWithdrawResultState stateMachineState) : base(stateMachineData, stateMachineState) { } public static explicit operator BankAccountStateMachineGrainState(ActiveWithdrawResult result) => new BankAccountStateMachineGrainState(result.StateMachineData, (BankAccountStateMachineState) result.StateMachineState); } } } public partial class BankAccountStateMachineGrain { private partial class ActiveStateMessageHandler { public Task<ActiveDepositResult> Deposit(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount) { var newBalance = state.StateMachineData.Balance.Deposit(amount); var stateMachineData = BankAccountStateMachineData.NewBalance(newBalance); var stateMachineState = ActiveDepositResultState.ActiveState; return Task.FromResult(new ActiveDepositResult(stateMachineData, stateMachineState)); } public Task<ActiveWithdrawResult> Withdraw(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount) { var newBalance = state.StateMachineData.Balance.Withdraw(amount); var stateMachineData = BankAccountStateMachineData.NewBalance(newBalance); var stateMachineState = newBalance.Match(() => ActiveWithdrawResultState.ZeroBalanceState, _ => ActiveWithdrawResultState.ActiveState, _ => ActiveWithdrawResultState.OverdrawnState); return Task.FromResult(new ActiveWithdrawResult(stateMachineData, stateMachineState)); } } } #endregion #region OverdrawnState public partial class BankAccountStateMachineGrain { private static async Task<BankAccountStateMachineGrainState> OverdrawnStateProcessor( BankAccountStateMachineGrainState state, BankAccountStateMachineMessage message) => await message.Match( HandleInvalidMessage, OverdrawnStateMessageDelegator.HandleOverdrawnStateDepositMessage(state), HandleInvalidMessage); private static class OverdrawnStateMessageDelegator { private static readonly IOverdrawnStateMessageHandler Handler = new OverdrawnStateMessageHandler(); public static Func<BankAccountStateMachineAmount, Task<BankAccountStateMachineGrainState>> HandleOverdrawnStateDepositMessage(BankAccountStateMachineGrainState state) { return async _ => { var result = await Handler.Deposit(state, _); return (BankAccountStateMachineGrainState) result; }; } } private interface IOverdrawnStateMessageHandler { Task<OverdrawnStateMessageHandler.OverdrawnDepositResult> Deposit(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount); } private partial class OverdrawnStateMessageHandler : IOverdrawnStateMessageHandler { internal abstract class OverdrawnDepositResultState { public static readonly OverdrawnDepositResultState ActiveState = new ChoiceTypes.ActiveState(); public static readonly OverdrawnDepositResultState OverdrawnState = new ChoiceTypes.OverdrawnState(); public static readonly OverdrawnDepositResultState ZeroBalanceState = new ChoiceTypes.ZeroBalanceState(); private readonly BankAccountStateMachineState _bankAccountState; private OverdrawnDepositResultState(BankAccountStateMachineState bankAccountStateMachineState) { _bankAccountState = bankAccountStateMachineState; } public static explicit operator BankAccountStateMachineState(OverdrawnDepositResultState _) => _._bankAccountState; private static class ChoiceTypes { // ReSharper disable MemberHidesStaticFromOuterClass public class ActiveState : OverdrawnDepositResultState { public ActiveState() : base(BankAccountStateMachineState.ActiveStateMachineState) { } } public class OverdrawnState : OverdrawnDepositResultState { public OverdrawnState() : base(BankAccountStateMachineState.OverdrawnStateMachineState) { } } public class ZeroBalanceState : OverdrawnDepositResultState { public ZeroBalanceState() : base(BankAccountStateMachineState.ZeroBalanceStateMachineState) { } } // ReSharper restore MemberHidesStaticFromOuterClass } } public class OverdrawnDepositResult : StateMachineGrainState<BankAccountStateMachineData, BankAccountStateMachineState>.StateTransitionResult <OverdrawnDepositResultState> { public OverdrawnDepositResult( BankAccountStateMachineData stateMachineData, OverdrawnDepositResultState stateMachineState) : base(stateMachineData, stateMachineState) { } public static explicit operator BankAccountStateMachineGrainState(OverdrawnDepositResult result) => new BankAccountStateMachineGrainState(result.StateMachineData, (BankAccountStateMachineState) result.StateMachineState); } } } public partial class BankAccountStateMachineGrain { private partial class OverdrawnStateMessageHandler { public Task<OverdrawnDepositResult> Deposit(BankAccountStateMachineGrainState state, BankAccountStateMachineAmount amount) { var newBalance = state.StateMachineData.Balance.Deposit(amount); var stateMachineData = BankAccountStateMachineData.NewBalance(newBalance); var stateMachineState = newBalance.Match(() => OverdrawnDepositResultState.ZeroBalanceState, _ => OverdrawnDepositResultState.ActiveState, _ => OverdrawnDepositResultState.OverdrawnState); return Task.FromResult(new OverdrawnDepositResult(stateMachineData, stateMachineState)); } } } #endregion #region ClosedState public partial class BankAccountStateMachineGrain { private static async Task<BankAccountStateMachineGrainState> ClosedStateProcessor( BankAccountStateMachineGrainState state, BankAccountStateMachineMessage message) => await message.Match( HandleInvalidMessage, HandleInvalidMessage, HandleInvalidMessage); } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using DataMigration.Tests.Helpers; using Microsoft.Azure.Management.DataMigration; using Microsoft.Azure.Management.DataMigration.Models; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; using Xunit.Abstractions; namespace DataMigration.Tests.ScenarioTests { public class CRUDTaskTests : CRUDDMSTestsBase { public CRUDTaskTests(ITestOutputHelper output) { var testDetails = (ITest)output.GetType().GetField("test", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(output); testName = testDetails.TestCase.TestMethod.Method.Name; } [Fact] public void CreateSqlResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSSqlProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSSqlTask(context, dmsClient, resourceGroup, service, project.Name, testName); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void CreatePGSyncResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSPGProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSPGSyncTask(context, dmsClient, resourceGroup, service, project.Name, testName); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void CreateMySQLOfflineResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSMySqlProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSMySqlOfflineTask(context, dmsClient, resourceGroup, service, project.Name, testName); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void CreateMySQLSyncResourceApiBlock() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSMySqlProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); Assert.Throws<ApiErrorException>(() => CreateDMSMySqlSyncTask(context, dmsClient, resourceGroup, service, project.Name, testName)); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void CreateSQLSyncResourceApiBlock() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSSqlProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); Assert.Throws<ApiErrorException>(() => CreateDMSSqlSyncTask(context, dmsClient, resourceGroup, service, project.Name, testName)); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void GetResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSSqlProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSSqlTask(context, dmsClient, resourceGroup, service, project.Name, testName); var getResult = dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, task.Name); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } [Fact] public void DeleteResourceSucceeds() { var dmsClientHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; var resourcesHandler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourceGroup = CreateResourceGroup(context, resourcesHandler, ResourceGroupName, TestConfiguration.Location); var dmsClient = Utilities.GetDataMigrationManagementClient(context, dmsClientHandler); var service = CreateDMSInstance(context, dmsClient, resourceGroup, DmsDeploymentName); var project = CreateDMSSqlProject(context, dmsClient, resourceGroup, service.Name, DmsProjectName); var task = CreateDMSSqlTask(context, dmsClient, resourceGroup, service, project.Name, testName); var getResult = dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, testName); dmsClient.Tasks.Cancel(resourceGroup.Name, service.Name, project.Name, testName); Utilities.WaitIfNotInPlaybackMode(); dmsClient.Tasks.Delete(resourceGroup.Name, service.Name, project.Name, testName); var x = Assert.Throws<ApiErrorException>(() => dmsClient.Tasks.Get(resourceGroup.Name, service.Name, project.Name, testName)); Assert.Equal(HttpStatusCode.NotFound, x.Response.StatusCode); } // Wait for resource group deletion to complete. Utilities.WaitIfNotInPlaybackMode(); } private ProjectTask CreateDMSSqlTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new ConnectToTargetSqlDbTaskProperties { Input = new ConnectToTargetSqlDbTaskInput( new SqlConnectionInfo { DataSource = "shuhuandmsdbs.database.windows.net", EncryptConnection = true, TrustServerCertificate = true, UserName = "testuser", Password = "testuserpw", Authentication = AuthenticationType.SqlAuthentication, } ) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } private ProjectTask CreateDMSPGSyncTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new MigratePostgreSqlAzureDbForPostgreSqlSyncTaskProperties { Input = new MigratePostgreSqlAzureDbForPostgreSqlSyncTaskInput( new List<MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseInput> { new MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseInput { Name = "someSourceDatabaseName", TargetDatabaseName = "someTargetDatabaseName", SelectedTables = new List<MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput> { new MigratePostgreSqlAzureDbForPostgreSqlSyncDatabaseTableInput("public.someTableName") } } }, new PostgreSqlConnectionInfo { ServerName = @"someTargetServerName", EncryptConnection = true, TrustServerCertificate = true, UserName = "someTargetUser", Password = "someTargetPassword" }, new PostgreSqlConnectionInfo { ServerName = @"someSourceServerName", EncryptConnection = true, TrustServerCertificate = true, UserName = "someSourceUser", Password = "someSourcePassword" }) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } private ProjectTask CreateDMSMySqlOfflineTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new MigrateMySqlAzureDbForMySqlOfflineTaskProperties { Input = new MigrateMySqlAzureDbForMySqlOfflineTaskInput( new MySqlConnectionInfo { ServerName = @"someSourceServerName", UserName = "someSourceUser", Password = "someSourcePassword" }, new MySqlConnectionInfo { ServerName = @"someTargetServerName", UserName = "someTargetUser", Password = "someTargetPassword" }, new List<MigrateMySqlAzureDbForMySqlOfflineDatabaseInput> { new MigrateMySqlAzureDbForMySqlOfflineDatabaseInput { Name = "someSourceDatabaseName", TargetDatabaseName = "someTargetDatabaseName", TableMap = new Dictionary<string, string> { { "someTableSource", "someTableSource" } } } }) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } private ProjectTask CreateDMSMySqlSyncTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new MigrateMySqlAzureDbForMySqlSyncTaskProperties { Input = new MigrateMySqlAzureDbForMySqlSyncTaskInput( new MySqlConnectionInfo { ServerName = @"someSourceServerName", UserName = "someSourceUser", Password = "someSourcePassword" }, new MySqlConnectionInfo { ServerName = @"someTargetServerName", UserName = "someTargetUser", Password = "someTargetPassword" }, new List<MigrateMySqlAzureDbForMySqlSyncDatabaseInput> { new MigrateMySqlAzureDbForMySqlSyncDatabaseInput { Name = "someSourceDatabaseName", TargetDatabaseName = "someTargetDatabaseName", TableMap = new Dictionary<string, string> { { "someTableSource", "someTableSource" } } } }) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } private ProjectTask CreateDMSSqlSyncTask(MockContext context, DataMigrationServiceClient client, ResourceGroup resourceGroup, DataMigrationService service, string dmsProjectName, string dmsTaskName) { var taskProps = new MigrateSqlServerSqlDbSyncTaskProperties { Input = new MigrateSqlServerSqlDbSyncTaskInput( new SqlConnectionInfo { DataSource = @"someSourceServerName", UserName = "someSourceUser", Password = "someSourcePassword" }, new SqlConnectionInfo { DataSource = @"someTargetServerName", UserName = "someTargetUser", Password = "someTargetPassword" }, new List<MigrateSqlServerSqlDbSyncDatabaseInput> { new MigrateSqlServerSqlDbSyncDatabaseInput { Name = "someSourceDatabaseName", TargetDatabaseName = "someTargetDatabaseName", TableMap = new Dictionary<string, string> { { "someTableSource", "someTableSource" } } } }) }; return client.Tasks.CreateOrUpdate( new ProjectTask( properties: taskProps), resourceGroup.Name, service.Name, dmsProjectName, dmsTaskName); } private string testName; } }
// 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.Dynamic; using System.Dynamic.Utils; using System.Linq.Expressions; using System.Reflection; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Runtime.CompilerServices { // // A CallSite provides a fast mechanism for call-site caching of dynamic dispatch // behavior. Each site will hold onto a delegate that provides a fast-path dispatch // based on previous types that have been seen at the call-site. This delegate will // call UpdateAndExecute if it is called with types that it hasn't seen before. // Updating the binding will typically create (or lookup) a new delegate // that supports fast-paths for both the new type and for any types that // have been seen previously. // // DynamicSites will generate the fast-paths specialized for sets of runtime argument // types. However, they will generate exactly the right amount of code for the types // that are seen in the program so that int addition will remain as fast as it would // be with custom implementation of the addition, and the user-defined types can be // as fast as ints because they will all have the same optimal dynamically generated // fast-paths. // // DynamicSites don't encode any particular caching policy, but use their // CallSiteBinding to encode a caching policy. // /// <summary> /// A Dynamic Call Site base class. This type is used as a parameter type to the /// dynamic site targets. The first parameter of the delegate (T) below must be /// of this type. /// </summary> public class CallSite { /// <summary> /// String used for generated CallSite methods. /// </summary> internal const string CallSiteTargetMethodName = "CallSite.Target"; /// <summary> /// Cache of CallSite constructors for a given delegate type. /// </summary> private static volatile CacheDict<Type, Func<CallSiteBinder, CallSite>> s_siteCtors; /// <summary> /// The Binder responsible for binding operations at this call site. /// This binder is invoked by the UpdateAndExecute below if all Level 0, /// Level 1 and Level 2 caches experience cache miss. /// </summary> internal readonly CallSiteBinder _binder; // only CallSite<T> derives from this internal CallSite(CallSiteBinder binder) { _binder = binder; } /// <summary> /// Used by Matchmaker sites to indicate rule match. /// </summary> internal bool _match; /// <summary> /// Class responsible for binding dynamic operations on the dynamic site. /// </summary> public CallSiteBinder Binder => _binder; /// <summary> /// Creates a CallSite with the given delegate type and binder. /// </summary> /// <param name="delegateType">The CallSite delegate type.</param> /// <param name="binder">The CallSite binder.</param> /// <returns>The new CallSite.</returns> public static CallSite Create(Type delegateType, CallSiteBinder binder) { ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); ContractUtils.RequiresNotNull(binder, nameof(binder)); if (!delegateType.IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate(); CacheDict<Type, Func<CallSiteBinder, CallSite>> ctors = s_siteCtors; if (ctors == null) { // It's okay to just set this, worst case we're just throwing away some data s_siteCtors = ctors = new CacheDict<Type, Func<CallSiteBinder, CallSite>>(100); } Func<CallSiteBinder, CallSite> ctor; MethodInfo method = null; if (!ctors.TryGetValue(delegateType, out ctor)) { method = typeof(CallSite<>).MakeGenericType(delegateType).GetMethod(nameof(Create)); if (delegateType.CanCache()) { ctor = (Func<CallSiteBinder, CallSite>)method.CreateDelegate(typeof(Func<CallSiteBinder, CallSite>)); ctors.Add(delegateType, ctor); } } if (ctor != null) { return ctor(binder); } // slow path return (CallSite)method.Invoke(null, new object[] { binder }); } } /// <summary> /// Dynamic site type. /// </summary> /// <typeparam name="T">The delegate type.</typeparam> public partial class CallSite<T> : CallSite where T : class { /// <summary> /// The update delegate. Called when the dynamic site experiences cache miss. /// </summary> /// <returns>The update delegate.</returns> public T Update { get { // if this site is set up for match making, then use NoMatch as an Update if (_match) { Debug.Assert(s_cachedNoMatch != null, "all normal sites should have Update cached once there is an instance."); return s_cachedNoMatch; } else { Debug.Assert(s_cachedUpdate != null, "all normal sites should have Update cached once there is an instance."); return s_cachedUpdate; } } } /// <summary> /// The Level 0 cache - a delegate specialized based on the site history. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] public T Target; /// <summary> /// The Level 1 cache - a history of the dynamic site. /// </summary> internal T[] Rules; // Cached update delegate for all sites with a given T private static T s_cachedUpdate; // Cached noMatch delegate for all sites with a given T private static volatile T s_cachedNoMatch; private CallSite(CallSiteBinder binder) : base(binder) { Target = GetUpdateDelegate(); } private CallSite() : base(null) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] internal CallSite<T> CreateMatchMaker() { return new CallSite<T>(); } /// <summary> /// Creates an instance of the dynamic call site, initialized with the binder responsible for the /// runtime binding of the dynamic operations at this call site. /// </summary> /// <param name="binder">The binder responsible for the runtime binding of the dynamic operations at this call site.</param> /// <returns>The new instance of dynamic call site.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static CallSite<T> Create(CallSiteBinder binder) { if (!typeof(T).IsSubclassOf(typeof(MulticastDelegate))) throw System.Linq.Expressions.Error.TypeMustBeDerivedFromSystemDelegate(); ContractUtils.RequiresNotNull(binder, nameof(binder)); return new CallSite<T>(binder); } private T GetUpdateDelegate() { // This is intentionally non-static to speed up creation - in particular MakeUpdateDelegate // as static generic methods are more expensive than instance methods. We call a ref helper // so we only access the generic static field once. return GetUpdateDelegate(ref s_cachedUpdate); } private T GetUpdateDelegate(ref T addr) { if (addr == null) { // reduce creation cost by not using Interlocked.CompareExchange. Calling I.CE causes // us to spend 25% of our creation time in JIT_GenericHandle. Instead we'll rarely // create 2 delegates with no other harm caused. addr = MakeUpdateDelegate(); } return addr; } /// <summary> /// Clears the rule cache ... used by the call site tests. /// </summary> private void ClearRuleCache() { // make sure it initialized/atomized etc... Binder.GetRuleCache<T>(); Dictionary<Type, object> cache = Binder.Cache; if (cache != null) { lock (cache) { cache.Clear(); } } } private const int MaxRules = 10; internal void AddRule(T newRule) { T[] rules = Rules; if (rules == null) { Rules = new[] { newRule }; return; } T[] temp; if (rules.Length < (MaxRules - 1)) { temp = new T[rules.Length + 1]; Array.Copy(rules, 0, temp, 1, rules.Length); } else { temp = new T[MaxRules]; Array.Copy(rules, 0, temp, 1, MaxRules - 1); } temp[0] = newRule; Rules = temp; } // moves rule +2 up. internal void MoveRule(int i) { if (i > 1) { T[] rules = Rules; T rule = rules[i]; rules[i] = rules[i - 1]; rules[i - 1] = rules[i - 2]; rules[i - 2] = rule; } } internal T MakeUpdateDelegate() { #if !FEATURE_COMPILE Type target = typeof(T); MethodInfo invoke = target.GetMethod("Invoke"); s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke); return CreateCustomUpdateDelegate(invoke); #else Type target = typeof(T); Type[] args; MethodInfo invoke = target.GetMethod("Invoke"); if (target.IsGenericType && IsSimpleSignature(invoke, out args)) { MethodInfo method = null; MethodInfo noMatchMethod = null; if (invoke.ReturnType == typeof(void)) { if (target == System.Linq.Expressions.Compiler.DelegateHelpers.GetActionType(args.AddFirst(typeof(CallSite)))) { method = typeof(UpdateDelegates).GetMethod("UpdateAndExecuteVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static); noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatchVoid" + args.Length, BindingFlags.NonPublic | BindingFlags.Static); } } else { if (target == System.Linq.Expressions.Compiler.DelegateHelpers.GetFuncType(args.AddFirst(typeof(CallSite)))) { method = typeof(UpdateDelegates).GetMethod("UpdateAndExecute" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static); noMatchMethod = typeof(UpdateDelegates).GetMethod("NoMatch" + (args.Length - 1), BindingFlags.NonPublic | BindingFlags.Static); } } if (method != null) { s_cachedNoMatch = (T)(object)CreateDelegateHelper(target, noMatchMethod.MakeGenericMethod(args)); return (T)(object)CreateDelegateHelper(target, method.MakeGenericMethod(args)); } } s_cachedNoMatch = CreateCustomNoMatchDelegate(invoke); return CreateCustomUpdateDelegate(invoke); #endif } #if FEATURE_COMPILE // This needs to be SafeCritical to allow access to // internal types from user code as generic parameters. // // It's safe for a few reasons: // 1. The internal types are coming from a lower trust level (app code) // 2. We got the internal types from our own generic parameter: T // 3. The UpdateAndExecute methods don't do anything with the types, // we just want the CallSite args to be strongly typed to avoid // casting. // 4. Works on desktop CLR with AppDomain that has only Execute // permission. In theory it might require RestrictedMemberAccess, // but it's unclear because we have tests passing without RMA. // // When Silverlight gets RMA we may be able to remove this. [System.Security.SecuritySafeCritical] private static Delegate CreateDelegateHelper(Type delegateType, MethodInfo method) { return method.CreateDelegate(delegateType); } private static bool IsSimpleSignature(MethodInfo invoke, out Type[] sig) { ParameterInfo[] pis = invoke.GetParametersCached(); ContractUtils.Requires(pis.Length > 0 && pis[0].ParameterType == typeof(CallSite), nameof(T)); Type[] args = new Type[invoke.ReturnType != typeof(void) ? pis.Length : pis.Length - 1]; bool supported = true; for (int i = 1; i < pis.Length; i++) { ParameterInfo pi = pis[i]; if (pi.IsByRefParameter()) { supported = false; } args[i - 1] = pi.ParameterType; } if (invoke.ReturnType != typeof(void)) { args[args.Length - 1] = invoke.ReturnType; } sig = args; return supported; } #endif [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private T CreateCustomUpdateDelegate(MethodInfo invoke) { Type returnType = invoke.GetReturnType(); bool isVoid = returnType == typeof(void); var body = new ArrayBuilder<Expression>(13); var vars = new ArrayBuilder<ParameterExpression>(8 + (isVoid ? 0 : 1)); ParameterExpression[] @params = Array.ConvertAll(invoke.GetParametersCached(), p => Expression.Parameter(p.ParameterType, p.Name)); LabelTarget @return = Expression.Label(returnType); Type[] typeArgs = new[] { typeof(T) }; ParameterExpression site = @params[0]; ParameterExpression[] arguments = @params.RemoveFirst(); ParameterExpression @this = Expression.Variable(typeof(CallSite<T>), "this"); vars.UncheckedAdd(@this); body.UncheckedAdd(Expression.Assign(@this, Expression.Convert(site, @this.Type))); ParameterExpression applicable = Expression.Variable(typeof(T[]), "applicable"); vars.UncheckedAdd(applicable); ParameterExpression rule = Expression.Variable(typeof(T), "rule"); vars.UncheckedAdd(rule); ParameterExpression originalRule = Expression.Variable(typeof(T), "originalRule"); vars.UncheckedAdd(originalRule); Expression target = Expression.Field(@this, nameof(Target)); body.UncheckedAdd(Expression.Assign(originalRule, target)); ParameterExpression result = null; if (!isVoid) { vars.UncheckedAdd(result = Expression.Variable(@return.Type, "result")); } ParameterExpression count = Expression.Variable(typeof(int), "count"); vars.UncheckedAdd(count); ParameterExpression index = Expression.Variable(typeof(int), "index"); vars.UncheckedAdd(index); body.UncheckedAdd( Expression.Assign( site, Expression.Call( CallSiteOps_CreateMatchmaker.MakeGenericMethod(typeArgs), @this ) ) ); Expression processRule; Expression getMatch = Expression.Call(CallSiteOps_GetMatch, site); Expression resetMatch = Expression.Call(CallSiteOps_ClearMatch, site); Expression invokeRule = Expression.Invoke(rule, new TrueReadOnlyCollection<Expression>(@params)); Expression onMatch = Expression.Call( CallSiteOps_UpdateRules.MakeGenericMethod(typeArgs), @this, index ); if (isVoid) { processRule = Expression.Block( invokeRule, Expression.IfThen( getMatch, Expression.Block(onMatch, Expression.Return(@return)) ) ); } else { processRule = Expression.Block( Expression.Assign(result, invokeRule), Expression.IfThen( getMatch, Expression.Block(onMatch, Expression.Return(@return, result)) ) ); } Expression getApplicableRuleAtIndex = Expression.Assign(rule, Expression.ArrayAccess(applicable, new TrueReadOnlyCollection<Expression>(index))); Expression getRule = getApplicableRuleAtIndex; LabelTarget @break = Expression.Label(); Expression breakIfDone = Expression.IfThen( Expression.Equal(index, count), Expression.Break(@break) ); Expression incrementIndex = Expression.PreIncrementAssign(index); body.UncheckedAdd( Expression.IfThen( Expression.NotEqual( Expression.Assign( applicable, Expression.Call( CallSiteOps_GetRules.MakeGenericMethod(typeArgs), @this ) ), Expression.Constant(null, applicable.Type) ), Expression.Block( Expression.Assign(count, Expression.ArrayLength(applicable)), Expression.Assign(index, Utils.Constant(0)), Expression.Loop( Expression.Block( breakIfDone, getRule, Expression.IfThen( Expression.NotEqual( Expression.Convert(rule, typeof(object)), Expression.Convert(originalRule, typeof(object)) ), Expression.Block( Expression.Assign( target, rule ), processRule, resetMatch ) ), incrementIndex ), @break, @continue: null ) ) ) ); //// //// Level 2 cache lookup //// // //// //// Any applicable rules in level 2 cache? //// ParameterExpression cache = Expression.Variable(typeof(RuleCache<T>), "cache"); vars.UncheckedAdd(cache); body.UncheckedAdd( Expression.Assign( cache, Expression.Call(CallSiteOps_GetRuleCache.MakeGenericMethod(typeArgs), @this) ) ); body.UncheckedAdd( Expression.Assign( applicable, Expression.Call(CallSiteOps_GetCachedRules.MakeGenericMethod(typeArgs), cache) ) ); // L2 invokeRule is different (no onMatch) if (isVoid) { processRule = Expression.Block( invokeRule, Expression.IfThen( getMatch, Expression.Return(@return) ) ); } else { processRule = Expression.Block( Expression.Assign(result, invokeRule), Expression.IfThen( getMatch, Expression.Return(@return, result) ) ); } Expression tryRule = Expression.TryFinally( processRule, Expression.IfThen( getMatch, Expression.Block( Expression.Call(CallSiteOps_AddRule.MakeGenericMethod(typeArgs), @this, rule), Expression.Call(CallSiteOps_MoveRule.MakeGenericMethod(typeArgs), cache, rule, index) ) ) ); getRule = Expression.Assign( target, getApplicableRuleAtIndex ); body.UncheckedAdd(Expression.Assign(index, Utils.Constant(0))); body.UncheckedAdd(Expression.Assign(count, Expression.ArrayLength(applicable))); body.UncheckedAdd( Expression.Loop( Expression.Block( breakIfDone, getRule, tryRule, resetMatch, incrementIndex ), @break, @continue: null ) ); //// //// Miss on Level 0, 1 and 2 caches. Create new rule //// body.UncheckedAdd(Expression.Assign(rule, Expression.Constant(null, rule.Type))); ParameterExpression args = Expression.Variable(typeof(object[]), "args"); Expression[] argsElements = Array.ConvertAll(arguments, p => Convert(p, typeof(object))); vars.UncheckedAdd(args); body.UncheckedAdd( Expression.Assign( args, Expression.NewArrayInit(typeof(object), new TrueReadOnlyCollection<Expression>(argsElements)) ) ); Expression setOldTarget = Expression.Assign( target, originalRule ); getRule = Expression.Assign( target, Expression.Assign( rule, Expression.Call( CallSiteOps_Bind.MakeGenericMethod(typeArgs), Expression.Property(@this, nameof(Binder)), @this, args ) ) ); tryRule = Expression.TryFinally( processRule, Expression.IfThen( getMatch, Expression.Call( CallSiteOps_AddRule.MakeGenericMethod(typeArgs), @this, rule ) ) ); body.UncheckedAdd( Expression.Loop( Expression.Block(setOldTarget, getRule, tryRule, resetMatch), @break: null, @continue: null ) ); body.UncheckedAdd(Expression.Default(@return.Type)); Expression<T> lambda = Expression.Lambda<T>( Expression.Label( @return, Expression.Block( vars.ToReadOnly(), body.ToReadOnly() ) ), CallSiteTargetMethodName, true, // always compile the rules with tail call optimization new TrueReadOnlyCollection<ParameterExpression>(@params) ); // Need to compile with forceDynamic because T could be invisible, // or one of the argument types could be invisible return lambda.Compile(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] private T CreateCustomNoMatchDelegate(MethodInfo invoke) { ParameterExpression[] @params = Array.ConvertAll(invoke.GetParametersCached(), p => Expression.Parameter(p.ParameterType, p.Name)); return Expression.Lambda<T>( Expression.Block( Expression.Call( typeof(CallSiteOps).GetMethod(nameof(CallSiteOps.SetNotMatched)), @params[0] ), Expression.Default(invoke.GetReturnType()) ), new TrueReadOnlyCollection<ParameterExpression>(@params) ).Compile(); } private static Expression Convert(Expression arg, Type type) { if (TypeUtils.AreReferenceAssignable(type, arg.Type)) { return arg; } return Expression.Convert(arg, type); } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using SchoolBusAPI.Models; using SchoolBusAPI.ViewModels; namespace SchoolBusAPI.Services.Impl { /// <summary> /// /// </summary> public class DistrictApiService : IDistrictApiService { private readonly DbAppContext _context; /// <summary> /// Create a service and set the database context /// </summary> public DistrictApiService(DbAppContext context) { _context = context; } /// <summary> /// /// </summary> /// <remarks>Adds a number of districts.</remarks> /// <param name="items"></param> /// <response code="200">OK</response> public virtual IActionResult DistrictsBulkPostAsync(District[] items) { if (items == null) { return new BadRequestResult(); } foreach (District item in items) { // avoid inserting a Region if possible. int region_id = item.Region.Id; var exists = _context.Regions.Any(a => a.Id == region_id); if (exists) { Region region = _context.Regions.First(a => a.Id == region_id); item.Region = region; } exists = _context.Districts.Any(a => a.Id == item.Id); if (exists) { _context.Districts.Update(item); } else { _context.Districts.Add(item); } } // Save the changes _context.SaveChanges(); return new NoContentResult(); } /// <summary> /// /// </summary> /// <remarks>Returns a list of available districts</remarks> /// <response code="200">OK</response> public virtual IActionResult DistrictsGetAsync() { // eager loading of regions var result = _context.Districts .Include(x => x.Region) .ToList(); return new ObjectResult(result); } /// <summary> /// /// </summary> /// <remarks>Deletes a district</remarks> /// <param name="id">id of District to delete</param> /// <response code="200">OK</response> /// <response code="404">District not found</response> public virtual IActionResult DistrictsIdDeletePostAsync(int id) { var exists = _context.Districts.Any(a => a.Id == id); if (exists) { var item = _context.Districts.First(a => a.Id == id); if (item != null) { _context.Districts.Remove(item); // Save the changes _context.SaveChanges(); } return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Returns a specific district</remarks> /// <param name="id">id of Districts to fetch</param> /// <response code="200">OK</response> public virtual IActionResult DistrictsIdGetAsync(int id) { var exists = _context.Districts.Any(a => a.Id == id); if (exists) { var result = _context.Districts .Where(a => a.Id == id) .Include(a => a.Region) .FirstOrDefault(); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Updates a district</remarks> /// <param name="id">id of District to update</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">District not found</response> public virtual IActionResult DistrictsIdPutAsync(int id, District body) { var exists = _context.Districts.Any(a => a.Id == id); if (exists && id == body.Id) { _context.Districts.Update(body); // Save the changes _context.SaveChanges(); return new ObjectResult(body); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <remarks>Returns the Service Areas for a specific region</remarks> /// <param name="id">id of District for which to fetch the ServiceAreas</param> /// <response code="200">OK</response> public virtual IActionResult DistrictsIdServiceareasGetAsync(int id) { var result = ""; return new ObjectResult(result); } /// <summary> /// /// </summary> /// <remarks>Adds a district</remarks> /// <param name="body"></param> /// <response code="200">OK</response> public virtual IActionResult DistrictsPostAsync(District body) { // adjust region int region_id = body.Region.Id; var exists = _context.Regions.Any(a => a.Id == region_id); if (exists) { Region region = _context.Regions.First(a => a.Id == region_id); body.Region = region; } _context.Districts.Add(body); _context.SaveChanges(); return new ObjectResult(body); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyInteger { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// IntModel operations. /// </summary> public partial class IntModel : IServiceOperations<AutoRestIntegerTestService>, IIntModel { /// <summary> /// Initializes a new instance of the IntModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> public IntModel(AutoRestIntegerTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestIntegerTestService /// </summary> public AutoRestIntegerTestService Client { get; private set; } /// <summary> /// Get null Int value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<int?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetNull", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/null").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<int?>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get invalid Int value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<int?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/invalid").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<int?>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<int?>> GetOverflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetOverflowInt32", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/overflowint32").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<int?>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<int?>> GetUnderflowInt32WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetUnderflowInt32", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/underflowint32").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<int?>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<int?>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<long?>> GetOverflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetOverflowInt64", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/overflowint64").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<long?>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<long?>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<long?>> GetUnderflowInt64WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetUnderflowInt64", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/underflowint64").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse<long?>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<long?>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put max int32 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutMax32WithHttpMessagesAsync(int? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (intBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "intBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutMax32", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/max/32").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put max int64 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutMax64WithHttpMessagesAsync(long? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (intBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "intBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutMax64", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/max/64").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put min int32 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutMin32WithHttpMessagesAsync(int? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (intBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "intBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutMin32", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/min/32").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// Put min int64 value /// </summary> /// <param name='intBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse> PutMin64WithHttpMessagesAsync(long? intBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (intBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "intBody"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("intBody", intBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "PutMin64", tracingParameters); } // Construct URL var url = new Uri(this.Client.BaseUri, "/int/min/64").ToString(); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } ex.Request = httpRequest; ex.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new HttpOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// 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; using System.Diagnostics.Contracts; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using DotNetty.Common; using DotNetty.Common.Utilities; /// <summary> /// Abstract base class implementation of a <see cref="IByteBuffer" /> /// </summary> public abstract class AbstractByteBuffer : IByteBuffer { internal static readonly ResourceLeakDetector LeakDetector = ResourceLeakDetector.Create<IByteBuffer>(); int markedReaderIndex; int markedWriterIndex; SwappedByteBuffer swappedByteBuffer; protected AbstractByteBuffer(int maxCapacity) { this.MaxCapacity = maxCapacity; } public abstract int Capacity { get; } public abstract IByteBuffer AdjustCapacity(int newCapacity); public int MaxCapacity { get; protected set; } public abstract IByteBufferAllocator Allocator { get; } public virtual int ReaderIndex { get; protected set; } public virtual int WriterIndex { get; protected set; } public virtual IByteBuffer SetWriterIndex(int writerIndex) { if (writerIndex < this.ReaderIndex || writerIndex > this.Capacity) { throw new IndexOutOfRangeException($"WriterIndex: {writerIndex} (expected: 0 <= readerIndex({this.ReaderIndex}) <= writerIndex <= capacity ({this.Capacity})"); } this.WriterIndex = writerIndex; return this; } public virtual IByteBuffer SetReaderIndex(int readerIndex) { if (readerIndex < 0 || readerIndex > this.WriterIndex) { throw new IndexOutOfRangeException($"ReaderIndex: {readerIndex} (expected: 0 <= readerIndex <= writerIndex({this.WriterIndex})"); } this.ReaderIndex = readerIndex; return this; } public virtual IByteBuffer SetIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > this.Capacity) { throw new IndexOutOfRangeException($"ReaderIndex: {readerIndex}, WriterIndex: {writerIndex} (expected: 0 <= readerIndex <= writerIndex <= capacity ({this.Capacity})"); } this.ReaderIndex = readerIndex; this.WriterIndex = writerIndex; return this; } public virtual int ReadableBytes => this.WriterIndex - this.ReaderIndex; public virtual int WritableBytes => this.Capacity - this.WriterIndex; public virtual int MaxWritableBytes => this.MaxCapacity - this.WriterIndex; public bool IsReadable() => this.IsReadable(1); public bool IsReadable(int size) => this.ReadableBytes >= size; public bool IsWritable() => this.IsWritable(1); public bool IsWritable(int size) => this.WritableBytes >= size; public virtual IByteBuffer Clear() { this.ReaderIndex = this.WriterIndex = 0; return this; } public virtual IByteBuffer MarkReaderIndex() { this.markedReaderIndex = this.ReaderIndex; return this; } public virtual IByteBuffer ResetReaderIndex() { this.SetReaderIndex(this.markedReaderIndex); return this; } public virtual IByteBuffer MarkWriterIndex() { this.markedWriterIndex = this.WriterIndex; return this; } public virtual IByteBuffer ResetWriterIndex() { this.SetWriterIndex(this.markedWriterIndex); return this; } public virtual IByteBuffer DiscardReadBytes() { this.EnsureAccessible(); if (this.ReaderIndex == 0) { return this; } if (this.ReaderIndex != this.WriterIndex) { this.SetBytes(0, this, this.ReaderIndex, this.WriterIndex - this.ReaderIndex); this.WriterIndex -= this.ReaderIndex; this.AdjustMarkers(this.ReaderIndex); this.ReaderIndex = 0; } else { this.AdjustMarkers(this.ReaderIndex); this.WriterIndex = this.ReaderIndex = 0; } return this; } public virtual IByteBuffer DiscardSomeReadBytes() { this.EnsureAccessible(); if (this.ReaderIndex == 0) { return this; } if (this.ReaderIndex == this.WriterIndex) { this.AdjustMarkers(this.ReaderIndex); this.WriterIndex = this.ReaderIndex = 0; return this; } if (this.ReaderIndex >= this.Capacity.RightUShift(1)) { this.SetBytes(0, this, this.ReaderIndex, this.WriterIndex - this.ReaderIndex); this.WriterIndex -= this.ReaderIndex; this.AdjustMarkers(this.ReaderIndex); this.ReaderIndex = 0; } return this; } public virtual IByteBuffer EnsureWritable(int minWritableBytes) { if (minWritableBytes < 0) { throw new ArgumentOutOfRangeException(nameof(minWritableBytes), "expected minWritableBytes to be greater than zero"); } if (minWritableBytes <= this.WritableBytes) { return this; } if (minWritableBytes > this.MaxCapacity - this.WriterIndex) { throw new IndexOutOfRangeException($"writerIndex({this.WriterIndex}) + minWritableBytes({minWritableBytes}) exceeds maxCapacity({this.MaxCapacity}): {this}"); } //Normalize the current capacity to the power of 2 int newCapacity = this.CalculateNewCapacity(this.WriterIndex + minWritableBytes); //Adjust to the new capacity this.AdjustCapacity(newCapacity); return this; } public int EnsureWritable(int minWritableBytes, bool force) { Contract.Ensures(minWritableBytes >= 0); if (minWritableBytes <= this.WritableBytes) { return 0; } if (minWritableBytes > this.MaxCapacity - this.WriterIndex) { if (force) { if (this.Capacity == this.MaxCapacity) { return 1; } this.AdjustCapacity(this.MaxCapacity); return 3; } } // Normalize the current capacity to the power of 2. int newCapacity = this.CalculateNewCapacity(this.WriterIndex + minWritableBytes); // Adjust to the new capacity. this.AdjustCapacity(newCapacity); return 2; } int CalculateNewCapacity(int minNewCapacity) { int maxCapacity = this.MaxCapacity; const int Threshold = 4 * 1024 * 1024; // 4 MiB page int newCapacity; if (minNewCapacity == Threshold) { return Threshold; } // If over threshold, do not double but just increase by threshold. if (minNewCapacity > Threshold) { newCapacity = minNewCapacity - (minNewCapacity % Threshold); return Math.Min(maxCapacity, newCapacity + Threshold); } // Not over threshold. Double up to 4 MiB, starting from 64. newCapacity = 64; while (newCapacity < minNewCapacity) { newCapacity <<= 1; } return Math.Min(newCapacity, maxCapacity); } public virtual bool GetBoolean(int index) => this.GetByte(index) != 0; public virtual byte GetByte(int index) { this.CheckIndex(index); return this._GetByte(index); } protected abstract byte _GetByte(int index); public virtual short GetShort(int index) { this.CheckIndex(index, 2); return this._GetShort(index); } protected abstract short _GetShort(int index); public virtual ushort GetUnsignedShort(int index) { unchecked { return (ushort)(this.GetShort(index)); } } public virtual int GetInt(int index) { this.CheckIndex(index, 4); return this._GetInt(index); } protected abstract int _GetInt(int index); public virtual uint GetUnsignedInt(int index) { unchecked { return (uint)(this.GetInt(index)); } } public virtual long GetLong(int index) { this.CheckIndex(index, 8); return this._GetLong(index); } protected abstract long _GetLong(int index); public virtual char GetChar(int index) => Convert.ToChar(this.GetShort(index)); public virtual double GetDouble(int index) => BitConverter.Int64BitsToDouble(this.GetLong(index)); public virtual IByteBuffer GetBytes(int index, IByteBuffer destination) { this.GetBytes(index, destination, destination.WritableBytes); return this; } public virtual IByteBuffer GetBytes(int index, IByteBuffer destination, int length) { this.GetBytes(index, destination, destination.WriterIndex, length); destination.SetWriterIndex(destination.WriterIndex + length); return this; } public abstract IByteBuffer GetBytes(int index, IByteBuffer destination, int dstIndex, int length); public virtual IByteBuffer GetBytes(int index, byte[] destination) { this.GetBytes(index, destination, 0, destination.Length); return this; } public abstract IByteBuffer GetBytes(int index, byte[] destination, int dstIndex, int length); public abstract IByteBuffer GetBytes(int index, Stream destination, int length); public virtual IByteBuffer SetBoolean(int index, bool value) { this.SetByte(index, value ? 1 : 0); return this; } public virtual IByteBuffer SetByte(int index, int value) { this.CheckIndex(index); this._SetByte(index, value); return this; } protected abstract void _SetByte(int index, int value); public virtual IByteBuffer SetShort(int index, int value) { this.CheckIndex(index, 2); this._SetShort(index, value); return this; } public IByteBuffer SetUnsignedShort(int index, ushort value) { this.SetShort(index, value); return this; } protected abstract void _SetShort(int index, int value); public virtual IByteBuffer SetInt(int index, int value) { this.CheckIndex(index, 4); this._SetInt(index, value); return this; } public IByteBuffer SetUnsignedInt(int index, uint value) { unchecked { this.SetInt(index, (int)value); } return this; } protected abstract void _SetInt(int index, int value); public virtual IByteBuffer SetLong(int index, long value) { this.CheckIndex(index, 8); this._SetLong(index, value); return this; } protected abstract void _SetLong(int index, long value); public virtual IByteBuffer SetChar(int index, char value) { this.SetShort(index, value); return this; } public virtual IByteBuffer SetDouble(int index, double value) { this.SetLong(index, BitConverter.DoubleToInt64Bits(value)); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src) { this.SetBytes(index, src, src.ReadableBytes); return this; } public virtual IByteBuffer SetBytes(int index, IByteBuffer src, int length) { this.CheckIndex(index, length); if (src == null) { throw new NullReferenceException("src cannot be null"); } if (length > src.ReadableBytes) { throw new IndexOutOfRangeException($"length({length}) exceeds src.readableBytes({src.ReadableBytes}) where src is: {src}"); } this.SetBytes(index, src, src.ReaderIndex, length); src.SetReaderIndex(src.ReaderIndex + length); return this; } public abstract IByteBuffer SetBytes(int index, IByteBuffer src, int srcIndex, int length); public virtual IByteBuffer SetBytes(int index, byte[] src) { this.SetBytes(index, src, 0, src.Length); return this; } public abstract IByteBuffer SetBytes(int index, byte[] src, int srcIndex, int length); public abstract Task<int> SetBytesAsync(int index, Stream src, int length, CancellationToken cancellationToken); public virtual bool ReadBoolean() => this.ReadByte() != 0; public virtual byte ReadByte() { this.CheckReadableBytes(1); int i = this.ReaderIndex; byte b = this.GetByte(i); this.ReaderIndex = i + 1; return b; } public virtual short ReadShort() { this.CheckReadableBytes(2); short v = this._GetShort(this.ReaderIndex); this.ReaderIndex += 2; return v; } public virtual ushort ReadUnsignedShort() { unchecked { return (ushort)(this.ReadShort()); } } public virtual int ReadInt() { this.CheckReadableBytes(4); int v = this._GetInt(this.ReaderIndex); this.ReaderIndex += 4; return v; } public virtual uint ReadUnsignedInt() { unchecked { return (uint)(this.ReadInt()); } } public virtual long ReadLong() { this.CheckReadableBytes(8); long v = this._GetLong(this.ReaderIndex); this.ReaderIndex += 8; return v; } public virtual char ReadChar() => (char)this.ReadShort(); public virtual double ReadDouble() => BitConverter.Int64BitsToDouble(this.ReadLong()); public IByteBuffer ReadBytes(int length) { this.CheckReadableBytes(length); if (length == 0) { return Unpooled.Empty; } IByteBuffer buf = this.Allocator.Buffer(length, this.MaxCapacity); buf.WriteBytes(this, this.ReaderIndex, length); this.ReaderIndex += length; return buf; } public virtual IByteBuffer ReadBytes(IByteBuffer destination) { this.ReadBytes(destination, destination.WritableBytes); return this; } public virtual IByteBuffer ReadBytes(IByteBuffer destination, int length) { if (length > destination.WritableBytes) { throw new IndexOutOfRangeException($"length({length}) exceeds destination.WritableBytes({destination.WritableBytes}) where destination is: {destination}"); } this.ReadBytes(destination, destination.WriterIndex, length); destination.SetWriterIndex(destination.WriterIndex + length); return this; } public virtual IByteBuffer ReadBytes(IByteBuffer destination, int dstIndex, int length) { this.CheckReadableBytes(length); this.GetBytes(this.ReaderIndex, destination, dstIndex, length); this.ReaderIndex += length; return this; } public virtual IByteBuffer ReadBytes(byte[] destination) { this.ReadBytes(destination, 0, destination.Length); return this; } public virtual IByteBuffer ReadBytes(byte[] destination, int dstIndex, int length) { this.CheckReadableBytes(length); this.GetBytes(this.ReaderIndex, destination, dstIndex, length); this.ReaderIndex += length; return this; } public virtual IByteBuffer ReadBytes(Stream destination, int length) { this.CheckReadableBytes(length); this.GetBytes(this.ReaderIndex, destination, length); this.ReaderIndex += length; return this; } public virtual IByteBuffer SkipBytes(int length) { this.CheckReadableBytes(length); this.ReaderIndex += length; return this; } public virtual IByteBuffer WriteBoolean(bool value) { this.WriteByte(value ? 1 : 0); return this; } public virtual IByteBuffer WriteByte(int value) { this.EnsureAccessible(); this.EnsureWritable(1); this.SetByte(this.WriterIndex, value); this.WriterIndex += 1; return this; } public virtual IByteBuffer WriteShort(int value) { this.EnsureAccessible(); this.EnsureWritable(2); this._SetShort(this.WriterIndex, value); this.WriterIndex += 2; return this; } public IByteBuffer WriteUnsignedShort(ushort value) { unchecked { this.WriteShort((short)value); } return this; } public virtual IByteBuffer WriteInt(int value) { this.EnsureAccessible(); this.EnsureWritable(4); this._SetInt(this.WriterIndex, value); this.WriterIndex += 4; return this; } public IByteBuffer WriteUnsignedInt(uint value) { unchecked { this.WriteInt((int)value); } return this; } public virtual IByteBuffer WriteLong(long value) { this.EnsureAccessible(); this.EnsureWritable(8); this._SetLong(this.WriterIndex, value); this.WriterIndex += 8; return this; } public virtual IByteBuffer WriteChar(char value) { this.WriteShort(value); return this; } public virtual IByteBuffer WriteDouble(double value) { this.WriteLong(BitConverter.DoubleToInt64Bits(value)); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src) { this.WriteBytes(src, src.ReadableBytes); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src, int length) { if (length > src.ReadableBytes) { throw new IndexOutOfRangeException($"length({length}) exceeds src.readableBytes({src.ReadableBytes}) where src is: {src}"); } this.WriteBytes(src, src.ReaderIndex, length); src.SetReaderIndex(src.ReaderIndex + length); return this; } public virtual IByteBuffer WriteBytes(IByteBuffer src, int srcIndex, int length) { this.EnsureAccessible(); this.EnsureWritable(length); this.SetBytes(this.WriterIndex, src, srcIndex, length); this.WriterIndex += length; return this; } public virtual IByteBuffer WriteBytes(byte[] src) { this.WriteBytes(src, 0, src.Length); return this; } public virtual IByteBuffer WriteBytes(byte[] src, int srcIndex, int length) { this.EnsureAccessible(); this.EnsureWritable(length); this.SetBytes(this.WriterIndex, src, srcIndex, length); this.WriterIndex += length; return this; } public abstract int IoBufferCount { get; } public ArraySegment<byte> GetIoBuffer() => this.GetIoBuffer(this.ReaderIndex, this.ReadableBytes); public abstract ArraySegment<byte> GetIoBuffer(int index, int length); public ArraySegment<byte>[] GetIoBuffers() => this.GetIoBuffers(this.ReaderIndex, this.ReadableBytes); public abstract ArraySegment<byte>[] GetIoBuffers(int index, int length); public async Task WriteBytesAsync(Stream stream, int length, CancellationToken cancellationToken) { this.EnsureAccessible(); this.EnsureWritable(length); if (this.WritableBytes < length) { throw new ArgumentOutOfRangeException(nameof(length)); } int writerIndex = this.WriterIndex; int wrote = await this.SetBytesAsync(writerIndex, stream, length, cancellationToken); Contract.Assert(writerIndex == this.WriterIndex); this.SetWriterIndex(writerIndex + wrote); } public Task WriteBytesAsync(Stream stream, int length) => this.WriteBytesAsync(stream, length, CancellationToken.None); public abstract bool HasArray { get; } public abstract byte[] Array { get; } public abstract int ArrayOffset { get; } public virtual byte[] ToArray() { int readableBytes = this.ReadableBytes; if (readableBytes == 0) { return ArrayExtensions.ZeroBytes; } if (this.HasArray) { return this.Array.Slice(this.ArrayOffset + this.ReaderIndex, readableBytes); } var bytes = new byte[readableBytes]; this.GetBytes(this.ReaderIndex, bytes); return bytes; } public virtual IByteBuffer Duplicate() => new DuplicatedByteBuffer(this); public abstract IByteBuffer Unwrap(); public virtual ByteOrder Order // todo: push to actual implementations for them to decide => ByteOrder.BigEndian; public IByteBuffer WithOrder(ByteOrder order) { if (order == this.Order) { return this; } SwappedByteBuffer swappedBuf = this.swappedByteBuffer; if (swappedBuf == null) { this.swappedByteBuffer = swappedBuf = this.NewSwappedByteBuffer(); } return swappedBuf; } /// <summary> /// Creates a new <see cref="SwappedByteBuffer" /> for this <see cref="IByteBuffer" /> instance. /// </summary> /// <returns>A <see cref="SwappedByteBuffer" /> for this buffer.</returns> protected SwappedByteBuffer NewSwappedByteBuffer() => new SwappedByteBuffer(this); protected void AdjustMarkers(int decrement) { int markedReaderIndex = this.markedReaderIndex; if (markedReaderIndex <= decrement) { this.markedReaderIndex = 0; int markedWriterIndex = this.markedWriterIndex; if (markedWriterIndex <= decrement) { this.markedWriterIndex = 0; } else { this.markedWriterIndex = markedWriterIndex - decrement; } } else { this.markedReaderIndex = markedReaderIndex - decrement; this.markedWriterIndex -= decrement; } } public override int GetHashCode() => ByteBufferUtil.HashCode(this); public override bool Equals(object o) => this.Equals(o as IByteBuffer); public bool Equals(IByteBuffer buffer) { if (ReferenceEquals(this, buffer)) { return true; } if (buffer != null) { return ByteBufferUtil.Equals(this, buffer); } return false; } public int CompareTo(IByteBuffer that) => ByteBufferUtil.Compare(this, that); public override string ToString() { if (this.ReferenceCount == 0) { return StringUtil.SimpleClassName(this) + "(freed)"; } StringBuilder buf = new StringBuilder() .Append(StringUtil.SimpleClassName(this)) .Append("(ridx: ").Append(this.ReaderIndex) .Append(", widx: ").Append(this.WriterIndex) .Append(", cap: ").Append(this.Capacity); if (this.MaxCapacity != int.MaxValue) { buf.Append('/').Append(this.MaxCapacity); } IByteBuffer unwrapped = this.Unwrap(); if (unwrapped != null) { buf.Append(", unwrapped: ").Append(unwrapped); } buf.Append(')'); return buf.ToString(); } protected void CheckIndex(int index) { this.EnsureAccessible(); if (index < 0 || index >= this.Capacity) { throw new IndexOutOfRangeException($"index: {index} (expected: range(0, {this.Capacity})"); } } protected void CheckIndex(int index, int fieldLength) { this.EnsureAccessible(); if (fieldLength < 0) { throw new IndexOutOfRangeException($"length: {fieldLength} (expected: >= 0)"); } if (index < 0 || index > this.Capacity - fieldLength) { throw new IndexOutOfRangeException($"index: {index}, length: {fieldLength} (expected: range(0, {this.Capacity})"); } } protected void CheckSrcIndex(int index, int length, int srcIndex, int srcCapacity) { this.CheckIndex(index, length); if (srcIndex < 0 || srcIndex > srcCapacity - length) { throw new IndexOutOfRangeException($"srcIndex: {srcIndex}, length: {length} (expected: range(0, {srcCapacity}))"); } } protected void CheckDstIndex(int index, int length, int dstIndex, int dstCapacity) { this.CheckIndex(index, length); if (dstIndex < 0 || dstIndex > dstCapacity - length) { throw new IndexOutOfRangeException($"dstIndex: {dstIndex}, length: {length} (expected: range(0, {dstCapacity}))"); } } /// <summary> /// Throws a <see cref="IndexOutOfRangeException" /> if the current <see cref="ReadableBytes" /> of this buffer /// is less than <see cref="minimumReadableBytes" />. /// </summary> protected void CheckReadableBytes(int minimumReadableBytes) { this.EnsureAccessible(); if (minimumReadableBytes < 0) { throw new ArgumentOutOfRangeException(nameof(minimumReadableBytes), $"minimumReadableBytes: {minimumReadableBytes} (expected: >= 0)"); } if (this.ReaderIndex > this.WriterIndex - minimumReadableBytes) { throw new IndexOutOfRangeException($"readerIndex({this.ReaderIndex}) + length({minimumReadableBytes}) exceeds writerIndex({this.WriterIndex}): {this}"); } } protected void CheckNewCapacity(int newCapacity) { this.EnsureAccessible(); if (newCapacity < 0 || newCapacity > this.MaxCapacity) { throw new ArgumentOutOfRangeException(nameof(newCapacity), $"newCapacity: {newCapacity} (expected: 0-{this.MaxCapacity})"); } } protected void EnsureAccessible() { if (this.ReferenceCount == 0) { throw new IllegalReferenceCountException(0); } } public IByteBuffer Copy() => this.Copy(this.ReaderIndex, this.ReadableBytes); public abstract IByteBuffer Copy(int index, int length); public IByteBuffer Slice() => this.Slice(this.ReaderIndex, this.ReadableBytes); public virtual IByteBuffer Slice(int index, int length) => new SlicedByteBuffer(this, index, length); public IByteBuffer ReadSlice(int length) { IByteBuffer slice = this.Slice(this.ReaderIndex, length); this.ReaderIndex += length; return slice; } public abstract int ReferenceCount { get; } public abstract IReferenceCounted Retain(); public abstract IReferenceCounted Retain(int increment); public abstract IReferenceCounted Touch(); public abstract IReferenceCounted Touch(object hint); public abstract bool Release(); public abstract bool Release(int decrement); protected void DiscardMarkers() { this.markedReaderIndex = this.markedWriterIndex = 0; } public string ToString(Encoding encoding) => this.ToString(this.ReaderIndex, this.ReadableBytes, encoding); public string ToString(int index, int length, Encoding encoding) => ByteBufferUtil.DecodeString(this, index, length, encoding); public int ForEachByte(ByteProcessor processor) { int index = this.ReaderIndex; int length = this.WriterIndex - index; this.EnsureAccessible(); return this.ForEachByteAsc0(index, length, processor); } public int ForEachByte(int index, int length, ByteProcessor processor) { this.CheckIndex(index, length); return this.ForEachByteAsc0(index, length, processor); } int ForEachByteAsc0(int index, int length, ByteProcessor processor) { if (processor == null) { throw new ArgumentNullException(nameof(processor)); } if (length == 0) { return -1; } int endIndex = index + length; int i = index; do { if (processor.Process(this._GetByte(i))) { i++; } else { return i; } } while (i < endIndex); return -1; } public int ForEachByteDesc(ByteProcessor processor) { int index = this.ReaderIndex; int length = this.WriterIndex - index; this.EnsureAccessible(); return this.ForEachByteDesc0(index, length, processor); } public int ForEachByteDesc(int index, int length, ByteProcessor processor) { this.CheckIndex(index, length); return this.ForEachByteDesc0(index, length, processor); } int ForEachByteDesc0(int index, int length, ByteProcessor processor) { if (processor == null) { throw new NullReferenceException("processor"); } if (length == 0) { return -1; } int i = index + length - 1; do { if (processor.Process(this._GetByte(i))) { i--; } else { return i; } } while (i >= index); return -1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.Location.Paths.Axes { /// <summary> /// Location Paths - Axes (matches) /// </summary> public static partial class MatchesTests { /// <summary> /// Expected: Error (Not supported for Matches). /// ancestor::* (Matches) /// </summary> [Fact] public static void MatchesTest71() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap/Para/Para/Origin"; var testExpression = @"ancestor::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// attribute::* (Matches = true) /// </summary> [Fact] public static void MatchesTest72() { var xml = "xp002.xml"; var startingNodePath = "/Doc/Chap/Title/@Attr1"; var testExpression = @"attribute::*"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). Fix test code to move to testexpr node, thus expected=true. /// attribute::* (Matches = true) /// </summary> [Fact] public static void MatchesTest73() { var xml = "xp002.xml"; var startingNodePath = "/Doc/Chap/Title"; var testExpression = @"attribute::*"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// /para/attribute::* (Matches = true) /// </summary> [Fact] public static void MatchesTest74() { var xml = "xp002.xml"; var startingNodePath = "/Doc/Chap/Title/@Attr1"; var testExpression = @"/Doc/Chap/Title/attribute::*"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// /para/attribute::* (Matches = false) /// </summary> [Fact] public static void MatchesTest75() { var xml = "xp002.xml"; var startingNodePath = "/Doc/Chap/Title/@Attr1"; var testExpression = @"/Doc/Chap/attribute::*"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// child::* (Matches = true) /// </summary> [Fact] public static void MatchesTest76() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"child::*"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// child::* (Matches = false) /// </summary> [Fact] public static void MatchesTest77() { var xml = "xp002.xml"; var startingNodePath = "/Doc/Chap/Title/@Attr1"; var testExpression = @"child::*"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// /para/child::* (Matches = true) /// </summary> [Fact] public static void MatchesTest78() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Title"; var testExpression = @"/Doc/child::*"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). Fix test code to move to testexpr node, thus expected=true. /// /para/child::* (Matches = true) /// </summary> [Fact] public static void MatchesTest79() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap/Title"; var testExpression = @"/Doc/child::*"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// descendant::* (Matches) /// </summary> [Fact] public static void MatchesTest710() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"descendant::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected Error, not supported for matches /// descendant-or-self::* (Matches) /// </summary> [Fact] public static void MatchesTest711() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"descendant-or-self::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// following::* (Matches) /// </summary> [Fact] public static void MatchesTest712() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"following::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// following-sibling::* (Matches) /// </summary> [Fact] public static void MatchesTest713() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"following-sibling::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// parent::* (Matches) /// </summary> [Fact] public static void MatchesTest714() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap/Para"; var testExpression = @"parent::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// preceding::* (Matches) /// </summary> [Fact] public static void MatchesTest715() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"preceding::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// preceding-sibling::* (Matches) /// </summary> [Fact] public static void MatchesTest716() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"preceding-sibling::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// self::* (Matches) /// </summary> [Fact] public static void MatchesTest717() { var xml = "xp001.xml"; var startingNodePath = "/Doc/Chap"; var testExpression = @"self::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the document root. /// / (Matches = true) /// </summary> [Fact] public static void MatchesTest718() { var xml = "xp001.xml"; var testExpression = @"/"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected); } /// <summary> /// Expected: Selects the document root. Fix test code to move to testexpr node, thus expected=true. /// / (Matches = true) /// </summary> [Fact] public static void MatchesTest719() { var xml = "xp001.xml"; var startingNodePath = "/Doc"; var testExpression = @"/"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// ancestor::bookstore /// </summary> [Fact] public static void MatchesTest720() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"ancestor::bookstore"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// ancestor-or-self::node() /// </summary> [Fact] public static void MatchesTest721() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"ancestor-or-self::node()"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// descendant::title /// </summary> [Fact] public static void MatchesTest722() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"descendant::title"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// descendant-or-self::node() /// </summary> [Fact] public static void MatchesTest723() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"descendant-or-self::node()"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// parent::bookstore /// </summary> [Fact] public static void MatchesTest724() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"parent::bookstore"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// following::book /// </summary> [Fact] public static void MatchesTest725() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"following::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// following-sibling::node() /// </summary> [Fact] public static void MatchesTest726() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[1]"; var testExpression = @"following-sibling::node()"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// preceding::book /// </summary> [Fact] public static void MatchesTest727() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[6]"; var testExpression = @"preceding::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// preceding-sibling::magazine /// </summary> [Fact] public static void MatchesTest728() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[6]"; var testExpression = @"preceding-sibling::magazine"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// self::book /// </summary> [Fact] public static void MatchesTest729() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[6]"; var testExpression = @"self::book"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// bookstore//book/parent::bookstore//title /// </summary> [Fact] public static void MatchesTest730() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[6]/title"; var testExpression = @"bookstore//book/parent::bookstore//title"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// //magazine/ancestor-or-self::bookstore//book[6] /// </summary> [Fact] public static void MatchesTest731() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[6]"; var testExpression = @"//magazine/ancestor-or-self::bookstore//book[6]"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error (Not supported for Matches). /// bookstore/self::bookstore/magazine /// </summary> [Fact] public static void MatchesTest732() { var xml = "books.xml"; var startingNodePath = "/bookstore/magazine"; var testExpression = @"bookstore/self::bookstore/magazine"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// Expected: Error /// string('abc') /// </summary> [Fact] public static void MatchesTest733() { var xml = "books.xml"; var startingNodePath = "/bookstore/magazine"; var testExpression = @"string('abc')"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// bookstore|bookstore/magazine|//title /// </summary> [Fact] public static void MatchesTest734() { var xml = "books.xml"; var startingNodePath = "/bookstore/magazine/title"; var testExpression = @"bookstore|bookstore/magazine|//title"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// /bookstore/book|/bookstore/magazine/@*|/bookstore/book[last()]/@style /// </summary> [Fact] public static void MatchesTest735() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[7]/@style"; var testExpression = @"/bookstore/book|/bookstore/magazine/@*|/bookstore/book[last()]/@style"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected Error : following::* not supported for matches /// /bookstore/book|/bookstore/magazine/@*|/bookstore/book[last()]/@style/following::* /// </summary> [Fact] public static void MatchesTest736() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[7]/@style"; var testExpression = @"/bookstore/book|/bookstore/magazine/@*|/bookstore/book[last()]/@style/following::*"; Utils.XPathMatchTestThrows<System.Xml.XPath.XPathException>(xml, testExpression, startingNodePath: startingNodePath); } /// <summary> /// /bookstore/book[last()]/title[text()] /// </summary> [Fact] public static void MatchesTest737() { var xml = "books.xml"; var startingNodePath = "/bookstore/book[7]/title"; var testExpression = @"/bookstore/book[last()]/title[text()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// /bookstore/*[last()]/node() /// </summary> [Fact] public static void MatchesTest738() { var xml = "books.xml"; var startingNodePath = "/bookstore/my:book[3]/my:title"; var testExpression = @"/bookstore/*[last()]/node()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("my", "urn:http//www.placeholder-name-here.com/schema/"); var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// 72687 /// child::*[position() =3][position() =3] /// </summary> [Fact] public static void MatchesTest739() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"child::*[position() =3][position() =3]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// 72687 /// child::*[position() =3 and position() =3] /// </summary> [Fact] public static void MatchesTest740() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"child::*[position() =3 and position() =3]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Regression case for 71617 /// child::*[position() >1][position() <=3] /// </summary> [Fact] public static void MatchesTest741() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"child::*[position() >1][position() <=3]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Alachisoft.NosDB.Common.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class ResponseSessionId { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId, global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static ResponseSessionId() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChdSZXNwb25zZVNlc3Npb25JZC5wcm90bxIgQWxhY2hpc29mdC5Ob3NEQi5D", "b21tb24uUHJvdG9idWYiRQoRUmVzcG9uc2VTZXNzaW9uSWQSFwoPcm91dGVy", "U2Vzc2lvbklkGAEgASgJEhcKD2NsaWVudFNlc3Npb25JZBgCIAEoCUJBCiRj", "b20uYWxhY2hpc29mdC5ub3NkYi5jb21tb24ucHJvdG9idWZCGVJlc3BvbnNl", "U2Vzc2lvbklkUHJvdG9jb2w=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId, global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__Descriptor, new string[] { "RouterSessionId", "ClientSessionId", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ResponseSessionId : pb::GeneratedMessage<ResponseSessionId, ResponseSessionId.Builder> { private ResponseSessionId() { } private static readonly ResponseSessionId defaultInstance = new ResponseSessionId().MakeReadOnly(); private static readonly string[] _responseSessionIdFieldNames = new string[] { "clientSessionId", "routerSessionId" }; private static readonly uint[] _responseSessionIdFieldTags = new uint[] { 18, 10 }; public static ResponseSessionId DefaultInstance { get { return defaultInstance; } } public override ResponseSessionId DefaultInstanceForType { get { return DefaultInstance; } } protected override ResponseSessionId ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.ResponseSessionId.internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<ResponseSessionId, ResponseSessionId.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.ResponseSessionId.internal__static_Alachisoft_NosDB_Common_Protobuf_ResponseSessionId__FieldAccessorTable; } } public const int RouterSessionIdFieldNumber = 1; private bool hasRouterSessionId; private string routerSessionId_ = ""; public bool HasRouterSessionId { get { return hasRouterSessionId; } } public string RouterSessionId { get { return routerSessionId_; } } public const int ClientSessionIdFieldNumber = 2; private bool hasClientSessionId; private string clientSessionId_ = ""; public bool HasClientSessionId { get { return hasClientSessionId; } } public string ClientSessionId { get { return clientSessionId_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _responseSessionIdFieldNames; if (hasRouterSessionId) { output.WriteString(1, field_names[1], RouterSessionId); } if (hasClientSessionId) { output.WriteString(2, field_names[0], ClientSessionId); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasRouterSessionId) { size += pb::CodedOutputStream.ComputeStringSize(1, RouterSessionId); } if (hasClientSessionId) { size += pb::CodedOutputStream.ComputeStringSize(2, ClientSessionId); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static ResponseSessionId ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ResponseSessionId ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ResponseSessionId ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ResponseSessionId ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ResponseSessionId ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ResponseSessionId ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static ResponseSessionId ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static ResponseSessionId ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static ResponseSessionId ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ResponseSessionId ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private ResponseSessionId MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(ResponseSessionId prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<ResponseSessionId, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(ResponseSessionId cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private ResponseSessionId result; private ResponseSessionId PrepareBuilder() { if (resultIsReadOnly) { ResponseSessionId original = result; result = new ResponseSessionId(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override ResponseSessionId MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId.Descriptor; } } public override ResponseSessionId DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId.DefaultInstance; } } public override ResponseSessionId BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is ResponseSessionId) { return MergeFrom((ResponseSessionId) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(ResponseSessionId other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.ResponseSessionId.DefaultInstance) return this; PrepareBuilder(); if (other.HasRouterSessionId) { RouterSessionId = other.RouterSessionId; } if (other.HasClientSessionId) { ClientSessionId = other.ClientSessionId; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_responseSessionIdFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _responseSessionIdFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasRouterSessionId = input.ReadString(ref result.routerSessionId_); break; } case 18: { result.hasClientSessionId = input.ReadString(ref result.clientSessionId_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasRouterSessionId { get { return result.hasRouterSessionId; } } public string RouterSessionId { get { return result.RouterSessionId; } set { SetRouterSessionId(value); } } public Builder SetRouterSessionId(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasRouterSessionId = true; result.routerSessionId_ = value; return this; } public Builder ClearRouterSessionId() { PrepareBuilder(); result.hasRouterSessionId = false; result.routerSessionId_ = ""; return this; } public bool HasClientSessionId { get { return result.hasClientSessionId; } } public string ClientSessionId { get { return result.ClientSessionId; } set { SetClientSessionId(value); } } public Builder SetClientSessionId(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasClientSessionId = true; result.clientSessionId_ = value; return this; } public Builder ClearClientSessionId() { PrepareBuilder(); result.hasClientSessionId = false; result.clientSessionId_ = ""; return this; } } static ResponseSessionId() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.ResponseSessionId.Descriptor, null); } } #endregion } #endregion Designer generated code
// // nullable.cs: Nullable types support // // Authors: Martin Baulig (martin@ximian.com) // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com) // Copyright 2004-2008 Novell, Inc // Copyright 2011 Xamarin Inc // using System; using SLE = System.Linq.Expressions; #if STATIC using IKVM.Reflection.Emit; #else using System.Reflection.Emit; #endif namespace Mono.CSharp.Nullable { public class NullableType : TypeExpr { readonly TypeSpec underlying; public NullableType (TypeSpec type, Location loc) { this.underlying = type; this.loc = loc; } public override TypeSpec ResolveAsType (IMemberContext ec, bool allowUnboundTypeArguments = false) { eclass = ExprClass.Type; var otype = ec.Module.PredefinedTypes.Nullable.Resolve (); if (otype == null) return null; TypeArguments args = new TypeArguments (new TypeExpression (underlying, loc)); GenericTypeExpr ctype = new GenericTypeExpr (otype, args, loc); type = ctype.ResolveAsType (ec); return type; } } static class NullableInfo { public static MethodSpec GetConstructor (TypeSpec nullableType) { return (MethodSpec) MemberCache.FindMember (nullableType, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (GetUnderlyingType (nullableType))), BindingRestriction.DeclaredOnly); } public static MethodSpec GetHasValue (TypeSpec nullableType) { return (MethodSpec) MemberCache.FindMember (nullableType, MemberFilter.Method ("get_HasValue", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None); } public static MethodSpec GetGetValueOrDefault (TypeSpec nullableType) { return (MethodSpec) MemberCache.FindMember (nullableType, MemberFilter.Method ("GetValueOrDefault", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None); } // // Don't use unless really required for correctness, see Unwrap::Emit // public static MethodSpec GetValue (TypeSpec nullableType) { return (MethodSpec) MemberCache.FindMember (nullableType, MemberFilter.Method ("get_Value", 0, ParametersCompiled.EmptyReadOnlyParameters, null), BindingRestriction.None); } public static TypeSpec GetUnderlyingType (TypeSpec nullableType) { return ((InflatedTypeSpec) nullableType).TypeArguments[0]; } public static TypeSpec GetEnumUnderlyingType (ModuleContainer module, TypeSpec nullableEnum) { return MakeType (module, EnumSpec.GetUnderlyingType (GetUnderlyingType (nullableEnum))); } public static TypeSpec MakeType (ModuleContainer module, TypeSpec underlyingType) { return module.PredefinedTypes.Nullable.TypeSpec.MakeGenericType (module, new[] { underlyingType }); } } public class Unwrap : Expression, IMemoryLocation { Expression expr; LocalTemporary temp; Expression temp_field; readonly bool useDefaultValue; public Unwrap (Expression expr, bool useDefaultValue = true) { this.expr = expr; this.loc = expr.Location; this.useDefaultValue = useDefaultValue; type = NullableInfo.GetUnderlyingType (expr.Type); eclass = expr.eclass; } public override bool ContainsEmitWithAwait () { return expr.ContainsEmitWithAwait (); } // TODO: REMOVE public static Expression Create (Expression expr) { // // Avoid unwraping and wraping of same type // Wrap wrap = expr as Wrap; if (wrap != null) return wrap.Child; return Create (expr, false); } public static Expression CreateUnwrapped (Expression expr) { // // Avoid unwraping and wraping of same type // Wrap wrap = expr as Wrap; if (wrap != null) return wrap.Child; return Create (expr, true); } public static Unwrap Create (Expression expr, bool useDefaultValue) { return new Unwrap (expr, useDefaultValue); } public override Expression CreateExpressionTree (ResolveContext ec) { return expr.CreateExpressionTree (ec); } protected override Expression DoResolve (ResolveContext ec) { return this; } public override Expression DoResolveLValue (ResolveContext ec, Expression right_side) { expr = expr.DoResolveLValue (ec, right_side); return this; } public override void Emit (EmitContext ec) { Store (ec); var call = new CallEmitter (); call.InstanceExpression = this; // // Using GetGetValueOrDefault is prefered because JIT can possibly // inline it whereas Value property contains a throw which is very // unlikely to be inlined // if (useDefaultValue) call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null); else call.EmitPredefined (ec, NullableInfo.GetValue (expr.Type), null); } public void EmitCheck (EmitContext ec) { Store (ec); var call = new CallEmitter (); call.InstanceExpression = this; call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null); } public override void EmitSideEffect (EmitContext ec) { expr.EmitSideEffect (ec); } public override Expression EmitToField (EmitContext ec) { if (temp_field == null) temp_field = this.expr.EmitToField (ec); return this; } public override bool Equals (object obj) { Unwrap uw = obj as Unwrap; return uw != null && expr.Equals (uw.expr); } public override void FlowAnalysis (FlowAnalysisContext fc) { expr.FlowAnalysis (fc); } public Expression Original { get { return expr; } } public override int GetHashCode () { return expr.GetHashCode (); } public override bool IsNull { get { return expr.IsNull; } } public void Store (EmitContext ec) { if (temp != null || temp_field != null) return; if (expr is VariableReference) return; expr.Emit (ec); LocalVariable.Store (ec); } public void Load (EmitContext ec) { if (temp_field != null) temp_field.Emit (ec); else if (expr is VariableReference) expr.Emit (ec); else LocalVariable.Emit (ec); } public override SLE.Expression MakeExpression (BuilderContext ctx) { return expr.MakeExpression (ctx); } public void AddressOf (EmitContext ec, AddressOp mode) { IMemoryLocation ml; if (temp_field != null) { ml = temp_field as IMemoryLocation; if (ml == null) { var lt = new LocalTemporary (temp_field.Type); temp_field.Emit (ec); lt.Store (ec); ml = lt; } } else { ml = expr as VariableReference; } if (ml != null) ml.AddressOf (ec, mode); else LocalVariable.AddressOf (ec, mode); } // // Keeps result of non-variable expression // LocalTemporary LocalVariable { get { if (temp == null && temp_field == null) temp = new LocalTemporary (expr.Type); return temp; } } } // // Calls get_Value method on nullable expression // public class UnwrapCall : CompositeExpression { public UnwrapCall (Expression expr) : base (expr) { } protected override Expression DoResolve (ResolveContext rc) { base.DoResolve (rc); if (type != null) type = NullableInfo.GetUnderlyingType (type); return this; } public override void Emit (EmitContext ec) { var call = new CallEmitter (); call.InstanceExpression = Child; call.EmitPredefined (ec, NullableInfo.GetValue (Child.Type), null); } } public class Wrap : TypeCast { private Wrap (Expression expr, TypeSpec type) : base (expr, type) { eclass = ExprClass.Value; } public override Expression CreateExpressionTree (ResolveContext ec) { TypeCast child_cast = child as TypeCast; if (child_cast != null) { child.Type = type; return child_cast.CreateExpressionTree (ec); } var user_cast = child as UserCast; if (user_cast != null) { child.Type = type; return user_cast.CreateExpressionTree (ec); } return base.CreateExpressionTree (ec); } public static Expression Create (Expression expr, TypeSpec type) { // // Avoid unwraping and wraping of the same type // Unwrap unwrap = expr as Unwrap; if (unwrap != null && expr.Type == NullableInfo.GetUnderlyingType (type)) return unwrap.Original; return new Wrap (expr, type); } public override void Emit (EmitContext ec) { child.Emit (ec); ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); } } // // Represents null literal lifted to nullable type // public class LiftedNull : NullConstant, IMemoryLocation { private LiftedNull (TypeSpec nullable_type, Location loc) : base (nullable_type, loc) { eclass = ExprClass.Value; } public static Constant Create (TypeSpec nullable, Location loc) { return new LiftedNull (nullable, loc); } public static Constant CreateFromExpression (ResolveContext rc, Expression e) { if (!rc.HasSet (ResolveContext.Options.ExpressionTreeConversion)) { rc.Report.Warning (458, 2, e.Location, "The result of the expression is always `null' of type `{0}'", e.Type.GetSignatureForError ()); } return ReducedExpression.Create (Create (e.Type, e.Location), e); } public override void Emit (EmitContext ec) { // TODO: generate less temporary variables LocalTemporary value_target = new LocalTemporary (type); value_target.AddressOf (ec, AddressOp.Store); ec.Emit (OpCodes.Initobj, type); value_target.Emit (ec); value_target.Release (ec); } public void AddressOf (EmitContext ec, AddressOp Mode) { LocalTemporary value_target = new LocalTemporary (type); value_target.AddressOf (ec, AddressOp.Store); ec.Emit (OpCodes.Initobj, type); value_target.AddressOf (ec, Mode); } } // // Generic lifting expression, supports all S/S? -> T/T? cases // public class LiftedConversion : Expression, IMemoryLocation { Expression expr, null_value; Unwrap unwrap; public LiftedConversion (Expression expr, Unwrap unwrap, TypeSpec type) { this.expr = expr; this.unwrap = unwrap; this.loc = expr.Location; this.type = type; } public LiftedConversion (Expression expr, Expression unwrap, TypeSpec type) : this (expr, unwrap as Unwrap, type) { } public override bool IsNull { get { return expr.IsNull; } } public override bool ContainsEmitWithAwait () { return unwrap.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext ec) { return expr.CreateExpressionTree (ec); } protected override Expression DoResolve (ResolveContext ec) { // // It's null when lifting non-nullable type // if (unwrap == null) { // S -> T? is wrap only if (type.IsNullableType) return Wrap.Create (expr, type); // S -> T can be simplified return expr; } // Wrap target for T? if (type.IsNullableType) { if (!expr.Type.IsNullableType) { expr = Wrap.Create (expr, type); if (expr == null) return null; } null_value = LiftedNull.Create (type, loc); } else if (TypeSpec.IsValueType (type)) { null_value = LiftedNull.Create (type, loc); } else { null_value = new NullConstant (type, loc); } eclass = ExprClass.Value; return this; } public override void Emit (EmitContext ec) { Label is_null_label = ec.DefineLabel (); Label end_label = ec.DefineLabel (); unwrap.EmitCheck (ec); ec.Emit (OpCodes.Brfalse, is_null_label); expr.Emit (ec); ec.Emit (OpCodes.Br, end_label); ec.MarkLabel (is_null_label); null_value.Emit (ec); ec.MarkLabel (end_label); } public override void FlowAnalysis (FlowAnalysisContext fc) { expr.FlowAnalysis (fc); } public void AddressOf (EmitContext ec, AddressOp mode) { unwrap.AddressOf (ec, mode); } } public class LiftedUnaryOperator : Unary, IMemoryLocation { Unwrap unwrap; Expression user_operator; public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc) : base (op, expr, loc) { } public void AddressOf (EmitContext ec, AddressOp mode) { unwrap.AddressOf (ec, mode); } public override Expression CreateExpressionTree (ResolveContext ec) { if (user_operator != null) return user_operator.CreateExpressionTree (ec); if (Oper == Operator.UnaryPlus) return Expr.CreateExpressionTree (ec); return base.CreateExpressionTree (ec); } protected override Expression DoResolve (ResolveContext ec) { unwrap = Unwrap.Create (Expr, false); if (unwrap == null) return null; Expression res = base.ResolveOperator (ec, unwrap); if (res == null) { Error_OperatorCannotBeApplied (ec, loc, OperName (Oper), Expr.Type); return null; } if (res != this) { if (user_operator == null) return res; } else { res = Expr = LiftExpression (ec, Expr); } if (res == null) return null; eclass = ExprClass.Value; type = res.Type; return this; } public override void Emit (EmitContext ec) { Label is_null_label = ec.DefineLabel (); Label end_label = ec.DefineLabel (); unwrap.EmitCheck (ec); ec.Emit (OpCodes.Brfalse, is_null_label); if (user_operator != null) { user_operator.Emit (ec); } else { EmitOperator (ec, NullableInfo.GetUnderlyingType (type)); } ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (is_null_label); LiftedNull.Create (type, loc).Emit (ec); ec.MarkLabel (end_label); } static Expression LiftExpression (ResolveContext ec, Expression expr) { var lifted_type = new NullableType (expr.Type, expr.Location); if (lifted_type.ResolveAsType (ec) == null) return null; expr.Type = lifted_type.Type; return expr; } protected override Expression ResolveEnumOperator (ResolveContext ec, Expression expr, TypeSpec[] predefined) { expr = base.ResolveEnumOperator (ec, expr, predefined); if (expr == null) return null; Expr = LiftExpression (ec, Expr); return LiftExpression (ec, expr); } protected override Expression ResolveUserOperator (ResolveContext ec, Expression expr) { expr = base.ResolveUserOperator (ec, expr); if (expr == null) return null; // // When a user operator is of non-nullable type // if (Expr is Unwrap) { user_operator = LiftExpression (ec, expr); return user_operator; } return expr; } } // // Lifted version of binary operators // class LiftedBinaryOperator : Expression { public LiftedBinaryOperator (Binary b) { this.Binary = b; this.loc = b.Location; } public Binary Binary { get; private set; } public Expression Left { get; set; } public Expression Right { get; set; } public Unwrap UnwrapLeft { get; set; } public Unwrap UnwrapRight { get; set; } public MethodSpec UserOperator { get; set; } bool IsBitwiseBoolean { get { return (Binary.Oper == Binary.Operator.BitwiseAnd || Binary.Oper == Binary.Operator.BitwiseOr) && ((UnwrapLeft != null && UnwrapLeft.Type.BuiltinType == BuiltinTypeSpec.Type.Bool) || (UnwrapRight != null && UnwrapRight.Type.BuiltinType == BuiltinTypeSpec.Type.Bool)); } } public override bool ContainsEmitWithAwait () { return Left.ContainsEmitWithAwait () || Right.ContainsEmitWithAwait (); } public override Expression CreateExpressionTree (ResolveContext rc) { if (UserOperator != null) { Arguments args = new Arguments (2); args.Add (new Argument (Binary.Left)); args.Add (new Argument (Binary.Right)); var method = new UserOperatorCall (UserOperator, args, Binary.CreateExpressionTree, loc); return method.CreateExpressionTree (rc); } return Binary.CreateExpressionTree (rc); } protected override Expression DoResolve (ResolveContext rc) { if (rc.IsRuntimeBinder) { if (UnwrapLeft == null && !Left.Type.IsNullableType) Left = LiftOperand (rc, Left); if (UnwrapRight == null && !Right.Type.IsNullableType) Right = LiftOperand (rc, Right); } else { if (UnwrapLeft == null && Left != null && Left.Type.IsNullableType) { Left = Unwrap.CreateUnwrapped (Left); UnwrapLeft = Left as Unwrap; } if (UnwrapRight == null && Right != null && Right.Type.IsNullableType) { Right = Unwrap.CreateUnwrapped (Right); UnwrapRight = Right as Unwrap; } if (Left.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) { var decimal_operators = MemberCache.GetUserOperator (Left.Type, Binary.ConvertBinaryToUserOperator (Binary.Oper), false); Arguments args = new Arguments (2); args.Add (new Argument (Left)); args.Add (new Argument (Right)); const OverloadResolver.Restrictions restr = OverloadResolver.Restrictions.ProbingOnly | OverloadResolver.Restrictions.NoBaseMembers | OverloadResolver.Restrictions.BaseMembersIncluded; var res = new OverloadResolver (decimal_operators, restr, loc); UserOperator = res.ResolveOperator (rc, ref args); } } type = Binary.Type; eclass = Binary.eclass; return this; } Expression LiftOperand (ResolveContext rc, Expression expr) { TypeSpec type; if (expr.IsNull) { type = Left.IsNull ? Right.Type : Left.Type; } else { type = expr.Type; } if (!type.IsNullableType) type = NullableInfo.MakeType (rc.Module, type); return Wrap.Create (expr, type); } public override void Emit (EmitContext ec) { if (IsBitwiseBoolean && UserOperator == null) { EmitBitwiseBoolean (ec); return; } if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) { EmitEquality (ec); return; } Label is_null_label = ec.DefineLabel (); Label end_label = ec.DefineLabel (); if (ec.HasSet (BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait ()) { Left = Left.EmitToField (ec); Right = Right.EmitToField (ec); } if (UnwrapLeft != null) { UnwrapLeft.EmitCheck (ec); } // // Don't emit HasValue check when left and right expressions are same // if (UnwrapRight != null && !Binary.Left.Equals (Binary.Right)) { UnwrapRight.EmitCheck (ec); if (UnwrapLeft != null) { ec.Emit (OpCodes.And); } } ec.Emit (OpCodes.Brfalse, is_null_label); if (UserOperator != null) { var args = new Arguments (2); args.Add (new Argument (Left)); args.Add (new Argument (Right)); var call = new CallEmitter (); call.EmitPredefined (ec, UserOperator, args); } else { Binary.EmitOperator (ec, Left, Right); } // // Wrap the result when the operator return type is nullable type // if (type.IsNullableType) ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (is_null_label); if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) { ec.EmitInt (0); } else { LiftedNull.Create (type, loc).Emit (ec); } ec.MarkLabel (end_label); } void EmitBitwiseBoolean (EmitContext ec) { Label load_left = ec.DefineLabel (); Label load_right = ec.DefineLabel (); Label end_label = ec.DefineLabel (); Label is_null_label = ec.DefineLabel (); bool or = Binary.Oper == Binary.Operator.BitwiseOr; // // Both operands are bool? types // if ((UnwrapLeft != null && !Left.IsNull) && (UnwrapRight != null && !Right.IsNull)) { if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) { Left = Left.EmitToField (ec); Right = Right.EmitToField (ec); } else { UnwrapLeft.Store (ec); UnwrapRight.Store (ec); } Left.Emit (ec); ec.Emit (OpCodes.Brtrue_S, load_right); Right.Emit (ec); ec.Emit (OpCodes.Brtrue_S, load_left); UnwrapLeft.EmitCheck (ec); ec.Emit (OpCodes.Brfalse_S, load_right); // load left ec.MarkLabel (load_left); if (or) UnwrapRight.Load (ec); else UnwrapLeft.Load (ec); ec.Emit (OpCodes.Br_S, end_label); // load right ec.MarkLabel (load_right); if (or) UnwrapLeft.Load (ec); else UnwrapRight.Load (ec); ec.MarkLabel (end_label); return; } // // Faster version when one operand is bool // if (UnwrapLeft == null) { // // (bool, bool?) // // Optimizes remaining (false & bool?), (true | bool?) which are not easy to handle // in binary expression reduction // var c = Left as BoolConstant; if (c != null) { // Keep evaluation order UnwrapRight.Store (ec); ec.EmitInt (or ? 1 : 0); ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); } else if (Left.IsNull) { UnwrapRight.Emit (ec); ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label); UnwrapRight.Load (ec); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (is_null_label); LiftedNull.Create (type, loc).Emit (ec); } else { Left.Emit (ec); UnwrapRight.Store (ec); ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_right); ec.EmitInt (or ? 1 : 0); ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (load_right); UnwrapRight.Load (ec); } } else { // // (bool?, bool) // // Keep left-right evaluation order UnwrapLeft.Store (ec); // // Optimizes remaining (bool? & false), (bool? | true) which are not easy to handle // in binary expression reduction // var c = Right as BoolConstant; if (c != null) { ec.EmitInt (or ? 1 : 0); ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); } else if (Right.IsNull) { UnwrapLeft.Emit (ec); ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, is_null_label); UnwrapLeft.Load (ec); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (is_null_label); LiftedNull.Create (type, loc).Emit (ec); } else if (Left.IsNull && UnwrapRight != null) { UnwrapRight.Emit (ec); ec.Emit (or ? OpCodes.Brtrue_S : OpCodes.Brfalse_S, load_right); LiftedNull.Create (type, loc).Emit (ec); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (load_right); UnwrapRight.Load (ec); } else { Right.Emit (ec); ec.Emit (or ? OpCodes.Brfalse_S : OpCodes.Brtrue_S, load_left); ec.EmitInt (or ? 1 : 0); ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (load_left); UnwrapLeft.Load (ec); } } ec.MarkLabel (end_label); } // // Emits optimized equality or inequality operator when possible // void EmitEquality (EmitContext ec) { // // Either left or right is null // if (UnwrapLeft != null && Binary.Right.IsNull) { // TODO: Optimize for EmitBranchable // // left.HasValue == false // UnwrapLeft.EmitCheck (ec); if (Binary.Oper == Binary.Operator.Equality) { ec.EmitInt (0); ec.Emit (OpCodes.Ceq); } return; } if (UnwrapRight != null && Binary.Left.IsNull) { // // right.HasValue == false // UnwrapRight.EmitCheck (ec); if (Binary.Oper == Binary.Operator.Equality) { ec.EmitInt (0); ec.Emit (OpCodes.Ceq); } return; } Label dissimilar_label = ec.DefineLabel (); Label end_label = ec.DefineLabel (); if (UserOperator != null) { var left = Left; if (UnwrapLeft != null) { UnwrapLeft.EmitCheck (ec); } else { // Keep evaluation order same if (!(Left is VariableReference)) { Left.Emit (ec); var lt = new LocalTemporary (Left.Type); lt.Store (ec); left = lt; } } if (UnwrapRight != null) { UnwrapRight.EmitCheck (ec); if (UnwrapLeft != null) { ec.Emit (OpCodes.Bne_Un, dissimilar_label); Label compare_label = ec.DefineLabel (); UnwrapLeft.EmitCheck (ec); ec.Emit (OpCodes.Brtrue, compare_label); if (Binary.Oper == Binary.Operator.Equality) ec.EmitInt (1); else ec.EmitInt (0); ec.Emit (OpCodes.Br, end_label); ec.MarkLabel (compare_label); } else { ec.Emit (OpCodes.Brfalse, dissimilar_label); } } else { ec.Emit (OpCodes.Brfalse, dissimilar_label); } var args = new Arguments (2); args.Add (new Argument (left)); args.Add (new Argument (Right)); var call = new CallEmitter (); call.EmitPredefined (ec, UserOperator, args); } else { if (ec.HasSet (BuilderContext.Options.AsyncBody) && Binary.Right.ContainsEmitWithAwait ()) { Left = Left.EmitToField (ec); Right = Right.EmitToField (ec); } // // Emit underlying value comparison first. // // For this code: int? a = 1; bool b = a == 1; // // We emit something similar to this. Expressions with side effects have local // variable created by Unwrap expression // // left.GetValueOrDefault () // right // bne.un.s dissimilar_label // left.HasValue // br.s end_label // dissimilar_label: // ldc.i4.0 // end_label: // Left.Emit (ec); Right.Emit (ec); ec.Emit (OpCodes.Bne_Un_S, dissimilar_label); // // Check both left and right expressions for Unwrap call in which // case we need to run get_HasValue() check because the type is // nullable and could have null value // if (UnwrapLeft != null) UnwrapLeft.EmitCheck (ec); if (UnwrapRight != null) UnwrapRight.EmitCheck (ec); if (UnwrapLeft != null && UnwrapRight != null) { if (Binary.Oper == Binary.Operator.Inequality) ec.Emit (OpCodes.Xor); else ec.Emit (OpCodes.Ceq); } else { if (Binary.Oper == Binary.Operator.Inequality) { ec.EmitInt (0); ec.Emit (OpCodes.Ceq); } } } ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (dissimilar_label); if (Binary.Oper == Binary.Operator.Inequality) ec.EmitInt (1); else ec.EmitInt (0); ec.MarkLabel (end_label); } public override void FlowAnalysis (FlowAnalysisContext fc) { Binary.FlowAnalysis (fc); } public override SLE.Expression MakeExpression (BuilderContext ctx) { return Binary.MakeExpression (ctx, Left, Right); } } public class NullCoalescingOperator : Expression { Expression left, right; Unwrap unwrap; bool user_conversion_left; public NullCoalescingOperator (Expression left, Expression right) { this.left = left; this.right = right; this.loc = left.Location; } public Expression LeftExpression { get { return left; } } public Expression RightExpression { get { return right; } } public override Expression CreateExpressionTree (ResolveContext ec) { if (left is NullLiteral) ec.Report.Error (845, loc, "An expression tree cannot contain a coalescing operator with null left side"); UserCast uc = left as UserCast; Expression conversion = null; if (uc != null) { left = uc.Source; Arguments c_args = new Arguments (2); c_args.Add (new Argument (uc.CreateExpressionTree (ec))); c_args.Add (new Argument (left.CreateExpressionTree (ec))); conversion = CreateExpressionFactoryCall (ec, "Lambda", c_args); } Arguments args = new Arguments (3); args.Add (new Argument (left.CreateExpressionTree (ec))); args.Add (new Argument (right.CreateExpressionTree (ec))); if (conversion != null) args.Add (new Argument (conversion)); return CreateExpressionFactoryCall (ec, "Coalesce", args); } Expression ConvertExpression (ResolveContext ec) { // TODO: ImplicitConversionExists should take care of this if (left.eclass == ExprClass.MethodGroup) return null; TypeSpec ltype = left.Type; // // If left is a nullable type and an implicit conversion exists from right to underlying type of left, // the result is underlying type of left // if (ltype.IsNullableType) { unwrap = Unwrap.Create (left, false); if (unwrap == null) return null; // // Reduce (left ?? null) to left // if (right.IsNull) return ReducedExpression.Create (left, this); Expression conv; if (right.Type.IsNullableType) { conv = right.Type == ltype ? right : Convert.ImplicitNulableConversion (ec, right, ltype); if (conv != null) { right = conv; type = ltype; return this; } } else { conv = Convert.ImplicitConversion (ec, right, unwrap.Type, loc); if (conv != null) { left = unwrap; ltype = left.Type; // // If right is a dynamic expression, the result type is dynamic // if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { type = right.Type; // Need to box underlying value type left = Convert.ImplicitBoxingConversion (left, ltype, type); return this; } right = conv; type = ltype; return this; } } } else if (TypeSpec.IsReferenceType (ltype)) { if (Convert.ImplicitConversionExists (ec, right, ltype)) { // // If right is a dynamic expression, the result type is dynamic // if (right.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) { type = right.Type; return this; } // // Reduce ("foo" ?? expr) to expression // Constant lc = left as Constant; if (lc != null && !lc.IsDefaultValue) return ReducedExpression.Create (lc, this, false); // // Reduce (left ?? null) to left OR (null-constant ?? right) to right // if (right.IsNull || lc != null) { // // Special case null ?? null // if (right is NullLiteral && ltype == right.Type) return null; return ReducedExpression.Create (lc != null ? right : left, this, false); } right = Convert.ImplicitConversion (ec, right, ltype, loc); type = ltype; return this; } } else if (ltype == InternalType.ThrowExpr) { // // LAMESPEC: I am not really sure what's point of allowing throw on left side // return ReducedExpression.Create (right, this, false).Resolve (ec); } else { return null; } TypeSpec rtype = right.Type; if (!Convert.ImplicitConversionExists (ec, unwrap ?? left, rtype) || right.eclass == ExprClass.MethodGroup) return null; // // Reduce (null ?? right) to right // if (left.IsNull) return ReducedExpression.Create (right, this, false).Resolve (ec); left = Convert.ImplicitConversion (ec, unwrap ?? left, rtype, loc); user_conversion_left = left is UserCast; type = rtype; return this; } public override bool ContainsEmitWithAwait () { if (unwrap != null) return unwrap.ContainsEmitWithAwait () || right.ContainsEmitWithAwait (); return left.ContainsEmitWithAwait () || right.ContainsEmitWithAwait (); } protected override Expression DoResolve (ResolveContext ec) { left = left.Resolve (ec); right = right.Resolve (ec); if (left == null || right == null) return null; eclass = ExprClass.Value; Expression e = ConvertExpression (ec); if (e == null) { Binary.Error_OperatorCannotBeApplied (ec, left, right, "??", loc); return null; } return e; } public override void Emit (EmitContext ec) { Label end_label = ec.DefineLabel (); if (unwrap != null) { Label is_null_label = ec.DefineLabel (); unwrap.EmitCheck (ec); ec.Emit (OpCodes.Brfalse, is_null_label); // // When both expressions are nullable the unwrap // is needed only for null check not for value uwrap // if (type.IsNullableType && TypeSpecComparer.IsEqual (NullableInfo.GetUnderlyingType (type), unwrap.Type)) unwrap.Load (ec); else left.Emit (ec); ec.Emit (OpCodes.Br, end_label); ec.MarkLabel (is_null_label); right.Emit (ec); ec.MarkLabel (end_label); return; } // // Null check is done on original expression not after expression is converted to // result type. This is in most cases same but when user conversion is involved // we can end up in situation when user operator does the null handling which is // not what the operator is supposed to do. // There is tricky case where cast of left expression is meant to be cast of // whole source expression (null check is done on it) and cast from right-to-left // conversion needs to do null check on unconverted source expression. // if (user_conversion_left) { var op_expr = (UserCast) left; op_expr.Source.Emit (ec); LocalTemporary temp; // TODO: More load kinds can be special cased if (!(op_expr.Source is VariableReference)) { temp = new LocalTemporary (op_expr.Source.Type); temp.Store (ec); temp.Emit (ec); op_expr.Source = temp; } else { temp = null; } var right_label = ec.DefineLabel (); ec.Emit (OpCodes.Brfalse_S, right_label); left.Emit (ec); ec.Emit (OpCodes.Br, end_label); ec.MarkLabel (right_label); if (temp != null) temp.Release (ec); } else { // // Common case where expression is not modified before null check and // we generate better/smaller code // left.Emit (ec); ec.Emit (OpCodes.Dup); // Only to make verifier happy if (left.Type.IsGenericParameter) ec.Emit (OpCodes.Box, left.Type); ec.Emit (OpCodes.Brtrue, end_label); ec.Emit (OpCodes.Pop); } right.Emit (ec); ec.MarkLabel (end_label); } public override void FlowAnalysis (FlowAnalysisContext fc) { left.FlowAnalysis (fc); var left_da = fc.BranchDefiniteAssignment (); right.FlowAnalysis (fc); fc.DefiniteAssignment = left_da; } protected override void CloneTo (CloneContext clonectx, Expression t) { NullCoalescingOperator target = (NullCoalescingOperator) t; target.left = left.Clone (clonectx); target.right = right.Clone (clonectx); } public override object Accept (StructuralVisitor visitor) { return visitor.Visit (this); } } class LiftedUnaryMutator : UnaryMutator { public LiftedUnaryMutator (Mode mode, Expression expr, Location loc) : base (mode, expr, loc) { } protected override Expression DoResolve (ResolveContext ec) { var orig_expr = expr; expr = Unwrap.Create (expr); var res = base.DoResolveOperation (ec); expr = orig_expr; type = expr.Type; return res; } protected override void EmitOperation (EmitContext ec) { Label is_null_label = ec.DefineLabel (); Label end_label = ec.DefineLabel (); LocalTemporary lt = new LocalTemporary (type); // Value is on the stack lt.Store (ec); var call = new CallEmitter (); call.InstanceExpression = lt; call.EmitPredefined (ec, NullableInfo.GetHasValue (expr.Type), null); ec.Emit (OpCodes.Brfalse, is_null_label); call = new CallEmitter (); call.InstanceExpression = lt; call.EmitPredefined (ec, NullableInfo.GetGetValueOrDefault (expr.Type), null); lt.Release (ec); base.EmitOperation (ec); ec.Emit (OpCodes.Newobj, NullableInfo.GetConstructor (type)); ec.Emit (OpCodes.Br_S, end_label); ec.MarkLabel (is_null_label); LiftedNull.Create (type, loc).Emit (ec); ec.MarkLabel (end_label); } } }
#region Copyright Information // Sentience Lab Unity Framework // (C) Sentience Lab (sentiencelab@aut.ac.nz), Auckland University of Technology, Auckland, New Zealand #endregion Copyright Information using SentienceLab.IO; using System; using System.Collections.Generic; using System.IO; using System.Threading; using UnityEngine; namespace SentienceLab.MoCap { /// <summary> /// Class for a MoCap client that reads from a .MOT file. /// </summary> /// public class FileClient : IMoCapClient { public class ConnectionInfo : IMoCapClient_ConnectionInfo { public ConnectionInfo(TextAsset asset) { dataStream = new DataStream_TextAsset(asset, '\t', false); // read TSV file as fast as possible } public ConnectionInfo(string filename) { // cut any leading character filename = filename.TrimStart('/'); dataStream = new DataStream_File(Path.Combine(Application.streamingAssetsPath, filename), '\t', false); } public DataStream dataStream; } /// <summary> /// Constructs a .MOT file client instance. /// </summary> /// public FileClient() { scene = new Scene(); dataStream = null; streamingTimer = null; paused = false; } public bool Connect(IMoCapClient_ConnectionInfo connectionInfo) { // extract filename from connection info dataStream = (connectionInfo is ConnectionInfo) ? ((ConnectionInfo)connectionInfo).dataStream : null; // fallback > no stream // try connecting try { if ((dataStream != null) && dataStream.Open()) { GetSceneDescription(); Debug.Log("Reading from MOT file '" + dataStream.GetName() + "'."); // immediately get first packet of frame data GetFrameData(); streamingTimer = new Timer(new TimerCallback(StreamingTimerCallback)); streamingTimer.Change(0, 1000 / updateRate); } } catch (Exception e) { Debug.LogWarning("Could not read from MOT file '" + dataStream.GetName() + "' (" + e.Message + ").\n" + e.StackTrace); dataStream.Close(); dataStream = null; } return IsConnected(); } public bool IsConnected() { return (dataStream != null); } public void Disconnect() { // stop streaming data if (streamingTimer != null) { streamingTimer.Dispose(); streamingTimer = null; } // close file if (dataStream != null) { dataStream.Close(); dataStream = null; } } public String GetDataSourceName() { return "MOT file '" + dataStream.GetName() + "'"; } public float GetFramerate() { return updateRate; } public void SetPaused(bool pause) { paused = pause; } public void Update(ref bool dataChanged, ref bool sceneChanged) { // timer takes care of the data reading // flag signals new data dataChanged = newFrameData; newFrameData = false; } public Scene GetScene() { return scene; } private void GetSceneDescription() { // read header int headerParts = dataStream.ReadNextLine(); if ((headerParts < 3) || !dataStream.GetNextString().Equals("MotionServer Data File")) { throw new FileLoadException("Invalid MOT file header"); } fileVersion = dataStream.GetNextInt(); if ((fileVersion < 1) || (fileVersion > 2)) { throw new FileLoadException("Invalid MOT file version number"); } updateRate = dataStream.GetNextInt(); int descriptionParts = dataStream.ReadNextLine(); if ((descriptionParts < 2) || !dataStream.GetNextString().Equals("Descriptions")) { throw new FileLoadException("Missing description section"); } int descriptionCount = dataStream.GetNextInt(); scene.actors.Clear(); scene.devices.Clear(); for (int descrIdx = 0; descrIdx < descriptionCount; descrIdx++) { int descrParts = dataStream.ReadNextLine(); if ((descrParts < 2) || (dataStream.GetNextInt() != descrIdx)) { throw new FileLoadException("Invalid description block #" + descrIdx); } switch (dataStream.GetNextString()[0]) { case 'M': ReadMarkersetDescription( scene.actors); break; case 'R': ReadRigidBodyDescription( scene.actors); break; case 'S': ReadSkeletonDescription( scene.actors); break; case 'F': ReadForcePlateDescription(scene.devices); break; default : throw new FileLoadException("Invalid description block #" + descrIdx); } } // here comes the frame data int frameParts = dataStream.ReadNextLine(); if ((frameParts < 1) || !dataStream.GetNextString().Equals("Frames")) { throw new FileLoadException("Missing frame section"); } // remember that this is the end of the header for rewinding/looping dataStream.MarkPosition(); } private void ReadMarkersetDescription(List<Actor> actors) { int id = 0; // no ID for markersets string name = dataStream.GetNextString(); // markerset name Actor actor = new Actor(scene, name, id); int nMarkers = dataStream.GetNextInt(); // marker count actor.markers = new Marker[nMarkers]; for (int markerIdx = 0; markerIdx < nMarkers; markerIdx++) { name = dataStream.GetNextString(); Marker marker = new Marker(actor, name); actor.markers[markerIdx] = marker; } actors.Add(actor); } private void ReadRigidBodyDescription(List<Actor> actors) { int id = dataStream.GetNextInt(); // ID string name = dataStream.GetNextString(); // name // rigid body name should be equal to actor name: search Actor actor = null; foreach (Actor a in actors) { if (a.name.Equals(name)) { actor = a; actor.id = id; // associate actor and rigid body ID } } if (actor == null) { Debug.LogWarning("Rigid Body " + name + " could not be matched to an actor."); actor = new Actor(scene, name, id); actors.Add(actor); } Bone bone = new Bone(actor, name, id); dataStream.GetNextInt(); // Parent ID (ignore for rigid body) bone.parent = null; // rigid bodies should not have a parent bone.ox = dataStream.GetNextFloat(); // X offset bone.oy = dataStream.GetNextFloat(); // Y offset bone.oz = dataStream.GetNextFloat(); // Z offset actor.bones = new Bone[1]; actor.bones[0] = bone; } private void ReadSkeletonDescription(List<Actor> actors) { int skeletonId = dataStream.GetNextInt(); // ID string skeletonName = dataStream.GetNextString(); // name // rigid body name should be equal to actor name: search Actor actor = null; foreach (Actor a in actors) { if (a.name.CompareTo(skeletonName) == 0) { actor = a; actor.id = skeletonId; // associate actor and skeleton } } if (actor == null) { // names don't match > try IDs if ((skeletonId >= 0) && (skeletonId < actors.Count)) { actor = actors[skeletonId]; } } if (actor == null) { Debug.LogWarning("Skeleton " + skeletonName + " could not be matched to an actor."); actor = new Actor(scene, skeletonName, skeletonId); actors.Add(actor); } int nBones = dataStream.GetNextInt(); // Skeleton bone count actor.bones = new Bone[nBones]; for (int boneIdx = 0; boneIdx < nBones; boneIdx++) { int id = dataStream.GetNextInt(); // bone ID String name = dataStream.GetNextString(); // bone name Bone bone = new Bone(actor, name, id); int parentId = dataStream.GetNextInt(); // Skeleton parent ID bone.parent = actor.FindBone(parentId); if (bone.parent != null) { // if bone has a parent, update child list of parent bone.parent.children.Add(bone); } bone.BuildChain(); // build chain from root to this bone bone.ox = dataStream.GetNextFloat(); // X offset bone.oy = dataStream.GetNextFloat(); // Y offset bone.oz = dataStream.GetNextFloat(); // Z offset actor.bones[boneIdx] = bone; } } private void ReadForcePlateDescription(List<Device> devices) { int id = dataStream.GetNextInt(); // ID string name = dataStream.GetNextString(); // name Device device = new Device(scene, name, id); // create device int nChannels = dataStream.GetNextInt(); // channel count device.channels = new Channel[nChannels]; for (int channelIdx = 0; channelIdx < nChannels; channelIdx++) { name = dataStream.GetNextString(); Channel channel = new Channel(device, name); device.channels[channelIdx] = channel; } devices.Add(device); } private void GetFrameData() { scene.mutex.WaitOne(); if (dataStream.EndOfStream()) { Debug.Log("End of MOT file reached > looping"); // end of file > start from beginning dataStream.Rewind(); } dataStream.ReadNextLine(); // frame number scene.frameNumber = dataStream.GetNextInt(); // timestamp (wasn't part of file version 1) if (fileVersion > 1) { scene.timestamp = dataStream.GetNextFloat(); } else { // no timestamp in file > reconstruct from frame number scene.timestamp = scene.frameNumber / (float) updateRate; } // latency in s scene.latency = dataStream.GetNextFloat(); if (!dataStream.GetNextString().Equals("M")) { throw new FileLoadException("Invalid marker frame block"); } // Read actor data int nActors = dataStream.GetNextInt(); // actor count for (int actorIdx = 0; actorIdx < nActors; actorIdx++) { Actor actor = scene.actors[actorIdx]; int nMarkers = dataStream.GetNextInt(); for (int markerIdx = 0; markerIdx < nMarkers; markerIdx++) { Marker marker = actor.markers[markerIdx]; // Read position marker.px = dataStream.GetNextFloat(); marker.py = dataStream.GetNextFloat(); marker.pz = dataStream.GetNextFloat(); TransformToUnity(ref marker); // marker is tracked when at least one coordinate is not 0 marker.tracked = (marker.px != 0) || (marker.py != 0) || (marker.pz != 0); } } // Read rigid body data if (!dataStream.GetNextString().Equals("R")) { throw new FileLoadException("Invalid rigid body frame block"); } int nRigidBodies = dataStream.GetNextInt(); // rigid body count for (int rigidBodyIdx = 0; rigidBodyIdx < nRigidBodies; rigidBodyIdx++) { int rigidBodyID = dataStream.GetNextInt(); // get rigid body ID Actor actor = scene.FindActor(rigidBodyID); if (actor != null) { Bone bone = actor.bones[0]; // Read position/rotation bone.px = dataStream.GetNextFloat(); // position bone.py = dataStream.GetNextFloat(); bone.pz = dataStream.GetNextFloat(); bone.qx = dataStream.GetNextFloat(); // rotation bone.qy = dataStream.GetNextFloat(); bone.qz = dataStream.GetNextFloat(); bone.qw = dataStream.GetNextFloat(); TransformToUnity(ref bone); bone.length = dataStream.GetNextFloat(); // Mean error, used as length int state = dataStream.GetNextInt(); // state bone.tracked = (state & 0x01) != 0; } else { Debug.LogWarning("Could not find actor with ID " + rigidBodyID + " for rigid body"); } } // Read skeleton data if (!dataStream.GetNextString().Equals("S")) { throw new FileLoadException("Invalid skeleton frame block"); } int nSkeletons = dataStream.GetNextInt(); // skeleton count for (int skeletonIdx = 0; skeletonIdx < nSkeletons; skeletonIdx++) { int skeletonId = dataStream.GetNextInt(); Actor actor = scene.FindActor(skeletonId); // # of bones in skeleton int nBones = dataStream.GetNextInt(); for (int nBodyIdx = 0; nBodyIdx < nBones; nBodyIdx++) { int boneId = dataStream.GetNextInt(); // TODO: add sanity check Bone bone = actor.bones[boneId]; // Read position/rotation bone.px = dataStream.GetNextFloat(); // position bone.py = dataStream.GetNextFloat(); bone.pz = dataStream.GetNextFloat(); bone.qx = dataStream.GetNextFloat(); // rotation bone.qy = dataStream.GetNextFloat(); bone.qz = dataStream.GetNextFloat(); bone.qw = dataStream.GetNextFloat(); TransformToUnity(ref bone); bone.length = dataStream.GetNextFloat(); // Mean error, used as length int state = dataStream.GetNextInt(); // state bone.tracked = (state & 0x01) != 0; } } // next skeleton // Read force plate data if (!dataStream.GetNextString().Equals("F")) { throw new FileLoadException("Invalid force plate frame block"); } int nForcePlates = dataStream.GetNextInt(); // force plate count for (int forcePlateIdx = 0; forcePlateIdx < nForcePlates; forcePlateIdx++) { // read force plate ID and find corresponding device int forcePlateId = dataStream.GetNextInt(); Device device = scene.FindDevice(forcePlateId); // channel count int nChannels = dataStream.GetNextInt(); // channel data for (int chn = 0; chn < nChannels; chn++) { float value = dataStream.GetNextFloat(); device.channels[chn].value = value; } } scene.mutex.ReleaseMutex(); } /// <summary> /// Converts a marker position from a right handed coordinate to a left handed (Unity). /// </summary> /// <param name="pos">the marker to convert</param> /// private void TransformToUnity(ref Marker marker) { marker.pz *= -1; // flip Z } /// <summary> /// Converts a bone from a right handed rotation to a left handed (Unity). /// </summary> /// <param name="bone">the bone to convert</param> /// private void TransformToUnity(ref Bone bone) { bone.pz *= -1; // flip Z pos bone.qx *= -1; // flip X/Y quaternion component bone.qy *= -1; } private void StreamingTimerCallback(object state) { if (paused) return; GetFrameData(); newFrameData = true; } private Scene scene; private DataStream dataStream; private int fileVersion, updateRate; private Timer streamingTimer; private bool paused, newFrameData; } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Threading; using System.Collections; using OpenSource.UPnP; using OpenSource.Utilities; namespace OpenSource.UPnP.AV { /// <summary> /// Transparent ClientSide UPnP Service /// </summary> public class CpContentDirectory { private Hashtable UnspecifiedTable = Hashtable.Synchronized(new Hashtable()); internal UPnPService _S; public UPnPService GetUPnPService() { return(_S); } public static string SERVICE_NAME = "urn:schemas-upnp-org:service:ContentDirectory:"; public double VERSION { get { return(double.Parse(_S.Version)); } } public delegate void StateVariableModifiedHandler_TransferIDs(CpContentDirectory sender, System.String NewValue); private WeakEvent OnStateVariable_TransferIDs_Event = new WeakEvent(); public event StateVariableModifiedHandler_TransferIDs OnStateVariable_TransferIDs { add{OnStateVariable_TransferIDs_Event.Register(value);} remove{OnStateVariable_TransferIDs_Event.UnRegister(value);} } protected void TransferIDs_ModifiedSink(UPnPStateVariable Var, object NewValue) { OnStateVariable_TransferIDs_Event.Fire(this, (System.String)NewValue); } public delegate void StateVariableModifiedHandler_ContainerUpdateIDs(CpContentDirectory sender, System.String NewValue); private WeakEvent OnStateVariable_ContainerUpdateIDs_Event = new WeakEvent(); public event StateVariableModifiedHandler_ContainerUpdateIDs OnStateVariable_ContainerUpdateIDs { add{OnStateVariable_ContainerUpdateIDs_Event.Register(value);} remove{OnStateVariable_ContainerUpdateIDs_Event.UnRegister(value);} } protected void ContainerUpdateIDs_ModifiedSink(UPnPStateVariable Var, object NewValue) { OnStateVariable_ContainerUpdateIDs_Event.Fire(this, (System.String)NewValue); } public delegate void StateVariableModifiedHandler_SystemUpdateID(CpContentDirectory sender, System.UInt32 NewValue); private WeakEvent OnStateVariable_SystemUpdateID_Event = new WeakEvent(); public event StateVariableModifiedHandler_SystemUpdateID OnStateVariable_SystemUpdateID { add{OnStateVariable_SystemUpdateID_Event.Register(value);} remove{OnStateVariable_SystemUpdateID_Event.UnRegister(value);} } protected void SystemUpdateID_ModifiedSink(UPnPStateVariable Var, object NewValue) { OnStateVariable_SystemUpdateID_Event.Fire(this, (System.UInt32)NewValue); } public delegate void SubscribeHandler(CpContentDirectory sender, bool Success); public event SubscribeHandler OnSubscribe; public delegate void Delegate_OnResult_ExportResource(CpContentDirectory sender, System.Uri SourceURI, System.Uri DestinationURI, System.UInt32 TransferID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_ExportResource_Event = new WeakEvent(); public event Delegate_OnResult_ExportResource OnResult_ExportResource { add{OnResult_ExportResource_Event.Register(value);} remove{OnResult_ExportResource_Event.UnRegister(value);} } public delegate void Delegate_OnResult_StopTransferResource(CpContentDirectory sender, System.UInt32 TransferID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_StopTransferResource_Event = new WeakEvent(); public event Delegate_OnResult_StopTransferResource OnResult_StopTransferResource { add{OnResult_StopTransferResource_Event.Register(value);} remove{OnResult_StopTransferResource_Event.UnRegister(value);} } public delegate void Delegate_OnResult_DestroyObject(CpContentDirectory sender, System.String ObjectID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_DestroyObject_Event = new WeakEvent(); public event Delegate_OnResult_DestroyObject OnResult_DestroyObject { add{OnResult_DestroyObject_Event.Register(value);} remove{OnResult_DestroyObject_Event.UnRegister(value);} } public delegate void Delegate_OnResult_UpdateObject(CpContentDirectory sender, System.String ObjectID, System.String CurrentTagValue, System.String NewTagValue, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_UpdateObject_Event = new WeakEvent(); public event Delegate_OnResult_UpdateObject OnResult_UpdateObject { add{OnResult_UpdateObject_Event.Register(value);} remove{OnResult_UpdateObject_Event.UnRegister(value);} } public delegate void Delegate_OnResult_GetSystemUpdateID(CpContentDirectory sender, System.UInt32 Id, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_GetSystemUpdateID_Event = new WeakEvent(); public event Delegate_OnResult_GetSystemUpdateID OnResult_GetSystemUpdateID { add{OnResult_GetSystemUpdateID_Event.Register(value);} remove{OnResult_GetSystemUpdateID_Event.UnRegister(value);} } public delegate void Delegate_OnResult_GetTransferProgress(CpContentDirectory sender, System.UInt32 TransferID, Enum_A_ARG_TYPE_TransferStatus TransferStatus, System.String TransferLength, System.String TransferTotal, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_GetTransferProgress_Event = new WeakEvent(); public event Delegate_OnResult_GetTransferProgress OnResult_GetTransferProgress { add{OnResult_GetTransferProgress_Event.Register(value);} remove{OnResult_GetTransferProgress_Event.UnRegister(value);} } public delegate void Delegate_OnResult_GetSearchCapabilities(CpContentDirectory sender, System.String SearchCaps, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_GetSearchCapabilities_Event = new WeakEvent(); public event Delegate_OnResult_GetSearchCapabilities OnResult_GetSearchCapabilities { add{OnResult_GetSearchCapabilities_Event.Register(value);} remove{OnResult_GetSearchCapabilities_Event.UnRegister(value);} } public delegate void Delegate_OnResult_CreateObject(CpContentDirectory sender, System.String ContainerID, System.String Elements, System.String ObjectID, System.String Result, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_CreateObject_Event = new WeakEvent(); public event Delegate_OnResult_CreateObject OnResult_CreateObject { add{OnResult_CreateObject_Event.Register(value);} remove{OnResult_CreateObject_Event.UnRegister(value);} } public delegate void Delegate_OnResult_ImportResource(CpContentDirectory sender, System.Uri SourceURI, System.Uri DestinationURI, System.UInt32 TransferID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_ImportResource_Event = new WeakEvent(); public event Delegate_OnResult_ImportResource OnResult_ImportResource { add{OnResult_ImportResource_Event.Register(value);} remove{OnResult_ImportResource_Event.UnRegister(value);} } public delegate void Delegate_OnResult_Search(CpContentDirectory sender, System.String ContainerID, System.String SearchCriteria, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, System.String Result, System.UInt32 NumberReturned, System.UInt32 TotalMatches, System.UInt32 UpdateID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_Search_Event = new WeakEvent(); public event Delegate_OnResult_Search OnResult_Search { add{OnResult_Search_Event.Register(value);} remove{OnResult_Search_Event.UnRegister(value);} } public delegate void Delegate_OnResult_GetSortCapabilities(CpContentDirectory sender, System.String SortCaps, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_GetSortCapabilities_Event = new WeakEvent(); public event Delegate_OnResult_GetSortCapabilities OnResult_GetSortCapabilities { add{OnResult_GetSortCapabilities_Event.Register(value);} remove{OnResult_GetSortCapabilities_Event.UnRegister(value);} } public delegate void Delegate_OnResult_Browse(CpContentDirectory sender, System.String ObjectID, Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, System.String Result, System.UInt32 NumberReturned, System.UInt32 TotalMatches, System.UInt32 UpdateID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_Browse_Event = new WeakEvent(); public event Delegate_OnResult_Browse OnResult_Browse { add{OnResult_Browse_Event.Register(value);} remove{OnResult_Browse_Event.UnRegister(value);} } public delegate void Delegate_OnResult_CreateReference(CpContentDirectory sender, System.String ContainerID, System.String ObjectID, System.String NewID, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_CreateReference_Event = new WeakEvent(); public event Delegate_OnResult_CreateReference OnResult_CreateReference { add{OnResult_CreateReference_Event.Register(value);} remove{OnResult_CreateReference_Event.UnRegister(value);} } public delegate void Delegate_OnResult_DeleteResource(CpContentDirectory sender, System.Uri ResourceURI, UPnPInvokeException e, object _Tag); private WeakEvent OnResult_DeleteResource_Event = new WeakEvent(); public event Delegate_OnResult_DeleteResource OnResult_DeleteResource { add{OnResult_DeleteResource_Event.Register(value);} remove{OnResult_DeleteResource_Event.UnRegister(value);} } public CpContentDirectory(UPnPService s) { _S = s; _S.OnSubscribe += new UPnPService.UPnPEventSubscribeHandler(_subscribe_sink); if(HasStateVariable_TransferIDs) _S.GetStateVariableObject("TransferIDs").OnModified += new UPnPStateVariable.ModifiedHandler(TransferIDs_ModifiedSink); if(HasStateVariable_ContainerUpdateIDs) _S.GetStateVariableObject("ContainerUpdateIDs").OnModified += new UPnPStateVariable.ModifiedHandler(ContainerUpdateIDs_ModifiedSink); if(HasStateVariable_SystemUpdateID) _S.GetStateVariableObject("SystemUpdateID").OnModified += new UPnPStateVariable.ModifiedHandler(SystemUpdateID_ModifiedSink); } public void Dispose() { _S.OnSubscribe -= new UPnPService.UPnPEventSubscribeHandler(_subscribe_sink); OnSubscribe = null; if(HasStateVariable_TransferIDs) _S.GetStateVariableObject("TransferIDs").OnModified -= new UPnPStateVariable.ModifiedHandler(TransferIDs_ModifiedSink); if(HasStateVariable_ContainerUpdateIDs) _S.GetStateVariableObject("ContainerUpdateIDs").OnModified -= new UPnPStateVariable.ModifiedHandler(ContainerUpdateIDs_ModifiedSink); if(HasStateVariable_SystemUpdateID) _S.GetStateVariableObject("SystemUpdateID").OnModified -= new UPnPStateVariable.ModifiedHandler(SystemUpdateID_ModifiedSink); } public void _subscribe(int Timeout) { _S.Subscribe(Timeout, null); } protected void _subscribe_sink(UPnPService sender, bool OK) { if(OnSubscribe!=null) { OnSubscribe(this, OK); } } public void SetUnspecifiedValue(string EnumType, string val) { string hash = Thread.CurrentThread.GetHashCode().ToString() + ":" + EnumType; UnspecifiedTable[hash] = val; } public string GetUnspecifiedValue(string EnumType) { string hash = Thread.CurrentThread.GetHashCode().ToString() + ":" + EnumType; if(UnspecifiedTable.ContainsKey(hash)==false) { return(""); } string RetVal = (string)UnspecifiedTable[hash]; return(RetVal); } public string[] Values_A_ARG_TYPE_TransferStatus { get { UPnPStateVariable sv = _S.GetStateVariableObject("A_ARG_TYPE_TransferStatus"); return(sv.AllowedStringValues); } } public string Enum_A_ARG_TYPE_TransferStatus_ToString(Enum_A_ARG_TYPE_TransferStatus en) { string RetVal = ""; switch(en) { case Enum_A_ARG_TYPE_TransferStatus.COMPLETED: RetVal = "COMPLETED"; break; case Enum_A_ARG_TYPE_TransferStatus.ERROR: RetVal = "ERROR"; break; case Enum_A_ARG_TYPE_TransferStatus.IN_PROGRESS: RetVal = "IN_PROGRESS"; break; case Enum_A_ARG_TYPE_TransferStatus.STOPPED: RetVal = "STOPPED"; break; case Enum_A_ARG_TYPE_TransferStatus._UNSPECIFIED_: RetVal = GetUnspecifiedValue("Enum_A_ARG_TYPE_TransferStatus"); break; } return(RetVal); } public enum Enum_A_ARG_TYPE_TransferStatus { _UNSPECIFIED_, COMPLETED, ERROR, IN_PROGRESS, STOPPED, } public Enum_A_ARG_TYPE_TransferStatus A_ARG_TYPE_TransferStatus { get { Enum_A_ARG_TYPE_TransferStatus RetVal = 0; string v = (string)_S.GetStateVariable("A_ARG_TYPE_TransferStatus"); switch(v) { case "COMPLETED": RetVal = Enum_A_ARG_TYPE_TransferStatus.COMPLETED; break; case "ERROR": RetVal = Enum_A_ARG_TYPE_TransferStatus.ERROR; break; case "IN_PROGRESS": RetVal = Enum_A_ARG_TYPE_TransferStatus.IN_PROGRESS; break; case "STOPPED": RetVal = Enum_A_ARG_TYPE_TransferStatus.STOPPED; break; default: RetVal = Enum_A_ARG_TYPE_TransferStatus._UNSPECIFIED_; SetUnspecifiedValue("Enum_A_ARG_TYPE_TransferStatus", v); break; } return(RetVal); } } public string[] Values_A_ARG_TYPE_BrowseFlag { get { UPnPStateVariable sv = _S.GetStateVariableObject("A_ARG_TYPE_BrowseFlag"); return(sv.AllowedStringValues); } } public string Enum_A_ARG_TYPE_BrowseFlag_ToString(Enum_A_ARG_TYPE_BrowseFlag en) { string RetVal = ""; switch(en) { case Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA: RetVal = "BrowseMetadata"; break; case Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN: RetVal = "BrowseDirectChildren"; break; case Enum_A_ARG_TYPE_BrowseFlag._UNSPECIFIED_: RetVal = GetUnspecifiedValue("Enum_A_ARG_TYPE_BrowseFlag"); break; } return(RetVal); } public enum Enum_A_ARG_TYPE_BrowseFlag { _UNSPECIFIED_, BROWSEMETADATA, BROWSEDIRECTCHILDREN, } public Enum_A_ARG_TYPE_BrowseFlag A_ARG_TYPE_BrowseFlag { get { Enum_A_ARG_TYPE_BrowseFlag RetVal = 0; string v = (string)_S.GetStateVariable("A_ARG_TYPE_BrowseFlag"); switch(v) { case "BrowseMetadata": RetVal = Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; break; case "BrowseDirectChildren": RetVal = Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; break; default: RetVal = Enum_A_ARG_TYPE_BrowseFlag._UNSPECIFIED_; SetUnspecifiedValue("Enum_A_ARG_TYPE_BrowseFlag", v); break; } return(RetVal); } } public System.String A_ARG_TYPE_SortCriteria { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_SortCriteria")); } } public System.String A_ARG_TYPE_TransferLength { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_TransferLength")); } } public System.String TransferIDs { get { return((System.String)_S.GetStateVariable("TransferIDs")); } } public System.UInt32 A_ARG_TYPE_UpdateID { get { return((System.UInt32)_S.GetStateVariable("A_ARG_TYPE_UpdateID")); } } public System.String A_ARG_TYPE_SearchCriteria { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_SearchCriteria")); } } public System.String A_ARG_TYPE_Filter { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_Filter")); } } public System.String ContainerUpdateIDs { get { return((System.String)_S.GetStateVariable("ContainerUpdateIDs")); } } public System.String A_ARG_TYPE_Result { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_Result")); } } public System.UInt32 A_ARG_TYPE_Index { get { return((System.UInt32)_S.GetStateVariable("A_ARG_TYPE_Index")); } } public System.UInt32 A_ARG_TYPE_TransferID { get { return((System.UInt32)_S.GetStateVariable("A_ARG_TYPE_TransferID")); } } public System.String A_ARG_TYPE_TagValueList { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_TagValueList")); } } public System.Uri A_ARG_TYPE_URI { get { return((System.Uri)_S.GetStateVariable("A_ARG_TYPE_URI")); } } public System.String A_ARG_TYPE_ObjectID { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_ObjectID")); } } public System.String SortCapabilities { get { return((System.String)_S.GetStateVariable("SortCapabilities")); } } public System.UInt32 A_ARG_TYPE_Count { get { return((System.UInt32)_S.GetStateVariable("A_ARG_TYPE_Count")); } } public System.String SearchCapabilities { get { return((System.String)_S.GetStateVariable("SearchCapabilities")); } } public System.UInt32 SystemUpdateID { get { return((System.UInt32)_S.GetStateVariable("SystemUpdateID")); } } public System.String A_ARG_TYPE_TransferTotal { get { return((System.String)_S.GetStateVariable("A_ARG_TYPE_TransferTotal")); } } public bool HasStateVariable_A_ARG_TYPE_SortCriteria { get { if(_S.GetStateVariableObject("A_ARG_TYPE_SortCriteria")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_TransferLength { get { if(_S.GetStateVariableObject("A_ARG_TYPE_TransferLength")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_TransferIDs { get { if(_S.GetStateVariableObject("TransferIDs")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_UpdateID { get { if(_S.GetStateVariableObject("A_ARG_TYPE_UpdateID")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_SearchCriteria { get { if(_S.GetStateVariableObject("A_ARG_TYPE_SearchCriteria")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_Filter { get { if(_S.GetStateVariableObject("A_ARG_TYPE_Filter")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_ContainerUpdateIDs { get { if(_S.GetStateVariableObject("ContainerUpdateIDs")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_Result { get { if(_S.GetStateVariableObject("A_ARG_TYPE_Result")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_Index { get { if(_S.GetStateVariableObject("A_ARG_TYPE_Index")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_TransferID { get { if(_S.GetStateVariableObject("A_ARG_TYPE_TransferID")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_TagValueList { get { if(_S.GetStateVariableObject("A_ARG_TYPE_TagValueList")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_URI { get { if(_S.GetStateVariableObject("A_ARG_TYPE_URI")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_BrowseFlag { get { if(_S.GetStateVariableObject("A_ARG_TYPE_BrowseFlag")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_ObjectID { get { if(_S.GetStateVariableObject("A_ARG_TYPE_ObjectID")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_SortCapabilities { get { if(_S.GetStateVariableObject("SortCapabilities")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_Count { get { if(_S.GetStateVariableObject("A_ARG_TYPE_Count")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_SearchCapabilities { get { if(_S.GetStateVariableObject("SearchCapabilities")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_SystemUpdateID { get { if(_S.GetStateVariableObject("SystemUpdateID")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_TransferStatus { get { if(_S.GetStateVariableObject("A_ARG_TYPE_TransferStatus")==null) { return(false); } else { return(true); } } } public bool HasStateVariable_A_ARG_TYPE_TransferTotal { get { if(_S.GetStateVariableObject("A_ARG_TYPE_TransferTotal")==null) { return(false); } else { return(true); } } } public bool HasAction_ExportResource { get { if(_S.GetAction("ExportResource")==null) { return(false); } else { return(true); } } } public bool HasAction_StopTransferResource { get { if(_S.GetAction("StopTransferResource")==null) { return(false); } else { return(true); } } } public bool HasAction_DestroyObject { get { if(_S.GetAction("DestroyObject")==null) { return(false); } else { return(true); } } } public bool HasAction_UpdateObject { get { if(_S.GetAction("UpdateObject")==null) { return(false); } else { return(true); } } } public bool HasAction_GetSystemUpdateID { get { if(_S.GetAction("GetSystemUpdateID")==null) { return(false); } else { return(true); } } } public bool HasAction_GetTransferProgress { get { if(_S.GetAction("GetTransferProgress")==null) { return(false); } else { return(true); } } } public bool HasAction_GetSearchCapabilities { get { if(_S.GetAction("GetSearchCapabilities")==null) { return(false); } else { return(true); } } } public bool HasAction_CreateObject { get { if(_S.GetAction("CreateObject")==null) { return(false); } else { return(true); } } } public bool HasAction_ImportResource { get { if(_S.GetAction("ImportResource")==null) { return(false); } else { return(true); } } } public bool HasAction_Search { get { if(_S.GetAction("Search")==null) { return(false); } else { return(true); } } } public bool HasAction_GetSortCapabilities { get { if(_S.GetAction("GetSortCapabilities")==null) { return(false); } else { return(true); } } } public bool HasAction_Browse { get { if(_S.GetAction("Browse")==null) { return(false); } else { return(true); } } } public bool HasAction_CreateReference { get { if(_S.GetAction("CreateReference")==null) { return(false); } else { return(true); } } } public bool HasAction_DeleteResource { get { if(_S.GetAction("DeleteResource")==null) { return(false); } else { return(true); } } } public void Sync_ExportResource(System.Uri SourceURI, System.Uri DestinationURI, out System.UInt32 TransferID) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("SourceURI", SourceURI); args[1] = new UPnPArgument("DestinationURI", DestinationURI); args[2] = new UPnPArgument("TransferID", ""); _S.InvokeSync("ExportResource", args); SourceURI = (System.Uri) args[0].DataValue; DestinationURI = (System.Uri) args[1].DataValue; TransferID = (System.UInt32) args[2].DataValue; return; } public void ExportResource(System.Uri SourceURI, System.Uri DestinationURI) { ExportResource(SourceURI, DestinationURI, null, null); } public void ExportResource(System.Uri SourceURI, System.Uri DestinationURI, object _Tag, Delegate_OnResult_ExportResource _Callback) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("SourceURI", SourceURI); args[1] = new UPnPArgument("DestinationURI", DestinationURI); args[2] = new UPnPArgument("TransferID", ""); _S.InvokeAsync("ExportResource", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_ExportResource), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_ExportResource)); } private void Sink_ExportResource(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_ExportResource)StateInfo[1])(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32 )Args[2].DataValue, null, StateInfo[0]); } else { OnResult_ExportResource_Event.Fire(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32 )Args[2].DataValue, null, StateInfo[0]); } } private void Error_Sink_ExportResource(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_ExportResource)StateInfo[1])(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } else { OnResult_ExportResource_Event.Fire(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } } public void Sync_StopTransferResource(System.UInt32 TransferID) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("TransferID", TransferID); _S.InvokeSync("StopTransferResource", args); TransferID = (System.UInt32) args[0].DataValue; return; } public void StopTransferResource(System.UInt32 TransferID) { StopTransferResource(TransferID, null, null); } public void StopTransferResource(System.UInt32 TransferID, object _Tag, Delegate_OnResult_StopTransferResource _Callback) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("TransferID", TransferID); _S.InvokeAsync("StopTransferResource", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_StopTransferResource), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_StopTransferResource)); } private void Sink_StopTransferResource(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_StopTransferResource)StateInfo[1])(this, (System.UInt32 )Args[0].DataValue, null, StateInfo[0]); } else { OnResult_StopTransferResource_Event.Fire(this, (System.UInt32 )Args[0].DataValue, null, StateInfo[0]); } } private void Error_Sink_StopTransferResource(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_StopTransferResource)StateInfo[1])(this, (System.UInt32 )Args[0].DataValue, e, StateInfo[0]); } else { OnResult_StopTransferResource_Event.Fire(this, (System.UInt32 )Args[0].DataValue, e, StateInfo[0]); } } public void Sync_DestroyObject(System.String ObjectID) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("ObjectID", ObjectID); _S.InvokeSync("DestroyObject", args); ObjectID = (System.String) args[0].DataValue; return; } public void DestroyObject(System.String ObjectID) { DestroyObject(ObjectID, null, null); } public void DestroyObject(System.String ObjectID, object _Tag, Delegate_OnResult_DestroyObject _Callback) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("ObjectID", ObjectID); _S.InvokeAsync("DestroyObject", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_DestroyObject), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_DestroyObject)); } private void Sink_DestroyObject(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_DestroyObject)StateInfo[1])(this, (System.String )Args[0].DataValue, null, StateInfo[0]); } else { OnResult_DestroyObject_Event.Fire(this, (System.String )Args[0].DataValue, null, StateInfo[0]); } } private void Error_Sink_DestroyObject(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_DestroyObject)StateInfo[1])(this, (System.String )Args[0].DataValue, e, StateInfo[0]); } else { OnResult_DestroyObject_Event.Fire(this, (System.String )Args[0].DataValue, e, StateInfo[0]); } } public void Sync_UpdateObject(System.String ObjectID, System.String CurrentTagValue, System.String NewTagValue) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("ObjectID", ObjectID); args[1] = new UPnPArgument("CurrentTagValue", CurrentTagValue); args[2] = new UPnPArgument("NewTagValue", NewTagValue); _S.InvokeSync("UpdateObject", args); ObjectID = (System.String) args[0].DataValue; CurrentTagValue = (System.String) args[1].DataValue; NewTagValue = (System.String) args[2].DataValue; return; } public void UpdateObject(System.String ObjectID, System.String CurrentTagValue, System.String NewTagValue) { UpdateObject(ObjectID, CurrentTagValue, NewTagValue, null, null); } public void UpdateObject(System.String ObjectID, System.String CurrentTagValue, System.String NewTagValue, object _Tag, Delegate_OnResult_UpdateObject _Callback) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("ObjectID", ObjectID); args[1] = new UPnPArgument("CurrentTagValue", CurrentTagValue); args[2] = new UPnPArgument("NewTagValue", NewTagValue); _S.InvokeAsync("UpdateObject", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_UpdateObject), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_UpdateObject)); } private void Sink_UpdateObject(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_UpdateObject)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, null, StateInfo[0]); } else { OnResult_UpdateObject_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, null, StateInfo[0]); } } private void Error_Sink_UpdateObject(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_UpdateObject)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, e, StateInfo[0]); } else { OnResult_UpdateObject_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, e, StateInfo[0]); } } public void Sync_GetSystemUpdateID(out System.UInt32 Id) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("Id", ""); _S.InvokeSync("GetSystemUpdateID", args); Id = (System.UInt32) args[0].DataValue; return; } public void GetSystemUpdateID() { GetSystemUpdateID(null, null); } public void GetSystemUpdateID(object _Tag, Delegate_OnResult_GetSystemUpdateID _Callback) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("Id", ""); _S.InvokeAsync("GetSystemUpdateID", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_GetSystemUpdateID), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_GetSystemUpdateID)); } private void Sink_GetSystemUpdateID(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetSystemUpdateID)StateInfo[1])(this, (System.UInt32 )Args[0].DataValue, null, StateInfo[0]); } else { OnResult_GetSystemUpdateID_Event.Fire(this, (System.UInt32 )Args[0].DataValue, null, StateInfo[0]); } } private void Error_Sink_GetSystemUpdateID(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetSystemUpdateID)StateInfo[1])(this, (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } else { OnResult_GetSystemUpdateID_Event.Fire(this, (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } } public void Sync_GetTransferProgress(System.UInt32 TransferID, out Enum_A_ARG_TYPE_TransferStatus TransferStatus, out System.String TransferLength, out System.String TransferTotal) { UPnPArgument[] args = new UPnPArgument[4]; args[0] = new UPnPArgument("TransferID", TransferID); args[1] = new UPnPArgument("TransferStatus", ""); args[2] = new UPnPArgument("TransferLength", ""); args[3] = new UPnPArgument("TransferTotal", ""); _S.InvokeSync("GetTransferProgress", args); for(int i=0;i<args.Length;++i) { switch(args[i].Name) { case "TransferStatus": switch((string)args[i].DataValue) { case "COMPLETED": args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.COMPLETED; break; case "ERROR": args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.ERROR; break; case "IN_PROGRESS": args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.IN_PROGRESS; break; case "STOPPED": args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.STOPPED; break; default: SetUnspecifiedValue("Enum_A_ARG_TYPE_TransferStatus", (string)args[i].DataValue); args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus._UNSPECIFIED_; break; } break; } } TransferID = (System.UInt32) args[0].DataValue; TransferStatus = (Enum_A_ARG_TYPE_TransferStatus) args[1].DataValue; TransferLength = (System.String) args[2].DataValue; TransferTotal = (System.String) args[3].DataValue; return; } public void GetTransferProgress(System.UInt32 TransferID) { GetTransferProgress(TransferID, null, null); } public void GetTransferProgress(System.UInt32 TransferID, object _Tag, Delegate_OnResult_GetTransferProgress _Callback) { UPnPArgument[] args = new UPnPArgument[4]; args[0] = new UPnPArgument("TransferID", TransferID); args[1] = new UPnPArgument("TransferStatus", ""); args[2] = new UPnPArgument("TransferLength", ""); args[3] = new UPnPArgument("TransferTotal", ""); _S.InvokeAsync("GetTransferProgress", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_GetTransferProgress), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_GetTransferProgress)); } private void Sink_GetTransferProgress(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { for(int i=0;i<Args.Length;++i) { switch(Args[i].Name) { case "TransferStatus": switch((string)Args[i].DataValue) { case "COMPLETED": Args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.COMPLETED; break; case "ERROR": Args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.ERROR; break; case "IN_PROGRESS": Args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.IN_PROGRESS; break; case "STOPPED": Args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus.STOPPED; break; default: SetUnspecifiedValue("Enum_A_ARG_TYPE_TransferStatus", (string)Args[i].DataValue); Args[i].DataValue = Enum_A_ARG_TYPE_TransferStatus._UNSPECIFIED_; break; } break; } } object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetTransferProgress)StateInfo[1])(this, (System.UInt32 )Args[0].DataValue, (Enum_A_ARG_TYPE_TransferStatus )Args[1].DataValue, (System.String )Args[2].DataValue, (System.String )Args[3].DataValue, null, StateInfo[0]); } else { OnResult_GetTransferProgress_Event.Fire(this, (System.UInt32 )Args[0].DataValue, (Enum_A_ARG_TYPE_TransferStatus )Args[1].DataValue, (System.String )Args[2].DataValue, (System.String )Args[3].DataValue, null, StateInfo[0]); } } private void Error_Sink_GetTransferProgress(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetTransferProgress)StateInfo[1])(this, (System.UInt32 )Args[0].DataValue, (Enum_A_ARG_TYPE_TransferStatus)0, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } else { OnResult_GetTransferProgress_Event.Fire(this, (System.UInt32 )Args[0].DataValue, (Enum_A_ARG_TYPE_TransferStatus)0, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } } public void Sync_GetSearchCapabilities(out System.String SearchCaps) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("SearchCaps", ""); _S.InvokeSync("GetSearchCapabilities", args); SearchCaps = (System.String) args[0].DataValue; return; } public void GetSearchCapabilities() { GetSearchCapabilities(null, null); } public void GetSearchCapabilities(object _Tag, Delegate_OnResult_GetSearchCapabilities _Callback) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("SearchCaps", ""); _S.InvokeAsync("GetSearchCapabilities", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_GetSearchCapabilities), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_GetSearchCapabilities)); } private void Sink_GetSearchCapabilities(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetSearchCapabilities)StateInfo[1])(this, (System.String )Args[0].DataValue, null, StateInfo[0]); } else { OnResult_GetSearchCapabilities_Event.Fire(this, (System.String )Args[0].DataValue, null, StateInfo[0]); } } private void Error_Sink_GetSearchCapabilities(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetSearchCapabilities)StateInfo[1])(this, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } else { OnResult_GetSearchCapabilities_Event.Fire(this, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } } public void Sync_CreateObject(System.String ContainerID, System.String Elements, out System.String ObjectID, out System.String Result) { UPnPArgument[] args = new UPnPArgument[4]; args[0] = new UPnPArgument("ContainerID", ContainerID); args[1] = new UPnPArgument("Elements", Elements); args[2] = new UPnPArgument("ObjectID", ""); args[3] = new UPnPArgument("Result", ""); _S.InvokeSync("CreateObject", args); ContainerID = (System.String) args[0].DataValue; Elements = (System.String) args[1].DataValue; ObjectID = (System.String) args[2].DataValue; Result = (System.String) args[3].DataValue; return; } public void CreateObject(System.String ContainerID, System.String Elements) { CreateObject(ContainerID, Elements, null, null); } public void CreateObject(System.String ContainerID, System.String Elements, object _Tag, Delegate_OnResult_CreateObject _Callback) { UPnPArgument[] args = new UPnPArgument[4]; args[0] = new UPnPArgument("ContainerID", ContainerID); args[1] = new UPnPArgument("Elements", Elements); args[2] = new UPnPArgument("ObjectID", ""); args[3] = new UPnPArgument("Result", ""); _S.InvokeAsync("CreateObject", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_CreateObject), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_CreateObject)); } private void Sink_CreateObject(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_CreateObject)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, (System.String )Args[3].DataValue, null, StateInfo[0]); } else { OnResult_CreateObject_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, (System.String )Args[3].DataValue, null, StateInfo[0]); } } private void Error_Sink_CreateObject(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_CreateObject)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } else { OnResult_CreateObject_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } } public void Sync_ImportResource(System.Uri SourceURI, System.Uri DestinationURI, out System.UInt32 TransferID) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("SourceURI", SourceURI); args[1] = new UPnPArgument("DestinationURI", DestinationURI); args[2] = new UPnPArgument("TransferID", ""); _S.InvokeSync("ImportResource", args); SourceURI = (System.Uri) args[0].DataValue; DestinationURI = (System.Uri) args[1].DataValue; TransferID = (System.UInt32) args[2].DataValue; return; } public void ImportResource(System.Uri SourceURI, System.Uri DestinationURI) { ImportResource(SourceURI, DestinationURI, null, null); } public void ImportResource(System.Uri SourceURI, System.Uri DestinationURI, object _Tag, Delegate_OnResult_ImportResource _Callback) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("SourceURI", SourceURI); args[1] = new UPnPArgument("DestinationURI", DestinationURI); args[2] = new UPnPArgument("TransferID", ""); _S.InvokeAsync("ImportResource", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_ImportResource), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_ImportResource)); } private void Sink_ImportResource(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_ImportResource)StateInfo[1])(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32 )Args[2].DataValue, null, StateInfo[0]); } else { OnResult_ImportResource_Event.Fire(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32 )Args[2].DataValue, null, StateInfo[0]); } } private void Error_Sink_ImportResource(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_ImportResource)StateInfo[1])(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } else { OnResult_ImportResource_Event.Fire(this, (System.Uri )Args[0].DataValue, (System.Uri )Args[1].DataValue, (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } } public void Sync_Search(System.String ContainerID, System.String SearchCriteria, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, out System.String Result, out System.UInt32 NumberReturned, out System.UInt32 TotalMatches, out System.UInt32 UpdateID) { UPnPArgument[] args = new UPnPArgument[10]; args[0] = new UPnPArgument("ContainerID", ContainerID); args[1] = new UPnPArgument("SearchCriteria", SearchCriteria); args[2] = new UPnPArgument("Filter", Filter); args[3] = new UPnPArgument("StartingIndex", StartingIndex); args[4] = new UPnPArgument("RequestedCount", RequestedCount); args[5] = new UPnPArgument("SortCriteria", SortCriteria); args[6] = new UPnPArgument("Result", ""); args[7] = new UPnPArgument("NumberReturned", ""); args[8] = new UPnPArgument("TotalMatches", ""); args[9] = new UPnPArgument("UpdateID", ""); _S.InvokeSync("Search", args); ContainerID = (System.String) args[0].DataValue; SearchCriteria = (System.String) args[1].DataValue; Filter = (System.String) args[2].DataValue; StartingIndex = (System.UInt32) args[3].DataValue; RequestedCount = (System.UInt32) args[4].DataValue; SortCriteria = (System.String) args[5].DataValue; Result = (System.String) args[6].DataValue; NumberReturned = (System.UInt32) args[7].DataValue; TotalMatches = (System.UInt32) args[8].DataValue; UpdateID = (System.UInt32) args[9].DataValue; return; } public void Search(System.String ContainerID, System.String SearchCriteria, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria) { Search(ContainerID, SearchCriteria, Filter, StartingIndex, RequestedCount, SortCriteria, null, null); } public void Search(System.String ContainerID, System.String SearchCriteria, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, object _Tag, Delegate_OnResult_Search _Callback) { UPnPArgument[] args = new UPnPArgument[10]; args[0] = new UPnPArgument("ContainerID", ContainerID); args[1] = new UPnPArgument("SearchCriteria", SearchCriteria); args[2] = new UPnPArgument("Filter", Filter); args[3] = new UPnPArgument("StartingIndex", StartingIndex); args[4] = new UPnPArgument("RequestedCount", RequestedCount); args[5] = new UPnPArgument("SortCriteria", SortCriteria); args[6] = new UPnPArgument("Result", ""); args[7] = new UPnPArgument("NumberReturned", ""); args[8] = new UPnPArgument("TotalMatches", ""); args[9] = new UPnPArgument("UpdateID", ""); _S.InvokeAsync("Search", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_Search), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_Search)); } private void Sink_Search(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_Search)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String )Args[6].DataValue, (System.UInt32 )Args[7].DataValue, (System.UInt32 )Args[8].DataValue, (System.UInt32 )Args[9].DataValue, null, StateInfo[0]); } else { OnResult_Search_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String )Args[6].DataValue, (System.UInt32 )Args[7].DataValue, (System.UInt32 )Args[8].DataValue, (System.UInt32 )Args[9].DataValue, null, StateInfo[0]); } } private void Error_Sink_Search(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_Search)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } else { OnResult_Search_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } } public void Sync_GetSortCapabilities(out System.String SortCaps) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("SortCaps", ""); _S.InvokeSync("GetSortCapabilities", args); SortCaps = (System.String) args[0].DataValue; return; } public void GetSortCapabilities() { GetSortCapabilities(null, null); } public void GetSortCapabilities(object _Tag, Delegate_OnResult_GetSortCapabilities _Callback) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("SortCaps", ""); _S.InvokeAsync("GetSortCapabilities", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_GetSortCapabilities), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_GetSortCapabilities)); } private void Sink_GetSortCapabilities(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetSortCapabilities)StateInfo[1])(this, (System.String )Args[0].DataValue, null, StateInfo[0]); } else { OnResult_GetSortCapabilities_Event.Fire(this, (System.String )Args[0].DataValue, null, StateInfo[0]); } } private void Error_Sink_GetSortCapabilities(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_GetSortCapabilities)StateInfo[1])(this, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } else { OnResult_GetSortCapabilities_Event.Fire(this, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } } public void Sync_Browse(System.String ObjectID, Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, out System.String Result, out System.UInt32 NumberReturned, out System.UInt32 TotalMatches, out System.UInt32 UpdateID) { UPnPArgument[] args = new UPnPArgument[10]; args[0] = new UPnPArgument("ObjectID", ObjectID); switch(BrowseFlag) { case Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA: args[1] = new UPnPArgument("BrowseFlag", "BrowseMetadata"); break; case Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN: args[1] = new UPnPArgument("BrowseFlag", "BrowseDirectChildren"); break; default: args[1] = new UPnPArgument("BrowseFlag", GetUnspecifiedValue("Enum_A_ARG_TYPE_BrowseFlag")); break; } args[2] = new UPnPArgument("Filter", Filter); args[3] = new UPnPArgument("StartingIndex", StartingIndex); args[4] = new UPnPArgument("RequestedCount", RequestedCount); args[5] = new UPnPArgument("SortCriteria", SortCriteria); args[6] = new UPnPArgument("Result", ""); args[7] = new UPnPArgument("NumberReturned", ""); args[8] = new UPnPArgument("TotalMatches", ""); args[9] = new UPnPArgument("UpdateID", ""); _S.InvokeSync("Browse", args); for(int i=0;i<args.Length;++i) { switch(args[i].Name) { case "BrowseFlag": switch((string)args[i].DataValue) { case "BrowseMetadata": args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; break; case "BrowseDirectChildren": args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; break; default: SetUnspecifiedValue("Enum_A_ARG_TYPE_BrowseFlag", (string)args[i].DataValue); args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag._UNSPECIFIED_; break; } break; } } ObjectID = (System.String) args[0].DataValue; BrowseFlag = (Enum_A_ARG_TYPE_BrowseFlag) args[1].DataValue; Filter = (System.String) args[2].DataValue; StartingIndex = (System.UInt32) args[3].DataValue; RequestedCount = (System.UInt32) args[4].DataValue; SortCriteria = (System.String) args[5].DataValue; Result = (System.String) args[6].DataValue; NumberReturned = (System.UInt32) args[7].DataValue; TotalMatches = (System.UInt32) args[8].DataValue; UpdateID = (System.UInt32) args[9].DataValue; return; } public void Browse(System.String ObjectID, Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria) { Browse(ObjectID, BrowseFlag, Filter, StartingIndex, RequestedCount, SortCriteria, null, null); } public void Browse(System.String ObjectID, Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, System.String Filter, System.UInt32 StartingIndex, System.UInt32 RequestedCount, System.String SortCriteria, object _Tag, Delegate_OnResult_Browse _Callback) { UPnPArgument[] args = new UPnPArgument[10]; args[0] = new UPnPArgument("ObjectID", ObjectID); switch(BrowseFlag) { case Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA: args[1] = new UPnPArgument("BrowseFlag", "BrowseMetadata"); break; case Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN: args[1] = new UPnPArgument("BrowseFlag", "BrowseDirectChildren"); break; default: args[1] = new UPnPArgument("BrowseFlag", GetUnspecifiedValue("Enum_A_ARG_TYPE_BrowseFlag")); break; } args[2] = new UPnPArgument("Filter", Filter); args[3] = new UPnPArgument("StartingIndex", StartingIndex); args[4] = new UPnPArgument("RequestedCount", RequestedCount); args[5] = new UPnPArgument("SortCriteria", SortCriteria); args[6] = new UPnPArgument("Result", ""); args[7] = new UPnPArgument("NumberReturned", ""); args[8] = new UPnPArgument("TotalMatches", ""); args[9] = new UPnPArgument("UpdateID", ""); _S.InvokeAsync("Browse", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_Browse), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_Browse)); } private void Sink_Browse(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { for(int i=0;i<Args.Length;++i) { switch(Args[i].Name) { case "BrowseFlag": switch((string)Args[i].DataValue) { case "BrowseMetadata": Args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; break; case "BrowseDirectChildren": Args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; break; default: SetUnspecifiedValue("Enum_A_ARG_TYPE_BrowseFlag", (string)Args[i].DataValue); Args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag._UNSPECIFIED_; break; } break; } } object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_Browse)StateInfo[1])(this, (System.String )Args[0].DataValue, (Enum_A_ARG_TYPE_BrowseFlag )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String )Args[6].DataValue, (System.UInt32 )Args[7].DataValue, (System.UInt32 )Args[8].DataValue, (System.UInt32 )Args[9].DataValue, null, StateInfo[0]); } else { OnResult_Browse_Event.Fire(this, (System.String )Args[0].DataValue, (Enum_A_ARG_TYPE_BrowseFlag )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String )Args[6].DataValue, (System.UInt32 )Args[7].DataValue, (System.UInt32 )Args[8].DataValue, (System.UInt32 )Args[9].DataValue, null, StateInfo[0]); } } private void Error_Sink_Browse(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { for(int i=0;i<Args.Length;++i) { switch(Args[i].Name) { case "BrowseFlag": switch((string)Args[i].DataValue) { case "BrowseMetadata": Args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag.BROWSEMETADATA; break; case "BrowseDirectChildren": Args[i].DataValue = Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN; break; } break; } } object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_Browse)StateInfo[1])(this, (System.String )Args[0].DataValue, (Enum_A_ARG_TYPE_BrowseFlag )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } else { OnResult_Browse_Event.Fire(this, (System.String )Args[0].DataValue, (Enum_A_ARG_TYPE_BrowseFlag )Args[1].DataValue, (System.String )Args[2].DataValue, (System.UInt32 )Args[3].DataValue, (System.UInt32 )Args[4].DataValue, (System.String )Args[5].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), (System.UInt32)UPnPService.CreateObjectInstance(typeof(System.UInt32),null), e, StateInfo[0]); } } public void Sync_CreateReference(System.String ContainerID, System.String ObjectID, out System.String NewID) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("ContainerID", ContainerID); args[1] = new UPnPArgument("ObjectID", ObjectID); args[2] = new UPnPArgument("NewID", ""); _S.InvokeSync("CreateReference", args); ContainerID = (System.String) args[0].DataValue; ObjectID = (System.String) args[1].DataValue; NewID = (System.String) args[2].DataValue; return; } public void CreateReference(System.String ContainerID, System.String ObjectID) { CreateReference(ContainerID, ObjectID, null, null); } public void CreateReference(System.String ContainerID, System.String ObjectID, object _Tag, Delegate_OnResult_CreateReference _Callback) { UPnPArgument[] args = new UPnPArgument[3]; args[0] = new UPnPArgument("ContainerID", ContainerID); args[1] = new UPnPArgument("ObjectID", ObjectID); args[2] = new UPnPArgument("NewID", ""); _S.InvokeAsync("CreateReference", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_CreateReference), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_CreateReference)); } private void Sink_CreateReference(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_CreateReference)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, null, StateInfo[0]); } else { OnResult_CreateReference_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String )Args[2].DataValue, null, StateInfo[0]); } } private void Error_Sink_CreateReference(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_CreateReference)StateInfo[1])(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } else { OnResult_CreateReference_Event.Fire(this, (System.String )Args[0].DataValue, (System.String )Args[1].DataValue, (System.String)UPnPService.CreateObjectInstance(typeof(System.String),null), e, StateInfo[0]); } } public void Sync_DeleteResource(System.Uri ResourceURI) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("ResourceURI", ResourceURI); _S.InvokeSync("DeleteResource", args); ResourceURI = (System.Uri) args[0].DataValue; return; } public void DeleteResource(System.Uri ResourceURI) { DeleteResource(ResourceURI, null, null); } public void DeleteResource(System.Uri ResourceURI, object _Tag, Delegate_OnResult_DeleteResource _Callback) { UPnPArgument[] args = new UPnPArgument[1]; args[0] = new UPnPArgument("ResourceURI", ResourceURI); _S.InvokeAsync("DeleteResource", args, new object[2]{_Tag,_Callback},new UPnPService.UPnPServiceInvokeHandler(Sink_DeleteResource), new UPnPService.UPnPServiceInvokeErrorHandler(Error_Sink_DeleteResource)); } private void Sink_DeleteResource(UPnPService sender, string MethodName, UPnPArgument[] Args, object RetVal, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_DeleteResource)StateInfo[1])(this, (System.Uri )Args[0].DataValue, null, StateInfo[0]); } else { OnResult_DeleteResource_Event.Fire(this, (System.Uri )Args[0].DataValue, null, StateInfo[0]); } } private void Error_Sink_DeleteResource(UPnPService sender, string MethodName, UPnPArgument[] Args, UPnPInvokeException e, object _Tag) { object[] StateInfo = (object[])_Tag; if(StateInfo[1]!=null) { ((Delegate_OnResult_DeleteResource)StateInfo[1])(this, (System.Uri )Args[0].DataValue, e, StateInfo[0]); } else { OnResult_DeleteResource_Event.Fire(this, (System.Uri )Args[0].DataValue, e, StateInfo[0]); } } } }
// // DatabaseImportManager.cs // // Authors: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@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. // using System; using System.Collections.Generic; using System.IO; using Mono.Unix; using Hyena; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.ServiceStack; using Banshee.Streaming; namespace Banshee.Collection.Database { public class DatabaseImportManager : ImportManager { // This is a list of known media files that we may encounter. The extensions // in this list do not mean they are actually supported - this list is just // used to see if we should allow the file to be processed by TagLib. The // point is to rule out, at the path level, files that we won't support. public static readonly Banshee.IO.ExtensionSet WhiteListFileExtensions = new Banshee.IO.ExtensionSet ( "3g2", "3gp", "3gp2", "3gpp", "aac", "ac3", "aif", "aifc", "aiff", "al", "alaw", "ape", "asf", "asx", "au", "avi", "cda", "cdr", "divx", "dv", "flac", "flv", "gvi", "gvp", "m1v", "m21", "m2p", "m2v", "m4a", "m4b", "m4e", "m4p", "m4u", "m4v", "mp+", "mid", "midi", "mjp", "mkv", "moov", "mov", "movie","mp1", "mp2", "mp21", "mp3", "mp4", "mpa", "mpc", "mpe", "mpeg", "mpg", "mpga", "mpp", "mpu", "mpv", "mpv2", "oga", "ogg", "ogv", "ogm", "omf", "qt", "ra", "ram", "raw", "rm", "rmvb", "rts", "smil", "swf", "tivo", "u", "vfw", "vob", "wav", "wave", "wax", "wm", "wma", "wmd", "wmv", "wmx", "wv", "wvc", "wvx", "yuv", "f4v", "f4a", "f4b", "669", "it", "med", "mod", "mol", "mtm", "nst", "s3m", "stm", "ult", "wow", "xm", "xnm", "spx", "ts", "webm", "spc", "mka", "opus", "amr" ); public static bool IsWhiteListedFile (string path) { return WhiteListFileExtensions.IsMatchingFile (path); } public delegate PrimarySource TrackPrimarySourceChooser (DatabaseTrackInfo track); private TrackPrimarySourceChooser trackPrimarySourceChooser; private Dictionary<long, int> counts; private ErrorSource error_source; private long [] primary_source_ids; private string base_directory; private bool force_copy; public event DatabaseImportResultHandler ImportResult; public DatabaseImportManager (PrimarySource psource) : this (psource.ErrorSource, delegate { return psource; }, new long [] {psource.DbId}, psource.BaseDirectory) { } public DatabaseImportManager (ErrorSource error_source, TrackPrimarySourceChooser chooser, long [] primarySourceIds, string baseDirectory) : this (chooser) { this.error_source = error_source; primary_source_ids = primarySourceIds; base_directory = baseDirectory; } public DatabaseImportManager (TrackPrimarySourceChooser chooser) { trackPrimarySourceChooser = chooser; counts = new Dictionary<long, int> (); } protected virtual ErrorSource ErrorSource { get { return error_source; } } protected virtual long [] PrimarySourceIds { get { return primary_source_ids; } set { primary_source_ids = value; } } protected virtual string BaseDirectory { get { return base_directory; } set { base_directory = value; } } protected virtual bool ForceCopy { get { return force_copy; } set { force_copy = value; } } protected override void OnImportRequested (string path) { try { DatabaseTrackInfo track = ImportTrack (path); if (track != null && track.TrackId > 0) { UpdateProgress (String.Format ("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle)); } else { UpdateProgress (null); } OnImportResult (track, path, null); } catch (Exception e) { LogError (SafeUri.UriToFilename (path), e); UpdateProgress (null); OnImportResult (null, path, e); } } protected virtual void OnImportResult (DatabaseTrackInfo track, string path, Exception error) { DatabaseImportResultHandler handler = ImportResult; if (handler != null) { handler (this, new DatabaseImportResultArgs (track, path, error)); } } public DatabaseTrackInfo ImportTrack (string path) { return ImportTrack (new SafeUri (path)); } public DatabaseTrackInfo ImportTrack (SafeUri uri) { if (!IsWhiteListedFile (uri.AbsoluteUri)) { return null; } if (DatabaseTrackInfo.ContainsUri (uri, PrimarySourceIds)) { // TODO add DatabaseTrackInfo.SyncedStamp property, and if the file has been // updated since the last sync, fetch its metadata into the db. return null; } if (!Banshee.IO.File.GetPermissions (uri).IsReadable) { throw new InvalidFileException (String.Format ( Catalog.GetString ("File is not readable so it could not be imported: {0}"), Path.GetFileName (uri.LocalPath))); } if (Banshee.IO.File.GetSize (uri) == 0) { throw new InvalidFileException (String.Format ( Catalog.GetString ("File is empty so it could not be imported: {0}"), Path.GetFileName (uri.LocalPath))); } DatabaseTrackInfo track = new DatabaseTrackInfo () { Uri = uri }; using (var file = StreamTagger.ProcessUri (uri)) { StreamTagger.TrackInfoMerge (track, file, false, true, true); } track.Uri = uri; if (FindOutdatedDupe (track)) { return null; } track.PrimarySource = trackPrimarySourceChooser (track); // TODO note, there is deadlock potential here b/c of locking of shared commands and blocking // because of transactions. Needs to be fixed in HyenaDatabaseConnection. ServiceManager.DbConnection.BeginTransaction (); try { bool save_track = true; if (track.PrimarySource is Banshee.Library.LibrarySource) { save_track = track.CopyToLibraryIfAppropriate (force_copy); } if (save_track) { track.Save (false); } ServiceManager.DbConnection.CommitTransaction (); } catch (Exception) { ServiceManager.DbConnection.RollbackTransaction (); throw; } counts[track.PrimarySourceId] = counts.ContainsKey (track.PrimarySourceId) ? counts[track.PrimarySourceId] + 1 : 1; // Reload every 20% or every 250 tracks, whatever is more (eg at most reload 5 times during an import) if (counts[track.PrimarySourceId] >= Math.Max (TotalCount/5, 250)) { counts[track.PrimarySourceId] = 0; track.PrimarySource.NotifyTracksAdded (); } return track; } private bool FindOutdatedDupe (DatabaseTrackInfo track) { if (DatabaseTrackInfo.MetadataHashCount (track.MetadataHash, PrimarySourceIds) != 1) { return false; } var track_to_update = DatabaseTrackInfo.GetTrackForMetadataHash (track.MetadataHash, PrimarySourceIds); if (track_to_update == null || Banshee.IO.File.Exists (track_to_update.Uri)) { return false; } track_to_update.Uri = track.Uri; track_to_update.Save (); return true; } private void LogError (string path, Exception e) { LogError (path, e.Message); if (!(e is TagLib.CorruptFileException) && !(e is TagLib.UnsupportedFormatException)) { Log.DebugFormat ("Full import exception: {0}", e.ToString ()); } } private void LogError (string path, string msg) { ErrorSource.AddMessage (path, msg); Log.Error (path, msg, false); } public void NotifyAllSources () { var all_primary_source_ids = new List<long> (counts.Keys); foreach (long primary_source_id in all_primary_source_ids) { PrimarySource.GetById (primary_source_id).NotifyTracksAdded (); } counts.Clear (); } protected override void OnFinished () { NotifyAllSources (); base.OnFinished (); } } }
using System; using System.IO; using System.Net; using System.Text; using NUnit.Framework; using NServiceKit.Common.Web; using NServiceKit.WebHost.IntegrationTests.Services; namespace NServiceKit.WebHost.IntegrationTests.Tests { /// <summary>A rest web service tests.</summary> [TestFixture] public class RestWebServiceTests : RestsTestBase { /// <summary>Can call echo request with accept all.</summary> [Test] public void Can_call_EchoRequest_with_AcceptAll() { var response = GetWebResponse(ServiceClientBaseUri + "/echo/1/One", "*/*"); var contents = GetContents(response); Assert.That(contents, Is.Not.Null); Assert.That(contents.Contains("\"id\":1")); Assert.That(contents.Contains("\"string\":\"One\"")); } /// <summary>Can call echo request with accept JSON.</summary> [Test] public void Can_call_EchoRequest_with_AcceptJson() { var response = GetWebResponse(ServiceClientBaseUri + "/echo/1/One", ContentType.Json); AssertResponse<EchoRequest>(response, ContentType.Json, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.String, Is.EqualTo("One")); }); } /// <summary>Can call echo request with accept XML.</summary> [Test] public void Can_call_EchoRequest_with_AcceptXml() { var response = GetWebResponse(ServiceClientBaseUri + "/echo/1/One", ContentType.Xml); AssertResponse<EchoRequest>(response, ContentType.Xml, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.String, Is.EqualTo("One")); }); } /// <summary>Can call echo request with accept jsv.</summary> [Test] public void Can_call_EchoRequest_with_AcceptJsv() { var response = GetWebResponse(ServiceClientBaseUri + "/echo/1/One", ContentType.Jsv); AssertResponse<EchoRequest>(response, ContentType.Jsv, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.String, Is.EqualTo("One")); }); } /// <summary>Can call echo request with query string.</summary> [Test] public void Can_call_EchoRequest_with_QueryString() { var response = GetWebResponse(ServiceClientBaseUri + "/echo/1/One?Long=2&Bool=True", ContentType.Json); AssertResponse<EchoRequest>(response, ContentType.Json, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.String, Is.EqualTo("One")); Assert.That(x.Long, Is.EqualTo(2)); Assert.That(x.Bool, Is.EqualTo(true)); }); } private HttpWebResponse EmulateHttpMethod(string emulateMethod, string useMethod) { var webRequest = (HttpWebRequest) WebRequest.Create(ServiceClientBaseUri + "/echomethod"); webRequest.Accept = ContentType.Json; webRequest.Method = useMethod; webRequest.Headers[HttpHeaders.XHttpMethodOverride] = emulateMethod; if (useMethod == HttpMethods.Post) webRequest.ContentLength = 0; var response = (HttpWebResponse) webRequest.GetResponse(); return response; } /// <summary>Can emulate put HTTP method with post.</summary> [Test] public void Can_emulate_Put_HttpMethod_with_POST() { var response = EmulateHttpMethod(HttpMethods.Put, HttpMethods.Post); AssertResponse<EchoMethodResponse>(response, ContentType.Json, x => Assert.That(x.Result, Is.EqualTo(HttpMethods.Put))); } /// <summary>Can emulate put HTTP method with get.</summary> [Test] public void Can_emulate_Put_HttpMethod_with_GET() { var response = EmulateHttpMethod(HttpMethods.Put, HttpMethods.Get); AssertResponse<EchoMethodResponse>(response, ContentType.Json, x => Assert.That(x.Result, Is.EqualTo(HttpMethods.Put))); } /// <summary>Can emulate delete HTTP method with get.</summary> [Test] public void Can_emulate_Delete_HttpMethod_with_GET() { var response = EmulateHttpMethod(HttpMethods.Delete, HttpMethods.Get); AssertResponse<EchoMethodResponse>(response, ContentType.Json, x => Assert.That(x.Result, Is.EqualTo(HttpMethods.Delete))); } /// <summary>Can call wild card request with alternate wild card defined.</summary> [Test] public void Can_call_WildCardRequest_with_alternate_WildCard_defined() { var response = GetWebResponse(ServiceClientBaseUri + "/wildcard/1/aPath/edit", ContentType.Json); AssertResponse<WildCardRequest>(response, ContentType.Json, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.Path, Is.EqualTo("aPath")); Assert.That(x.Action, Is.EqualTo("edit")); Assert.That(x.RemainingPath, Is.Null); }); } /// <summary>Can call wild card request wild card mapping.</summary> [Test] public void Can_call_WildCardRequest_WildCard_mapping() { var response = GetWebResponse(ServiceClientBaseUri + "/wildcard/1/remaining/path/to/here", ContentType.Json); AssertResponse<WildCardRequest>(response, ContentType.Json, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.Path, Is.Null); Assert.That(x.Action, Is.Null); Assert.That(x.RemainingPath, Is.EqualTo("remaining/path/to/here")); }); } /// <summary>Can call wild card request wild card mapping with query string.</summary> [Test] public void Can_call_WildCardRequest_WildCard_mapping_with_QueryString() { var response = GetWebResponse(ServiceClientBaseUri + "/wildcard/1/remaining/path/to/here?Action=edit", ContentType.Json); AssertResponse<WildCardRequest>(response, ContentType.Json, x => { Assert.That(x.Id, Is.EqualTo(1)); Assert.That(x.Path, Is.Null); Assert.That(x.Action, Is.EqualTo("edit")); Assert.That(x.RemainingPath, Is.EqualTo("remaining/path/to/here")); }); } /// <summary>Can call reset movies mapping with empty XML post.</summary> [Test(Description = "Test for error processing empty XML request")] public void Can_call_ResetMovies_mapping_with_empty_Xml_post() { var response = GetWebResponse(HttpMethods.Post, ServiceClientBaseUri + "/reset-movies", ContentType.Xml, 0); AssertResponse<ResetMoviesResponse>(response, ContentType.Xml, x => { }); } /// <summary>Can post new movie with form data.</summary> /// /// <exception cref="WebException">Thrown when a Web error condition occurs.</exception> [Test] public void Can_POST_new_movie_with_FormData() { const string formData = "Id=0&ImdbId=tt0110912&Title=Pulp+Fiction&Rating=8.9&Director=Quentin+Tarantino&ReleaseDate=1994-11-24&TagLine=Girls+like+me+don't+make+invitations+like+this+to+just+anyone!&Genres=Crime%2CDrama%2CThriller"; var formDataBytes = Encoding.UTF8.GetBytes(formData); var webRequest = (HttpWebRequest)WebRequest.Create(ServiceClientBaseUri + "/movies"); webRequest.Accept = ContentType.Json; webRequest.ContentType = ContentType.FormUrlEncoded; webRequest.Method = HttpMethods.Post; webRequest.ContentLength = formDataBytes.Length; webRequest.GetRequestStream().Write(formDataBytes, 0, formDataBytes.Length); try { var response = (HttpWebResponse)webRequest.GetResponse(); AssertResponse<MovieResponse>(response, ContentType.Json, x => { Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created)); Assert.That(response.Headers["Location"], Is.EqualTo(ServiceClientBaseUri + "/movies/" + x.Movie.Id)); }); } catch (WebException webEx) { if (webEx.Status == WebExceptionStatus.ProtocolError) { var errorResponse = ((HttpWebResponse)webEx.Response); Console.WriteLine("Error: " + webEx); Console.WriteLine("Status Code : {0}", errorResponse.StatusCode); Console.WriteLine("Status Description : {0}", errorResponse.StatusDescription); Console.WriteLine("Body:" + new StreamReader(errorResponse.GetResponseStream()).ReadToEnd()); } throw; } } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using System.Globalization; namespace WebApplication2 { /// <summary> /// Summary description for frmResourcesInfo. /// </summary> public partial class frmOrgLocSEProcs: System.Web.UI.Page { /*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+ "uid=tauheed;pwd=tauheed;");*/ 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); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (!IsPostBack) { lblLoc.Text="Location: " + Session["LocationName"].ToString(); lblService.Text="Service: " + Session["ServiceName"].ToString(); if (Session["MgrOption"] == "Plan") { lblOrg.Text=Session["MgrName"].ToString(); lblContents1.Text="Given below are the different types of procedures" + " that are undertaken to deliver the above service." + " Click on the appropriate button to assign resources as needed."; DataGrid2.Visible = false; loadData1(); } else if (Session["MgrOption"] == "Budget") { lblOrg.Text = Session["OrgName"].ToString(); lblContents1.Text = "Given below are the different types of procedures" + " that are undertaken to deliver the above service." + " You may now provide a for them as needed."; DataGrid1.Visible = false; loadData2(); } } } #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 loadData1() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.Connection=this.epsDbConn; cmd.CommandText="wms_RetrieveOrgLocSEProcs"; if (Session["PRS"].ToString() == "1") { cmd.Parameters.Add ("@ProjectId",SqlDbType.Int); cmd.Parameters["@ProjectId"].Value=Session["ProjectId"].ToString(); } cmd.Parameters.Add ("@ProfileServicesId",SqlDbType.Int); cmd.Parameters["@ProfileServicesId"].Value=Session["ProfileServicesId"].ToString(); cmd.Parameters.Add ("@OrgLocId",SqlDbType.Int); cmd.Parameters["@OrgLocId"].Value=Session["OrgLocId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"OrgLocSEProcs"); if (ds.Tables["OrgLocSEProcs"].Rows.Count == 0) { DataGrid1.Visible=false; lblContents1.ForeColor=System.Drawing.Color.White; lblContents1.Text="Note: There are no existing procedures identified for this service." + " Please contact your system administrator."; } Session["ds"] = ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); refreshGrid1(); } private void refreshGrid1() { if ((Session["startForm"].ToString() == "frmMainWP") || (Session["startForm"].ToString() == "frmMainMgr")) { foreach (DataGridItem i in DataGrid1.Items) { Button bnSt = (Button)(i.Cells[2].FindControl("btnStaff")); Button bnO = (Button)(i.Cells[2].FindControl("btnOther")); Button bnOutputs = (Button) (i.Cells[5].FindControl("btnOutputs")); Button bnClients = (Button) (i.Cells[5].FindControl("btnClients")); if (Int32.Parse(i.Cells[3].Text) > 0) { bnSt.Enabled = true; bnSt.ForeColor = bnSt.BackColor; } else { bnSt.Visible = false; } if (Int32.Parse(i.Cells[4].Text) > 0) { bnO.Enabled = true; bnO.ForeColor = bnO.BackColor; } else { bnO.Visible = false; } } } else if (Session["startForm"].ToString() == "frmMainBMgr") { foreach (DataGridItem i in DataGrid1.Items) { Button bnO = (Button)(i.Cells[2].FindControl("btnOther")); bnO.Visible = false; } } } private void loadData2() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = this.epsDbConn; cmd.CommandText = "wms_RetrieveOrgLocSEProcs"; cmd.Parameters.Add("@ProfileServicesId", SqlDbType.Int); cmd.Parameters["@ProfileServicesId"].Value = Session["ProfileServicesId"].ToString(); cmd.Parameters.Add("@OrgLocId", SqlDbType.Int); cmd.Parameters["@OrgLocId"].Value = Session["OrgLocId"].ToString(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "OrgLocSEProcs"); if (ds.Tables["OrgLocSEProcs"].Rows.Count == 0) { DataGrid1.Visible = false; lblContents1.ForeColor = System.Drawing.Color.White; lblContents1.Text = "Note: There are no existing procedures identified for this service." + " Please contact your system administrator."; } Session["ds"] = ds; DataGrid2.DataSource = ds; DataGrid2.DataBind(); refreshGrid2(); } private void refreshGrid2() { foreach (DataGridItem i in DataGrid2.Items) { TextBox tb = (TextBox)(i.Cells[2].FindControl("txtBud")); SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = this.epsDbConn; cmd.CommandText = "fms_RetrieveBudProjProcs"; cmd.Parameters.Add("@ProfileSEProcsId", SqlDbType.Int); cmd.Parameters["@ProfileSEProcsId"].Value = Int32.Parse(i.Cells[9].Text); cmd.Parameters.Add("@OrgLocId", SqlDbType.Int); cmd.Parameters["@OrgLocId"].Value = Int32.Parse(Session["OrgLocId"].ToString()); cmd.Parameters.Add("@BudOLServiceId", SqlDbType.Int); cmd.Parameters["@BudOLServiceId"].Value = Int32.Parse(Session["BudOLServicesId"].ToString()); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Tasks"); if (ds.Tables["Tasks"].Rows.Count != 0) { tb.Text = ds.Tables["Tasks"].Rows[0][0].ToString(); i.Cells[4].Text = "y"; } else { tb.Text = null; } } } protected void btnExit_Click(object sender, System.EventArgs e) { if (Session["MgrOption"].ToString() == "Budget") { updateBudAmt(); } Exit(); } private void updateBudAmt() { foreach (DataGridItem i in DataGrid2.Items) { TextBox tb = (TextBox)(i.Cells[2].FindControl("txtBud")); { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdateBudProjectProcAmt"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Flag", SqlDbType.Int); if (i.Cells[4].Text == "y") { cmd.Parameters["@Flag"].Value = 1; } cmd.Parameters.Add("@PSEPId", SqlDbType.Int); cmd.Parameters["@PSEPId"].Value = Int32.Parse(i.Cells[0].Text); cmd.Parameters.Add("@BudgetsId", SqlDbType.Int); cmd.Parameters["@BudgetsId"].Value = Int32.Parse(Session["BudgetsId"].ToString()); cmd.Parameters.Add("@OrgLocId", SqlDbType.Int); cmd.Parameters["@OrgLocId"].Value = Int32.Parse(Session["OrgLocId"].ToString()); cmd.Parameters.Add("@BudAmt", SqlDbType.Decimal); if (tb.Text != "") { cmd.Parameters["@BudAmt"].Value = decimal.Parse(tb.Text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands); } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } private void Exit() { Response.Redirect (strURL + Session["COrgLocSEProcs"].ToString() + ".aspx?"); } protected void btnAdd_Click(object sender, System.EventArgs e) { Exit(); } protected void DataGrid2_ItemCommand(object source, DataGridCommandEventArgs e) { } protected void DataGrid1_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "Task") { Session["CProj"]="frmOrgLocSEProcs"; Session["ProcName"]=e.Item.Cells[1].Text; Session["PSEPID"]=e.Item.Cells[0].Text; Response.Redirect (strURL + "frmOLPProjects.aspx?"); } else if (e.CommandName == "Outputs") { Session["CPSEPO"] = "frmOrgLocSEProcs"; Session["ProcessName"] = e.Item.Cells[1].Text; Session["PSEPID"] = e.Item.Cells[0].Text; //Session["RType"] = 1; Response.Redirect(strURL + "frmPSEPO.aspx?"); } else if (e.CommandName == "Clients") { Session["CPSEPC"] = "frmOrgLocSEProcs"; Session["ProcessName"] = e.Item.Cells[1].Text; Session["PSEPID"] = e.Item.Cells[0].Text; Response.Redirect(strURL + "frmPSEPClient.aspx?"); } else if (e.CommandName == "Staff") { Session["PSEPID"]=e.Item.Cells[0].Text; Session["ProcName"]=e.Item.Cells[1].Text; if (Session["startForm"].ToString() == "frmMainBMgr") { Session["CBudSerWS"]="frmOrgLocSEProcs"; Session["GS"]="Staff"; Response.Redirect (strURL + "frmBudStaffWorkSheet.aspx?"); } else { Session["CPStaff"]="frmOrgLocSEProcs"; Response.Redirect (strURL + "frmProcStaff.aspx?"); } } else if (e.CommandName == "Services") { Session["PSEPID"]=e.Item.Cells[0].Text; Session["ProcName"]=e.Item.Cells[1].Text; if (Session["startForm"].ToString() == "frmMainBMgr") { Session["CBudSerWS"]="frmOrgLocSEProcs"; Session["GS"]="Staff"; Response.Redirect (strURL + "frmBudSerWorkSheet.aspx?"); } else { Session["CPRes"]="frmOrgLocSEProcs"; Session["RType"]=1; Response.Redirect (strURL + "frmProcRes.aspx?"); } } else if (e.CommandName == "Other") { Session["CPRes"]="frmOrgLocSEProcs"; Session["PSEPID"]=e.Item.Cells[0].Text; Session["RType"]=0; Session["ProcName"]=e.Item.Cells[1].Text; Response.Redirect (strURL + "frmProcRes.aspx?"); } else if (e.CommandName == "Timetable") { Session["CUpdTT"]="frmOrgLocSEProcs"; Session["PSEPId"]=e.Item.Cells[0].Text; Session["ProcName"]=e.Item.Cells[1].Text; Response.Redirect (strURL + "frmUpdTimetable.aspx?"); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Physics; using Microsoft.MixedReality.Toolkit.Utilities; using System.Collections; using Unity.Profiling; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// This class allows for HoloLens 1 style input, using a far gaze ray /// for focus with hand and gesture-based input and interaction across it. /// </summary> /// <remarks> /// GGV stands for gaze, gesture, and voice. /// This pointer's position is given by hand position (grip pose), /// and the input focus is given by head gaze. /// </remarks> [AddComponentMenu("Scripts/MRTK/SDK/GGVPointer")] public class GGVPointer : InputSystemGlobalHandlerListener, IMixedRealityPointer, IMixedRealityInputHandler, IMixedRealityInputHandler<MixedRealityPose>, IMixedRealitySourceStateHandler { [Header("Pointer")] [SerializeField] private MixedRealityInputAction selectAction = MixedRealityInputAction.None; [SerializeField] private MixedRealityInputAction poseAction = MixedRealityInputAction.None; private IMixedRealityGazeProvider gazeProvider; private Vector3 sourcePosition; private bool isSelectPressed; private Handedness lastControllerHandedness; #region IMixedRealityPointer private IMixedRealityController controller; /// <inheritdoc /> public IMixedRealityController Controller { get { return controller; } set { controller = value; if (controller != null && this != null) { gameObject.name = $"{Controller.ControllerHandedness}_GGVPointer"; pointerName = gameObject.name; InputSourceParent = controller.InputSource; } } } private uint pointerId; /// <inheritdoc /> public uint PointerId { get { if (pointerId == 0) { pointerId = CoreServices.InputSystem.FocusProvider.GenerateNewPointerId(); } return pointerId; } } private string pointerName = string.Empty; /// <inheritdoc /> public string PointerName { get { return pointerName; } set { pointerName = value; if (this != null) { gameObject.name = value; } } } /// <inheritdoc /> public IMixedRealityInputSource InputSourceParent { get; private set; } /// <inheritdoc /> public IMixedRealityCursor BaseCursor { get; set; } /// <inheritdoc /> public ICursorModifier CursorModifier { get; set; } /// <inheritdoc /> public bool IsInteractionEnabled => IsActive; /// <inheritdoc /> public bool IsActive { get; set; } /// <inheritdoc /> public bool IsFocusLocked { get; set; } /// <inheritdoc /> public bool IsTargetPositionLockedOnFocusLock { get; set; } public RayStep[] Rays { get; protected set; } = { new RayStep(Vector3.zero, Vector3.forward) }; public LayerMask[] PrioritizedLayerMasksOverride { get; set; } public IMixedRealityFocusHandler FocusTarget { get; set; } /// <inheritdoc /> public IPointerResult Result { get; set; } /// <inheritdoc /> public virtual SceneQueryType SceneQueryType { get; set; } = SceneQueryType.SimpleRaycast; /// <inheritdoc /> public float SphereCastRadius { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } private static bool Equals(IMixedRealityPointer left, IMixedRealityPointer right) { return left != null && left.Equals(right); } /// <inheritdoc /> bool IEqualityComparer.Equals(object left, object right) { return left.Equals(right); } /// <inheritdoc /> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((IMixedRealityPointer)obj); } private bool Equals(IMixedRealityPointer other) { return other != null && PointerId == other.PointerId && string.Equals(PointerName, other.PointerName); } /// <inheritdoc /> int IEqualityComparer.GetHashCode(object obj) { return obj.GetHashCode(); } /// <inheritdoc /> public override int GetHashCode() { unchecked { int hashCode = 0; hashCode = (hashCode * 397) ^ (int)PointerId; hashCode = (hashCode * 397) ^ (PointerName != null ? PointerName.GetHashCode() : 0); return hashCode; } } private static readonly ProfilerMarker OnPostSceneQueryPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnPostSceneQuery"); /// <inheritdoc /> public void OnPostSceneQuery() { using (OnPostSceneQueryPerfMarker.Auto()) { if (isSelectPressed && IsInteractionEnabled) { CoreServices.InputSystem.RaisePointerDragged(this, MixedRealityInputAction.None, Controller.ControllerHandedness); } } } private static readonly ProfilerMarker OnPreSceneQueryPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnPreSceneQuery"); /// <inheritdoc /> public void OnPreSceneQuery() { using (OnPreSceneQueryPerfMarker.Auto()) { Vector3 newGazeOrigin = gazeProvider.GazePointer.Rays[0].Origin; Vector3 endPoint = newGazeOrigin + (gazeProvider.GazePointer.Rays[0].Direction * CoreServices.InputSystem.FocusProvider.GlobalPointingExtent); Rays[0].UpdateRayStep(ref newGazeOrigin, ref endPoint); } } /// <inheritdoc /> public void OnPreCurrentPointerTargetChange() { } /// <inheritdoc /> public void Reset() { Controller = null; BaseCursor = null; IsActive = false; IsFocusLocked = false; } /// <inheritdoc /> public virtual Vector3 Position => sourcePosition; /// <inheritdoc /> public virtual Quaternion Rotation { get { // Previously we were simply returning the InternalGazeProvider rotation here. // This caused issues when the head rotated, but the hand stayed where it was. // Now we're returning a rotation based on the vector from the camera position // to the hand. This rotation is not affected by rotating your head. Vector3 look = Position - CameraCache.Main.transform.position; return Quaternion.LookRotation(look); } } #endregion #region IMixedRealityInputHandler Implementation private static readonly ProfilerMarker OnInputUpPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnInputUp"); /// <inheritdoc /> public void OnInputUp(InputEventData eventData) { using (OnInputUpPerfMarker.Auto()) { if (eventData.SourceId == InputSourceParent.SourceId) { if (eventData.MixedRealityInputAction == selectAction) { isSelectPressed = false; if (IsInteractionEnabled) { BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor; if (c != null) { c.SourceDownIds.Remove(eventData.SourceId); } CoreServices.InputSystem.RaisePointerClicked(this, selectAction, 0, Controller.ControllerHandedness); CoreServices.InputSystem.RaisePointerUp(this, selectAction, Controller.ControllerHandedness); // For GGV, the gaze pointer does not set this value itself. // See comment in OnInputDown for more details. gazeProvider.GazePointer.IsFocusLocked = false; } } } } } private static readonly ProfilerMarker OnInputDownPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnInputDown"); /// <inheritdoc /> public void OnInputDown(InputEventData eventData) { using (OnInputDownPerfMarker.Auto()) { if (eventData.SourceId == InputSourceParent.SourceId) { if (eventData.MixedRealityInputAction == selectAction) { isSelectPressed = true; lastControllerHandedness = Controller.ControllerHandedness; if (IsInteractionEnabled) { BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor; if (c != null) { c.SourceDownIds.Add(eventData.SourceId); } CoreServices.InputSystem.RaisePointerDown(this, selectAction, Controller.ControllerHandedness); // For GGV, the gaze pointer does not set this value itself as it does not receive input // events from the hands. Because this value is important for certain gaze behavior, // such as positioning the gaze cursor, it is necessary to set it here. gazeProvider.GazePointer.IsFocusLocked = (gazeProvider.GazePointer.Result?.Details.Object != null); } } } } } #endregion IMixedRealityInputHandler Implementation protected override void OnEnable() { base.OnEnable(); gazeProvider = CoreServices.InputSystem.GazeProvider; BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor; if (c != null) { c.VisibleSourcesCount++; } } protected override void OnDisable() { base.OnDisable(); if (gazeProvider != null) { BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor; if (c != null) { c.VisibleSourcesCount--; } } } #region InputSystemGlobalHandlerListener Implementation /// <inheritdoc /> protected override void RegisterHandlers() { CoreServices.InputSystem?.RegisterHandler<IMixedRealityInputHandler>(this); CoreServices.InputSystem?.RegisterHandler<IMixedRealityInputHandler<MixedRealityPose>>(this); CoreServices.InputSystem?.RegisterHandler<IMixedRealitySourceStateHandler>(this); } /// <inheritdoc /> protected override void UnregisterHandlers() { CoreServices.InputSystem?.UnregisterHandler<IMixedRealityInputHandler>(this); CoreServices.InputSystem?.UnregisterHandler<IMixedRealityInputHandler<MixedRealityPose>>(this); CoreServices.InputSystem?.UnregisterHandler<IMixedRealitySourceStateHandler>(this); } #endregion InputSystemGlobalHandlerListener Implementation #region IMixedRealitySourceStateHandler /// <inheritdoc /> public void OnSourceDetected(SourceStateEventData eventData) { } private static readonly ProfilerMarker OnSourceLostPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnSourceLost"); /// <inheritdoc /> public void OnSourceLost(SourceStateEventData eventData) { using (OnSourceLostPerfMarker.Auto()) { if (eventData.SourceId == InputSourceParent.SourceId) { BaseCursor c = gazeProvider.GazePointer.BaseCursor as BaseCursor; if (c != null) { c.SourceDownIds.Remove(eventData.SourceId); } if (isSelectPressed) { // Raise OnInputUp if pointer is lost while select is pressed CoreServices.InputSystem.RaisePointerUp(this, selectAction, lastControllerHandedness); // For GGV, the gaze pointer does not set this value itself. // See comment in OnInputDown for more details. gazeProvider.GazePointer.IsFocusLocked = false; } // Destroy the pointer since nobody else is destroying us GameObjectExtensions.DestroyGameObject(gameObject); } } } #endregion IMixedRealitySourceStateHandler #region IMixedRealityInputHandler<MixedRealityPose> private static readonly ProfilerMarker OnInputChangedPerfMarker = new ProfilerMarker("[MRTK] GGVPointer.OnInputChanged"); /// <inheritdoc /> public void OnInputChanged(InputEventData<MixedRealityPose> eventData) { using (OnInputChangedPerfMarker.Auto()) { if (eventData.SourceId == Controller?.InputSource.SourceId && eventData.Handedness == Controller?.ControllerHandedness && eventData.MixedRealityInputAction == poseAction) { sourcePosition = eventData.InputData.Position; } } } #endregion IMixedRealityInputHandler<MixedRealityPose> } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Threading; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile { /// <summary> /// Used by the 2 Create factory method groups. A null fileHandle specifies that the /// memory mapped file should not be associated with an exsiting file on disk (ie start /// out empty). /// </summary> private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); [SecurityCritical] private static SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked((int)(capacity >> 32)); SafeMemoryMappedFileHandle handle = fileHandle != null ? Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) : Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.mincore.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return handle; } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen) { return OpenCore(mapName, inheritability, GetFileMapAccess(access), createOrOpen); } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen) { return OpenCore(mapName, inheritability, GetFileMapAccess(rights), createOrOpen); } /// <summary> /// Used by the CreateOrOpen factory method groups. /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { /// Try to open the file if it exists -- this requires a bit more work. Loop until we can /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail /// if the file exists and we have non-null security attributes, in which case we need to /// use OpenFileMapping. But, there exists a race condition because the memory mapped file /// may have closed inbetween the two calls -- hence the loop. /// /// The retry/timeout logic increases the wait time each pass through the loop and times /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened, /// throw an InvalidOperationException. Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked((int)(capacity >> 32)); int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we we get valid handle while (waitRetries > 0) { // try to create handle = Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); if (!handle.IsInvalid) { break; } else { int createErrorCode = Marshal.GetLastWin32Error(); if (createErrorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED) { throw Win32Marshal.GetExceptionForWin32Error(createErrorCode); } } // try to open handle = Interop.mincore.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { int openErrorCode = Marshal.GetLastWin32Error(); if (openErrorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { throw Win32Marshal.GetExceptionForWin32Error(openErrorCode); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { ThreadSleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping); } return handle; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// This converts a MemoryMappedFileRights to its corresponding native FILE_MAP_XXX value to be used when /// creating new views. /// </summary> private static int GetFileMapAccess(MemoryMappedFileRights rights) { return (int)rights; } /// <summary> /// This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when /// creating new views. /// </summary> internal static int GetFileMapAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: return Interop.mincore.FileMapOptions.FILE_MAP_READ; case MemoryMappedFileAccess.Write: return Interop.mincore.FileMapOptions.FILE_MAP_WRITE; case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE; case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.FileMapOptions.FILE_MAP_COPY; case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ; default: Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute); return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE; } } /// <summary> /// This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the /// factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not /// valid here since there is no corresponding PAGE_XXX value. /// </summary> internal static int GetPageAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: return Interop.mincore.PageOptions.PAGE_READONLY; case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.PageOptions.PAGE_READWRITE; case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.PageOptions.PAGE_WRITECOPY; case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.PageOptions.PAGE_EXECUTE_READ; default: Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute); return Interop.mincore.PageOptions.PAGE_EXECUTE_READWRITE; } } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, int desiredAccessRights, bool createOrOpen) { SafeMemoryMappedFileHandle handle = Interop.mincore.OpenFileMapping( desiredAccessRights, (inheritability & HandleInheritability.Inheritable) != 0, mapName); int lastError = Marshal.GetLastWin32Error(); if (handle.IsInvalid) { if (createOrOpen && (lastError == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } else { throw Win32Marshal.GetExceptionForWin32Error(lastError); } } return handle; } /// <summary> /// Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity /// type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned. /// </summary> [SecurityCritical] private unsafe static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability) { Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES(); secAttrs.nLength = (uint)sizeof(Interop.mincore.SECURITY_ATTRIBUTES); secAttrs.bInheritHandle = Interop.BOOL.TRUE; } return secAttrs; } /// <summary> /// Replacement for Thread.Sleep(milliseconds), which isn't available. /// </summary> internal static void ThreadSleep(int milliseconds) { new ManualResetEventSlim(initialState: false).Wait(milliseconds); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Globalization; using System.IO; using System.Diagnostics; using System.Net; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; namespace OpenLiveWriter.Extensibility.BlogClient { public class BlogClientPostUrlNotFoundException : BlogClientException { public BlogClientPostUrlNotFoundException(string targetUrl, string description) : base(StringId.BCEPostUrlNotFoundTitle, StringId.BCEPostUrlNotFoundMessage, targetUrl, description) { } } public class BlogClientHttpErrorException : BlogClientException { private WebException _exception; public BlogClientHttpErrorException(string targetUrl, string description, WebException exception) : base(StringId.BCEHttpErrorTitle, StringId.BCEHttpErrorMessage, targetUrl, description) { _exception = exception; } public WebException Exception { get { return _exception; } } } public class BlogClientConnectionErrorException : BlogClientException { public BlogClientConnectionErrorException(string targetUrl, string description) : base(StringId.BCEConnectionErrorTitle, StringId.BCEConnectionErrorMessage, targetUrl, description) { TargetUrl = targetUrl; Description = description; } public readonly string TargetUrl; public readonly string Description; } public class BlogClientInvalidServerResponseException : BlogClientException { public BlogClientInvalidServerResponseException(string method, string errorMessage, string response) : base(StringId.BCEInvalidServerResponseTitle, StringId.BCEInvalidServerResponseMessage, method, errorMessage) { Method = method; ErrorMessage = errorMessage; Response = response; } public readonly string Method; public readonly string ErrorMessage = String.Empty; public readonly string Response; } public class BlogClientFileTransferException : BlogClientException { public BlogClientFileTransferException(string context, string errorCode, string errorMessage) : base(StringId.BCEFileTransferTitle, StringId.BCEFileTransferMessage, context, errorCode, errorMessage) { } public BlogClientFileTransferException(FileInfo file, string errorCode, string errorMessage) : this(string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.BCEFileTransferTransferringFile), file.Name), errorCode, errorMessage) { } } public class BlogClientFileUploadNotSupportedException : BlogClientException { public BlogClientFileUploadNotSupportedException() : base(StringId.BCEFileUploadNotSupportedTitle, StringId.BCEFileUploadNotSupportedMessage) { } public BlogClientFileUploadNotSupportedException(string errorCode, string errorString) : this() { ErrorCode = errorCode; ErrorString = errorString; } public readonly string ErrorCode = String.Empty; public readonly string ErrorString = String.Empty; } public class BlogClientAccessDeniedException : BlogClientAuthenticationException { public BlogClientAccessDeniedException(string providerErrorCode, string providerErrorString) : base(providerErrorCode, providerErrorString) { } } public class BlogClientAuthenticationException : BlogClientProviderException { private WebException _webException; public BlogClientAuthenticationException(string providerErrorCode, string providerErrorString) : this(providerErrorCode, providerErrorString, null) { } public BlogClientAuthenticationException(string providerErrorCode, string providerErrorString, WebException webException) : base(StringId.BCEAuthenticationTitle, StringId.BCEAuthenticationMessage, providerErrorCode, providerErrorString) { _webException = webException; } public WebException WebException { get { return _webException; } } } public class BlogClientProviderException : BlogClientException { public BlogClientProviderException(string providerErrorCode, string providerErrorString) : this(StringId.BCEProviderTitle, StringId.BCEProviderMessage, providerErrorCode, providerErrorString) { } public BlogClientProviderException(StringId titleFormat, StringId textFormat, string providerErrorCode, string providerErrorString) : base(titleFormat, textFormat, providerErrorCode, providerErrorString) { ErrorCode = providerErrorCode; ErrorString = providerErrorString; } public readonly string ErrorCode; public readonly string ErrorString; } public class BlogClientIOException : BlogClientException { public BlogClientIOException(string context, IOException ioException) : base(StringId.BCENetworkIOTitle, StringId.BCENetworkIOMessage, context, ioException.GetType().Name, ioException.Message) { } public BlogClientIOException(FileInfo file, IOException ioException) : base(StringId.BCEFileIOTitle, StringId.BCEFileIOMessage, file.Name, ioException.GetType().Name, ioException.Message) { } } public class BlogClientOperationCancelledException : BlogClientException { public BlogClientOperationCancelledException() : base(StringId.BCEOperationCancelledTitle, StringId.BCEOperationCancelledMessage) { } } public class BlogClientMethodUnsupportedException : BlogClientException { public BlogClientMethodUnsupportedException(string methodName) : base(StringId.BCEMethodUnsupportedTitle, StringId.BCEMethodUnsupportedMessage, methodName) { } } public class BlogClientPostAsDraftUnsupportedException : BlogClientException { public BlogClientPostAsDraftUnsupportedException() : base(StringId.BCEPostAsDraftUnsupportedTitle, StringId.BCEPostAsDraftUnsupportedMessage) { } } public class BlogClientException : DisplayableException { public BlogClientException(StringId titleFormat, StringId textFormat, params object[] textFormatArgs) : base(titleFormat, textFormat, textFormatArgs) { } public BlogClientException(string title, string text, params object[] textFormatArgs) : base(title, text, textFormatArgs) { } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System.ComponentModel; using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.Controls { /// <summary> /// Subclass of the System.Windows.Forms.Label control that paints itself in the disabled state /// using opacity as opposed to simply calling ControlPaint.DrawStringDisabled using the system /// control color. /// </summary> public class LabelControl : Label { /// <summary> /// Required designer variable. /// </summary> private Container components = null; /// <summary> /// String format we use to format text. /// </summary> private TextFormatFlags stringFormat; /// <summary> /// A value which indicates whether the label control is multi-line. /// </summary> private bool multiLine; /// <summary> /// The actual measured size of the text after drawing. /// </summary> private SizeF measuredTextSize = SizeF.Empty; /// <summary> /// Initializes a new instance of the LabelControl class. /// </summary> public LabelControl() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Set the initial string format. SetStringFormat(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion /// <summary> /// Disable the FlatStyle property and force it to be standard. /// </summary> [ Category("Appearence") ] public bool MultiLine { get { return multiLine; } set { multiLine = value; SetStringFormat(); Invalidate(); } } /// <summary> /// Disable the FlatStyle property and force it to be standard. /// </summary> [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden) ] public new FlatStyle FlatStyle { get { return FlatStyle.Standard; } } /// <summary> /// Gets or sets the alignment of text in the label. /// </summary> public override ContentAlignment TextAlign { get { return base.TextAlign; } set { if (base.TextAlign != value) { base.TextAlign = value; SetStringFormat(); Invalidate(); } } } /// <summary> /// Raises the Paint event. /// </summary> /// <param name="e">A PaintEventArgs that contains the event data.</param> protected override void OnPaint(PaintEventArgs e) { BidiGraphics g = new BidiGraphics(e.Graphics, ClientRectangle); // Paint. g.DrawText(Text, Font, ClientRectangle, Color.FromArgb(GraphicsHelper.Opacity(Enabled ? 100.0 : 50.0), ForeColor), stringFormat); Size size = new Size(ClientSize.Width, ClientSize.Height); measuredTextSize = g.MeasureText(Text, Font, size, stringFormat); } /// <summary> /// Set the string format. /// </summary> private void SetStringFormat() { // Instantiate the string format. stringFormat = new TextFormatFlags(); // No wrapping and ellipsis on truncation. if (!multiLine) stringFormat |= TextFormatFlags.SingleLine; stringFormat |= TextFormatFlags.ExpandTabs; stringFormat |= TextFormatFlags.EndEllipsis; if (!this.UseMnemonic) stringFormat |= TextFormatFlags.NoPrefix; else if (!ShowKeyboardCues) stringFormat |= TextFormatFlags.HidePrefix; // Map ContentAlignment to the StringFormat we use to draw the string. switch (TextAlign) { case ContentAlignment.BottomCenter: stringFormat |= TextFormatFlags.Right; // Vertical stringFormat |= TextFormatFlags.HorizontalCenter; // Horizontal break; case ContentAlignment.BottomLeft: stringFormat |= TextFormatFlags.Right; // Vertical break; case ContentAlignment.BottomRight: stringFormat |= TextFormatFlags.Right; // Vertical stringFormat |= TextFormatFlags.Bottom; // Horizontal break; case ContentAlignment.MiddleCenter: stringFormat |= TextFormatFlags.VerticalCenter; // Vertical stringFormat |= TextFormatFlags.HorizontalCenter; // Horizontal break; case ContentAlignment.MiddleLeft: stringFormat |= TextFormatFlags.VerticalCenter; // Vertical break; case ContentAlignment.MiddleRight: stringFormat |= TextFormatFlags.VerticalCenter; // Vertical stringFormat |= TextFormatFlags.Bottom; // Horizontal break; case ContentAlignment.TopCenter: stringFormat |= TextFormatFlags.HorizontalCenter; // Horizontal break; case ContentAlignment.TopLeft: break; case ContentAlignment.TopRight: stringFormat |= TextFormatFlags.Bottom; // Horizontal break; } } protected bool IsInText(Point point) { return IsWithin(point.X, Width, measuredTextSize.Width, InvertIfRightToLeft(stringFormat)) && IsWithin(point.Y, Height, measuredTextSize.Height, stringFormat); } /// <summary> /// Returns the rectangle region occupied by the painted label text. /// </summary> /// <returns></returns> protected Rectangle GetMeasuredTextRectangle() { Rectangle textRect = new Rectangle(Point.Empty, measuredTextSize.ToSize()); //shift the X position based on the alignment if (TextFormatFlags.HorizontalCenter == (stringFormat & TextFormatFlags.HorizontalCenter)) { textRect.X = Utility.CenterInRectangle(textRect.Size, ClientRectangle).X; } else if (TextFormatFlags.Right == (stringFormat & TextFormatFlags.Right)) { textRect.Offset(ClientRectangle.Width - textRect.Width, 0); } //shift the Y position based on the lineAlignment if (TextFormatFlags.VerticalCenter == (stringFormat & TextFormatFlags.VerticalCenter)) { textRect.Y = Utility.CenterInRectangle(textRect.Size, ClientRectangle).Y; } else if (TextFormatFlags.Bottom == (stringFormat & TextFormatFlags.Bottom)) { textRect.Offset(0, ClientRectangle.Height - textRect.Height); } return textRect; } /// <summary> /// Given a point, a region, a text size, and alignment, determines if the point /// is located within the text. /// </summary> private bool IsWithin(double testVal, double regionSize, float textVal, TextFormatFlags alignment) { double min = 0; double max = regionSize; if ((TextFormatFlags.VerticalCenter == (stringFormat & TextFormatFlags.VerticalCenter)) || (TextFormatFlags.HorizontalCenter == (stringFormat & TextFormatFlags.HorizontalCenter))) { min = (max - textVal) / 2.0; max -= min; } else if ((TextFormatFlags.Bottom == (stringFormat & TextFormatFlags.Bottom)) || (TextFormatFlags.Right == (stringFormat & TextFormatFlags.Right))) { min = max - textVal; } else { max = textVal; } return !(testVal < min || testVal > max); } /// <summary> /// Used for calculations in IsInText. /// /// </summary> private TextFormatFlags InvertIfRightToLeft(TextFormatFlags sa) { RightToLeft rtl = RightToLeft; Control c = this; while (rtl == RightToLeft.Inherit) { c = c.Parent; if (c == null) rtl = RightToLeft.No; else rtl = c.RightToLeft; } if (rtl != RightToLeft.Yes) return sa; if ((TextFormatFlags.VerticalCenter == (sa & TextFormatFlags.VerticalCenter)) || (TextFormatFlags.HorizontalCenter == (sa & TextFormatFlags.HorizontalCenter))) { return sa; } else if ((TextFormatFlags.Bottom == (sa & TextFormatFlags.Bottom)) || (TextFormatFlags.Right == (sa & TextFormatFlags.Right))) { return new TextFormatFlags(); } else { return (TextFormatFlags.Right | TextFormatFlags.Bottom); } } } }
using System; using System.Collections; using System.Collections.Generic; using Int8 = System.SByte; using UInt8 = System.Byte; using ViEntityID = System.UInt64; using ViString = System.String; using ViArrayIdx = System.Int32; public struct LogicAuraValueArray { public Int32 Element0; public Int32 Element1; public Int32 Element2; public Int32 Element3; public Int32 this[int index] { get { switch(index) { case 0: return Element0; case 1: return Element1; case 2: return Element2; case 3: return Element3; } ViDebuger.Error(""); return Element0; } } } public static class LogicAuraValueArraySerialize { public static void Append(this ViOStream OS, LogicAuraValueArray value) { OS.Append(value.Element0); OS.Append(value.Element1); OS.Append(value.Element2); OS.Append(value.Element3); } public static void Append(this ViOStream OS, List<LogicAuraValueArray> list) { ViArrayIdx size = (ViArrayIdx)list.Count; OS.Append(size); foreach (LogicAuraValueArray value in list) { OS.Append(value); } } public static void Read(this ViIStream IS, out LogicAuraValueArray value) { IS.Read(out value.Element0); IS.Read(out value.Element1); IS.Read(out value.Element2); IS.Read(out value.Element3); } public static void Read(this ViIStream IS, out List<LogicAuraValueArray> list) { ViArrayIdx size; IS.Read(out size); list = new List<LogicAuraValueArray>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { LogicAuraValueArray value; IS.Read(out value); list.Add(value); } } public static bool Read(this ViStringIStream IS, out LogicAuraValueArray value) { value = default(LogicAuraValueArray); if(IS.Read(out value.Element0) == false){return false;} if(IS.Read(out value.Element1) == false){return false;} if(IS.Read(out value.Element2) == false){return false;} if(IS.Read(out value.Element3) == false){return false;} return true; } public static bool Read(this ViStringIStream IS, out List<LogicAuraValueArray> list) { list = null; ViArrayIdx size; if(IS.Read(out size) == false){return false;} list = new List<LogicAuraValueArray>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { LogicAuraValueArray value; if(IS.Read(out value) == false){return false;} list.Add(value); } return true; } } public class ReceiveDataLogicAuraValueArray: ViReceiveDataNode { public static readonly new int SIZE = 4; public static readonly int Count = 4; public ViReceiveDataInt32 Element0 = new ViReceiveDataInt32(); public ViReceiveDataInt32 Element1 = new ViReceiveDataInt32(); public ViReceiveDataInt32 Element2 = new ViReceiveDataInt32(); public ViReceiveDataInt32 Element3 = new ViReceiveDataInt32(); public override void Start(UInt8 channel, ViIStream IS, ViEntity entity) { Element0.Start(channel, IS, entity); Element0.Parent = this; Element1.Start(channel, IS, entity); Element1.Parent = this; Element2.Start(channel, IS, entity); Element2.Parent = this; Element3.Start(channel, IS, entity); Element3.Parent = this; } public override void Start(UInt16 channelMask, ViIStream IS, ViEntity entity) { Element0.Start(channelMask, IS, entity); Element0.Parent = this; Element1.Start(channelMask, IS, entity); Element1.Parent = this; Element2.Start(channelMask, IS, entity); Element2.Parent = this; Element3.Start(channelMask, IS, entity); Element3.Parent = this; } public override void End(ViEntity entity) { Element0.End(entity); Element1.End(entity); Element2.End(entity); Element3.End(entity); base.End(entity); } public override void Clear() { Element0.Clear(); Element1.Clear(); Element2.Clear(); Element3.Clear(); base.Clear(); } public new void RegisterTo(UInt16 channelMask, ViReceiveProperty property) { Element0.RegisterTo(channelMask, property); Element1.RegisterTo(channelMask, property); Element2.RegisterTo(channelMask, property); Element3.RegisterTo(channelMask, property); } public override void StartByArray() { RegisterTo(ViConstValueDefine.MAX_UINT16, this); } public static implicit operator LogicAuraValueArray(ReceiveDataLogicAuraValueArray data) { LogicAuraValueArray value = new LogicAuraValueArray(); value.Element0 = data.Element0; value.Element1 = data.Element1; value.Element2 = data.Element2; value.Element3 = data.Element3; return value; } public ViReceiveDataInt32 this[int index] { get { switch(index) { case 0: return Element0; case 1: return Element1; case 2: return Element2; case 3: return Element3; } ViDebuger.Error(""); return Element0; } } } public struct LogicAuraCastorValueArray { public Int32 Element0; public Int32 Element1; public Int32 Element2; public Int32 Element3; public Int32 this[int index] { get { switch(index) { case 0: return Element0; case 1: return Element1; case 2: return Element2; case 3: return Element3; } ViDebuger.Error(""); return Element0; } } } public static class LogicAuraCastorValueArraySerialize { public static void Append(this ViOStream OS, LogicAuraCastorValueArray value) { OS.Append(value.Element0); OS.Append(value.Element1); OS.Append(value.Element2); OS.Append(value.Element3); } public static void Append(this ViOStream OS, List<LogicAuraCastorValueArray> list) { ViArrayIdx size = (ViArrayIdx)list.Count; OS.Append(size); foreach (LogicAuraCastorValueArray value in list) { OS.Append(value); } } public static void Read(this ViIStream IS, out LogicAuraCastorValueArray value) { IS.Read(out value.Element0); IS.Read(out value.Element1); IS.Read(out value.Element2); IS.Read(out value.Element3); } public static void Read(this ViIStream IS, out List<LogicAuraCastorValueArray> list) { ViArrayIdx size; IS.Read(out size); list = new List<LogicAuraCastorValueArray>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { LogicAuraCastorValueArray value; IS.Read(out value); list.Add(value); } } public static bool Read(this ViStringIStream IS, out LogicAuraCastorValueArray value) { value = default(LogicAuraCastorValueArray); if(IS.Read(out value.Element0) == false){return false;} if(IS.Read(out value.Element1) == false){return false;} if(IS.Read(out value.Element2) == false){return false;} if(IS.Read(out value.Element3) == false){return false;} return true; } public static bool Read(this ViStringIStream IS, out List<LogicAuraCastorValueArray> list) { list = null; ViArrayIdx size; if(IS.Read(out size) == false){return false;} list = new List<LogicAuraCastorValueArray>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { LogicAuraCastorValueArray value; if(IS.Read(out value) == false){return false;} list.Add(value); } return true; } } public class ReceiveDataLogicAuraCastorValueArray: ViReceiveDataNode { public static readonly new int SIZE = 4; public static readonly int Count = 4; public ViReceiveDataInt32 Element0 = new ViReceiveDataInt32(); public ViReceiveDataInt32 Element1 = new ViReceiveDataInt32(); public ViReceiveDataInt32 Element2 = new ViReceiveDataInt32(); public ViReceiveDataInt32 Element3 = new ViReceiveDataInt32(); public override void Start(UInt8 channel, ViIStream IS, ViEntity entity) { Element0.Start(channel, IS, entity); Element0.Parent = this; Element1.Start(channel, IS, entity); Element1.Parent = this; Element2.Start(channel, IS, entity); Element2.Parent = this; Element3.Start(channel, IS, entity); Element3.Parent = this; } public override void Start(UInt16 channelMask, ViIStream IS, ViEntity entity) { Element0.Start(channelMask, IS, entity); Element0.Parent = this; Element1.Start(channelMask, IS, entity); Element1.Parent = this; Element2.Start(channelMask, IS, entity); Element2.Parent = this; Element3.Start(channelMask, IS, entity); Element3.Parent = this; } public override void End(ViEntity entity) { Element0.End(entity); Element1.End(entity); Element2.End(entity); Element3.End(entity); base.End(entity); } public override void Clear() { Element0.Clear(); Element1.Clear(); Element2.Clear(); Element3.Clear(); base.Clear(); } public new void RegisterTo(UInt16 channelMask, ViReceiveProperty property) { Element0.RegisterTo(channelMask, property); Element1.RegisterTo(channelMask, property); Element2.RegisterTo(channelMask, property); Element3.RegisterTo(channelMask, property); } public override void StartByArray() { RegisterTo(ViConstValueDefine.MAX_UINT16, this); } public static implicit operator LogicAuraCastorValueArray(ReceiveDataLogicAuraCastorValueArray data) { LogicAuraCastorValueArray value = new LogicAuraCastorValueArray(); value.Element0 = data.Element0; value.Element1 = data.Element1; value.Element2 = data.Element2; value.Element3 = data.Element3; return value; } public ViReceiveDataInt32 this[int index] { get { switch(index) { case 0: return Element0; case 1: return Element1; case 2: return Element2; case 3: return Element3; } ViDebuger.Error(""); return Element0; } } } public struct VisualAuraProperty { public UInt32 SpellID; public UInt8 EffectIdx; public Int64 EndTime; } public static class VisualAuraPropertySerialize { public static void Append(this ViOStream OS, VisualAuraProperty value) { OS.Append(value.SpellID); OS.Append(value.EffectIdx); OS.Append(value.EndTime); } public static void Append(this ViOStream OS, List<VisualAuraProperty> list) { ViArrayIdx size = (ViArrayIdx)list.Count; OS.Append(size); foreach (VisualAuraProperty value in list) { OS.Append(value); } } public static void Read(this ViIStream IS, out VisualAuraProperty value) { IS.Read(out value.SpellID); IS.Read(out value.EffectIdx); IS.Read(out value.EndTime); } public static void Read(this ViIStream IS, out List<VisualAuraProperty> list) { ViArrayIdx size; IS.Read(out size); list = new List<VisualAuraProperty>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { VisualAuraProperty value; IS.Read(out value); list.Add(value); } } public static bool Read(this ViStringIStream IS, out VisualAuraProperty value) { value = default(VisualAuraProperty); if(IS.Read(out value.SpellID) == false){return false;} if(IS.Read(out value.EffectIdx) == false){return false;} if(IS.Read(out value.EndTime) == false){return false;} return true; } public static bool Read(this ViStringIStream IS, out List<VisualAuraProperty> list) { list = null; ViArrayIdx size; if(IS.Read(out size) == false){return false;} list = new List<VisualAuraProperty>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { VisualAuraProperty value; if(IS.Read(out value) == false){return false;} list.Add(value); } return true; } } public class ReceiveDataVisualAuraProperty: ViReceiveDataNode { public static readonly new int SIZE = 3; public ViReceiveDataUInt32 SpellID = new ViReceiveDataUInt32(); public ViReceiveDataUInt8 EffectIdx = new ViReceiveDataUInt8(); public ViReceiveDataInt64 EndTime = new ViReceiveDataInt64(); public override void Start(UInt8 channel, ViIStream IS, ViEntity entity) { SpellID.Start(channel, IS, entity); SpellID.Parent = this; EffectIdx.Start(channel, IS, entity); EffectIdx.Parent = this; EndTime.Start(channel, IS, entity); EndTime.Parent = this; } public override void Start(UInt16 channelMask, ViIStream IS, ViEntity entity) { SpellID.Start(channelMask, IS, entity); SpellID.Parent = this; EffectIdx.Start(channelMask, IS, entity); EffectIdx.Parent = this; EndTime.Start(channelMask, IS, entity); EndTime.Parent = this; } public override void End(ViEntity entity) { SpellID.End(entity); EffectIdx.End(entity); EndTime.End(entity); base.End(entity); } public override void Clear() { SpellID.Clear(); EffectIdx.Clear(); EndTime.Clear(); base.Clear(); } public new void RegisterTo(UInt16 channelMask, ViReceiveProperty property) { SpellID.RegisterTo(channelMask, property); EffectIdx.RegisterTo(channelMask, property); EndTime.RegisterTo(channelMask, property); } public override void StartByArray() { RegisterTo(ViConstValueDefine.MAX_UINT16, this); } public static implicit operator VisualAuraProperty(ReceiveDataVisualAuraProperty data) { VisualAuraProperty value = new VisualAuraProperty(); value.SpellID = data.SpellID; value.EffectIdx = data.EffectIdx; value.EndTime = data.EndTime; return value; } } public struct LogicAuraProperty { public UInt32 SpellID; public UInt8 EffectIdx; public Int64 EndTime; public LogicAuraCastorValueArray CastorValue; public LogicAuraValueArray Value; } public static class LogicAuraPropertySerialize { public static void Append(this ViOStream OS, LogicAuraProperty value) { OS.Append(value.SpellID); OS.Append(value.EffectIdx); OS.Append(value.EndTime); OS.Append(value.CastorValue); OS.Append(value.Value); } public static void Append(this ViOStream OS, List<LogicAuraProperty> list) { ViArrayIdx size = (ViArrayIdx)list.Count; OS.Append(size); foreach (LogicAuraProperty value in list) { OS.Append(value); } } public static void Read(this ViIStream IS, out LogicAuraProperty value) { IS.Read(out value.SpellID); IS.Read(out value.EffectIdx); IS.Read(out value.EndTime); IS.Read(out value.CastorValue); IS.Read(out value.Value); } public static void Read(this ViIStream IS, out List<LogicAuraProperty> list) { ViArrayIdx size; IS.Read(out size); list = new List<LogicAuraProperty>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { LogicAuraProperty value; IS.Read(out value); list.Add(value); } } public static bool Read(this ViStringIStream IS, out LogicAuraProperty value) { value = default(LogicAuraProperty); if(IS.Read(out value.SpellID) == false){return false;} if(IS.Read(out value.EffectIdx) == false){return false;} if(IS.Read(out value.EndTime) == false){return false;} if(IS.Read(out value.CastorValue) == false){return false;} if(IS.Read(out value.Value) == false){return false;} return true; } public static bool Read(this ViStringIStream IS, out List<LogicAuraProperty> list) { list = null; ViArrayIdx size; if(IS.Read(out size) == false){return false;} list = new List<LogicAuraProperty>((int)size); for (ViArrayIdx idx = 0; idx < size; ++idx ) { LogicAuraProperty value; if(IS.Read(out value) == false){return false;} list.Add(value); } return true; } } public class ReceiveDataLogicAuraProperty: ViReceiveDataNode { public static readonly new int SIZE = 11; public ViReceiveDataUInt32 SpellID = new ViReceiveDataUInt32(); public ViReceiveDataUInt8 EffectIdx = new ViReceiveDataUInt8(); public ViReceiveDataInt64 EndTime = new ViReceiveDataInt64(); public ReceiveDataLogicAuraCastorValueArray CastorValue = new ReceiveDataLogicAuraCastorValueArray(); public ReceiveDataLogicAuraValueArray Value = new ReceiveDataLogicAuraValueArray(); public override void Start(UInt8 channel, ViIStream IS, ViEntity entity) { SpellID.Start(channel, IS, entity); SpellID.Parent = this; EffectIdx.Start(channel, IS, entity); EffectIdx.Parent = this; EndTime.Start(channel, IS, entity); EndTime.Parent = this; CastorValue.Start(channel, IS, entity); CastorValue.Parent = this; Value.Start(channel, IS, entity); Value.Parent = this; } public override void Start(UInt16 channelMask, ViIStream IS, ViEntity entity) { SpellID.Start(channelMask, IS, entity); SpellID.Parent = this; EffectIdx.Start(channelMask, IS, entity); EffectIdx.Parent = this; EndTime.Start(channelMask, IS, entity); EndTime.Parent = this; CastorValue.Start(channelMask, IS, entity); CastorValue.Parent = this; Value.Start(channelMask, IS, entity); Value.Parent = this; } public override void End(ViEntity entity) { SpellID.End(entity); EffectIdx.End(entity); EndTime.End(entity); CastorValue.End(entity); Value.End(entity); base.End(entity); } public override void Clear() { SpellID.Clear(); EffectIdx.Clear(); EndTime.Clear(); CastorValue.Clear(); Value.Clear(); base.Clear(); } public new void RegisterTo(UInt16 channelMask, ViReceiveProperty property) { SpellID.RegisterTo(channelMask, property); EffectIdx.RegisterTo(channelMask, property); EndTime.RegisterTo(channelMask, property); CastorValue.RegisterTo(channelMask, property); Value.RegisterTo(channelMask, property); } public override void StartByArray() { RegisterTo(ViConstValueDefine.MAX_UINT16, this); } public static implicit operator LogicAuraProperty(ReceiveDataLogicAuraProperty data) { LogicAuraProperty value = new LogicAuraProperty(); value.SpellID = data.SpellID; value.EffectIdx = data.EffectIdx; value.EndTime = data.EndTime; value.CastorValue = data.CastorValue; value.Value = data.Value; return value; } }
//------------------------------------------------------------------------------ // <copyright file="TemplatedMailWebEventProvider .cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Management { using System.Configuration; using System.Configuration.Provider; using System.Collections.Specialized; using System.Web.Util; using System.Net.Mail; using System.Globalization; using System.Web.Configuration; using System.Text; using System.IO; using System.Runtime.Remoting.Messaging; using System.Security.Permissions; using System.Threading; public sealed class TemplatedMailWebEventProvider : MailWebEventProvider, IInternalWebEventProvider { int _nonBufferNotificationSequence = 0; string _templateUrl; bool _detailedTemplateErrors = false; class TemplatedMailErrorFormatterGenerator : ErrorFormatterGenerator { int _eventsRemaining; bool _showDetails; bool _errorFormatterCalled; internal TemplatedMailErrorFormatterGenerator(int eventsRemaining, bool showDetails) { _eventsRemaining = eventsRemaining; _showDetails = showDetails; } internal bool ErrorFormatterCalled { get { return _errorFormatterCalled; } } internal override ErrorFormatter GetErrorFormatter(Exception e) { Exception inner = e.InnerException; _errorFormatterCalled = true; while (inner != null) { if (inner is HttpCompileException) { return new TemplatedMailCompileErrorFormatter((HttpCompileException)inner, _eventsRemaining, _showDetails); } else { inner = inner.InnerException; } } return new TemplatedMailRuntimeErrorFormatter(e, _eventsRemaining, _showDetails); } } internal TemplatedMailWebEventProvider() { } public override void Initialize(string name, NameValueCollection config) { Debug.Trace("TemplatedMailWebEventProvider", "Initializing: name=" + name); ProviderUtil.GetAndRemoveStringAttribute(config, "template", name, ref _templateUrl); if (_templateUrl == null) { throw new ConfigurationErrorsException(SR.GetString(SR.Provider_missing_attribute, "template", name)); } _templateUrl = _templateUrl.Trim(); if (_templateUrl.Length == 0) { throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_provider_attribute, "template", name, _templateUrl)); } if (!UrlPath.IsRelativeUrl(_templateUrl)) { throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_mail_template_provider_attribute, "template", name, _templateUrl)); } _templateUrl = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, _templateUrl); // VSWhidbey 440081: Guard against templates outside the AppDomain path if (!HttpRuntime.IsPathWithinAppRoot(_templateUrl)) { throw new ConfigurationErrorsException(SR.GetString(SR.Invalid_mail_template_provider_attribute, "template", name, _templateUrl)); } ProviderUtil.GetAndRemoveBooleanAttribute(config, "detailedTemplateErrors", name, ref _detailedTemplateErrors); base.Initialize(name, config); } void GenerateMessageBody( MailMessage msg, WebBaseEventCollection events, DateTime lastNotificationUtc, int discardedSinceLastNotification, int eventsInBuffer, int notificationSequence, EventNotificationType notificationType, int eventsInNotification, int eventsRemaining, int messagesInNotification, int eventsLostDueToMessageLimit, int messageSequence, out bool fatalError) { StringWriter writer = new StringWriter(CultureInfo.InstalledUICulture); MailEventNotificationInfo info = new MailEventNotificationInfo( msg, events, lastNotificationUtc, discardedSinceLastNotification, eventsInBuffer, notificationSequence, notificationType, eventsInNotification, eventsRemaining, messagesInNotification, eventsLostDueToMessageLimit, messageSequence); CallContext.SetData(CurrentEventsName, info); try { TemplatedMailErrorFormatterGenerator gen = new TemplatedMailErrorFormatterGenerator(events.Count + eventsRemaining, _detailedTemplateErrors); HttpServerUtility.ExecuteLocalRequestAndCaptureResponse(_templateUrl, writer, gen); fatalError = gen.ErrorFormatterCalled; if (fatalError) { msg.Subject = HttpUtility.HtmlEncode(SR.GetString(SR.WebEvent_event_email_subject_template_error, notificationSequence.ToString(CultureInfo.InstalledUICulture), messageSequence.ToString(CultureInfo.InstalledUICulture), SubjectPrefix)); } msg.Body = writer.ToString(); msg.IsBodyHtml = true; } finally { CallContext.FreeNamedDataSlot(CurrentEventsName); } } internal override void SendMessage(WebBaseEvent eventRaised) { WebBaseEventCollection events = new WebBaseEventCollection(eventRaised); bool templateError; SendMessageInternal(events, // events DateTime.MinValue, // lastNotificationUtc 0, // discardedSinceLastNotification 0, // eventsInBuffer Interlocked.Increment(ref _nonBufferNotificationSequence), // notificationSequence EventNotificationType.Unbuffered, // notificationType 1, // eventsInNotification 0, // eventsRemaining 1, // messagesInNotification 0, // eventsLostDueToMessageLimit MessageSequenceBase, // messageSequence out templateError); // templateError } internal override void SendMessage(WebBaseEventCollection events, WebEventBufferFlushInfo flushInfo, int eventsInNotification, int eventsRemaining, int messagesInNotification, int eventsLostDueToMessageLimit, int messageSequence, int eventsSent, out bool fatalError) { SendMessageInternal(events, flushInfo.LastNotificationUtc, flushInfo.EventsDiscardedSinceLastNotification, flushInfo.EventsInBuffer, flushInfo.NotificationSequence, flushInfo.NotificationType, eventsInNotification, eventsRemaining, messagesInNotification, eventsLostDueToMessageLimit, messageSequence, out fatalError); } void SendMessageInternal(WebBaseEventCollection events, DateTime lastNotificationUtc, int discardedSinceLastNotification, int eventsInBuffer, int notificationSequence, EventNotificationType notificationType, int eventsInNotification, int eventsRemaining, int messagesInNotification, int eventsLostDueToMessageLimit, int messageSequence, out bool fatalError) { using (MailMessage msg = GetMessage()) { msg.Subject = GenerateSubject(notificationSequence, messageSequence, events, events.Count); GenerateMessageBody( msg, events, lastNotificationUtc, discardedSinceLastNotification, eventsInBuffer, notificationSequence, notificationType, eventsInNotification, eventsRemaining, messagesInNotification, eventsLostDueToMessageLimit, messageSequence, out fatalError); SendMail(msg); } } internal const string CurrentEventsName = "_TWCurEvt"; public static MailEventNotificationInfo CurrentNotification { get { return (MailEventNotificationInfo)CallContext.GetData(CurrentEventsName); } } } public sealed class MailEventNotificationInfo { WebBaseEventCollection _events; DateTime _lastNotificationUtc; int _discardedSinceLastNotification; int _eventsInBuffer; int _notificationSequence; EventNotificationType _notificationType; int _eventsInNotification; int _eventsRemaining; int _messagesInNotification; int _eventsLostDueToMessageLimit; int _messageSequence; MailMessage _msg; internal MailEventNotificationInfo( MailMessage msg, WebBaseEventCollection events, DateTime lastNotificationUtc, int discardedSinceLastNotification, int eventsInBuffer, int notificationSequence, EventNotificationType notificationType, int eventsInNotification, int eventsRemaining, int messagesInNotification, int eventsLostDueToMessageLimit, int messageSequence) { _events = events; _lastNotificationUtc = lastNotificationUtc; _discardedSinceLastNotification = discardedSinceLastNotification; _eventsInBuffer = eventsInBuffer; _notificationSequence = notificationSequence; _notificationType = notificationType; _eventsInNotification = eventsInNotification; _eventsRemaining = eventsRemaining ; _messagesInNotification = messagesInNotification; _eventsLostDueToMessageLimit = eventsLostDueToMessageLimit; _messageSequence = messageSequence; _msg = msg; } public WebBaseEventCollection Events { get { return _events; } } public EventNotificationType NotificationType { get { return _notificationType; } } public int EventsInNotification { get { return _eventsInNotification; } } public int EventsRemaining { get { return _eventsRemaining; } } public int MessagesInNotification { get { return _messagesInNotification; } } public int EventsInBuffer { get { return _eventsInBuffer; } } public int EventsDiscardedByBuffer { get { return _discardedSinceLastNotification; } } public int EventsDiscardedDueToMessageLimit { get { return _eventsLostDueToMessageLimit; } } public int NotificationSequence { get { return _notificationSequence; } } public int MessageSequence { get { return _messageSequence; } } public DateTime LastNotificationUtc { get { return _lastNotificationUtc; } } public MailMessage Message { get { return _msg; } } } internal class TemplatedMailCompileErrorFormatter : DynamicCompileErrorFormatter { int _eventsRemaining; bool _showDetails; internal TemplatedMailCompileErrorFormatter(HttpCompileException e, int eventsRemaining, bool showDetails) : base(e) { _eventsRemaining = eventsRemaining; _showDetails = showDetails; _hideDetailedCompilerOutput = true; _dontShowVersion = true; } protected override string ErrorTitle { get { return SR.GetString(SR.MailWebEventProvider_template_compile_error, _eventsRemaining.ToString(CultureInfo.InstalledUICulture)); } } protected override string Description { get { if (_showDetails) { return base.Description; } else { return SR.GetString(SR.MailWebEventProvider_template_error_no_details); } } } protected override string MiscSectionTitle { get { if (_showDetails) { return base.MiscSectionTitle; } else { return null; } } } protected override string MiscSectionContent { get { if (_showDetails) { return base.MiscSectionContent; } else { return null; } } } } internal class TemplatedMailRuntimeErrorFormatter : UnhandledErrorFormatter { int _eventsRemaining; bool _showDetails; internal TemplatedMailRuntimeErrorFormatter(Exception e, int eventsRemaining, bool showDetails) : base(e) { _eventsRemaining = eventsRemaining; _showDetails = showDetails; _dontShowVersion = true; } protected override string ErrorTitle { get { if (HttpException.GetHttpCodeForException(Exception) == 404) { return SR.GetString(SR.MailWebEventProvider_template_file_not_found_error, _eventsRemaining.ToString(CultureInfo.InstalledUICulture)); } else { return SR.GetString(SR.MailWebEventProvider_template_runtime_error, _eventsRemaining.ToString(CultureInfo.InstalledUICulture)); } } } protected override string ColoredSquareTitle { get { return null;} } protected override string ColoredSquareContent { get { return null; } } protected override string Description { get { if (_showDetails) { return base.Description; } else { return SR.GetString(SR.MailWebEventProvider_template_error_no_details); } } } protected override string MiscSectionTitle { get { if (_showDetails) { return base.MiscSectionTitle; } else { return null; } } } protected override string MiscSectionContent { get { if (_showDetails) { return base.MiscSectionContent; } else { return null; } } } protected override string ColoredSquare2Title { get { if (_showDetails) { return base.ColoredSquare2Title; } else { return null; } } } protected override string ColoredSquare2Content { get { if (_showDetails) { return base.ColoredSquare2Content; } else { return null; } } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Input.TouchDevice.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Input { abstract public partial class TouchDevice : InputDevice, IManipulator { #region Methods and constructors protected void Activate() { } public bool Capture(System.Windows.IInputElement element, CaptureMode captureMode) { return default(bool); } public bool Capture(System.Windows.IInputElement element) { return default(bool); } protected void Deactivate() { } public abstract TouchPointCollection GetIntermediateTouchPoints(System.Windows.IInputElement relativeTo); public abstract TouchPoint GetTouchPoint(System.Windows.IInputElement relativeTo); protected virtual new void OnCapture(System.Windows.IInputElement element, CaptureMode captureMode) { } protected virtual new void OnManipulationEnded(bool cancel) { } protected virtual new void OnManipulationStarted() { } protected bool ReportDown() { return default(bool); } protected bool ReportMove() { return default(bool); } protected bool ReportUp() { return default(bool); } protected void SetActiveSource(System.Windows.PresentationSource activeSource) { } public void Synchronize() { } System.Windows.Point System.Windows.Input.IManipulator.GetPosition(System.Windows.IInputElement relativeTo) { return default(System.Windows.Point); } void System.Windows.Input.IManipulator.ManipulationEnded(bool cancel) { } protected TouchDevice(int deviceId) { } #endregion #region Properties and indexers public override sealed System.Windows.PresentationSource ActiveSource { get { return default(System.Windows.PresentationSource); } } public System.Windows.IInputElement Captured { get { return default(System.Windows.IInputElement); } } public CaptureMode CaptureMode { get { return default(CaptureMode); } } public System.Windows.IInputElement DirectlyOver { get { return default(System.Windows.IInputElement); } } public int Id { get { return default(int); } } public bool IsActive { get { return default(bool); } } int System.Windows.Input.IManipulator.Id { get { return default(int); } } public override sealed System.Windows.IInputElement Target { get { return default(System.Windows.IInputElement); } } #endregion #region Events public event EventHandler Activated { add { } remove { } } public event EventHandler Deactivated { add { } remove { } } public event EventHandler Updated { add { } remove { } } #endregion } }
using System.Collections.Immutable; using System.Diagnostics; using System.Text; using JetBrains.Annotations; namespace System.Reflection.Metadata.Model { // todo: attributes [DebuggerDisplay("{DebugView,nq}")] public struct MetadataTypeDefinition { [DebuggerBrowsable(DebuggerBrowsableState.Never)] [NotNull] private readonly MetadataReader myMetadataReader; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private TypeDefinition myTypeDefinition; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private ImmutableArray<MetadataMethodDefinition> myMethods; public MetadataTypeDefinition([NotNull] MetadataReader metadataReader, TypeDefinition typeDefinition) { myMetadataReader = metadataReader; myTypeDefinition = typeDefinition; myMethods = default(ImmutableArray<MetadataMethodDefinition>); } public TypeDefinition Definition => myTypeDefinition; [NotNull] public string Name => myMetadataReader.GetString(myTypeDefinition.Name); [NotNull] public string FullName { get { var declaringType = myTypeDefinition.GetDeclaringType(); if (!declaringType.IsNil) { var builder = new StringBuilder(); BuildFullName(builder, declaringType); builder.Append('+').Append(Name); return builder.ToString(); } var namespaceHandle = myTypeDefinition.Namespace; if (namespaceHandle.IsNil) return Name; var nameSpace = myMetadataReader.GetString(namespaceHandle); return nameSpace + "." + Name; } } private void BuildFullName([NotNull] StringBuilder builder, TypeDefinitionHandle type) { var typeDefinition = myMetadataReader.GetTypeDefinition(type); var containingType = typeDefinition.GetDeclaringType(); if (containingType.IsNil) { var namespaceHandle = typeDefinition.Namespace; if (!namespaceHandle.IsNil) { var namespaceName = myMetadataReader.GetString(namespaceHandle); builder.Append(namespaceName).Append('.'); } } else { BuildFullName(builder, containingType); builder.Append('+'); } var shortName = myMetadataReader.GetString(typeDefinition.Name); builder.Append(shortName); } [NotNull] public string Namespace { get { var type = myTypeDefinition; for (var declaringType = type.GetDeclaringType(); !declaringType.IsNil;) { type = myMetadataReader.GetTypeDefinition(declaringType); declaringType = type.GetDeclaringType(); } var namespaceHandle = type.Namespace; if (namespaceHandle.IsNil) return string.Empty; return myMetadataReader.GetString(namespaceHandle); } } public MetadataTypeDefinition? ContainingType { get { var declaringType = myTypeDefinition.GetDeclaringType(); if (declaringType.IsNil) return null; var typeDefinition = myMetadataReader.GetTypeDefinition(declaringType); return new MetadataTypeDefinition(myMetadataReader, typeDefinition); } } public bool IsClass => !IsInterface; public bool IsInterface => (myTypeDefinition.Attributes & TypeAttributes.Interface) != 0; public bool IsAbstract => (myTypeDefinition.Attributes & TypeAttributes.Abstract) != 0; public bool IsSealed => (myTypeDefinition.Attributes & TypeAttributes.Sealed) != 0; public bool IsNested => !myTypeDefinition.GetDeclaringType().IsNil; public MetadataVisibility Visibility { get { var attributes = myTypeDefinition.Attributes & TypeAttributes.VisibilityMask; switch (attributes) { case TypeAttributes.NestedAssembly: return MetadataVisibility.Internal; case TypeAttributes.NestedFamANDAssem: return MetadataVisibility.ProtectedAndInternal; case TypeAttributes.NestedFamily: return MetadataVisibility.Protected; case TypeAttributes.NestedFamORAssem: return MetadataVisibility.ProtectedOrInternal; case TypeAttributes.NestedPublic: case TypeAttributes.Public: return MetadataVisibility.Public; default: return MetadataVisibility.Private; } } } public ImmutableArray<MetadataMethodDefinition> Methods { get { if (myMethods.IsDefault) { var handleCollection = myTypeDefinition.GetMethods(); var builder = ImmutableArray.CreateBuilder<MetadataMethodDefinition>(handleCollection.Count); var metadataReader = myMetadataReader; foreach (var definitionHandle in handleCollection) { var methodDefinition = metadataReader.GetMethodDefinition(definitionHandle); builder.Add(new MetadataMethodDefinition(metadataReader, methodDefinition)); } myMethods = builder.MoveToImmutable(); } return myMethods; } } public bool IsValueType { get { if ((myTypeDefinition.Attributes & TypeAttributes.Interface) != 0) return false; var baseTypeHandle = myTypeDefinition.BaseType; if (baseTypeHandle.Kind == HandleKind.TypeDefinition) { var typeDefinition = myMetadataReader.GetTypeDefinition((TypeDefinitionHandle) baseTypeHandle); var namespaceHandle = typeDefinition.Namespace; if (namespaceHandle.IsNil) return false; var namespaceName = myMetadataReader.GetString(namespaceHandle); if (namespaceName != "System") return false; var typeName = myMetadataReader.GetString(typeDefinition.Name); return typeName == "ValueType" || typeName == "Enum"; } if (baseTypeHandle.Kind == HandleKind.TypeReference) { var typeReference = myMetadataReader.GetTypeReference((TypeReferenceHandle) baseTypeHandle); var namespaceHandle = typeReference.Namespace; if (namespaceHandle.IsNil) return false; var namespaceName = myMetadataReader.GetString(namespaceHandle); if (namespaceName != "System") return false; var typeName = myMetadataReader.GetString(typeReference.Name); return typeName == "ValueType" || typeName == "Enum"; } return false; } } public MetadataTypeDefinition? GetBaseTypeDefinition() { var baseTypeHadle = myTypeDefinition.BaseType; if (baseTypeHadle.Kind == HandleKind.TypeDefinition) { var typeDefinition = myMetadataReader.GetTypeDefinition((TypeDefinitionHandle) baseTypeHadle); return new MetadataTypeDefinition(myMetadataReader, typeDefinition); } return null; } // TODO: GetBaseTypeSpecification // TODO: GetBaseTypeReference [NotNull, DebuggerBrowsable(DebuggerBrowsableState.Never)] private string DebugView => "[typedef] " + FullName; public override string ToString() { return FullName; } } }
// // 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.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Database /// security policy. Contains operations to: Retrieve and Update security /// policy /// </summary> internal partial class SecurityOperations : IServiceOperations<SqlManagementClient>, ISecurityOperations { /// <summary> /// Initializes a new instance of the SecurityOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SecurityOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Gets Azure SQL Database security policy object according to a given /// Azure SQL Database Server and Database. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// Azure SQL Database hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// policy is being retreived. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get Azure SQL Database security policy /// request /// </returns> public async Task<DatabaseSecurityPolicyGetResponse> GetAsync(string resourceGroupName, string serverName, string databaseName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers/" + serverName.Trim() + "/databaseSecurityPolicies/" + databaseName.Trim() + "?"; url = url + "api-version=2014-04-01"; 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 DatabaseSecurityPolicyGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DatabaseSecurityPolicyGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DatabaseSecurityPolicy databaseSecurityPolicyInstance = new DatabaseSecurityPolicy(); result.DatabaseSecurityPolicy = databaseSecurityPolicyInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); databaseSecurityPolicyInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DatabaseSecurityPolicyProperties propertiesInstance = new DatabaseSecurityPolicyProperties(); databaseSecurityPolicyInstance.Properties = propertiesInstance; JToken isAuditingEnabledValue = propertiesValue["isAuditingEnabled"]; if (isAuditingEnabledValue != null && isAuditingEnabledValue.Type != JTokenType.Null) { bool isAuditingEnabledInstance = ((bool)isAuditingEnabledValue); propertiesInstance.IsAuditingEnabled = isAuditingEnabledInstance; } JToken retentionDaysValue = propertiesValue["retentionDays"]; if (retentionDaysValue != null && retentionDaysValue.Type != JTokenType.Null) { int retentionDaysInstance = ((int)retentionDaysValue); propertiesInstance.RetentionDays = retentionDaysInstance; } JToken isEventTypeDataAccessEnabledValue = propertiesValue["isEventTypeDataAccessEnabled"]; if (isEventTypeDataAccessEnabledValue != null && isEventTypeDataAccessEnabledValue.Type != JTokenType.Null) { bool isEventTypeDataAccessEnabledInstance = ((bool)isEventTypeDataAccessEnabledValue); propertiesInstance.IsEventTypeDataAccessEnabled = isEventTypeDataAccessEnabledInstance; } JToken isEventTypeSchemaChangeEnabledValue = propertiesValue["isEventTypeSchemaChangeEnabled"]; if (isEventTypeSchemaChangeEnabledValue != null && isEventTypeSchemaChangeEnabledValue.Type != JTokenType.Null) { bool isEventTypeSchemaChangeEnabledInstance = ((bool)isEventTypeSchemaChangeEnabledValue); propertiesInstance.IsEventTypeSchemaChangeEnabled = isEventTypeSchemaChangeEnabledInstance; } JToken isEventTypeDataChangesEnabledValue = propertiesValue["isEventTypeDataChangesEnabled"]; if (isEventTypeDataChangesEnabledValue != null && isEventTypeDataChangesEnabledValue.Type != JTokenType.Null) { bool isEventTypeDataChangesEnabledInstance = ((bool)isEventTypeDataChangesEnabledValue); propertiesInstance.IsEventTypeDataChangesEnabled = isEventTypeDataChangesEnabledInstance; } JToken isEventTypeSecurityExceptionsEnabledValue = propertiesValue["isEventTypeSecurityExceptionsEnabled"]; if (isEventTypeSecurityExceptionsEnabledValue != null && isEventTypeSecurityExceptionsEnabledValue.Type != JTokenType.Null) { bool isEventTypeSecurityExceptionsEnabledInstance = ((bool)isEventTypeSecurityExceptionsEnabledValue); propertiesInstance.IsEventTypeSecurityExceptionsEnabled = isEventTypeSecurityExceptionsEnabledInstance; } JToken isEventTypeGrantRevokePermissionsEnabledValue = propertiesValue["isEventTypeGrantRevokePermissionsEnabled"]; if (isEventTypeGrantRevokePermissionsEnabledValue != null && isEventTypeGrantRevokePermissionsEnabledValue.Type != JTokenType.Null) { bool isEventTypeGrantRevokePermissionsEnabledInstance = ((bool)isEventTypeGrantRevokePermissionsEnabledValue); propertiesInstance.IsEventTypeGrantRevokePermissionsEnabled = isEventTypeGrantRevokePermissionsEnabledInstance; } JToken storageAccountNameValue = propertiesValue["storageAccountName"]; if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null) { string storageAccountNameInstance = ((string)storageAccountNameValue); propertiesInstance.StorageAccountName = storageAccountNameInstance; } JToken storageAccountKeyValue = propertiesValue["storageAccountKey"]; if (storageAccountKeyValue != null && storageAccountKeyValue.Type != JTokenType.Null) { string storageAccountKeyInstance = ((string)storageAccountKeyValue); propertiesInstance.StorageAccountKey = storageAccountKeyInstance; } JToken secondaryStorageAccountKeyValue = propertiesValue["secondaryStorageAccountKey"]; if (secondaryStorageAccountKeyValue != null && secondaryStorageAccountKeyValue.Type != JTokenType.Null) { string secondaryStorageAccountKeyInstance = ((string)secondaryStorageAccountKeyValue); propertiesInstance.SecondaryStorageAccountKey = secondaryStorageAccountKeyInstance; } JToken storageTableEndpointValue = propertiesValue["storageTableEndpoint"]; if (storageTableEndpointValue != null && storageTableEndpointValue.Type != JTokenType.Null) { string storageTableEndpointInstance = ((string)storageTableEndpointValue); propertiesInstance.StorageTableEndpoint = storageTableEndpointInstance; } JToken storageAccountResourceGroupNameValue = propertiesValue["storageAccountResourceGroupName"]; if (storageAccountResourceGroupNameValue != null && storageAccountResourceGroupNameValue.Type != JTokenType.Null) { string storageAccountResourceGroupNameInstance = ((string)storageAccountResourceGroupNameValue); propertiesInstance.StorageAccountResourceGroupName = storageAccountResourceGroupNameInstance; } JToken storageAccountSubscriptionIdValue = propertiesValue["storageAccountSubscriptionId"]; if (storageAccountSubscriptionIdValue != null && storageAccountSubscriptionIdValue.Type != JTokenType.Null) { string storageAccountSubscriptionIdInstance = ((string)storageAccountSubscriptionIdValue); propertiesInstance.StorageAccountSubscriptionId = storageAccountSubscriptionIdInstance; } JToken adoNetConnectionStringValue = propertiesValue["adoNetConnectionString"]; if (adoNetConnectionStringValue != null && adoNetConnectionStringValue.Type != JTokenType.Null) { string adoNetConnectionStringInstance = ((string)adoNetConnectionStringValue); propertiesInstance.AdoNetConnectionString = adoNetConnectionStringInstance; } JToken odbcConnectionStringValue = propertiesValue["odbcConnectionString"]; if (odbcConnectionStringValue != null && odbcConnectionStringValue.Type != JTokenType.Null) { string odbcConnectionStringInstance = ((string)odbcConnectionStringValue); propertiesInstance.OdbcConnectionString = odbcConnectionStringInstance; } JToken phpConnectionStringValue = propertiesValue["phpConnectionString"]; if (phpConnectionStringValue != null && phpConnectionStringValue.Type != JTokenType.Null) { string phpConnectionStringInstance = ((string)phpConnectionStringValue); propertiesInstance.PhpConnectionString = phpConnectionStringInstance; } JToken jdbcConnectionStringValue = propertiesValue["jdbcConnectionString"]; if (jdbcConnectionStringValue != null && jdbcConnectionStringValue.Type != JTokenType.Null) { string jdbcConnectionStringInstance = ((string)jdbcConnectionStringValue); propertiesInstance.JdbcConnectionString = jdbcConnectionStringInstance; } JToken proxyDnsNameValue = propertiesValue["proxyDnsName"]; if (proxyDnsNameValue != null && proxyDnsNameValue.Type != JTokenType.Null) { string proxyDnsNameInstance = ((string)proxyDnsNameValue); propertiesInstance.ProxyDnsName = proxyDnsNameInstance; } JToken useServerDefaultValue = propertiesValue["useServerDefault"]; if (useServerDefaultValue != null && useServerDefaultValue.Type != JTokenType.Null) { bool useServerDefaultInstance = ((bool)useServerDefaultValue); propertiesInstance.UseServerDefault = useServerDefaultInstance; } JToken isBlockDirectAccessEnabledValue = propertiesValue["isBlockDirectAccessEnabled"]; if (isBlockDirectAccessEnabledValue != null && isBlockDirectAccessEnabledValue.Type != JTokenType.Null) { bool isBlockDirectAccessEnabledInstance = ((bool)isBlockDirectAccessEnabledValue); propertiesInstance.IsBlockDirectAccessEnabled = isBlockDirectAccessEnabledInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); databaseSecurityPolicyInstance.Id = idInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); databaseSecurityPolicyInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); databaseSecurityPolicyInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); databaseSecurityPolicyInstance.Tags.Add(tagsKey, tagsValue); } } } 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(); } } } /// <summary> /// Updates an Azure SQL Database security policy object. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server to which the /// Azure SQL Database belongs. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database to which the security /// policy is applied. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating a security policy. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<OperationResponse> UpdateAsync(string resourceGroupName, string serverName, string databaseName, DatabaseSecurityPolicyUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (databaseName == null) { throw new ArgumentNullException("databaseName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("databaseName", databaseName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = "/subscriptions/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/resourceGroups/" + resourceGroupName.Trim() + "/providers/Microsoft.Sql/servers/" + serverName.Trim() + "/databaseSecurityPolicies/" + databaseName.Trim() + "?"; url = url + "api-version=2014-04-01"; 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.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject databaseSecurityPolicyUpdateParametersValue = new JObject(); requestDoc = databaseSecurityPolicyUpdateParametersValue; JObject propertiesValue = new JObject(); databaseSecurityPolicyUpdateParametersValue["properties"] = propertiesValue; propertiesValue["isAuditingEnabled"] = parameters.Properties.IsAuditingEnabled; propertiesValue["retentionDays"] = parameters.Properties.RetentionDays; propertiesValue["isEventTypeDataAccessEnabled"] = parameters.Properties.IsEventTypeDataAccessEnabled; propertiesValue["isEventTypeSchemaChangeEnabled"] = parameters.Properties.IsEventTypeSchemaChangeEnabled; propertiesValue["isEventTypeDataChangesEnabled"] = parameters.Properties.IsEventTypeDataChangesEnabled; propertiesValue["isEventTypeSecurityExceptionsEnabled"] = parameters.Properties.IsEventTypeSecurityExceptionsEnabled; propertiesValue["isEventTypeGrantRevokePermissionsEnabled"] = parameters.Properties.IsEventTypeGrantRevokePermissionsEnabled; if (parameters.Properties.StorageAccountName != null) { propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName; } if (parameters.Properties.StorageAccountKey != null) { propertiesValue["storageAccountKey"] = parameters.Properties.StorageAccountKey; } if (parameters.Properties.SecondaryStorageAccountKey != null) { propertiesValue["secondaryStorageAccountKey"] = parameters.Properties.SecondaryStorageAccountKey; } if (parameters.Properties.StorageTableEndpoint != null) { propertiesValue["storageTableEndpoint"] = parameters.Properties.StorageTableEndpoint; } if (parameters.Properties.StorageAccountResourceGroupName != null) { propertiesValue["storageAccountResourceGroupName"] = parameters.Properties.StorageAccountResourceGroupName; } if (parameters.Properties.StorageAccountSubscriptionId != null) { propertiesValue["storageAccountSubscriptionId"] = parameters.Properties.StorageAccountSubscriptionId; } if (parameters.Properties.AdoNetConnectionString != null) { propertiesValue["adoNetConnectionString"] = parameters.Properties.AdoNetConnectionString; } if (parameters.Properties.OdbcConnectionString != null) { propertiesValue["odbcConnectionString"] = parameters.Properties.OdbcConnectionString; } if (parameters.Properties.PhpConnectionString != null) { propertiesValue["phpConnectionString"] = parameters.Properties.PhpConnectionString; } if (parameters.Properties.JdbcConnectionString != null) { propertiesValue["jdbcConnectionString"] = parameters.Properties.JdbcConnectionString; } if (parameters.Properties.ProxyDnsName != null) { propertiesValue["proxyDnsName"] = parameters.Properties.ProxyDnsName; } propertiesValue["useServerDefault"] = parameters.Properties.UseServerDefault; propertiesValue["isBlockDirectAccessEnabled"] = parameters.Properties.IsBlockDirectAccessEnabled; requestContent = requestDoc.ToString(Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 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, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); 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(); } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Abstractions.PhysicalFileSystem; using Microsoft.TemplateEngine.Core; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.Config; using Microsoft.TemplateEngine.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects { public class RunnableProjectGenerator : IGenerator { private static readonly Guid GeneratorId = new Guid("0C434DF7-E2CB-4DEE-B216-D7C58C8EB4B3"); private static readonly string GeneratorVersion = "1.0.0.0"; public Guid Id => GeneratorId; public static readonly string TemplateConfigDirectoryName = ".template.config"; public static readonly string TemplateConfigFileName = "template.json"; public Task<ICreationResult> CreateAsync(IEngineEnvironmentSettings environmentSettings, ITemplate templateData, IParameterSet parameters, IComponentManager componentManager, string targetDirectory) { RunnableProjectTemplate template = (RunnableProjectTemplate)templateData; ProcessMacros(environmentSettings, componentManager, template.Config.OperationConfig, parameters); IVariableCollection variables = VariableCollection.SetupVariables(environmentSettings, parameters, template.Config.OperationConfig.VariableSetup); template.Config.Evaluate(parameters, variables, template.ConfigFile); IOrchestrator2 basicOrchestrator = new Core.Util.Orchestrator(); RunnableProjectOrchestrator orchestrator = new RunnableProjectOrchestrator(basicOrchestrator); GlobalRunSpec runSpec = new GlobalRunSpec(template.TemplateSourceRoot, componentManager, parameters, variables, template.Config.OperationConfig, template.Config.SpecialOperationConfig, template.Config.LocalizationOperations, template.Config.IgnoreFileNames); foreach (FileSourceMatchInfo source in template.Config.Sources) { runSpec.SetupFileSource(source); string target = Path.Combine(targetDirectory, source.Target); orchestrator.Run(runSpec, template.TemplateSourceRoot.DirectoryInfo(source.Source), target); } return Task.FromResult(GetCreationResult(environmentSettings, template, variables)); } private static ICreationResult GetCreationResult(IEngineEnvironmentSettings environmentSettings, RunnableProjectTemplate template, IVariableCollection variables) { return new CreationResult() { PostActions = PostAction.ListFromModel(environmentSettings, template.Config.PostActionModel, variables), PrimaryOutputs = CreationPath.ListFromModel(environmentSettings, template.Config.PrimaryOutputs, variables) }; } // Note the deferred-config macros (generated) are part of the runConfig.Macros // and not in the ComputedMacros. // Possibly make a separate property for the deferred-config macros private static void ProcessMacros(IEngineEnvironmentSettings environmentSettings, IComponentManager componentManager, IGlobalRunConfig runConfig, IParameterSet parameters) { if (runConfig.Macros != null) { IVariableCollection varsForMacros = VariableCollection.SetupVariables(environmentSettings, parameters, runConfig.VariableSetup); MacrosOperationConfig macroProcessor = new MacrosOperationConfig(); macroProcessor.ProcessMacros(environmentSettings, componentManager, runConfig.Macros, varsForMacros, parameters); } if (runConfig.ComputedMacros != null) { IVariableCollection varsForMacros = VariableCollection.SetupVariables(environmentSettings, parameters, runConfig.VariableSetup); MacrosOperationConfig macroProcessor = new MacrosOperationConfig(); macroProcessor.ProcessMacros(environmentSettings, componentManager, runConfig.ComputedMacros, varsForMacros, parameters); } } public IParameterSet GetParametersForTemplate(IEngineEnvironmentSettings environmentSettings, ITemplate template) { RunnableProjectTemplate tmplt = (RunnableProjectTemplate)template; return new ParameterSet(tmplt.Config); } private bool TryGetLangPackFromFile(IFile file, out ILocalizationModel locModel) { if (file == null) { locModel = null; return false; } try { JObject srcObject = ReadJObjectFromIFile(file); locModel = SimpleConfigModel.LocalizationFromJObject(srcObject); return true; } catch (Exception ex) { ITemplateEngineHost host = file.MountPoint.EnvironmentSettings.Host; host.LogMessage($"Error reading Langpack from file: {file.FullPath} | Error = {ex.ToString()}"); } locModel = null; return false; } public IList<ITemplate> GetTemplatesAndLangpacksFromDir(IMountPoint source, out IList<ILocalizationLocator> localizations) { IDirectory folder = source.Root; Regex localeFileRegex = new Regex(@" ^ (?<locale> [a-z]{2} (?:-[A-Z]{2})? ) \." + Regex.Escape(TemplateConfigFileName) + "$" , RegexOptions.IgnorePatternWhitespace); IList<ITemplate> templateList = new List<ITemplate>(); localizations = new List<ILocalizationLocator>(); foreach (IFile file in folder.EnumerateFiles("*" + TemplateConfigFileName, SearchOption.AllDirectories)) { if (string.Equals(file.Name, TemplateConfigFileName, StringComparison.OrdinalIgnoreCase)) { IFile hostConfigFile = file.MountPoint.EnvironmentSettings.SettingsLoader.FindBestHostTemplateConfigFile(file); if (TryGetTemplateFromConfigInfo(file, out ITemplate template, hostTemplateConfigFile: hostConfigFile)) { templateList.Add(template); } continue; } Match localeMatch = localeFileRegex.Match(file.Name); if (localeMatch.Success) { string locale = localeMatch.Groups["locale"].Value; if (TryGetLangPackFromFile(file, out ILocalizationModel locModel)) { ILocalizationLocator locator = new LocalizationLocator() { Locale = locale, MountPointId = source.Info.MountPointId, ConfigPlace = file.FullPath, Identity = locModel.Identity, Author = locModel.Author, Name = locModel.Name, Description = locModel.Description, ParameterSymbols = locModel.ParameterSymbols }; localizations.Add(locator); } continue; } } return templateList; } // TODO: localize the diagnostic strings // checks that all the template sources are under the template root, and they exist. internal bool AreAllTemplatePathsValid(IRunnableProjectConfig templateConfig, RunnableProjectTemplate runnableTemplate) { ITemplateEngineHost host = runnableTemplate.Source.EnvironmentSettings.Host; if (runnableTemplate.TemplateSourceRoot == null) { host.LogDiagnosticMessage(string.Empty, "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateRootOutsideInstallSource, runnableTemplate.Name), "Authoring"); return false; } // check if any sources get out of the mount point bool allSourcesValid = true; foreach (FileSourceMatchInfo source in templateConfig.Sources) { try { IFile file = runnableTemplate.TemplateSourceRoot.FileInfo(source.Source); if (file?.Exists ?? false) { allSourcesValid = false; host.LogDiagnosticMessage(string.Empty, "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateNameDisplay, runnableTemplate.Name), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateSourceRoot, runnableTemplate.TemplateSourceRoot.FullPath), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_SourceMustBeDirectory, source.Source), "Authoring"); } else { IDirectory sourceRoot = runnableTemplate.TemplateSourceRoot.DirectoryInfo(source.Source); if (!(sourceRoot?.Exists ?? false)) { // non-existant directory allSourcesValid = false; host.LogDiagnosticMessage(string.Empty, "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateNameDisplay, runnableTemplate.Name), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateSourceRoot, runnableTemplate.TemplateSourceRoot.FullPath), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_SourceDoesNotExist, source.Source), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_SourceIsOutsideInstallSource, sourceRoot.FullPath), "Authoring"); } } } catch { // outside the mount point root // TODO: after the null ref exception in DirectoryInfo is fixed, change how this check works. allSourcesValid = false; host.LogDiagnosticMessage(string.Empty, "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateNameDisplay, runnableTemplate.Name), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateSourceRoot, runnableTemplate.TemplateSourceRoot.FullPath), "Authoring"); host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateRootOutsideInstallSource, source.Source), "Authoring"); } } return allSourcesValid; } public bool TryGetTemplateFromConfigInfo(IFileSystemInfo templateFileConfig, out ITemplate template, IFileSystemInfo localeFileConfig = null, IFile hostTemplateConfigFile = null, string baselineName = null) { IFile templateFile = templateFileConfig as IFile; if (templateFile == null) { template = null; return false; } IFile localeFile = localeFileConfig as IFile; ITemplateEngineHost host = templateFileConfig.MountPoint.EnvironmentSettings.Host; try { JObject baseSrcObject = ReadJObjectFromIFile(templateFile); JObject srcObject = MergeAdditionalConfiguration(baseSrcObject, templateFileConfig); JObject localeSourceObject = null; if (localeFile != null) { localeSourceObject = ReadJObjectFromIFile(localeFile); } ISimpleConfigModifiers configModifiers = new SimpleConfigModifiers() { BaselineName = baselineName }; SimpleConfigModel templateModel = SimpleConfigModel.FromJObject(templateFile.MountPoint.EnvironmentSettings, srcObject, configModifiers, localeSourceObject); if (!PerformTemplateValidation(templateModel, templateFile, host)) { template = null; return false; } if (!CheckGeneratorVersionRequiredByTemplate(templateModel.GeneratorVersions)) { // template isn't compatible with this generator version template = null; return false; } RunnableProjectTemplate runnableProjectTemplate = new RunnableProjectTemplate(srcObject, this, templateFile, templateModel, null, hostTemplateConfigFile); if (!AreAllTemplatePathsValid(templateModel, runnableProjectTemplate)) { template = null; return false; } // Record the timestamp of the template file so we // know to reload it if it changes if (host.FileSystem is IFileLastWriteTimeSource timeSource) { runnableProjectTemplate.ConfigTimestampUtc = timeSource.GetLastWriteTimeUtc(templateFile.FullPath); } template = runnableProjectTemplate; return true; } catch (Exception ex) { host.LogMessage($"Error reading template from file: {templateFile.FullPath} | Error = {ex.Message}"); } template = null; return false; } private bool PerformTemplateValidation(SimpleConfigModel templateModel, IFile templateFile, ITemplateEngineHost host) { //Do some basic checks... List<string> errorMessages = new List<string>(); List<string> warningMessages = new List<string>(); if (string.IsNullOrEmpty(templateModel.Identity)) { errorMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "identity", templateFile.FullPath)); } if (string.IsNullOrEmpty(templateModel.Name)) { errorMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "name", templateFile.FullPath)); } if ((templateModel.ShortNameList?.Count ?? 0) == 0) { errorMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "shortName", templateFile.FullPath)); } if (string.IsNullOrEmpty(templateModel.SourceName)) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "sourceName", templateFile.FullPath)); } if (string.IsNullOrEmpty(templateModel.Author)) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "author", templateFile.FullPath)); } if (string.IsNullOrEmpty(templateModel.GroupIdentity)) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "groupIdentity", templateFile.FullPath)); } if (string.IsNullOrEmpty(templateModel.GeneratorVersions)) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "generatorVersions", templateFile.FullPath)); } if (templateModel.Precedence == 0) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "precedence", templateFile.FullPath)); } if ((templateModel.Classifications?.Count ?? 0) == 0) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MissingValue, "classifications", templateFile.FullPath)); } if (templateModel.PostActionModel != null && templateModel.PostActionModel.Any(x => x.ManualInstructionInfo == null || x.ManualInstructionInfo.Count == 0)) { warningMessages.Add(string.Format(LocalizableStrings.Authoring_MalformedPostActionManualInstructions, templateFile.FullPath)); } if (warningMessages.Count > 0) { host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateMissingCommonInformation, templateFile.FullPath), "Authoring"); foreach (string message in warningMessages) { host.LogDiagnosticMessage(" " + message, "Authoring"); } } if (errorMessages.Count > 0) { host.LogDiagnosticMessage(string.Format(LocalizableStrings.Authoring_TemplateNotInstalled, templateFile.FullPath), "Authoring"); foreach (string message in errorMessages) { host.LogDiagnosticMessage(" " + message, "Authoring"); } return false; } return true; } private bool CheckGeneratorVersionRequiredByTemplate(string generatorVersionsAllowed) { if (string.IsNullOrEmpty(generatorVersionsAllowed)) { return true; } if (!VersionStringHelpers.TryParseVersionSpecification(generatorVersionsAllowed, out IVersionSpecification versionChecker)) { return false; } return versionChecker.CheckIfVersionIsValid(GeneratorVersion); } private static readonly string AdditionalConfigFilesIndicator = "AdditionalConfigFiles"; // Checks the primarySource for additional configuration files. // If found, merges them all together. // Returns the merged JObject (or the original if there was nothing to merge). // Additional files must be in the same dir as the template file. private JObject MergeAdditionalConfiguration(JObject primarySource, IFileSystemInfo primarySourceConfig) { IReadOnlyList<string> otherFiles = primarySource.ArrayAsStrings(AdditionalConfigFilesIndicator); if (!otherFiles.Any()) { return primarySource; } JObject combinedSource = (JObject)primarySource.DeepClone(); foreach (string partialConfigFileName in otherFiles) { if (!partialConfigFileName.EndsWith("." + TemplateConfigFileName)) { throw new TemplateAuthoringException($"Split configuration error with file [{partialConfigFileName}]. Additional configuration file names must end with '.{TemplateConfigFileName}'.", partialConfigFileName); } IFile partialConfigFile = primarySourceConfig.Parent.EnumerateFiles(partialConfigFileName, SearchOption.TopDirectoryOnly).FirstOrDefault(x => string.Equals(x.Name, partialConfigFileName)); if (partialConfigFile == null) { throw new TemplateAuthoringException($"Split configuration file [{partialConfigFileName}] could not be found.", partialConfigFileName); } JObject partialConfigJson = ReadJObjectFromIFile(partialConfigFile); combinedSource.Merge(partialConfigJson); } return combinedSource; } internal JObject ReadJObjectFromIFile(IFile file) { using (Stream s = file.OpenRead()) using (TextReader tr = new StreamReader(s, true)) using (JsonReader r = new JsonTextReader(tr)) { return JObject.Load(r); } } // // Converts the raw, string version of a parameter to a strongly typed value. // If the param has a datatype specified, use that. Otherwise attempt to infer the type. // Throws a TemplateParamException if the conversion fails for any reason. // public object ConvertParameterValueToType(IEngineEnvironmentSettings environmentSettings, ITemplateParameter parameter, string untypedValue, out bool valueResolutionError) { return InternalConvertParameterValueToType(environmentSettings, parameter, untypedValue, out valueResolutionError); } internal static object InternalConvertParameterValueToType(IEngineEnvironmentSettings environmentSettings, ITemplateParameter parameter, string untypedValue, out bool valueResolutionError) { if (untypedValue == null) { valueResolutionError = false; return null; } if (!string.IsNullOrEmpty(parameter.DataType)) { object convertedValue = DataTypeSpecifiedConvertLiteral(environmentSettings, parameter, untypedValue, out valueResolutionError); return convertedValue; } else { valueResolutionError = false; return InferTypeAndConvertLiteral(untypedValue); } } // For explicitly data-typed variables, attempt to convert the variable value to the specified type. // Data type names: // - choice // - bool // - float // - int // - hex // - text // The data type names are case insensitive. // // Returns the converted value if it can be converted, throw otherwise internal static object DataTypeSpecifiedConvertLiteral(IEngineEnvironmentSettings environmentSettings, ITemplateParameter param, string literal, out bool valueResolutionError) { valueResolutionError = false; if (string.Equals(param.DataType, "bool", StringComparison.OrdinalIgnoreCase)) { if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase)) { return true; } else if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase)) { return false; } else { bool boolVal = false; // Note: if the literal is ever null, it is probably due to a problem in TemplateCreator.Instantiate() // which takes care of making null bool -> true as appropriate. // This else can also happen if there is a value but it can't be converted. string val; while (environmentSettings.Host.OnParameterError(param, null, "ParameterValueNotSpecified", out val) && !bool.TryParse(val, out boolVal)) { } valueResolutionError = !bool.TryParse(val, out boolVal); return boolVal; } } else if (string.Equals(param.DataType, "choice", StringComparison.OrdinalIgnoreCase)) { if (TryResolveChoiceValue(literal, param, out string match)) { return match; } if (literal == null && param.Priority != TemplateParameterPriority.Required) { return param.DefaultValue; } string val; while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValid:" + string.Join(",", param.Choices.Keys), out val) && !TryResolveChoiceValue(literal, param, out val)) { } valueResolutionError = val == null; return val; } else if (string.Equals(param.DataType, "float", StringComparison.OrdinalIgnoreCase)) { if (double.TryParse(literal, out double convertedFloat)) { return convertedFloat; } else { string val; while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValidMustBeFloat", out val) && (val == null || !double.TryParse(val, out convertedFloat))) { } valueResolutionError = !double.TryParse(val, out convertedFloat); return convertedFloat; } } else if (string.Equals(param.DataType, "int", StringComparison.OrdinalIgnoreCase) || string.Equals(param.DataType, "integer", StringComparison.OrdinalIgnoreCase)) { if (long.TryParse(literal, out long convertedInt)) { return convertedInt; } else { string val; while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValidMustBeInteger", out val) && (val == null || !long.TryParse(val, out convertedInt))) { } valueResolutionError = !long.TryParse(val, out convertedInt); return convertedInt; } } else if (string.Equals(param.DataType, "hex", StringComparison.OrdinalIgnoreCase)) { if (long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long convertedHex)) { return convertedHex; } else { string val; while (environmentSettings.Host.OnParameterError(param, null, "ValueNotValidMustBeHex", out val) && (val == null || val.Length < 3 || !long.TryParse(val.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out convertedHex))) { } valueResolutionError = !long.TryParse(val.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out convertedHex); return convertedHex; } } else if (string.Equals(param.DataType, "text", StringComparison.OrdinalIgnoreCase) || string.Equals(param.DataType, "string", StringComparison.OrdinalIgnoreCase)) { // "text" is a valid data type, but doesn't need any special handling. return literal; } else { return literal; } } private static bool TryResolveChoiceValue(string literal, ITemplateParameter param, out string match) { if (literal == null) { match = null; return false; } string partialMatch = null; foreach (string choiceValue in param.Choices.Keys) { if (string.Equals(choiceValue, literal, StringComparison.OrdinalIgnoreCase)) { // exact match is good, regardless of partial matches match = choiceValue; return true; } else if (choiceValue.StartsWith(literal, StringComparison.OrdinalIgnoreCase)) { if (partialMatch == null) { partialMatch = choiceValue; } else { // multiple partial matches, can't take one. match = null; return false; } } } match = partialMatch; return match != null; } internal static object InferTypeAndConvertLiteral(string literal) { if (literal == null) { return null; } if (!literal.Contains("\"")) { if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase)) { return true; } if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase)) { return false; } if (string.Equals(literal, "null", StringComparison.OrdinalIgnoreCase)) { return null; } if (literal.Contains(".") && double.TryParse(literal, out double literalDouble)) { return literalDouble; } if (long.TryParse(literal, out long literalLong)) { return literalLong; } if (literal.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out literalLong)) { return literalLong; } } return literal; } public ICreationEffects GetCreationEffects(IEngineEnvironmentSettings environmentSettings, ITemplate templateData, IParameterSet parameters, IComponentManager componentManager, string targetDirectory) { RunnableProjectTemplate template = (RunnableProjectTemplate)templateData; ProcessMacros(environmentSettings, componentManager, template.Config.OperationConfig, parameters); IVariableCollection variables = VariableCollection.SetupVariables(environmentSettings, parameters, template.Config.OperationConfig.VariableSetup); template.Config.Evaluate(parameters, variables, template.ConfigFile); IOrchestrator2 basicOrchestrator = new Core.Util.Orchestrator(); RunnableProjectOrchestrator orchestrator = new RunnableProjectOrchestrator(basicOrchestrator); GlobalRunSpec runSpec = new GlobalRunSpec(template.TemplateSourceRoot, componentManager, parameters, variables, template.Config.OperationConfig, template.Config.SpecialOperationConfig, template.Config.LocalizationOperations, template.Config.IgnoreFileNames); List<IFileChange2> changes = new List<IFileChange2>(); foreach (FileSourceMatchInfo source in template.Config.Sources) { runSpec.SetupFileSource(source); string target = Path.Combine(targetDirectory, source.Target); changes.AddRange(orchestrator.GetFileChanges(runSpec, template.TemplateSourceRoot.DirectoryInfo(source.Source), target)); } return new CreationEffects2 { FileChanges = changes, CreationResult = GetCreationResult(environmentSettings, template, variables) }; } internal class ParameterSet : IParameterSet { private readonly IDictionary<string, ITemplateParameter> _parameters = new Dictionary<string, ITemplateParameter>(StringComparer.OrdinalIgnoreCase); public ParameterSet(IRunnableProjectConfig config) { foreach (KeyValuePair<string, Parameter> p in config.Parameters) { p.Value.Name = p.Key; _parameters[p.Key] = p.Value; } } public IEnumerable<ITemplateParameter> ParameterDefinitions => _parameters.Values; public IDictionary<ITemplateParameter, object> ResolvedValues { get; } = new Dictionary<ITemplateParameter, object>(); public IEnumerable<string> RequiredBrokerCapabilities => Enumerable.Empty<string>(); public void AddParameter(ITemplateParameter param) { _parameters[param.Name] = param; } public bool TryGetParameterDefinition(string name, out ITemplateParameter parameter) { if (_parameters.TryGetValue(name, out parameter)) { return true; } parameter = new Parameter { Name = name, Requirement = TemplateParameterPriority.Optional, IsVariable = true, Type = "string" }; return true; } } } }
// 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 gagvr = Google.Ads.GoogleAds.V10.Resources; 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.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="AccountLinkServiceClient"/> instances.</summary> public sealed partial class AccountLinkServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AccountLinkServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AccountLinkServiceSettings"/>.</returns> public static AccountLinkServiceSettings GetDefault() => new AccountLinkServiceSettings(); /// <summary>Constructs a new <see cref="AccountLinkServiceSettings"/> object with default settings.</summary> public AccountLinkServiceSettings() { } private AccountLinkServiceSettings(AccountLinkServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CreateAccountLinkSettings = existing.CreateAccountLinkSettings; MutateAccountLinkSettings = existing.MutateAccountLinkSettings; OnCopy(existing); } partial void OnCopy(AccountLinkServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AccountLinkServiceClient.CreateAccountLink</c> and <c>AccountLinkServiceClient.CreateAccountLinkAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 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: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateAccountLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AccountLinkServiceClient.MutateAccountLink</c> and <c>AccountLinkServiceClient.MutateAccountLinkAsync</c> /// . /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 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: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAccountLinkSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AccountLinkServiceSettings"/> object.</returns> public AccountLinkServiceSettings Clone() => new AccountLinkServiceSettings(this); } /// <summary> /// Builder class for <see cref="AccountLinkServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AccountLinkServiceClientBuilder : gaxgrpc::ClientBuilderBase<AccountLinkServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AccountLinkServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AccountLinkServiceClientBuilder() { UseJwtAccessWithScopes = AccountLinkServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AccountLinkServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AccountLinkServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AccountLinkServiceClient Build() { AccountLinkServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AccountLinkServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AccountLinkServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AccountLinkServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AccountLinkServiceClient.Create(callInvoker, Settings); } private async stt::Task<AccountLinkServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AccountLinkServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AccountLinkServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AccountLinkServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AccountLinkServiceClient.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>AccountLinkService client wrapper, for convenient use.</summary> /// <remarks> /// This service allows management of links between Google Ads accounts and other /// accounts. /// </remarks> public abstract partial class AccountLinkServiceClient { /// <summary> /// The default endpoint for the AccountLinkService service, which is a host of "googleads.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AccountLinkService scopes.</summary> /// <remarks> /// The default AccountLinkService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); 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="AccountLinkServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="AccountLinkServiceClientBuilder"/> /// . /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AccountLinkServiceClient"/>.</returns> public static stt::Task<AccountLinkServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AccountLinkServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AccountLinkServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="AccountLinkServiceClientBuilder"/> /// . /// </summary> /// <returns>The created <see cref="AccountLinkServiceClient"/>.</returns> public static AccountLinkServiceClient Create() => new AccountLinkServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AccountLinkServiceClient"/> 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="AccountLinkServiceSettings"/>.</param> /// <returns>The created <see cref="AccountLinkServiceClient"/>.</returns> internal static AccountLinkServiceClient Create(grpccore::CallInvoker callInvoker, AccountLinkServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AccountLinkService.AccountLinkServiceClient grpcClient = new AccountLinkService.AccountLinkServiceClient(callInvoker); return new AccountLinkServiceClientImpl(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 AccountLinkService client</summary> public virtual AccountLinkService.AccountLinkServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </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 CreateAccountLinkResponse CreateAccountLink(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, st::CancellationToken cancellationToken) => CreateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer for which the account link is created. /// </param> /// <param name="accountLink"> /// Required. The account link to be created. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual CreateAccountLinkResponse CreateAccountLink(string customerId, gagvr::AccountLink accountLink, gaxgrpc::CallSettings callSettings = null) => CreateAccountLink(new CreateAccountLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), AccountLink = gax::GaxPreconditions.CheckNotNull(accountLink, nameof(accountLink)), }, callSettings); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer for which the account link is created. /// </param> /// <param name="accountLink"> /// Required. The account link to be created. /// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(string customerId, gagvr::AccountLink accountLink, gaxgrpc::CallSettings callSettings = null) => CreateAccountLinkAsync(new CreateAccountLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), AccountLink = gax::GaxPreconditions.CheckNotNull(accountLink, nameof(accountLink)), }, callSettings); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer for which the account link is created. /// </param> /// <param name="accountLink"> /// Required. The account link to be created. /// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(string customerId, gagvr::AccountLink accountLink, st::CancellationToken cancellationToken) => CreateAccountLinkAsync(customerId, accountLink, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </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 MutateAccountLinkResponse MutateAccountLink(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, st::CancellationToken cancellationToken) => MutateAccountLinkAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer being modified. /// </param> /// <param name="operation"> /// Required. The operation to perform on the link. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAccountLinkResponse MutateAccountLink(string customerId, AccountLinkOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateAccountLink(new MutateAccountLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer being modified. /// </param> /// <param name="operation"> /// Required. The operation to perform on the link. /// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(string customerId, AccountLinkOperation operation, gaxgrpc::CallSettings callSettings = null) => MutateAccountLinkAsync(new MutateAccountLinkRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operation = gax::GaxPreconditions.CheckNotNull(operation, nameof(operation)), }, callSettings); /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer being modified. /// </param> /// <param name="operation"> /// Required. The operation to perform on the link. /// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(string customerId, AccountLinkOperation operation, st::CancellationToken cancellationToken) => MutateAccountLinkAsync(customerId, operation, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AccountLinkService client wrapper implementation, for convenient use.</summary> /// <remarks> /// This service allows management of links between Google Ads accounts and other /// accounts. /// </remarks> public sealed partial class AccountLinkServiceClientImpl : AccountLinkServiceClient { private readonly gaxgrpc::ApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse> _callCreateAccountLink; private readonly gaxgrpc::ApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse> _callMutateAccountLink; /// <summary> /// Constructs a client wrapper for the AccountLinkService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="AccountLinkServiceSettings"/> used within this client.</param> public AccountLinkServiceClientImpl(AccountLinkService.AccountLinkServiceClient grpcClient, AccountLinkServiceSettings settings) { GrpcClient = grpcClient; AccountLinkServiceSettings effectiveSettings = settings ?? AccountLinkServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callCreateAccountLink = clientHelper.BuildApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse>(grpcClient.CreateAccountLinkAsync, grpcClient.CreateAccountLink, effectiveSettings.CreateAccountLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callCreateAccountLink); Modify_CreateAccountLinkApiCall(ref _callCreateAccountLink); _callMutateAccountLink = clientHelper.BuildApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse>(grpcClient.MutateAccountLinkAsync, grpcClient.MutateAccountLink, effectiveSettings.MutateAccountLinkSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAccountLink); Modify_MutateAccountLinkApiCall(ref _callMutateAccountLink); 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_CreateAccountLinkApiCall(ref gaxgrpc::ApiCall<CreateAccountLinkRequest, CreateAccountLinkResponse> call); partial void Modify_MutateAccountLinkApiCall(ref gaxgrpc::ApiCall<MutateAccountLinkRequest, MutateAccountLinkResponse> call); partial void OnConstruction(AccountLinkService.AccountLinkServiceClient grpcClient, AccountLinkServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AccountLinkService client</summary> public override AccountLinkService.AccountLinkServiceClient GrpcClient { get; } partial void Modify_CreateAccountLinkRequest(ref CreateAccountLinkRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateAccountLinkRequest(ref MutateAccountLinkRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </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 CreateAccountLinkResponse CreateAccountLink(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateAccountLinkRequest(ref request, ref callSettings); return _callCreateAccountLink.Sync(request, callSettings); } /// <summary> /// Creates an account link. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// [ThirdPartyAppAnalyticsLinkError]() /// </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<CreateAccountLinkResponse> CreateAccountLinkAsync(CreateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateAccountLinkRequest(ref request, ref callSettings); return _callCreateAccountLink.Async(request, callSettings); } /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </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 MutateAccountLinkResponse MutateAccountLink(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAccountLinkRequest(ref request, ref callSettings); return _callMutateAccountLink.Sync(request, callSettings); } /// <summary> /// Creates or removes an account link. /// From V5, create is not supported through /// AccountLinkService.MutateAccountLink. Please use /// AccountLinkService.CreateAccountLink instead. /// /// List of thrown errors: /// [AccountLinkError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldMaskError]() /// [HeaderError]() /// [InternalError]() /// [MutateError]() /// [QuotaError]() /// [RequestError]() /// </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<MutateAccountLinkResponse> MutateAccountLinkAsync(MutateAccountLinkRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAccountLinkRequest(ref request, ref callSettings); return _callMutateAccountLink.Async(request, callSettings); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.Protocols.TestTools; using Microsoft.Modeling; namespace Microsoft.Protocols.TestSuites.FileSharing.FSA.Adapter { internal static class SMB2_TDIWorkaround { internal static MessageStatus WorkaroundFsCtlSetZeroData(BufferSize bufferSize, InputBuffer_FSCTL_SET_ZERO_DATA inputBuffer, bool isIsDeletedTrue, bool isConflictDetected, MessageStatus returnedStatus, ITestSite site) { if (isIsDeletedTrue && bufferSize == BufferSize.BufferSizeSuccess && (inputBuffer == InputBuffer_FSCTL_SET_ZERO_DATA.BufferSuccess || inputBuffer == InputBuffer_FSCTL_SET_ZERO_DATA.FileOffsetGreatThanBeyondFinalZero) ) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1309, MessageStatus.FILE_DELETED, returnedStatus, site); } else if (isConflictDetected && bufferSize == BufferSize.BufferSizeSuccess && (inputBuffer == InputBuffer_FSCTL_SET_ZERO_DATA.BufferSuccess || inputBuffer == InputBuffer_FSCTL_SET_ZERO_DATA.FileOffsetGreatThanBeyondFinalZero)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1316, MessageStatus.FILE_LOCK_CONFLICT, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundSetFileRenameInfo(InputBufferFileNameLength inputBufferFileNameLength, MessageStatus returnedStatus, ITestSite site) { if (inputBufferFileNameLength == InputBufferFileNameLength.Greater) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3025, MessageStatus.MEDIA_WRITE_PROTECTED, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundQueryFileInfoPart1(FileSystem fileSystem, FileInfoClass fileInfoClass, OutputBufferSize outputBufferSize, ref ByteCount byteCount, ref OutputBuffer outputBuffer, MessageStatus returnedStatus, ITestSite site) { if (fileInfoClass == FileInfoClass.NOT_DEFINED_IN_FSCC || fileInfoClass == FileInfoClass.FILE_BOTH_DIR_INFORMATION || fileInfoClass == FileInfoClass.FILE_DIRECTORY_INFORMATION || fileInfoClass == FileInfoClass.FILE_FULL_DIR_INFORMATIO || fileInfoClass == FileInfoClass.FILE_LINKS_INFORMATION || fileInfoClass == FileInfoClass.FILE_ID_BOTH_DIR_INFORMATION || fileInfoClass == FileInfoClass.FILE_ID_FULL_DIR_INFORMATION || fileInfoClass == FileInfoClass.FILE_ID_GLOBAL_TX_DIR_INFORMATION || fileInfoClass == FileInfoClass.FILE_NAME_INFORMATION || fileInfoClass == FileInfoClass.FILE_NAMES_INFORMATION || fileInfoClass == FileInfoClass.FILE_OBJECTID_INFORMATION || fileInfoClass == FileInfoClass.FILE_QUOTA_INFORMATION || fileInfoClass == FileInfoClass.FILE_REPARSE_POINT_INFORMATION || fileInfoClass == FileInfoClass.FILE_SFIO_RESERVE_INFORMATION || fileInfoClass == FileInfoClass.FILE_STANDARD_LINK_INFORMATION) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2749, MessageStatus.INVALID_INFO_CLASS, returnedStatus, site); } else if (fileInfoClass == FileInfoClass.FILE_ACCESS_INFORMATION && outputBufferSize == OutputBufferSize.NotLessThan) { outputBuffer = FsaUtility.TransferExpectedResult<OutputBuffer>(1421, new OutputBuffer(), outputBuffer, site); } else if (fileInfoClass == FileInfoClass.FILE_FULLEA_INFORMATION && outputBufferSize == OutputBufferSize.LessThan) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3994, MessageStatus.BUFFER_TOO_SMALL, returnedStatus, site); } else if (fileInfoClass == FileInfoClass.FILE_FULLEA_INFORMATION && returnedStatus == MessageStatus.NO_EAS_ON_FILE) { // For query FILE_FULLEA_INFORMATION, when server returns STATUS_NO_EAS_ON_FILE, this result is valid according to model design. // Transfer the return code and byteCount to make model test cases passed. byteCount = FsaUtility.TransferExpectedResult<ByteCount>(3992, ByteCount.SizeofFILE_FULL_EA_INFORMATION, byteCount, site); returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1187, MessageStatus.SUCCESS, returnedStatus, site); } else if (fileInfoClass == FileInfoClass.FILE_FULLEA_INFORMATION && fileSystem == FileSystem.REFS && outputBufferSize == OutputBufferSize.NotLessThan) { // REFS file system does not support FILE_FULLEA_INFORMATION, will failed with STATUS_INVALID_DEVICE_REQUEST // Transfer the return code and byteCount to make model test cases passed. byteCount = FsaUtility.TransferExpectedResult<ByteCount>(3992, ByteCount.SizeofFILE_FULL_EA_INFORMATION, byteCount, site); returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1187, MessageStatus.SUCCESS, returnedStatus, site); } else if (fileInfoClass == FileInfoClass.FILE_ALTERNATENAME_INFORMATION && fileSystem == FileSystem.REFS && outputBufferSize == OutputBufferSize.NotLessThan) { // REFS file system does not support FILE_ALTERNATENAME_INFORMATION, will failed with STATUS_OBJECT_NAME_NOT_FOUND // Transfer the return code and byteCount to make model test cases passed. byteCount = FsaUtility.TransferExpectedResult<ByteCount>(3992, ByteCount.FieldOffsetFILE_NAME_INFORMATION_FileNameAddOutputBuffer_FileNameLength, byteCount, site); returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1187, MessageStatus.SUCCESS, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlSetObjID(FsControlRequestType requestType, BufferSize bufferSize, MessageStatus returnedStatus, ITestSite site) { if (returnedStatus != MessageStatus.INVALID_DEVICE_REQUEST) { if (requestType == FsControlRequestType.SET_OBJECT_ID_EXTENDED && bufferSize == BufferSize.NotEqualFILE_OBJECTID_BUFFER) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1206, MessageStatus.SUCCESS, returnedStatus, site); } else if ((requestType == FsControlRequestType.SET_OBJECT_ID || requestType == FsControlRequestType.SET_OBJECT_ID_EXTENDED) && bufferSize == BufferSize.BufferSizeSuccess) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1187, MessageStatus.SUCCESS, returnedStatus, site); } } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlForEasyRequest(FileSystem fileSystem, FsControlRequestType requestType, BufferSize bufferSize, bool fileVolReadOnly, bool fileVolUsnAct, ref bool isBytesReturnedSet, ref bool isOutputBufferSizeReturn, MessageStatus returnedStatus, ITestSite site) { if (requestType == FsControlRequestType.RECALL_FILE) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1136, MessageStatus.SUCCESS, returnedStatus, site); } else if (requestType == FsControlRequestType.FSCTL_SET_SHORT_NAME_BEHAVIOR) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1274, MessageStatus.INVALID_DEVICE_REQUEST, returnedStatus, site); } else if (requestType == FsControlRequestType.WRITE_USN_CLOSE_RECORD && bufferSize == BufferSize.LessThanTwoBytes && !fileVolReadOnly && fileVolUsnAct) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(3966, true, isBytesReturnedSet, site); } else if (requestType == FsControlRequestType.SET_ZERO_ON_DEALLOCATION && bufferSize == BufferSize.LessThanSizeofUsn) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(1388, false, isBytesReturnedSet, site); } else if (requestType == FsControlRequestType.SET_OBJECT_ID && bufferSize == BufferSize.LessThan0x24 && !fileVolReadOnly && !fileVolUsnAct) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(1068, true, isBytesReturnedSet, site); } else if (requestType == FsControlRequestType.QUERY_FAT_BPB && bufferSize == BufferSize.LessThanTotalSizeOfStatistics) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(1121, true, isBytesReturnedSet, site); } else if (requestType == FsControlRequestType.QUERY_ON_DISK_VOLUME_INFO && bufferSize == BufferSize.LessThanFILE_QUERY_SPARING_BUFFER && fileVolReadOnly && fileVolUsnAct) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(5522, true, isBytesReturnedSet, site); } else if (requestType == FsControlRequestType.WRITE_USN_CLOSE_RECORD && returnedStatus == MessageStatus.JOURNAL_NOT_ACTIVE && fileSystem == FileSystem.NTFS) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1274, MessageStatus.SUCCESS, returnedStatus, site); isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(3966, true, isBytesReturnedSet, site); isOutputBufferSizeReturn = FsaUtility.TransferExpectedResult<bool>(3966, true, isOutputBufferSizeReturn, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsctlSisCopy(BufferSize bufferSize, InputBufferFSCTL_SIS_COPYFILE inputBuffer, bool isCOPYFILE_SIS_LINKTrue, bool isIsEncryptedTrue, MessageStatus returnedStatus, ITestSite site) { if (bufferSize == BufferSize.BufferSizeSuccess && inputBuffer == InputBufferFSCTL_SIS_COPYFILE.Initial && isCOPYFILE_SIS_LINKTrue == false && isIsEncryptedTrue == false) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(4773, MessageStatus.SUCCESS, returnedStatus, site); } else if ((bufferSize == BufferSize.LessThanSI_COPYFILE) || (inputBuffer == InputBufferFSCTL_SIS_COPYFILE.FlagsNotContainCOPYFILE_SIS_LINKAndCOPYFILE_SIS_REPLACE) || (inputBuffer == InputBufferFSCTL_SIS_COPYFILE.DestinationFileNameLengthLessThanZero) || (inputBuffer == InputBufferFSCTL_SIS_COPYFILE.DestinationFileNameLengthLargeThanMAXUSHORT) || (inputBuffer == InputBufferFSCTL_SIS_COPYFILE.InputBufferSizeLessThanOtherPlus)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(4734, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (isCOPYFILE_SIS_LINKTrue || isIsEncryptedTrue) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(4755, MessageStatus.OBJECT_TYPE_MISMATCH, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundSetFileShortNameInfo(InputBufferFileName inputBufferFileName, MessageStatus returnedstatus, ITestSite site) { if (inputBufferFileName == InputBufferFileName.StartWithBackSlash) { returnedstatus = FsaUtility.TransferExpectedResult<MessageStatus>(3173, MessageStatus.INVALID_PARAMETER, returnedstatus, site); } else if (inputBufferFileName == InputBufferFileName.NotValid) { returnedstatus = FsaUtility.TransferExpectedResult<MessageStatus>(3176, MessageStatus.INVALID_PARAMETER, returnedstatus, site); } else if (inputBufferFileName == InputBufferFileName.Empty) { returnedstatus = FsaUtility.TransferExpectedResult<MessageStatus>(3180, MessageStatus.ACCESS_DENIED, returnedstatus, site); } return returnedstatus; } internal static MessageStatus WorkaroundStreamRename(FileSystem fileSystem, InputBufferFileName NewStreamName, InputBufferFileName StreamTypeName, bool ReplaceIfExists, MessageStatus returnedStatus, ITestSite site) { if (fileSystem == FileSystem.REFS) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3146, MessageStatus.NOT_SUPPORTED, returnedStatus, site); } else if (NewStreamName == InputBufferFileName.ContainsWildcard) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3146, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundQueryDirectoryInfo(FileNamePattern fileNamePattern, bool isNoRecordsReturned, bool isOutBufferSizeLess, MessageStatus returnedStatus, ITestSite site) { if (isOutBufferSizeLess) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(4836, MessageStatus.INFO_LENGTH_MISMATCH, returnedStatus, site); } else if (fileNamePattern == FileNamePattern.NotValidFilenameComponent) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(849, MessageStatus.OBJECT_NAME_INVALID, returnedStatus, site); } else if (isNoRecordsReturned) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(865, MessageStatus.NO_SUCH_FILE, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundSetFileFullEaInfo(EainInputBuffer eAValidate, MessageStatus returnedStatus, ITestSite site) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2853, MessageStatus.SUCCESS, returnedStatus, site); if (eAValidate == EainInputBuffer.EaNameExistinOpenFileExtendedAttribute) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2853, MessageStatus.SUCCESS, returnedStatus, site); } else if (eAValidate == EainInputBuffer.EaNameNotWellForm || eAValidate == EainInputBuffer.EaFlagsInvalid) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2927, MessageStatus.INVALID_EA_NAME, returnedStatus, site); } return returnedStatus; } internal static bool WorkaroundFsCtlGetReparsePoint(BufferSize bufferSize, ReparseTag openFileReparseTag, bool isBytesReturnedSet, ref MessageStatus returnedStatus, ITestSite site) { if ((bufferSize == BufferSize.BufferSizeSuccess && openFileReparseTag == ReparseTag.NON_MICROSOFT_RANGE_TAG) || (bufferSize == BufferSize.LessThanREPARSE_DATA_BUFFER && openFileReparseTag == ReparseTag.NON_MICROSOFT_RANGE_TAG) || (bufferSize == BufferSize.BufferSizeSuccess && openFileReparseTag == ReparseTag.IO_REPARSE_TAG_RESERVED_ZERO)) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(1091, true, isBytesReturnedSet, site); if (returnedStatus == MessageStatus.NOT_A_REPARSE_POINT) { // If the open file is not a reparse point, SMB2 server will return STATUS_NOT_A_REPARSE_POINT // This is acceptable in model and expect as STATUS_SUCCESS. returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2853, MessageStatus.SUCCESS, returnedStatus, site); } } else if (openFileReparseTag == ReparseTag.EMPTY) { return isBytesReturnedSet; } else if (((openFileReparseTag != ReparseTag.NON_MICROSOFT_RANGE_TAG) && (BufferSize.LessThanREPARSE_DATA_BUFFER == bufferSize)) || ((openFileReparseTag == ReparseTag.NON_MICROSOFT_RANGE_TAG) && (BufferSize.LessThanREPARSE_GUID_DATA_BUFFER == bufferSize))) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1083, MessageStatus.BUFFER_TOO_SMALL, returnedStatus, site); } else if (bufferSize == BufferSize.LessThanREPARSE_GUID_DATA_BUFFER && openFileReparseTag == ReparseTag.IO_REPARSE_TAG_RESERVED_ZERO) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(1091, true, isBytesReturnedSet, site); } return isBytesReturnedSet; } internal static MessageStatus WorkaroundFsCtlSetReparsePoint(ReparseTag inputReparseTag, BufferSize bufferSize, bool isReparseGUIDNotEqual, bool isFileReparseTagNotEqualInputBufferReparseTag, MessageStatus returnedStatus, ITestSite site) { if ((inputReparseTag == ReparseTag.SYMLINK)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1231, MessageStatus.ACCESS_DENIED, returnedStatus, site); } else if (returnedStatus == MessageStatus.INVALID_PARAMETER) { if (inputReparseTag != ReparseTag.EMPTY) { if (isFileReparseTagNotEqualInputBufferReparseTag) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1237, MessageStatus.IO_REPARSE_TAG_MISMATCH, returnedStatus, site); } else if ((inputReparseTag == ReparseTag.NON_MICROSOFT_RANGE_TAG) && (!isReparseGUIDNotEqual)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1238, MessageStatus.REPARSE_ATTRIBUTE_CONFLICT, returnedStatus, site); } } else { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1246, MessageStatus.SUCCESS, returnedStatus, site); } } return returnedStatus; } internal static MessageStatus WorkaroundSetFileLinkInfo(bool inputNameInvalid, bool replaceIfExist, MessageStatus returnedStatus, ITestSite site) { if (inputNameInvalid == false && replaceIfExist == true) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2974, MessageStatus.SUCCESS, returnedStatus, site); } else if (inputNameInvalid) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2941, MessageStatus.OBJECT_NAME_INVALID, returnedStatus, site); } else if (!replaceIfExist) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2954, MessageStatus.OBJECT_NAME_COLLISION, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkAroundSetFilePositionInfo(InputBufferSize inputBufferSize, InputBufferCurrentByteOffset currentByteOffset, MessageStatus returnedStatus, ITestSite site) { if (inputBufferSize != InputBufferSize.LessThan && currentByteOffset == InputBufferCurrentByteOffset.NotValid) { // [MS-SMB2] Section 3.3.5.20.1 Handling SMB2_0_INFO_FILE // If the request is for the FilePositionInformation information class, the SMB2 server SHOULD (348) set the CurrentByteOffset field to zero. // (348) Section 3.3.5.20.1: Windows-based SMB2 servers will set CurrentByteOffset to any value. // Per tested with Win2012/Win2012R2 SMB2 server, they return STATUS_SUCCESS. // To keep same model behavior according to MS-FSA, transfer the error code to STATUS_INVALID_PARAMETER returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3004, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundCreateFile(FileNameStatus fileNameStatus, CreateOptions createOption, FileAccess desiredAccess, FileType openFileType, FileAttribute desiredFileAttribute, MessageStatus returnedStatus, ITestSite site) { if (openFileType == FileType.DirectoryFile && desiredFileAttribute == FileAttribute.TEMPORARY) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(507, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.SYNCHRONOUS_IO_ALERT && desiredAccess == FileAccess.FILE_READ_DATA) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(369, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.SYNCHRONOUS_IO_NONALERT && desiredAccess == FileAccess.FILE_READ_DATA) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2373, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.DELETE_ON_CLOSE && (desiredAccess == FileAccess.ACCESS_SYSTEM_SECURITY)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(371, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == (CreateOptions.SYNCHRONOUS_IO_NONALERT | CreateOptions.SYNCHRONOUS_IO_ALERT)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(373, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == (CreateOptions.COMPLETE_IF_OPLOCKED | CreateOptions.RESERVE_OPFILTER)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(375, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (fileNameStatus == FileNameStatus.StreamTypeNameIsINDEX_ALLOCATION) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(507, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.NO_INTERMEDIATE_BUFFERING && (desiredAccess == FileAccess.FILE_APPEND_DATA || desiredAccess == FileAccess.FILE_ADD_SUBDIRECTORY)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(376, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundOpenExistingFile(ShareAccess shareAccess, FileAccess desiredAccess, bool streamFound, bool isSymbolicLink, FileType openFileType, FileNameStatus fileNameStatus, CreateOptions existingOpenModeCreateOption, ShareAccess existOpenShareModeShareAccess, FileAccess existOpenDesiredAccess, CreateOptions createOption, CreateDisposition createDisposition, StreamTypeNameToOPen streamTypeNameToOPen, FileAttribute fileAttribute, FileAttribute desiredFileAttribute, MessageStatus returnedStatus, ITestSite site) { if (shareAccess == ShareAccess.FILE_SHARE_READ && desiredAccess == FileAccess.FILE_ADD_SUBDIRECTORY && !streamFound && !isSymbolicLink && openFileType == FileType.DataFile && fileNameStatus == FileNameStatus.Normal && existingOpenModeCreateOption == CreateOptions.NON_DIRECTORY_FILE && existOpenShareModeShareAccess == ShareAccess.FILE_SHARE_READ && existOpenDesiredAccess == FileAccess.FILE_LIST_DIRECTORY && createOption == CreateOptions.NO_INTERMEDIATE_BUFFERING && createDisposition == CreateDisposition.OPEN_IF && streamTypeNameToOPen == StreamTypeNameToOPen.NULL && fileAttribute == FileAttribute.NORMAL && desiredFileAttribute == FileAttribute.NORMAL) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(376, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == (CreateOptions.SYNCHRONOUS_IO_NONALERT | CreateOptions.SYNCHRONOUS_IO_ALERT)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(373, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.SYNCHRONOUS_IO_ALERT && desiredAccess == FileAccess.FILE_READ_DATA) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(369, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.SYNCHRONOUS_IO_NONALERT && desiredAccess == FileAccess.FILE_READ_DATA) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2373, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == CreateOptions.DELETE_ON_CLOSE && (desiredAccess == FileAccess.ACCESS_SYSTEM_SECURITY)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(371, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (createOption == (CreateOptions.COMPLETE_IF_OPLOCKED | CreateOptions.RESERVE_OPFILTER)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(375, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (streamFound && !isSymbolicLink && openFileType == FileType.DataFile && existingOpenModeCreateOption == CreateOptions.DIRECTORY_FILE && existOpenDesiredAccess == FileAccess.FILE_LIST_DIRECTORY && createOption == CreateOptions.DIRECTORY_FILE) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(375, MessageStatus.ACCESS_VIOLATION, returnedStatus, site); } else if (!streamFound && !isSymbolicLink && openFileType == FileType.DataFile && existingOpenModeCreateOption == CreateOptions.NON_DIRECTORY_FILE && existOpenDesiredAccess == FileAccess.FILE_LIST_DIRECTORY && createOption == CreateOptions.NON_DIRECTORY_FILE && fileAttribute == FileAttribute.READONLY) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(375, MessageStatus.ACCESS_DENIED, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundQueryFileObjectIdInfo(bool isObjectIDsSupported, FileNamePattern fileNamePattern, bool restartScan, bool isDirectoryNotRight, bool isOutPutBufferNotEnough, MessageStatus returnedStatus, ITestSite site) { if (!isObjectIDsSupported) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.INVALID_DEVICE_REQUEST, returnedStatus, site); } else if (fileNamePattern != FileNamePattern.NotEmpty_LengthIsNotAMultipleOf4 && restartScan && !isDirectoryNotRight && !isOutPutBufferNotEnough) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.SUCCESS, returnedStatus, site); } else if ((!restartScan) && (fileNamePattern == FileNamePattern.Empty) && (isDirectoryNotRight)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.NO_MORE_FILES, returnedStatus, site); } else if ((fileNamePattern == FileNamePattern.NotEmpty_LengthIsNotAMultipleOf4) && (isDirectoryNotRight) && (!isOutPutBufferNotEnough)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } // EmptyPattern is FALSE and there is no match. else if ((!(fileNamePattern == FileNamePattern.Empty)) && (isDirectoryNotRight)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.NO_SUCH_FILE, returnedStatus, site); } // EmptyPattern is true and RestartScan is false and there is no match and output Buffer is not enough. else if ((fileNamePattern == FileNamePattern.Empty) && (!restartScan) && (!isDirectoryNotRight) && (!isOutPutBufferNotEnough)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.SUCCESS, returnedStatus, site); } // EmptyPattern is true and RestartScan is true and there is no match. else if ((fileNamePattern == FileNamePattern.Empty) && (restartScan) && (isDirectoryNotRight) && (!isOutPutBufferNotEnough)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.NO_SUCH_FILE, returnedStatus, site); } else if (isOutPutBufferNotEnough) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.INFO_LENGTH_MISMATCH, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundQueryFileReparsePointInfo(FileSystem fileSystem, FileNamePattern fileNamePattern, bool restartScan, bool isDirectoryNotRight, bool isOutPutBufferNotEnough, MessageStatus returnedStatus, ITestSite site) { bool EmptyPattern = false; if (fileNamePattern == FileNamePattern.Empty) { EmptyPattern = true; } else { EmptyPattern = false; } if (fileSystem == FileSystem.REFS) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.INVALID_DEVICE_REQUEST, returnedStatus, site); } else if (fileNamePattern == FileNamePattern.NotEmpty_LengthIsNotAMultipleOf4) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (!restartScan && EmptyPattern && isDirectoryNotRight) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.NO_MORE_FILES, returnedStatus, site); } else if ((!EmptyPattern && isDirectoryNotRight) || (EmptyPattern && restartScan && isDirectoryNotRight)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.NO_SUCH_FILE, returnedStatus, site); } else if (isOutPutBufferNotEnough) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.INFO_LENGTH_MISMATCH, returnedStatus, site); } //If there is at least one match, the operation is considered successful else if (!isDirectoryNotRight) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(830, MessageStatus.SUCCESS, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlDeleteReparsePoint(ReparseTag reparseTag, bool reparseGuidEqualOpenGuid, MessageStatus returnedStatus, ITestSite site) { if (reparseTag == ReparseTag.EMPTY && reparseGuidEqualOpenGuid) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(5001, MessageStatus.SUCCESS, returnedStatus, site); } else if (reparseTag == ReparseTag.IO_REPARSE_TAG_RESERVED_ONE || reparseTag == ReparseTag.IO_REPARSE_TAG_RESERVED_ZERO) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2437, MessageStatus.IO_REPARSE_TAG_INVALID, returnedStatus, site); } else if ((reparseTag == ReparseTag.NON_MICROSOFT_RANGE_TAG) && (!reparseGuidEqualOpenGuid)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(990, MessageStatus.REPARSE_ATTRIBUTE_CONFLICT, returnedStatus, site); } else if (reparseTag == ReparseTag.NON_MICROSOFT_RANGE_TAG && reparseGuidEqualOpenGuid) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1257, MessageStatus.IO_REPARSE_DATA_INVALID, returnedStatus, site); } else if (reparseTag == ReparseTag.NotEqualOpenFileReparseTag) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(989, MessageStatus.IO_REPARSE_TAG_MISMATCH, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlGetRetrivalPoints(BufferSize bufferSize, bool isStartingVcnNegative, bool isStartingVcnGreatThanAllocationSize, bool isElementsNotAllCopied, ref bool isBytesReturnedSet, MessageStatus returnedStatus, ITestSite site) { if (bufferSize == BufferSize.LessThanSTARTING_VCN_INPUT_BUFFER || (isStartingVcnNegative && !isStartingVcnGreatThanAllocationSize)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1103, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (bufferSize == BufferSize.BufferSizeSuccess && !isStartingVcnNegative && !isStartingVcnGreatThanAllocationSize && !isElementsNotAllCopied) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(5041, MessageStatus.SUCCESS, returnedStatus, site); isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(1112, true, isBytesReturnedSet, site); } return returnedStatus; } internal static MessageStatus WorkaroundQuerySecurityInfo(bool isByteCountGreater, MessageStatus returnedStatus, ITestSite site) { if (isByteCountGreater && returnedStatus == MessageStatus.BUFFER_TOO_SMALL) { // TD description: // [MS-SMB2] 3.3.5.20.3 Handling SMB2_0_INFO_SECURITY // If the OutputBufferLength given in the client request is either zero or is insufficient to hold the information requested, // the server MUST fail the request with STATUS_BUFFER_TOO_SMALL. // Note: // SMB2 server responses with STATUS_BUFFER_TOO_SMALL instead of STATUS_BUFFER_OVERFLOW // To keep same model behavior, transfer the error code to STATUS_BUFFER_OVERFLOW. returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2799, MessageStatus.BUFFER_OVERFLOW, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlQueryAllocatedRanges(BufferSize bufferSize, MessageStatus returnedStatus, ref bool isBytesReturnedSet, ITestSite site) { if (bufferSize == BufferSize.OutLessThanFILE_ALLOCATED_RANGE_BUFFER) { isBytesReturnedSet = FsaUtility.TransferExpectedResult<bool>(3778, false, isBytesReturnedSet, site); returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3778, MessageStatus.BUFFER_TOO_SMALL, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundSetSecurityInfo(SecurityInformation securityInformation, OwnerSid ownerSidEnum, MessageStatus returnedStatus, ITestSite site) { if (((securityInformation == SecurityInformation.OWNER_SECURITY_INFORMATION || securityInformation == SecurityInformation.GROUP_SECURITY_INFORMATION || securityInformation == SecurityInformation.LABEL_SECURITY_INFORMATION)) || (securityInformation == SecurityInformation.DACL_SECURITY_INFORMATION) || (securityInformation == SecurityInformation.SACL_SECURITY_INFORMATION)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3239, MessageStatus.ACCESS_DENIED, returnedStatus, site); } else if ((securityInformation == SecurityInformation.OWNER_SECURITY_INFORMATION && ownerSidEnum == OwnerSid.InputBufferOwnerSidNotPresent) || (securityInformation == SecurityInformation.OWNER_SECURITY_INFORMATION && ownerSidEnum == OwnerSid.InputBufferOwnerSidNotValid) || (securityInformation != SecurityInformation.OWNER_SECURITY_INFORMATION && ownerSidEnum == OwnerSid.OpenFileSecDesOwnerIsNull)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3239, MessageStatus.INVALID_OWNER, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlReadFileUSNData(BufferSize bufferSize, MessageStatus returnedStatus, ITestSite site) { if (bufferSize == BufferSize.LessThanRecordLength) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3873, MessageStatus.INFO_LENGTH_MISMATCH, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundFsCtlSetEncrypion(bool isIsCompressedTrue, EncryptionOperation encryptionOpteration, BufferSize bufferSize, MessageStatus returnedStatus, ITestSite site) { if (bufferSize == BufferSize.LessThanENCRYPTION_BUFFER) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3899, MessageStatus.BUFFER_TOO_SMALL, returnedStatus, site); } else if ((encryptionOpteration == EncryptionOperation.NOT_VALID_IN_FSCC) || ((encryptionOpteration == EncryptionOperation.STREAM_SET_ENCRYPTION) && isIsCompressedTrue)) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3900, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if (!isIsCompressedTrue && encryptionOpteration == EncryptionOperation.STREAM_SET_ENCRYPTION && bufferSize == BufferSize.BufferSizeSuccess) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(3919, MessageStatus.SUCCESS, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundWriteFile(long byteOffset, bool isOpenVolumeReadOnly, long byteCount, ref long bytesWritten, MessageStatus returnedStatus, ITestSite site) { if (byteOffset == -2 && !isOpenVolumeReadOnly && byteCount == 2) { bytesWritten = FsaUtility.TransferExpectedResult<long>(742, 2, bytesWritten, site); returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(715, MessageStatus.SUCCESS, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkaroundChangeNotificationForDir(bool allEntriesFitBufSize, MessageStatus returnedStatus, ITestSite site) { if (!allEntriesFitBufSize) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1399, MessageStatus.NOTIFY_ENUM_DIR, returnedStatus, site); } else if (allEntriesFitBufSize) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(1399, MessageStatus.SUCCESS, returnedStatus, site); } return returnedStatus; } internal static MessageStatus WorkAroundQueryFileSystemInfo(FileSystemInfoClass fileInfoClass, OutputBufferSize outBufSmall, MessageStatus returnedStatus, ref FsInfoByteCount byteCount, ITestSite site) { if (fileInfoClass == FileSystemInfoClass.File_FsObjectId_Information && returnedStatus == MessageStatus.OBJECT_NAME_NOT_FOUND) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(2674, MessageStatus.SUCCESS, returnedStatus, site); byteCount = FsInfoByteCount.SizeOf_FILE_FS_OBJECTID_INFORMATION; } return returnedStatus; } internal static MessageStatus WorkaroundReadFile(CreateOptions gOpenMode, long byteCount, MessageStatus returnedStatus, ITestSite site) { long gOpenFileVolumeSize = long.Parse(site.Properties["FSA.OpenFileVolumeSize"]); if ((byteCount % gOpenFileVolumeSize) != 0) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(669, MessageStatus.INVALID_PARAMETER, returnedStatus, site); } else if ((gOpenMode & CreateOptions.NO_INTERMEDIATE_BUFFERING) != 0) { returnedStatus = FsaUtility.TransferExpectedResult<MessageStatus>(693, MessageStatus.SUCCESS, returnedStatus, site); } return returnedStatus; } internal static long WorkaroundReadFileForByteRead(CreateOptions gOpenMode, long byteCount, long readCount, ITestSite site) { if ((gOpenMode & CreateOptions.NO_INTERMEDIATE_BUFFERING) != 0) { readCount = FsaUtility.TransferExpectedResult<long>(692, byteCount, readCount, site); } return readCount; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDate { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Date operations. /// </summary> public partial class Date : IServiceOperations<AutoRestDateTestService>, IDate { /// <summary> /// Initializes a new instance of the Date class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Date(AutoRestDateTestService client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestDateTestService /// </summary> public AutoRestDateTestService Client { get; private set; } /// <summary> /// Get null date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/null").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DateTime?>> GetInvalidDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalidDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/invaliddate").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get overflow date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DateTime?>> GetOverflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOverflowDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/overflowdate").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get underflow date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DateTime?>> GetUnderflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='dateBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMaxDateWithHttpMessagesAsync(DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dateBody", dateBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMaxDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DateTime?>> GetMaxDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMaxDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='dateBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMinDateWithHttpMessagesAsync(DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dateBody", dateBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMinDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<DateTime?>> GetMinDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMinDate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Linq; using System.Collections.Generic; using NLog.MessageTemplates; using Xunit; namespace NLog.UnitTests.Internal { public class PropertiesDictionaryTests : NLogTestBase { [Fact] public void DefaultPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.DoesNotContain("Hello World", dictionary); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(new KeyValuePair<object, object>[0], 0); dictionary.Values.CopyTo(new object[0], 0); dictionary.Keys.CopyTo(new object[0], 0); dictionary.Clear(); } [Fact] public void EmptyEventPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(); IDictionary<object, object> dictionary = logEvent.Properties; dictionary.Add("Hello World", 42); Assert.True(dictionary.Remove("Hello World")); Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.DoesNotContain("Hello World", dictionary); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(new KeyValuePair<object, object>[0], 0); dictionary.Values.CopyTo(new object[0], 0); dictionary.Keys.CopyTo(new object[0], 0); dictionary.Clear(); } [Fact] public void EmptyMessagePropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, (IList<MessageTemplateParameter>)null); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); Assert.DoesNotContain("Hello World", dictionary); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(new KeyValuePair<object, object>[0], 0); dictionary.Values.CopyTo(new object[0], 0); dictionary.Keys.CopyTo(new object[0], 0); dictionary.Clear(); } [Fact] public void EmptyPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, (IList<MessageTemplateParameter>)null); IDictionary<object, object> dictionary = logEvent.Properties; dictionary.Add("Hello World", null); Assert.True(dictionary.Remove("Hello World")); Assert.Empty(dictionary); foreach (var item in dictionary) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Keys) Assert.False(true, "Should be empty"); foreach (var item in dictionary.Values) Assert.False(true, "Should be empty"); Assert.False(dictionary.ContainsKey("Hello World")); Assert.False(dictionary.Keys.Contains("Hello World")); Assert.False(dictionary.Values.Contains(42)); Assert.DoesNotContain("Hello World", dictionary); object value; Assert.False(dictionary.TryGetValue("Hello World", out value)); Assert.Null(value); Assert.False(dictionary.Remove("Hello World")); dictionary.CopyTo(new KeyValuePair<object, object>[0], 0); dictionary.Values.CopyTo(new object[0], 0); dictionary.Keys.CopyTo(new object[0], 0); dictionary.Clear(); } [Fact] public void SingleItemEventPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(); IDictionary<object, object> dictionary = logEvent.Properties; dictionary.Add("Hello World", 42); Assert.Single(dictionary); foreach (var item in dictionary) { Assert.Equal("Hello World", item.Key); Assert.Equal(42, item.Value); } foreach (var item in dictionary.Keys) Assert.Equal("Hello World", item); foreach (var item in dictionary.Values) Assert.Equal(42, item); AssertContainsInDictionary(dictionary, "Hello World", 42); Assert.True(dictionary.ContainsKey("Hello World")); Assert.True(dictionary.Keys.Contains("Hello World")); Assert.True(dictionary.Values.Contains(42)); Assert.False(dictionary.ContainsKey("Goodbye World")); Assert.False(dictionary.Keys.Contains("Goodbye World")); Assert.DoesNotContain("Goodbye World", dictionary); object value; Assert.True(dictionary.TryGetValue("Hello World", out value)); Assert.Equal(42, value); Assert.False(dictionary.TryGetValue("Goodbye World", out value)); Assert.Null(value); var copyToArray = new KeyValuePair<object, object>[1]; dictionary.CopyTo(copyToArray, 0); Assert.Equal("Hello World", copyToArray[0].Key); Assert.Equal(42, copyToArray[0].Value); var copyToValuesArray = new object[1]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Equal(42, copyToValuesArray[0]); var copyToKeysArray = new object[1]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Equal("Hello World", copyToKeysArray[0]); Assert.True(dictionary.Remove("Hello World")); Assert.Empty(dictionary); dictionary["Hello World"] = 42; Assert.Single(dictionary); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void SingleItemMessagePropertiesDictionaryNoLookup() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Single(dictionary); foreach (var item in dictionary) { Assert.Equal("Hello World", item.Key); Assert.Equal(42, item.Value); } foreach (var item in dictionary.Keys) Assert.Equal("Hello World", item); foreach (var item in dictionary.Values) Assert.Equal(42, item); var copyToArray = new KeyValuePair<object, object>[1]; dictionary.CopyTo(copyToArray, 0); Assert.Equal("Hello World", copyToArray[0].Key); Assert.Equal(42, copyToArray[0].Value); var copyToValuesArray = new object[1]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Equal(42, copyToValuesArray[0]); var copyToKeysArray = new object[1]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Equal("Hello World", copyToKeysArray[0]); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void SingleItemMessagePropertiesDictionaryWithLookup() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Single(dictionary); AssertContainsInDictionary(dictionary, "Hello World", 42); Assert.True(dictionary.ContainsKey("Hello World")); Assert.True(dictionary.Keys.Contains("Hello World")); Assert.True(dictionary.Values.Contains(42)); Assert.False(dictionary.ContainsKey("Goodbye World")); Assert.False(dictionary.Keys.Contains("Goodbye World")); Assert.DoesNotContain("Goodbye World", dictionary); object value; Assert.True(dictionary.TryGetValue("Hello World", out value)); Assert.Equal(42, value); Assert.False(dictionary.TryGetValue("Goodbye World", out value)); Assert.Null(value); var copyToArray = new KeyValuePair<object, object>[1]; dictionary.CopyTo(copyToArray, 0); Assert.Equal("Hello World", copyToArray[0].Key); Assert.Equal(42, copyToArray[0].Value); var copyToValuesArray = new object[1]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Equal(42, copyToValuesArray[0]); var copyToKeysArray = new object[1]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Equal("Hello World", copyToKeysArray[0]); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void MultiItemPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; dictionary["Goodbye World"] = 666; Assert.Equal(2, dictionary.Count); int i = 0; foreach (var item in dictionary) { switch (i++) { case 0: Assert.Equal("Hello World", item.Key); Assert.Equal(42, item.Value); break; case 1: Assert.Equal("Goodbye World", item.Key); Assert.Equal(666, item.Value); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Keys) { switch (i++) { case 0: Assert.Equal("Hello World", item); break; case 1: Assert.Equal("Goodbye World", item); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Values) { switch (i++) { case 0: Assert.Equal(42, item); break; case 1: Assert.Equal(666, item); break; } } Assert.True(dictionary.ContainsKey("Hello World")); AssertContainsInDictionary(dictionary, "Hello World", 42); Assert.True(dictionary.Keys.Contains("Hello World")); Assert.True(dictionary.Values.Contains(42)); Assert.True(dictionary.ContainsKey("Goodbye World")); AssertContainsInDictionary(dictionary, "Goodbye World", 666); Assert.True(dictionary.Keys.Contains("Goodbye World")); Assert.True(dictionary.Values.Contains(666)); Assert.False(dictionary.Keys.Contains("Mad World")); Assert.False(dictionary.ContainsKey("Mad World")); object value; Assert.True(dictionary.TryGetValue("Hello World", out value)); Assert.Equal(42, value); Assert.True(dictionary.TryGetValue("Goodbye World", out value)); Assert.Equal(666, value); Assert.False(dictionary.TryGetValue("Mad World", out value)); Assert.Null(value); var copyToArray = new KeyValuePair<object, object>[2]; dictionary.CopyTo(copyToArray, 0); Assert.Contains(new KeyValuePair<object, object>("Hello World", 42), copyToArray); Assert.Contains(new KeyValuePair<object, object>("Goodbye World", 666), copyToArray); var copyToValuesArray = new object[2]; dictionary.Values.CopyTo(copyToValuesArray, 0); Assert.Contains(42, copyToValuesArray); Assert.Contains(666, copyToValuesArray); var copyToKeysArray = new object[2]; dictionary.Keys.CopyTo(copyToKeysArray, 0); Assert.Contains("Hello World", copyToKeysArray); Assert.Contains("Goodbye World", copyToKeysArray); Assert.True(dictionary.Remove("Goodbye World")); Assert.Single(dictionary); dictionary["Goodbye World"] = 666; Assert.Equal(2, dictionary.Count); dictionary.Clear(); Assert.Empty(dictionary); } [Fact] public void OverrideMessagePropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal), new MessageTemplateParameter("Goodbye World", 666, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Equal(42, dictionary["Hello World"]); dictionary["Hello World"] = 999; Assert.Equal(999, dictionary["Hello World"]); Assert.True(dictionary.Values.Contains(999)); Assert.True(dictionary.Values.Contains(666)); Assert.False(dictionary.Values.Contains(42)); int i = 0; foreach (var item in dictionary) { switch (i++) { case 1: Assert.Equal("Hello World", item.Key); Assert.Equal(999, item.Value); break; case 0: Assert.Equal("Goodbye World", item.Key); Assert.Equal(666, item.Value); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Keys) { switch (i++) { case 1: Assert.Equal("Hello World", item); break; case 0: Assert.Equal("Goodbye World", item); break; } } Assert.Equal(2, i); i = 0; foreach (var item in dictionary.Values) { switch (i++) { case 1: Assert.Equal(999, item); break; case 0: Assert.Equal(666, item); break; } } dictionary["Goodbye World"] = 42; i = 0; foreach (var item in dictionary.Keys) { switch (i++) { case 0: Assert.Equal("Hello World", item); break; case 1: Assert.Equal("Goodbye World", item); break; } } Assert.Equal(2, i); dictionary.Remove("Hello World"); Assert.Single(dictionary); dictionary.Remove("Goodbye World"); Assert.Empty(dictionary); } [Fact] public void NonUniqueMessagePropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new MessageTemplateParameter("Hello World", 42, null, CaptureType.Normal), new MessageTemplateParameter("Hello World", 666, null, CaptureType.Normal) }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Equal(2, dictionary.Count); Assert.Equal(42, dictionary["Hello World"]); Assert.Equal(666, dictionary["Hello World_1"]); foreach (var property in dictionary) { if (property.Value.Equals(42)) Assert.Equal("Hello World", property.Key); else if (property.Value.Equals(666)) Assert.Equal("Hello World_1", property.Key); else Assert.Null(property.Key); } } #if !NET35 [Fact] public void NonUniqueEventPropertiesDictionary() { LogEventInfo logEvent = new LogEventInfo(LogLevel.Info, "MyLogger", string.Empty, new[] { new KeyValuePair<object,object>("Hello World", 42), new KeyValuePair<object,object>("Hello World", 666), }); IDictionary<object, object> dictionary = logEvent.Properties; Assert.Single(dictionary); Assert.Equal(666, dictionary["Hello World"]); // Last one wins } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; namespace Internal.TypeSystem { /// <summary> /// Represents an array type - either a multidimensional array, or a vector /// (a one-dimensional array with a zero lower bound). /// </summary> public sealed partial class ArrayType : ParameterizedType { private int _rank; // -1 for regular single dimensional arrays, > 0 for multidimensional arrays internal ArrayType(TypeDesc elementType, int rank) : base(elementType) { _rank = rank; } public override int GetHashCode() { return Internal.NativeFormat.TypeHashingAlgorithms.ComputeArrayTypeHashCode(this.ElementType.GetHashCode(), _rank == -1 ? 1 : _rank); } public override DefType BaseType { get { return this.Context.GetWellKnownType(WellKnownType.Array); } } /// <summary> /// Gets the type of the element of this array. /// </summary> public TypeDesc ElementType { get { return this.ParameterType; } } internal MethodDesc[] _methods; /// <summary> /// Gets a value indicating whether this type is a vector. /// </summary> public new bool IsSzArray { get { return _rank < 0; } } /// <summary> /// Gets the rank of this array. Note this returns "1" for both vectors, and /// for general arrays of rank 1. Use <see cref="IsSzArray"/> to disambiguate. /// </summary> public int Rank { get { return (_rank < 0) ? 1 : _rank; } } private void InitializeMethods() { int numCtors; if (IsSzArray) { numCtors = 1; var t = this.ElementType; while (t.IsSzArray) { t = ((ArrayType)t).ElementType; numCtors++; } } else { // ELEMENT_TYPE_ARRAY has two ctor functions, one with and one without lower bounds numCtors = 2; } MethodDesc[] methods = new MethodDesc[(int)ArrayMethodKind.Ctor + numCtors]; for (int i = 0; i < methods.Length; i++) methods[i] = new ArrayMethod(this, (ArrayMethodKind)i); Interlocked.CompareExchange(ref _methods, methods, null); } public override IEnumerable<MethodDesc> GetMethods() { if (_methods == null) InitializeMethods(); return _methods; } public MethodDesc GetArrayMethod(ArrayMethodKind kind) { if (_methods == null) InitializeMethods(); return _methods[(int)kind]; } public override TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { TypeDesc instantiatedElementType = this.ElementType.InstantiateSignature(typeInstantiation, methodInstantiation); return instantiatedElementType.Context.GetArrayType(instantiatedElementType, _rank); } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = _rank == -1 ? TypeFlags.SzArray : TypeFlags.Array; if ((mask & TypeFlags.ContainsGenericVariablesComputed) != 0) { flags |= TypeFlags.ContainsGenericVariablesComputed; if (this.ParameterType.ContainsGenericVariables) flags |= TypeFlags.ContainsGenericVariables; } flags |= TypeFlags.HasGenericVarianceComputed; return flags; } public override string ToString() { return this.ElementType.ToString() + "[" + new String(',', Rank - 1) + "]"; } } public enum ArrayMethodKind { Get, Set, Address, Ctor } /// <summary> /// Represents one of the methods on array types. While array types are not typical /// classes backed by metadata, they do have methods that can be referenced from the IL /// and the type system needs to provide a way to represent them. /// </summary> public partial class ArrayMethod : MethodDesc { private ArrayType _owningType; private ArrayMethodKind _kind; internal ArrayMethod(ArrayType owningType, ArrayMethodKind kind) { _owningType = owningType; _kind = kind; } public override TypeSystemContext Context { get { return _owningType.Context; } } public override TypeDesc OwningType { get { return _owningType; } } public ArrayMethodKind Kind { get { return _kind; } } private MethodSignature _signature; public override MethodSignature Signature { get { if (_signature == null) { switch (_kind) { case ArrayMethodKind.Get: { var parameters = new TypeDesc[_owningType.Rank]; for (int i = 0; i < _owningType.Rank; i++) parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, _owningType.ElementType, parameters); break; } case ArrayMethodKind.Set: { var parameters = new TypeDesc[_owningType.Rank + 1]; for (int i = 0; i < _owningType.Rank; i++) parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); parameters[_owningType.Rank] = _owningType.ElementType; _signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), parameters); break; } case ArrayMethodKind.Address: { var parameters = new TypeDesc[_owningType.Rank]; for (int i = 0; i < _owningType.Rank; i++) parameters[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, _owningType.ElementType.MakeByRefType(), parameters); } break; default: { int numArgs; if (_owningType.IsSzArray) { numArgs = 1 + (int)_kind - (int)ArrayMethodKind.Ctor; } else { numArgs = (_kind == ArrayMethodKind.Ctor) ? _owningType.Rank : 2 * _owningType.Rank; } var argTypes = new TypeDesc[numArgs]; for (int i = 0; i < argTypes.Length; i++) argTypes[i] = _owningType.Context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, this.Context.GetWellKnownType(WellKnownType.Void), argTypes); } break; } } return _signature; } } public override string Name { get { switch (_kind) { case ArrayMethodKind.Get: return "Get"; case ArrayMethodKind.Set: return "Set"; case ArrayMethodKind.Address: return "Address"; default: return ".ctor"; } } } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } public override MethodDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { TypeDesc owningType = this.OwningType; TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation); if (owningType != instantiatedOwningType) return ((ArrayType)instantiatedOwningType).GetArrayMethod(_kind); else return this; } public override string ToString() { return _owningType.ToString() + "." + Name; } } }
// Copyright (c) 2011, Eric Maupin // All rights reserved. // // Redistribution and use in source and binary forms, with // or without modification, are permitted provided that // the following conditions are met: // // - Redistributions of source code must retain the above // copyright notice, this list of conditions and the // following disclaimer. // // - Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other // materials provided with the distribution. // // - Neither the name of Gablarski nor the names of its // contributors may be used to endorse or promote products // or services derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS // AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Security; using Cadenza; using Cadenza.Collections; namespace Gablarski.OpenAL { [SuppressUnmanagedCodeSecurity] public class Source : IDisposable { internal Source (uint sourceID) { this.sourceID = sourceID; } public SourceState State { get { int state; alGetSourcei (this.sourceID, IntSourceProperty.AL_SOURCE_STATE, out state); OpenAL.ErrorCheck (); return (SourceState)state; } } public bool IsPlaying { get { return (this.State == SourceState.Playing); } } public bool IsPaused { get { return (this.State == SourceState.Paused); } } public bool IsStopped { get { return (this.State == SourceState.Stopped); } } public int ProcessedBuffers { get { int buffers; alGetSourcei (this.sourceID, IntSourceProperty.AL_BUFFERS_PROCESSED, out buffers); OpenAL.ErrorCheck(); return buffers; } } public float Pitch { get { return GetPropertyF (this.sourceID, FloatSourceProperty.AL_PITCH); } set { SetPropertyF (this.sourceID, FloatSourceProperty.AL_PITCH, value); } } /// <summary> /// Gets or sets the minimum gain for this source. /// </summary> public float MinimumGain { get { return GetPropertyF (this.sourceID, FloatSourceProperty.AL_MIN_GAIN); } set { SetPropertyF (this.sourceID, FloatSourceProperty.AL_MIN_GAIN, value); } } /// <summary> /// Gets or sets the source's gain. /// </summary> public float Gain { get { return GetPropertyF (this.sourceID, FloatSourceProperty.AL_GAIN); } set { SetPropertyF (this.sourceID, FloatSourceProperty.AL_GAIN, value); } } /// <summary> /// Gets or sets the maximum gain for this source. /// </summary> public float MaximumGain { get { return GetPropertyF (this.sourceID, FloatSourceProperty.AL_MAX_GAIN); } set { SetPropertyF (this.sourceID, FloatSourceProperty.AL_MAX_GAIN, value); } } public void Queue (SourceBuffer buffer) { Queue (new [] { buffer.bufferID }); } public void QueueAndPlay (SourceBuffer buffer) { this.Queue (buffer); this.Play (); } public void Queue (IEnumerable<SourceBuffer> buffers) { uint[] bufferIDs = buffers.Select (b => b.bufferID).ToArray (); Queue (bufferIDs); } public SourceBuffer[] Dequeue () { OpenAL.DebugFormat ("Dequeing all processed buffers for source {0}", this.sourceID); return Dequeue (this.ProcessedBuffers); } public SourceBuffer[] Dequeue (int buffers) { OpenAL.DebugFormat ("Dequeing {0} buffers for source {1}", buffers, this.sourceID); uint[] bufferIDs = new uint[buffers]; alSourceUnqueueBuffers (this.sourceID, buffers, bufferIDs); OpenAL.ErrorCheck (); SourceBuffer[] dequeued = new SourceBuffer[bufferIDs.Length]; for (int i = 0; i < bufferIDs.Length; ++i) { OpenAL.DebugFormat ("Dequeued source buffer {0} for source {1}", bufferIDs[i], this.sourceID); dequeued[i] = SourceBuffer.GetBuffer (bufferIDs[i]); } return dequeued; } public void Play () { PlayCore (true); } public void Replay () { PlayCore (false); } public void Pause () { OpenAL.DebugFormat ("Pausing source {0}", this.sourceID); alSourcePause (this.sourceID); OpenAL.ErrorCheck (); } public void Stop () { OpenAL.DebugFormat ("Stopping source {0}", this.sourceID); alSourceStop (this.sourceID); OpenAL.ErrorCheck (); } private readonly uint sourceID; protected void Queue (uint[] bufferIDs) { OpenAL.DebugFormat ("Enqueuing buffers {0} to source {1}", bufferIDs.Implode (", "), this.sourceID); alSourceQueueBuffers (this.sourceID, bufferIDs.Length, bufferIDs); OpenAL.ErrorCheck (); } protected void PlayCore (bool check) { if (check && this.IsPlaying) return; OpenAL.DebugFormat ("Playing source {0}", this.sourceID); alSourcePlay (this.sourceID); OpenAL.ErrorCheck (); } public override string ToString () { return "Source:" + this.sourceID; } #region IDisposable Members public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } private bool disposed; protected void Dispose (bool disposing) { if (this.disposed) return; OpenAL.DebugFormat ("Destroying source {0}", this.sourceID); uint[] id = new[] { this.sourceID }; alDeleteSources (1, id); OpenAL.DebugFormat ("Destroyed source {0}", this.sourceID); this.disposed = true; } ~Source () { Dispose (false); } #endregion public static Source Generate () { return Generate (1)[0]; } public static Source[] Generate (int count) { OpenAL.DebugFormat ("Generating {0} sources", count); if (count > MaxSources) { OpenAL.Log.ErrorFormat ("Requested {0} sources which is more than maximum {1}", count, MaxSources); throw new InvalidOperationException(); } Source[] sources = new Source[count]; uint[] sourceIDs = new uint[count]; alGenSources (count, sourceIDs); OpenAL.ErrorCheck (); for (int i = 0; i < count; ++i) { OpenAL.DebugFormat ("Generated source {0}", sourceIDs[i]); sources[i] = new Source (sourceIDs[i]); } return sources; } // ReSharper disable InconsistentNaming [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alGetSourcei (uint sourceID, IntSourceProperty property, out int value); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alSourcePlay (uint sourceID); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alSourcePause (uint sourceID); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alSourceStop (uint sourceID); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alSourceQueueBuffers (uint sourceID, int number, uint[] bufferIDs); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alSourceUnqueueBuffers (uint sourceID, int buffers, uint[] buffersDequeued); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alGenSources (int count, uint[] sources); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alDeleteSources (int count, uint[] sources); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alGetSourcef (uint sourceID, FloatSourceProperty property, out float value); [DllImport ("OpenAL32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern void alSourcef (uint sourceID, FloatSourceProperty property, float value); // ReSharper restore InconsistentNaming internal static float GetPropertyF (uint sourceID, FloatSourceProperty property) { float value; alGetSourcef (sourceID, property, out value); OpenAL.ErrorCheck (); return value; } internal static void SetPropertyF (uint sourceID, FloatSourceProperty property, float value) { OpenAL.DebugFormat ("Setting source {0} property {1} to {2}", sourceID, property, value); alSourcef (sourceID, property, value); OpenAL.ErrorCheck (); } internal static int MaxSources { get { return 32; } } } public enum SourceState { Initial = 0x1011, Playing = 0x1012, Paused = 0x1013, Stopped = 0x1014 } // ReSharper disable InconsistentNaming internal enum IntSourceProperty { AL_SOURCE_STATE = 0x1010, AL_BUFFERS_QUEUED = 0x1015, AL_BUFFERS_PROCESSED = 0x1016 } internal enum FloatSourceProperty { AL_PITCH = 0x1003, AL_GAIN = 0x100A, AL_MIN_GAIN = 0x100D, AL_MAX_GAIN = 0x100E, AL_MAX_DISTANCE = 0x1023, AL_ROLLOFF_FACTOR = 0x1021, AL_CONE_OUTER_GAIN = 0x1022, AL_CONE_INNER_ANGLE = 0x1001, AL_CONE_OUTER_ANGLE = 0x1002, AL_REFERENCE_DISTANCE = 0x1020 } // ReSharper restore InconsistentNaming }
// 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; using static System.Runtime.Intrinsics.X86.Sse; using static System.Runtime.Intrinsics.X86.Sse2; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertSingle129() { var test = new InsertVector128Test__InsertSingle129(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 InsertVector128Test__InsertSingle129 { private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(InsertVector128Test__InsertSingle129 testClass) { var result = Sse41.Insert(_fld1, _fld2, 129); 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<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static InsertVector128Test__InsertSingle129() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public InsertVector128Test__InsertSingle129() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse41.Insert( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse41.Insert( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse41.Insert( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), 129 ); 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(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), LoadVector128((Single*)(_dataTable.inArray2Ptr)), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)), (byte)129 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse41.Insert( _clsVar1, _clsVar2, 129 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse41.Insert(left, right, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse41.Insert(left, right, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new InsertVector128Test__InsertSingle129(); var result = Sse41.Insert(test._fld1, test._fld2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse41.Insert(_fld1, _fld2, 129); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse41.Insert(test._fld1, test._fld2, 129); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(0.0f)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.129): {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; } } } }
/*************************************************************************** * AudioCdRipper.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <aaron@abock.org> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Collections; using System.Threading; using Banshee.Winforms; using Banshee.Winforms.Controls; using Banshee.Widgets; using Banshee.Base; using Banshee.AudioProfiles; using Banshee.Configuration.Schema; using Ripper; using Yeti.MMedia; using Yeti.MMedia.Mp3; using WaveLib; //Cornel - I have decided not to use the WMP SDK for ripping // although it does support ripping etc the files get added to the wmp media library // i would like to stick to the banshee convention of allowing the user to specify the // location of the banshee media library. Using lame_enc.dll seems like a good option // To start with only mp3 is supported namespace Banshee.Base { public delegate void AudioCdRipperProgressHandler(object o, AudioCdRipperProgressArgs args); public delegate void AudioCdRipperTrackFinishedHandler(object o, AudioCdRipperTrackFinishedArgs args); public class AudioCdRipperProgressArgs : EventArgs { public int SecondsEncoded; public int TotalSeconds; public AudioCdTrackInfo Track; } public class AudioCdRipperTrackFinishedArgs : EventArgs { public AudioCdTrackInfo Track; public int TrackNumber; public SafeUri Uri; } public class AudioCdTrackRipper : IDisposable { private string error_message; private SafeUri output_uri; private int track_number; private AudioCdTrackInfo current_track; public event AudioCdRipperProgressHandler Progress; public event AudioCdRipperTrackFinishedHandler TrackFinished; public event EventHandler Error; CDDrive drive; Mp3Writer writer; public AudioCdTrackRipper(CDDrive drv, int paranoiaMode, string encoderPipeline) { drive = drv; } public void Dispose() { drive.Dispose(); } public void RipTrack(AudioCdTrackInfo track, int trackNumber, SafeUri outputUri) { error_message = null; RipTrack_010(track, trackNumber, outputUri); } private void RipTrack_010(AudioCdTrackInfo track, int trackNumber, SafeUri outputUri) { current_track = track; track_number = trackNumber; output_uri = outputUri; Stream WaveFile=null; try { WaveFormat Format = new WaveFormat(44100, 16, 2); WaveFile = new FileStream(outputUri.AbsolutePath, FileMode.Create, FileAccess.Write); try { writer = new Mp3Writer(WaveFile, Format); int n = drive.ReadTrack(track_number, new CdDataReadEventHandler(WriteWaveData), new CdReadProgressEventHandler(OnProgress)); if (n > 0) { LogCore.Instance.PushInformation("CD Ripping", string.Format("Ripping track {0}",track_number)); } else { writer.Close(); writer = null; WaveFile.Close(); if(System.IO.File.Exists(outputUri.AbsolutePath)) System.IO.File.Delete(outputUri.AbsolutePath); LogCore.Instance.PushError("CD Ripping", string.Format(" Error Ripping track {0}",track_number)); } } finally { writer.Close(); writer = null; } } catch (Exception ex) { error_message = ex.Message; } finally { WaveFile.Close(); drive.UnLockCD(); OnTrackFinished(current_track, (int)current_track.TrackNumber, outputUri); } track = null; } private void WriteWaveData(object sender, DataReadEventArgs ea) { if (writer != null) { writer.Write(ea.Data, 0, (int)ea.DataSize); } } private void OnTrackFinished(AudioCdTrackInfo track, int trackNumber, SafeUri outputUri) { track.IsRipped = true; track.Uri = outputUri; AudioCdRipperTrackFinishedHandler handler = TrackFinished; if(handler != null) { AudioCdRipperTrackFinishedArgs args = new AudioCdRipperTrackFinishedArgs(); args.Track = track; args.TrackNumber = trackNumber; args.Uri = outputUri; handler(this, args); } } public void Cancel() { //gst_cd_ripper_cancel(handle); } public string ErrorMessage { get { return error_message; } } private void OnProgress(object sender, ReadProgressEventArgs ea) { ulong Percent = ((ulong)ea.BytesRead * 100) / ea.Bytes2Read; int dur = (int)current_track.Duration.TotalSeconds; int secondsread = (dur / 100) * (int)Percent; System.Windows.Forms.Application.DoEvents(); AudioCdRipperProgressHandler handler = Progress; if (handler == null) return; AudioCdRipperProgressArgs args = new AudioCdRipperProgressArgs(); args.TotalSeconds = (int)current_track.Duration.TotalSeconds; args.SecondsEncoded = secondsread; args.Track = current_track; handler(this, args); } /* private void OnProgress(object ripper, int seconds, IntPtr user_info) { } */ private void OnFinished(IntPtr ripper) { OnTrackFinished(current_track, track_number, output_uri); } private void OnError(IntPtr ripper, IntPtr error, IntPtr debug) { error_message = error.ToString(); if(debug != IntPtr.Zero) { string debug_string = debug.ToString(); if(debug_string != null && debug_string != String.Empty) { error_message += ": " + debug_string; } } if(Error != null) { Error(this, new EventArgs()); } } } public class AudioCdRipper { private Queue tracks = new Queue(); private AudioCdTrackRipper ripper; private string device; private int currentIndex = 0; private int overallProgress = 0; private string status; private int total_tracks; // speed calculations private int currentSeconds = 0; private int lastPollSeconds = 0; private uint pollDelay = 1000; private long totalCount; private uint timeout_id; private int current = 1; private Profile profile; public event HaveTrackInfoHandler HaveTrackInfo; public event EventHandler Finished; private ActiveUserEvent user_event; private void LockDrive() { lock(this) { bool t = drive.UnLockCD(); if(!drive.LockCD()) { LogCore.Instance.PushWarning("Could not lock CD-ROM drive", device, false); } } } private void UnlockDrive() { lock(this) { if(!drive.UnLockCD()) { LogCore.Instance.PushWarning("Could not unlock CD-ROM drive", device, false); } } } CDDrive drive = new CDDrive(); char devchar; public AudioCdRipper(string DriveLetter) { devchar = DriveLetter[0]; user_event = new ActiveUserEvent(Catalog.GetString("Importing CD")); user_event.Icon = IconThemeUtils.LoadIcon(ConfigureDefines.ICON_THEME_DIR+@"\cd-action-rip-24.png"); user_event.CancelRequested += OnCancelRequested; } public void QueueTrack(AudioCdTrackInfo track) { if(user_event.CancelMessage == null) { user_event.CancelMessage = String.Format(Catalog.GetString( "{0} is still being imported into the music library. Would you like to stop it?" ), track.Album); } if(device == null) { device = track.Device; } else if(device != track.Device) { throw new ApplicationException(String.Format(Catalog.GetString( "The device node '{0}' differs from the device node " + "already set for previously queued tracks ({1})"), track.Device, device)); } tracks.Enqueue(track); totalCount += (int)track.Duration.TotalSeconds; } public void Start() { //ActiveUserEventsManager.Register(user_event); current = 1; user_event.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate() { user_event.Header = Catalog.GetString("Importing Audio CD"); user_event.OnUpdateStatus(); user_event.Message = Catalog.GetString("Initializing Drive"); user_event.OnUpdateStatus(); drive.Open(devchar); if (drive.IsCDReady()) { bool refreshed = drive.Refresh(); user_event.Message = Catalog.GetString("Initializing Drive"); user_event.OnUpdateStatus(); } /* profile = Globals.AudioProfileManager.GetConfiguredActiveProfile("cd-importing", new string [] { "audio/ogg", "audio/mp3", "audio/wav" }); try { if(profile == null) { throw new ApplicationException(Catalog.GetString("No encoder was found on your system.")); } string encodePipeline = profile.Pipeline.GetProcessById("gstreamer"); */ LogCore.Instance.PushDebug("Ripping CD and Encoding with Pipeline: ", "lame"); try { //LockDrive(); bool locked = drive.LockCD(); int paranoiaMode = 0; try { if (ImportSchema.AudioCDErrorCorrection.Get()) { paranoiaMode = 255; LogCore.Instance.PushDebug("CD Error-correction enabled", "using full paranoia mode (255)"); } } catch (Exception e) { Console.WriteLine(e); } ripper = new AudioCdTrackRipper(drive, paranoiaMode, string.Empty);//encodePipeline); ripper.Progress += OnRipperProgress; ripper.TrackFinished += OnTrackRipped; ripper.Error += OnRipperError; //timeout_id = GLib.Timeout.Add(pollDelay, OnTimeout); total_tracks = tracks.Count; RipNextTrack(); } catch (Exception e) { LogCore.Instance.PushError(Catalog.GetString("Cannot Import CD"), e.Message); //user_event.Dispose(); OnFinished(); } }); } public void Cancel() { user_event.Dispose(); OnFinished(); } private void RipNextTrack() { if(tracks.Count <= 0) { return; } AudioCdTrackInfo track = tracks.Dequeue() as AudioCdTrackInfo; user_event.Header = String.Format(Catalog.GetString("Importing {0} of {1}"), current++, QueueSize); user_event.OnUpdateStatus(); status = String.Format("{0} - {1}", track.Artist, track.Title); user_event.Message = status; Console.WriteLine("Importing {0} of {1}", current++, QueueSize); SafeUri uri = new SafeUri(FileNamePattern.BuildFull(track, "mp3"));//profile.OutputFileExtension)); user_event.OnUpdateStatus(); ripper.RipTrack(track, track.TrackIndex, uri); } private void OnTrackRipped(object o, AudioCdRipperTrackFinishedArgs args) { overallProgress += (int)args.Track.Duration.TotalSeconds; if(!user_event.IsCancelRequested) { TrackInfo lti; try { lti = new LibraryTrackInfo(args.Uri, args.Track); } catch(ApplicationException) { lti = Globals.Library.TracksFnKeyed[Library.MakeFilenameKey(args.Uri)] as TrackInfo; } if(lti != null) { HaveTrackInfoHandler handler = HaveTrackInfo; if(handler != null) { HaveTrackInfoArgs hargs = new HaveTrackInfoArgs(); hargs.TrackInfo = lti; handler(this, hargs); } } } currentIndex++; if(tracks.Count > 0 && !user_event.IsCancelRequested) { RipNextTrack(); return; } if(timeout_id > 0) { // GLib.Source.Remove(timeout_id); } ripper.Dispose(); user_event.Dispose(); OnFinished(); } private void OnRipperError(object o, EventArgs args) { ripper.Dispose(); user_event.Dispose(); OnFinished(); LogCore.Instance.PushError(Catalog.GetString("Cannot Import CD"), ripper.ErrorMessage); } private void OnFinished() { drive.UnLockCD(); EventHandler handler = Finished; if(handler != null) { handler(this, new EventArgs()); } } private bool OnTimeout() { int diff = currentSeconds - lastPollSeconds; lastPollSeconds = currentSeconds; if(diff <= 0) { user_event.Message = status; return true; } user_event.Message = status + String.Format(" ({0}x)", diff); user_event.OnUpdateStatus(); return true; } private void OnRipperProgress(object o, AudioCdRipperProgressArgs args) { user_event.Header = "Importing CD..."; user_event.Message = args.Track.Title; if(args.SecondsEncoded == 0) { return; } double totalprogress = (double)(args.SecondsEncoded + overallProgress) / (double)(totalCount); user_event.Progress = totalprogress; //LogCore.Instance.PushInformation("CD Ripping", string.Format("{0}% Total", user_event.Progress)); currentSeconds = args.SecondsEncoded; user_event.OnUpdateStatus(); } private void OnCancelRequested(object o, EventArgs args) { if(ripper != null) { ripper.Cancel(); ripper.Dispose(); } user_event.Dispose(); OnFinished(); } public int QueueSize { get { return total_tracks; } } } }
/* * 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 Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Hypergrid { public class HGFriendsServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IUserAgentService m_UserAgentService; private IFriendsSimConnector m_FriendsLocalSimConnector; private IHGFriendsService m_TheService; public HGFriendsServerPostHandler(IHGFriendsService service, IUserAgentService uas, IFriendsSimConnector friendsConn) : base("POST", "/hgfriends") { m_TheService = service; m_UserAgentService = uas; m_FriendsLocalSimConnector = friendsConn; m_log.DebugFormat("[HGFRIENDS HANDLER]: HGFriendsServerPostHandler is On ({0})", (m_FriendsLocalSimConnector == null ? "robust" : "standalone")); if (m_TheService == null) m_log.ErrorFormat("[HGFRIENDS HANDLER]: TheService is null!"); } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "getfriendperms": return GetFriendPerms(request); case "newfriendship": return NewFriendship(request); case "deletefriendship": return DeleteFriendship(request); /* Same as inter-sim */ case "friendship_offered": return FriendshipOffered(request); case "validate_friendship_offered": return ValidateFriendshipOffered(request); case "statusnotification": return StatusNotification(request); /* case "friendship_approved": return FriendshipApproved(request); case "friendship_denied": return FriendshipDenied(request); case "friendship_terminated": return FriendshipTerminated(request); case "grant_rights": return GrantRights(request); */ } m_log.DebugFormat("[HGFRIENDS HANDLER]: unknown method {0}", method); } catch (Exception e) { m_log.DebugFormat("[HGFRIENDS HANDLER]: Exception {0}", e); } return FailureResult(); } #region Method-specific handlers byte[] GetFriendPerms(Dictionary<string, object> request) { if (!VerifyServiceKey(request)) return FailureResult(); UUID principalID = UUID.Zero; if (request.ContainsKey("PRINCIPALID")) UUID.TryParse(request["PRINCIPALID"].ToString(), out principalID); else { m_log.WarnFormat("[HGFRIENDS HANDLER]: no principalID in request to get friend perms"); return FailureResult(); } UUID friendID = UUID.Zero; if (request.ContainsKey("FRIENDID")) UUID.TryParse(request["FRIENDID"].ToString(), out friendID); else { m_log.WarnFormat("[HGFRIENDS HANDLER]: no friendID in request to get friend perms"); return FailureResult(); } int perms = m_TheService.GetFriendPerms(principalID, friendID); if (perms < 0) return FailureResult("Friend not found"); return SuccessResult(perms.ToString()); } byte[] NewFriendship(Dictionary<string, object> request) { bool verified = VerifyServiceKey(request); FriendInfo friend = new FriendInfo(request); bool success = m_TheService.NewFriendship(friend, verified); if (success) return SuccessResult(); else return FailureResult(); } byte[] DeleteFriendship(Dictionary<string, object> request) { FriendInfo friend = new FriendInfo(request); string secret = string.Empty; if (request.ContainsKey("SECRET")) secret = request["SECRET"].ToString(); if (secret == string.Empty) return BoolResult(false); bool success = m_TheService.DeleteFriendship(friend, secret); return BoolResult(success); } byte[] FriendshipOffered(Dictionary<string, object> request) { UUID fromID = UUID.Zero; UUID toID = UUID.Zero; string message = string.Empty; string name = string.Empty; if (!request.ContainsKey("FromID") || !request.ContainsKey("ToID")) return BoolResult(false); if (!UUID.TryParse(request["ToID"].ToString(), out toID)) return BoolResult(false); message = request["Message"].ToString(); if (!UUID.TryParse(request["FromID"].ToString(), out fromID)) return BoolResult(false); if (request.ContainsKey("FromName")) name = request["FromName"].ToString(); bool success = m_TheService.FriendshipOffered(fromID, name, toID, message); return BoolResult(success); } byte[] ValidateFriendshipOffered(Dictionary<string, object> request) { FriendInfo friend = new FriendInfo(request); UUID friendID = UUID.Zero; if (!UUID.TryParse(friend.Friend, out friendID)) return BoolResult(false); bool success = m_TheService.ValidateFriendshipOffered(friend.PrincipalID, friendID); return BoolResult(success); } byte[] StatusNotification(Dictionary<string, object> request) { UUID principalID = UUID.Zero; if (request.ContainsKey("userID")) UUID.TryParse(request["userID"].ToString(), out principalID); else { m_log.WarnFormat("[HGFRIENDS HANDLER]: no userID in request to notify"); return FailureResult(); } bool online = true; if (request.ContainsKey("online")) Boolean.TryParse(request["online"].ToString(), out online); else { m_log.WarnFormat("[HGFRIENDS HANDLER]: no online in request to notify"); return FailureResult(); } List<string> friends = new List<string>(); int i = 0; foreach (KeyValuePair<string, object> kvp in request) { if (kvp.Key.Equals("friend_" + i.ToString())) { friends.Add(kvp.Value.ToString()); i++; } } List<UUID> onlineFriends = m_TheService.StatusNotification(friends, principalID, online); Dictionary<string, object> result = new Dictionary<string, object>(); if ((onlineFriends == null) || ((onlineFriends != null) && (onlineFriends.Count == 0))) result["RESULT"] = "NULL"; else { i = 0; foreach (UUID f in onlineFriends) { result["friend_" + i] = f.ToString(); i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } #endregion #region Misc private bool VerifyServiceKey(Dictionary<string, object> request) { if (!request.ContainsKey("KEY") || !request.ContainsKey("SESSIONID")) { m_log.WarnFormat("[HGFRIENDS HANDLER]: ignoring request without Key or SessionID"); return false; } if (request["KEY"] == null || request["SESSIONID"] == null) return false; string serviceKey = request["KEY"].ToString(); string sessionStr = request["SESSIONID"].ToString(); UUID sessionID; if (!UUID.TryParse(sessionStr, out sessionID) || serviceKey == string.Empty) return false; if (!m_UserAgentService.VerifyAgent(sessionID, serviceKey)) { m_log.WarnFormat("[HGFRIENDS HANDLER]: Key {0} for session {1} did not match existing key. Ignoring request", serviceKey, sessionID); return false; } m_log.DebugFormat("[HGFRIENDS HANDLER]: Verification ok"); return true; } private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return Util.DocToBytes(doc); } private byte[] SuccessResult(string value) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "RESULT", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Value", ""); message.AppendChild(doc.CreateTextNode(value)); rootElement.AppendChild(message); return Util.DocToBytes(doc); } private byte[] FailureResult() { return FailureResult(String.Empty); } private byte[] FailureResult(string msg) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "RESULT", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Message", ""); message.AppendChild(doc.CreateTextNode(msg)); rootElement.AppendChild(message); return Util.DocToBytes(doc); } private byte[] BoolResult(bool value) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "RESULT", ""); result.AppendChild(doc.CreateTextNode(value.ToString())); rootElement.AppendChild(result); return Util.DocToBytes(doc); } #endregion } }