context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using UnityEngine; using System; using System.Collections.Generic; #if !UNITY_FLASH && !UNITY_METRO && !UNITY_WP8 using System.Text.RegularExpressions; #endif // Part of MegaShape? public class MegaShapeSVG { public void LoadXML(string svgdata, MegaShape shape, bool clear, int start) { MegaXMLReader xml = new MegaXMLReader(); MegaXMLNode node = xml.read(svgdata); if ( !clear ) shape.splines.Clear(); shape.selcurve = start; splineindex = start; ParseXML(node, shape); } int splineindex = 0; public void ParseXML(MegaXMLNode node, MegaShape shape) { foreach ( MegaXMLNode n in node.children ) { switch ( n.tagName ) { case "circle": ParseCircle(n, shape); break; case "path": ParsePath(n, shape); break; case "ellipse": ParseEllipse(n, shape); break; case "rect": ParseRect(n, shape); break; case "polygon": ParsePolygon(n, shape); break; default: break; } ParseXML(n, shape); } } MegaSpline GetSpline(MegaShape shape) { MegaSpline spline; if ( splineindex < shape.splines.Count ) spline = shape.splines[splineindex]; else { spline = new MegaSpline(); shape.splines.Add(spline); } splineindex++; return spline; } Vector3 SwapAxis(Vector3 val, MegaAxis axis) { float v = 0.0f; switch ( axis ) { case MegaAxis.X: v = val.x; val.x = val.y; val.y = v; break; case MegaAxis.Y: break; case MegaAxis.Z: v = val.y; val.y = val.z; val.z = v; break; } return val; } void AddKnot(MegaSpline spline, Vector3 p, Vector3 invec, Vector3 outvec, MegaAxis axis) { spline.AddKnot(SwapAxis(p, axis), SwapAxis(invec, axis), SwapAxis(outvec, axis)); } void ParseCircle(MegaXMLNode node, MegaShape shape) { MegaSpline spline = GetSpline(shape); float cx = 0.0f; float cy = 0.0f; float r = 0.0f; for ( int i = 0; i < node.values.Count; i++ ) { MegaXMLValue val = node.values[i]; switch ( val.name ) { case "cx": cx = float.Parse(val.value); break; case "cy": cy = float.Parse(val.value); break; case "r": r = float.Parse(val.value); break; } } float vector = CIRCLE_VECTOR_LENGTH * r; spline.knots.Clear(); for ( int ix = 0; ix < 4; ++ix ) { float angle = (Mathf.PI * 2.0f) * (float)ix / (float)4; float sinfac = Mathf.Sin(angle); float cosfac = Mathf.Cos(angle); Vector3 p = new Vector3((cosfac * r) + cx, 0.0f, (sinfac * r) + cy); Vector3 rotvec = new Vector3(sinfac * vector, 0.0f, -cosfac * vector); //spline.AddKnot(p, p + rotvec, p - rotvec); AddKnot(spline, p, p + rotvec, p - rotvec, shape.axis); } spline.closed = true; } void ParseEllipse(MegaXMLNode node, MegaShape shape) { MegaSpline spline = GetSpline(shape); float cx = 0.0f; float cy = 0.0f; float rx = 0.0f; float ry = 0.0f; for ( int i = 0; i < node.values.Count; i++ ) { MegaXMLValue val = node.values[i]; switch ( val.name ) { case "cx": cx = float.Parse(val.value); break; case "cy": cy = float.Parse(val.value); break; case "rx": rx = float.Parse(val.value); break; case "ry": ry = float.Parse(val.value); break; } } ry = Mathf.Clamp(ry, 0.0f, float.MaxValue); rx = Mathf.Clamp(rx, 0.0f, float.MaxValue); float radius, xmult, ymult; if ( ry < rx ) { radius = rx; xmult = 1.0f; ymult = ry / rx; } else { if ( rx < ry ) { radius = ry; xmult = rx / ry; ymult = 1.0f; } else { radius = ry; xmult = ymult = 1.0f; } } float vector = CIRCLE_VECTOR_LENGTH * radius; Vector3 mult = new Vector3(xmult, ymult, 1.0f); for ( int ix = 0; ix < 4; ++ix ) { float angle = 6.2831853f * (float)ix / 4.0f; float sinfac = Mathf.Sin(angle); float cosfac = Mathf.Cos(angle); Vector3 p = new Vector3(cosfac * radius + cx, 0.0f, sinfac * radius + cy); Vector3 rotvec = new Vector3(sinfac * vector, 0.0f, -cosfac * vector); //spline.AddKnot(Vector3.Scale(p, mult), Vector3.Scale((p + rotvec), mult), Vector3.Scale((p - rotvec), mult)); //, tm); AddKnot(spline, Vector3.Scale(p, mult), Vector3.Scale((p + rotvec), mult), Vector3.Scale((p - rotvec), mult), shape.axis); //, tm); } spline.closed = true; } void ParseRect(MegaXMLNode node, MegaShape shape) { MegaSpline spline = GetSpline(shape); Vector3[] ppoints = new Vector3[4]; float w = 0.0f; float h = 0.0f; float x = 0.0f; float y = 0.0f; for ( int i = 0; i < node.values.Count; i++ ) { MegaXMLValue val = node.values[i]; switch ( val.name ) { case "x": x = float.Parse(val.value); break; case "y": y = float.Parse(val.value); break; case "width": w = float.Parse(val.value); break; case "height": h = float.Parse(val.value); break; case "transform": Debug.Log("SVG Transform not implemented yet"); break; } } ppoints[0] = new Vector3(x, 0.0f, y); ppoints[1] = new Vector3(x, 0.0f, y + h); ppoints[2] = new Vector3(x + w, 0.0f, y + h); ppoints[3] = new Vector3(x + w, 0.0f, y); spline.closed = true; spline.knots.Clear(); //spline.AddKnot(ppoints[0], ppoints[0], ppoints[0]); //spline.AddKnot(ppoints[1], ppoints[1], ppoints[1]); //spline.AddKnot(ppoints[2], ppoints[2], ppoints[2]); //spline.AddKnot(ppoints[3], ppoints[3], ppoints[3]); AddKnot(spline, ppoints[0], ppoints[0], ppoints[0], shape.axis); AddKnot(spline, ppoints[1], ppoints[1], ppoints[1], shape.axis); AddKnot(spline, ppoints[2], ppoints[2], ppoints[2], shape.axis); AddKnot(spline, ppoints[3], ppoints[3], ppoints[3], shape.axis); } void ParsePolygon(MegaXMLNode node, MegaShape shape) { MegaSpline spline = GetSpline(shape); spline.knots.Clear(); spline.closed = true; char[] charSeparators = new char[] { ' ' }; for ( int i = 0; i < node.values.Count; i++ ) { MegaXMLValue val = node.values[i]; switch ( val.name ) { case "points": string[] coordinates = val.value.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); for ( int j = 0; j < coordinates.Length; j++ ) { Vector3 p = ParseV2Split(coordinates[j], 0); MegaKnot k = new MegaKnot(); k.p = SwapAxis(new Vector3(p.x, 0.0f, p.y), shape.axis); k.invec = k.p; k.outvec = k.p; spline.knots.Add(k); } break; } } if ( spline.closed ) { Vector3 delta1 = spline.knots[0].outvec - spline.knots[0].p; spline.knots[0].invec = spline.knots[0].p - delta1; } } char[] commaspace = new char[] { ',', ' ' }; void ParsePath(MegaXMLNode node, MegaShape shape) { Vector3 cp = Vector3.zero; Vector2 cP1; Vector2 cP2; char[] charSeparators = new char[] { ',', ' ' }; MegaSpline spline = null; MegaKnot k; string[] coord; for ( int i = 0; i < node.values.Count; i++ ) { MegaXMLValue val = node.values[i]; //Debug.Log("val name " + val.name); switch ( val.name ) { case "d": #if UNITY_FLASH || UNITY_WP8 || UNITY_METRO string[] coordinates = null; //string.Split(val.value, @"(?=[MmLlCcSsZzHhVv])"); #else string[] coordinates = Regex.Split(val.value, @"(?=[MmLlCcSsZzHhVv])"); #endif for ( int j = 0; j < coordinates.Length; j++ ) { if ( coordinates[j].Length > 0 ) { string v = coordinates[j].Substring(1); if ( v != null && v.Length > 0 ) { v = v.Replace("-", ",-"); while ( v.Length > 0 && (v[0] == ',' || v[0] == ' ') ) v = v.Substring(1); } switch ( coordinates[j][0] ) { case 'Z': case 'z': if ( spline != null ) { spline.closed = true; #if false Vector3 delta1 = spline.knots[0].outvec - spline.knots[0].p; spline.knots[0].invec = spline.knots[0].p - delta1; if ( spline.knots[0].p == spline.knots[spline.knots.Count - 1].p ) spline.knots.Remove(spline.knots[spline.knots.Count - 1]); #else int kc = spline.knots.Count - 1; spline.knots[0].invec = spline.knots[kc].invec; spline.knots.Remove(spline.knots[kc]); #endif } break; case 'M': spline = GetSpline(shape); spline.knots.Clear(); cp = ParseV2Split(v, 0); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = k.p; k.outvec = k.p; spline.knots.Add(k); break; case 'm': spline = GetSpline(shape); spline.knots.Clear(); //Debug.Log("v: " + v); coord = v.Split(" "[0]); //Debug.Log("m coords " + coord.Length); //Debug.Log("v2 " + coord[0]); for ( int k0 = 0; k0 < coord.Length - 1; k0 = k0 + 1 ) { //Debug.Log("v2 " + coord[k0]); Vector3 cp1 = ParseV2Split(coord[k0], 0); //Debug.Log("cp1 " + cp1); cp.x += cp1.x; //ParseV2Split(coord[k0], 0); // ParseV2(coord, k0); cp.y += cp1.y; k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = k.p; k.outvec = k.p; spline.knots.Add(k); } #if false Vector3 cp1 = ParseV2Split(v, 0); cp.x += cp1.x; cp.y += cp1.y; k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = k.p; k.outvec = k.p; spline.knots.Add(k); #endif break; case 'l': coord = v.Split(","[0]); for ( int k0 = 0; k0 < coord.Length; k0 = k0 + 2 ) cp += ParseV2(coord, k0); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); break; case 'c': coord = v.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); for ( int k2 = 0; k2 < coord.Length; k2 += 6 ) { cP1 = cp + ParseV2(coord, k2); cP2 = cp + ParseV2(coord, k2 + 2); cp += ParseV2(coord, k2 + 4); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cP2.x, 0.0f, cP2.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); } break; case 'L': coord = v.Split(","[0]); for ( int k3 = 0; k3 < coord.Length; k3 = k3 + 2 ) cp = ParseV2(coord, k3); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); break; case 'v': //Debug.Log("v: " + v); coord = v.Split(","[0]); for ( int k4 = 0; k4 < coord.Length; k4++ ) cp.y += float.Parse(coord[k4]); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); break; case 'V': coord = v.Split(","[0]); for ( int k9 = 0; k9 < coord.Length; k9++ ) cp.y = float.Parse(coord[k9]); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); break; case 'h': coord = v.Split(","[0]); for ( int k5 = 0; k5 < coord.Length; k5++ ) cp.x += float.Parse(coord[k5]); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); break; case 'H': coord = v.Split(","[0]); for ( int k6 = 0; k6 < coord.Length; k6++ ) cp.x = float.Parse(coord[k6]); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); break; case 'S': coord = v.Split(","[0]); for ( int k7 = 0; k7 < coord.Length; k7 = k7 + 4 ) { cp = ParseV2(coord, k7 + 2); cP1 = ParseV2(coord, k7); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); } break; case 's': coord = v.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); for ( int k7 = 0; k7 < coord.Length; k7 = k7 + 4 ) { cP1 = cp + ParseV2(coord, k7); cp += ParseV2(coord, k7 + 2); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); } break; case 'C': coord = v.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); for ( int k2 = 0; k2 < coord.Length; k2 += 6 ) { cP1 = ParseV2(coord, k2); cP2 = ParseV2(coord, k2 + 2); cp = ParseV2(coord, k2 + 4); spline.knots[spline.knots.Count - 1].outvec = SwapAxis(new Vector3(cP1.x, 0.0f, cP1.y), shape.axis); k = new MegaKnot(); k.p = SwapAxis(new Vector3(cp.x, 0.0f, cp.y), shape.axis); k.invec = SwapAxis(new Vector3(cP2.x, 0.0f, cP2.y), shape.axis); k.outvec = k.p - (k.invec - k.p); spline.knots.Add(k); } break; default: break; } } } break; } } } public void importData(string svgdata, MegaShape shape, float scale, bool clear, int start) { LoadXML(svgdata, shape, clear, start); for ( int i = start; i < splineindex; i++ ) { float area = shape.splines[i].Area(); if ( area < 0.0f ) shape.splines[i].reverse = false; else shape.splines[i].reverse = true; } //shape.Centre(0.01f, new Vector3(-1.0f, 1.0f, 1.0f)); //shape.Centre(scale, new Vector3(-1.0f, 1.0f, 1.0f), start); shape.CoordAdjust(scale, new Vector3(-1.0f, 1.0f, 1.0f), start); shape.CalcLength(); //10); } const float CIRCLE_VECTOR_LENGTH = 0.5517861843f; Vector2 ParseV2Split(string str, int i) { return ParseV2(str.Split(commaspace, StringSplitOptions.RemoveEmptyEntries), i); } Vector3 ParseV2(string[] str, int i) { Vector3 p = Vector2.zero; p.x = float.Parse(str[i]); p.y = float.Parse(str[i + 1]); return p; } static public string Export(MegaShape shape, int x, int y, float strokewidth, Color col) { string file = ""; Color32 c = col; file += "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; file += "<!-- MegaShapes SVG Exporter v1.0 -->\n"; file += "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"; file += "<svg version=\"1.1\" id=\"" + shape.name + "\" x=\"0px\" y=\"0px\" width=\"640.0px\" height=\"480.0px\">\n"; for ( int i = 0; i < shape.splines.Count; i++ ) { MegaSpline spline = shape.splines[i]; file += "<path d=\""; MegaKnot k1; MegaKnot k = spline.knots[0]; k1 = k; file += "M" + k.p[x] + "," + -k.p[y]; //Vector3 cp = k.p; for ( int j = 1; j < spline.knots.Count; j++ ) { k = spline.knots[j]; Vector3 po = k1.outvec; // - cp; // - k1.p; Vector3 pi = k.invec; // - cp; // - k.p; Vector3 kp = k.p; // - cp; kp[y] = -kp[y]; po[y] = -po[y]; pi[y] = -pi[y]; file += "C" + po[x] + "," + po[y]; file += " " + pi[x] + "," + pi[y]; file += " " + kp[x] + "," + kp[y]; k1 = k; } if ( spline.closed ) { file += "z\""; } file += " fill=\"none\""; file += " stroke=\"#" + c.r.ToString("x") + c.g.ToString("x") + c.b.ToString("x") + "\""; file += " stroke-width=\"" + strokewidth + "\""; file += "/>\n"; } file += "</svg>\n"; return file; } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="AdGroupExtensionSettingServiceClient"/> instances.</summary> public sealed partial class AdGroupExtensionSettingServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupExtensionSettingServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupExtensionSettingServiceSettings"/>.</returns> public static AdGroupExtensionSettingServiceSettings GetDefault() => new AdGroupExtensionSettingServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupExtensionSettingServiceSettings"/> object with default settings. /// </summary> public AdGroupExtensionSettingServiceSettings() { } private AdGroupExtensionSettingServiceSettings(AdGroupExtensionSettingServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateAdGroupExtensionSettingsSettings = existing.MutateAdGroupExtensionSettingsSettings; OnCopy(existing); } partial void OnCopy(AdGroupExtensionSettingServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupExtensionSettingServiceClient.MutateAdGroupExtensionSettings</c> and /// <c>AdGroupExtensionSettingServiceClient.MutateAdGroupExtensionSettingsAsync</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 MutateAdGroupExtensionSettingsSettings { 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="AdGroupExtensionSettingServiceSettings"/> object.</returns> public AdGroupExtensionSettingServiceSettings Clone() => new AdGroupExtensionSettingServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupExtensionSettingServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class AdGroupExtensionSettingServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupExtensionSettingServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupExtensionSettingServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupExtensionSettingServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupExtensionSettingServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupExtensionSettingServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupExtensionSettingServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupExtensionSettingServiceClient Build() { AdGroupExtensionSettingServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupExtensionSettingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupExtensionSettingServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupExtensionSettingServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupExtensionSettingServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupExtensionSettingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupExtensionSettingServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupExtensionSettingServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupExtensionSettingServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupExtensionSettingServiceClient.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>AdGroupExtensionSettingService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group extension settings. /// </remarks> public abstract partial class AdGroupExtensionSettingServiceClient { /// <summary> /// The default endpoint for the AdGroupExtensionSettingService 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 AdGroupExtensionSettingService scopes.</summary> /// <remarks> /// The default AdGroupExtensionSettingService 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="AdGroupExtensionSettingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupExtensionSettingServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupExtensionSettingServiceClient"/>.</returns> public static stt::Task<AdGroupExtensionSettingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupExtensionSettingServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupExtensionSettingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupExtensionSettingServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupExtensionSettingServiceClient"/>.</returns> public static AdGroupExtensionSettingServiceClient Create() => new AdGroupExtensionSettingServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupExtensionSettingServiceClient"/> 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="AdGroupExtensionSettingServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupExtensionSettingServiceClient"/>.</returns> internal static AdGroupExtensionSettingServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupExtensionSettingServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient grpcClient = new AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient(callInvoker); return new AdGroupExtensionSettingServiceClientImpl(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 AdGroupExtensionSettingService client</summary> public virtual AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupExtensionSettingsResponse MutateAdGroupExtensionSettings(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(MutateAdGroupExtensionSettingsRequest request, st::CancellationToken cancellationToken) => MutateAdGroupExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group extension settings are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group extension /// settings. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupExtensionSettingsResponse MutateAdGroupExtensionSettings(string customerId, scg::IEnumerable<AdGroupExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupExtensionSettings(new MutateAdGroupExtensionSettingsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group extension settings are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group extension /// settings. /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(string customerId, scg::IEnumerable<AdGroupExtensionSettingOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupExtensionSettingsAsync(new MutateAdGroupExtensionSettingsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group extension settings are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group extension /// settings. /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(string customerId, scg::IEnumerable<AdGroupExtensionSettingOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupExtensionSettingsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupExtensionSettingService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group extension settings. /// </remarks> public sealed partial class AdGroupExtensionSettingServiceClientImpl : AdGroupExtensionSettingServiceClient { private readonly gaxgrpc::ApiCall<MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse> _callMutateAdGroupExtensionSettings; /// <summary> /// Constructs a client wrapper for the AdGroupExtensionSettingService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupExtensionSettingServiceSettings"/> used within this client. /// </param> public AdGroupExtensionSettingServiceClientImpl(AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient grpcClient, AdGroupExtensionSettingServiceSettings settings) { GrpcClient = grpcClient; AdGroupExtensionSettingServiceSettings effectiveSettings = settings ?? AdGroupExtensionSettingServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateAdGroupExtensionSettings = clientHelper.BuildApiCall<MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse>(grpcClient.MutateAdGroupExtensionSettingsAsync, grpcClient.MutateAdGroupExtensionSettings, effectiveSettings.MutateAdGroupExtensionSettingsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupExtensionSettings); Modify_MutateAdGroupExtensionSettingsApiCall(ref _callMutateAdGroupExtensionSettings); 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_MutateAdGroupExtensionSettingsApiCall(ref gaxgrpc::ApiCall<MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse> call); partial void OnConstruction(AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient grpcClient, AdGroupExtensionSettingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupExtensionSettingService client</summary> public override AdGroupExtensionSettingService.AdGroupExtensionSettingServiceClient GrpcClient { get; } partial void Modify_MutateAdGroupExtensionSettingsRequest(ref MutateAdGroupExtensionSettingsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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 MutateAdGroupExtensionSettingsResponse MutateAdGroupExtensionSettings(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupExtensionSettingsRequest(ref request, ref callSettings); return _callMutateAdGroupExtensionSettings.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group extension settings. Operation /// statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CollectionSizeError]() /// [CriterionError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [ExtensionSettingError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [ListOperationError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperationAccessDeniedError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// [UrlFieldError]() /// </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<MutateAdGroupExtensionSettingsResponse> MutateAdGroupExtensionSettingsAsync(MutateAdGroupExtensionSettingsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupExtensionSettingsRequest(ref request, ref callSettings); return _callMutateAdGroupExtensionSettings.Async(request, callSettings); } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Windows.Forms; using Microsoft.VisualStudio.Designer.Interfaces; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.Project { /// <summary> /// The base class for property pages. /// </summary> public abstract class SettingsPage : LocalizableProperties, IPropertyPage, IDisposable { #region fields private Panel panel; private bool active; private bool dirty; private IPropertyPageSite site; private ProjectNode project; private ProjectConfig[] projectConfigs; private IVSMDPropertyGrid grid; private string name; private static volatile object Mutex = new object(); private bool isDisposed; #endregion #region properties [Browsable(false)] [AutomationBrowsable(false)] public string Name { get { return this.name; } set { this.name = value; } } [Browsable(false)] [AutomationBrowsable(false)] public ProjectNode ProjectMgr { get { return this.project; } } protected IVSMDPropertyGrid Grid { get { return this.grid; } } protected bool IsDirty { get { return this.dirty; } set { if(this.dirty != value) { this.dirty = value; if(this.site != null) site.OnStatusChange((uint)(this.dirty ? PropPageStatus.Dirty : PropPageStatus.Clean)); } } } protected Panel ThePanel { get { return this.panel; } } #endregion #region abstract methods protected abstract void BindProperties(); protected abstract int ApplyChanges(); #endregion #region public methods public object GetTypedConfigProperty(string name, Type type) { string value = GetConfigProperty(name); if(string.IsNullOrEmpty(value)) return null; TypeConverter tc = TypeDescriptor.GetConverter(type); return tc.ConvertFromInvariantString(value); } public object GetTypedProperty(string name, Type type) { string value = GetProperty(name); if(string.IsNullOrEmpty(value)) return null; TypeConverter tc = TypeDescriptor.GetConverter(type); return tc.ConvertFromInvariantString(value); } public string GetProperty(string propertyName) { if(this.ProjectMgr != null) { string property; bool found = this.ProjectMgr.BuildProject.GlobalProperties.TryGetValue(propertyName, out property); if(found) { return property; } } return String.Empty; } // relative to active configuration. public string GetConfigProperty(string propertyName) { if(this.ProjectMgr != null) { string unifiedResult = null; bool cacheNeedReset = true; for(int i = 0; i < this.projectConfigs.Length; i++) { ProjectConfig config = projectConfigs[i]; string property = config.GetConfigurationProperty(propertyName, cacheNeedReset); cacheNeedReset = false; if(property != null) { string text = property.Trim(); if(i == 0) unifiedResult = text; else if(unifiedResult != text) return ""; // tristate value is blank then } } return unifiedResult; } return String.Empty; } /// <summary> /// Sets the value of a configuration dependent property. /// If the attribute does not exist it is created. /// If value is null it will be set to an empty string. /// </summary> /// <param name="name">property name.</param> /// <param name="value">value of property</param> public void SetConfigProperty(string name, string value) { CCITracing.TraceCall(); if(value == null) { value = String.Empty; } if(this.ProjectMgr != null) { for(int i = 0, n = this.projectConfigs.Length; i < n; i++) { ProjectConfig config = projectConfigs[i]; config.SetConfigurationProperty(name, value); } this.ProjectMgr.SetProjectFileDirty(true); } } #endregion #region IPropertyPage methods. public virtual void Activate(IntPtr parent, RECT[] pRect, int bModal) { if(this.panel == null) { if (pRect == null) { throw new ArgumentNullException("pRect"); } this.panel = new Panel(); this.panel.Size = new Size(pRect[0].right - pRect[0].left, pRect[0].bottom - pRect[0].top); this.panel.Text = SR.GetString(SR.Settings, CultureInfo.CurrentUICulture); this.panel.Visible = false; this.panel.Size = new Size(550, 300); this.panel.CreateControl(); NativeMethods.SetParent(this.panel.Handle, parent); } if(this.grid == null && this.project != null && this.project.Site != null) { IVSMDPropertyBrowser pb = this.project.Site.GetService(typeof(IVSMDPropertyBrowser)) as IVSMDPropertyBrowser; this.grid = pb.CreatePropertyGrid(); } if(this.grid != null) { this.active = true; Control cGrid = Control.FromHandle(new IntPtr(this.grid.Handle)); cGrid.Parent = Control.FromHandle(parent);//this.panel; cGrid.Size = new Size(544, 294); cGrid.Location = new Point(3, 3); cGrid.Visible = true; this.grid.SetOption(_PROPERTYGRIDOPTION.PGOPT_TOOLBAR, false); this.grid.GridSort = _PROPERTYGRIDSORT.PGSORT_CATEGORIZED | _PROPERTYGRIDSORT.PGSORT_ALPHABETICAL; NativeMethods.SetParent(new IntPtr(this.grid.Handle), this.panel.Handle); UpdateObjects(); } } public virtual int Apply() { if(IsDirty) { return this.ApplyChanges(); } return VSConstants.S_OK; } public virtual void Deactivate() { if(null != this.panel) { this.panel.Dispose(); this.panel = null; } this.active = false; } public virtual void GetPageInfo(PROPPAGEINFO[] arrInfo) { if (arrInfo == null) { throw new ArgumentNullException("arrInfo"); } PROPPAGEINFO info = new PROPPAGEINFO(); info.cb = (uint)Marshal.SizeOf(typeof(PROPPAGEINFO)); info.dwHelpContext = 0; info.pszDocString = null; info.pszHelpFile = null; info.pszTitle = this.name; info.SIZE.cx = 550; info.SIZE.cy = 300; arrInfo[0] = info; } public virtual void Help(string helpDir) { } public virtual int IsPageDirty() { // Note this returns an HRESULT not a Bool. return (IsDirty ? (int)VSConstants.S_OK : (int)VSConstants.S_FALSE); } public virtual void Move(RECT[] arrRect) { if (arrRect == null) { throw new ArgumentNullException("arrRect"); } RECT r = arrRect[0]; this.panel.Location = new Point(r.left, r.top); this.panel.Size = new Size(r.right - r.left, r.bottom - r.top); } public virtual void SetObjects(uint count, object[] punk) { if (punk == null) { return; } if(count > 0) { if(punk[0] is ProjectConfig) { ArrayList configs = new ArrayList(); for(int i = 0; i < count; i++) { ProjectConfig config = (ProjectConfig)punk[i]; if(this.project == null || (this.project != (punk[0] as ProjectConfig).ProjectMgr)) { this.project = config.ProjectMgr; } configs.Add(config); } this.projectConfigs = (ProjectConfig[])configs.ToArray(typeof(ProjectConfig)); } else if(punk[0] is NodeProperties) { if (this.project == null || (this.project != (punk[0] as NodeProperties).Node.ProjectMgr)) { this.project = (punk[0] as NodeProperties).Node.ProjectMgr; } System.Collections.Generic.Dictionary<string, ProjectConfig> configsMap = new System.Collections.Generic.Dictionary<string, ProjectConfig>(); for(int i = 0; i < count; i++) { NodeProperties property = (NodeProperties)punk[i]; IVsCfgProvider provider; ErrorHandler.ThrowOnFailure(property.Node.ProjectMgr.GetCfgProvider(out provider)); uint[] expected = new uint[1]; ErrorHandler.ThrowOnFailure(provider.GetCfgs(0, null, expected, null)); if(expected[0] > 0) { ProjectConfig[] configs = new ProjectConfig[expected[0]]; uint[] actual = new uint[1]; ErrorHandler.ThrowOnFailure(provider.GetCfgs(expected[0], configs, actual, null)); foreach(ProjectConfig config in configs) { if(!configsMap.ContainsKey(config.ConfigName)) { configsMap.Add(config.ConfigName, config); } } } } if(configsMap.Count > 0) { if(this.projectConfigs == null) { this.projectConfigs = new ProjectConfig[configsMap.Keys.Count]; } configsMap.Values.CopyTo(this.projectConfigs, 0); } } } else { this.project = null; } if(this.active && this.project != null) { UpdateObjects(); } } public virtual void SetPageSite(IPropertyPageSite theSite) { this.site = theSite; } public virtual void Show(uint cmd) { this.panel.Visible = true; // TODO: pass SW_SHOW* flags through this.panel.Show(); } public virtual int TranslateAccelerator(MSG[] arrMsg) { if (arrMsg == null) { throw new ArgumentNullException("arrMsg"); } MSG msg = arrMsg[0]; if((msg.message < NativeMethods.WM_KEYFIRST || msg.message > NativeMethods.WM_KEYLAST) && (msg.message < NativeMethods.WM_MOUSEFIRST || msg.message > NativeMethods.WM_MOUSELAST)) return 1; return (NativeMethods.IsDialogMessageA(this.panel.Handle, ref msg)) ? 0 : 1; } #endregion #region helper methods protected ProjectConfig[] GetProjectConfigurations() { return this.projectConfigs; } protected void UpdateObjects() { if(this.projectConfigs != null && this.project != null) { // Demand unmanaged permissions in order to access unmanaged memory. new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); IntPtr p = Marshal.GetIUnknownForObject(this); IntPtr ppUnk = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(IntPtr))); try { Marshal.WriteIntPtr(ppUnk, p); this.BindProperties(); // BUGBUG -- this is really bad casting a pointer to "int"... this.grid.SetSelectedObjects(1, ppUnk.ToInt32()); this.grid.Refresh(); } finally { if(ppUnk != IntPtr.Zero) { Marshal.FreeCoTaskMem(ppUnk); } if(p != IntPtr.Zero) { Marshal.Release(p); } } } } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion private void Dispose(bool disposing) { if(!this.isDisposed) { lock(Mutex) { if(disposing) { this.panel.Dispose(); } this.isDisposed = true; } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: ProviderMetadataCachedInformation ** ** Purpose: ** This internal class exposes a limited set of cached Provider ** metadata information. It is meant to support the Metadata ** ============================================================*/ using System; using System.Globalization; using System.Collections.Generic; using System.Threading; using System.Timers; using System.Security.Permissions; using Microsoft.Win32; namespace System.Diagnostics.Eventing.Reader { // // this class does not expose underlying Provider metadata objects. Instead it // exposes a limited set of Provider metadata information from the cache. The reason // for this is so the cache can easily Dispose the metadata object without worrying // about who is using it. // internal class ProviderMetadataCachedInformation { private Dictionary<ProviderMetadataId, CacheItem> cache; private int maximumCacheSize; private EventLogSession session; private string logfile; private class ProviderMetadataId { private string providerName; private CultureInfo cultureInfo; public ProviderMetadataId(string providerName, CultureInfo cultureInfo) { this.providerName = providerName; this.cultureInfo = cultureInfo; } public override bool Equals(object obj) { ProviderMetadataId rhs = obj as ProviderMetadataId; if (rhs == null) return false; if (this.providerName.Equals(rhs.providerName) && (cultureInfo == rhs.cultureInfo)) return true; return false; } public override int GetHashCode() { return this.providerName.GetHashCode() ^ cultureInfo.GetHashCode(); } public string ProviderName { get { return providerName; } } public CultureInfo TheCultureInfo { get { return cultureInfo; } } } private class CacheItem { private ProviderMetadata pm; private DateTime theTime; public CacheItem(ProviderMetadata pm) { this.pm = pm; theTime = DateTime.Now; } public DateTime TheTime { get { return theTime; } set { theTime = value; } } public ProviderMetadata ProviderMetadata { get { return pm; } } } public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) { Debug.Assert(session != null); this.session = session; this.logfile = logfile; cache = new Dictionary<ProviderMetadataId, CacheItem>(); this.maximumCacheSize = maximumCacheSize; } private bool IsCacheFull() { return cache.Count == maximumCacheSize; } private bool IsProviderinCache(ProviderMetadataId key) { return cache.ContainsKey(key); } private void DeleteCacheEntry(ProviderMetadataId key) { if (!IsProviderinCache(key)) return; CacheItem value = cache[key]; cache.Remove(key); value.ProviderMetadata.Dispose(); } private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm) { if (IsCacheFull()) FlushOldestEntry(); CacheItem value = new CacheItem(pm); cache.Add(key, value); return; } private void FlushOldestEntry() { double maxPassedTime = -10; DateTime timeNow = DateTime.Now; ProviderMetadataId keyToDelete = null; //get the entry in the cache which was not accessed for the longest time. foreach (KeyValuePair<ProviderMetadataId, CacheItem> kvp in cache) { //the time difference (in ms) between the timeNow and the last used time of each entry TimeSpan timeDifference = timeNow.Subtract(kvp.Value.TheTime); //for the "unused" items (with ReferenceCount == 0) -> can possible be deleted. if (timeDifference.TotalMilliseconds >= maxPassedTime) { maxPassedTime = timeDifference.TotalMilliseconds; keyToDelete = kvp.Key; } } if (keyToDelete != null) DeleteCacheEntry(keyToDelete); } private static void UpdateCacheValueInfoForHit(CacheItem cacheItem) { cacheItem.TheTime = DateTime.Now; } private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { if (!IsProviderinCache(key)) { ProviderMetadata pm; try { pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo, this.logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo); } AddCacheEntry(key, pm); return pm; } else { CacheItem cacheItem = cache[key]; ProviderMetadata pm = cacheItem.ProviderMetadata; // // check Provider metadata to be sure it's hasn't been // uninstalled since last time it was used. // try { pm.CheckReleased(); UpdateCacheValueInfoForHit(cacheItem); } catch (EventLogException) { DeleteCacheEntry(key); try { pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo, this.logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, this.session, key.TheCultureInfo); } AddCacheEntry(key, pm); } return pm; } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); try { ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent); } catch (EventLogNotFoundException) { return null; } } } public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); try { return NativeWrapper.EvtFormatMessageFormatDescription(pm.Handle, eventHandle, values); } catch (EventLogNotFoundException) { return null; } } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public IEnumerable<string> GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword); } } } }
// 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 BlendInt321() { var test = new ImmBinaryOpTest__BlendInt321(); 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 ImmBinaryOpTest__BlendInt321 { private struct TestStruct { public Vector128<Int32> _fld1; public Vector128<Int32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__BlendInt321 testClass) { var result = Avx2.Blend(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static Int32[] _data1 = new Int32[Op1ElementCount]; private static Int32[] _data2 = new Int32[Op2ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32, Int32, Int32> _dataTable; static ImmBinaryOpTest__BlendInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmBinaryOpTest__BlendInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32, Int32, Int32>(_data1, _data2, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Blend( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Blend( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Blend( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)), 1 ); 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(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Blend( _clsVar1, _clsVar2, 1 ); 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<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Avx2.Blend(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__BlendInt321(); var result = Avx2.Blend(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Blend(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Blend(test._fld1, test._fld2, 1); 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<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[Op1ElementCount]; Int32[] inArray2 = new Int32[Op2ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != (((1 & (1 << 0)) == 0) ? left[0] : right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (((1 & (1 << i)) == 0) ? left[i] : right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<Int32>(Vector128<Int32>.1, Vector128<Int32>): {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; } } } }
/// <summary> /// Xcode PBX support library. This is from the Unity open source. /// https://bitbucket.org/Unity-Technologies/xcodeapi/overview /// </summary> /// /// The MIT License (MIT) /// Copyright (c) 2014 Unity Technologies /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. /// #if !UNITY_5 namespace GooglePlayGames.xcode { using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System.Linq; class PropertyCommentChecker { private int m_Level; private bool m_All; private List<List<string>> m_Props; /* The argument is an array of matcher strings each of which determine whether a property with a certain path needs to be decorated with a comment. A path is a number of path elements concatenated by '/'. The last path element is either: the key if we're referring to a dict key the value if we're referring to a value in an array the value if we're referring to a value in a dict All other path elements are either: the key if the container is dict '*' if the container is array Path matcher has the same structure as a path, except that any of the elements may be '*'. Matcher matches a path if both have the same number of elements and for each pair matcher element is the same as path element or is '*'. a/b/c matches a/b/c but not a/b nor a/b/c/d a/* /c matches a/d/c but not a/b nor a/b/c/d * /* /* matches any path from three elements */ protected PropertyCommentChecker(int level, List<List<string>> props) { m_Level = level; m_All = false; m_Props = props; } public PropertyCommentChecker() { m_Level = 0; m_All = false; m_Props = new List<List<string>>(); } public PropertyCommentChecker(IEnumerable<string> props) { m_Level = 0; m_All = false; m_Props = new List<List<string>>(); foreach (var prop in props) { m_Props.Add(new List<string>(prop.Split('/'))); } } bool CheckContained(string prop) { if (m_All) return true; foreach (var list in m_Props) { if (list.Count == m_Level+1) { if (list[m_Level] == prop) return true; if (list[m_Level] == "*") { m_All = true; // short-circuit all at this level return true; } } } return false; } public bool CheckStringValueInArray(string value) { return CheckContained(value); } public bool CheckKeyInDict(string key) { return CheckContained(key); } public bool CheckStringValueInDict(string key, string value) { foreach (var list in m_Props) { if (list.Count == m_Level + 2) { if ((list[m_Level] == "*" || list[m_Level] == key) && list[m_Level+1] == "*" || list[m_Level+1] == value) return true; } } return false; } public PropertyCommentChecker NextLevel(string prop) { var newList = new List<List<string>>(); foreach (var list in m_Props) { if (list.Count <= m_Level+1) continue; if (list[m_Level] == "*" || list[m_Level] == prop) newList.Add(list); } return new PropertyCommentChecker(m_Level + 1, newList); } } class Serializer { public static PBXElementDict ParseTreeAST(TreeAST ast, TokenList tokens, string text) { var el = new PBXElementDict(); foreach (var kv in ast.values) { PBXElementString key = ParseIdentifierAST(kv.key, tokens, text); PBXElement value = ParseValueAST(kv.value, tokens, text); el[key.value] = value; } return el; } public static PBXElementArray ParseArrayAST(ArrayAST ast, TokenList tokens, string text) { var el = new PBXElementArray(); foreach (var v in ast.values) { el.values.Add(ParseValueAST(v, tokens, text)); } return el; } public static PBXElement ParseValueAST(ValueAST ast, TokenList tokens, string text) { if (ast is TreeAST) return ParseTreeAST((TreeAST)ast, tokens, text); if (ast is ArrayAST) return ParseArrayAST((ArrayAST)ast, tokens, text); if (ast is IdentifierAST) return ParseIdentifierAST((IdentifierAST)ast, tokens, text); return null; } public static PBXElementString ParseIdentifierAST(IdentifierAST ast, TokenList tokens, string text) { Token tok = tokens[ast.value]; string value; switch (tok.type) { case TokenType.String: value = text.Substring(tok.begin, tok.end - tok.begin); return new PBXElementString(value); case TokenType.QuotedString: value = text.Substring(tok.begin, tok.end - tok.begin); value = PBXStream.UnquoteString(value); return new PBXElementString(value); default: throw new Exception("Internal parser error"); } } static string k_Indent = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; static string GetIndent(int indent) { return k_Indent.Substring(0, indent); } static void WriteStringImpl(StringBuilder sb, string s, bool comment, GUIDToCommentMap comments) { if (comment) comments.WriteStringBuilder(sb, s); else sb.Append(PBXStream.QuoteStringIfNeeded(s)); } public static void WriteDictKeyValue(StringBuilder sb, string key, PBXElement value, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } WriteStringImpl(sb, key, checker.CheckKeyInDict(key), comments); sb.Append(" = "); if (value is PBXElementString) WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInDict(key, value.AsString()), comments); else if (value is PBXElementDict) WriteDict(sb, value.AsDict(), indent, compact, checker.NextLevel(key), comments); else if (value is PBXElementArray) WriteArray(sb, value.AsArray(), indent, compact, checker.NextLevel(key), comments); sb.Append(";"); if (compact) sb.Append(" "); } public static void WriteDict(StringBuilder sb, PBXElementDict el, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { sb.Append("{"); if (el.Contains("isa")) WriteDictKeyValue(sb, "isa", el["isa"], indent+1, compact, checker, comments); var keys = new List<string>(el.values.Keys); keys.Sort(StringComparer.Ordinal); foreach (var key in keys) { if (key != "isa") WriteDictKeyValue(sb, key, el[key], indent+1, compact, checker, comments); } if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } sb.Append("}"); } public static void WriteArray(StringBuilder sb, PBXElementArray el, int indent, bool compact, PropertyCommentChecker checker, GUIDToCommentMap comments) { sb.Append("("); foreach (var value in el.values) { if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent+1)); } if (value is PBXElementString) WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInArray(value.AsString()), comments); else if (value is PBXElementDict) WriteDict(sb, value.AsDict(), indent+1, compact, checker.NextLevel("*"), comments); else if (value is PBXElementArray) WriteArray(sb, value.AsArray(), indent+1, compact, checker.NextLevel("*"), comments); sb.Append(","); if (compact) sb.Append(" "); } if (!compact) { sb.Append("\n"); sb.Append(GetIndent(indent)); } sb.Append(")"); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // QueuedMap.cs // // // A key-value pair queue, where pushing an existing key into the collection overwrites // the existing value. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading.Tasks.Dataflow.Internal { /// <summary> /// Provides a data structure that supports pushing and popping key/value pairs. /// Pushing a key/value pair for which the key already exists results in overwriting /// the existing key entry's value. /// </summary> /// <typeparam name="TKey">Specifies the type of keys in the map.</typeparam> /// <typeparam name="TValue">Specifies the type of values in the map.</typeparam> /// <remarks>This type is not thread-safe.</remarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(EnumerableDebugView<,>))] internal sealed class QueuedMap<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { /// <summary> /// A queue structure that uses an array-based list to store its items /// and that supports overwriting elements at specific indices. /// </summary> /// <typeparam name="T">The type of the items storedin the queue</typeparam> /// <remarks>This type is not thread-safe.</remarks> private sealed class ArrayBasedLinkedQueue<T> : IEnumerable<T> { /// <summary>Terminator index.</summary> private const int TERMINATOR_INDEX = -1; /// <summary> /// The queue where the items will be stored. /// The key of each entry is the index of the next entry in the queue. /// </summary> private readonly List<KeyValuePair<int, T>> _storage; /// <summary>Index of the first queue item.</summary> private int _headIndex = TERMINATOR_INDEX; /// <summary>Index of the last queue item.</summary> private int _tailIndex = TERMINATOR_INDEX; /// <summary>Index of the first free slot.</summary> private int _freeIndex = TERMINATOR_INDEX; /// <summary>Initializes the Queue instance.</summary> internal ArrayBasedLinkedQueue() { _storage = new List<KeyValuePair<int, T>>(); } /// <summary>Initializes the Queue instance.</summary> /// <param name="capacity">The capacity of the internal storage.</param> internal ArrayBasedLinkedQueue(int capacity) { _storage = new List<KeyValuePair<int, T>>(capacity); } /// <summary>Enqueues an item.</summary> /// <param name="item">The item to be enqueued.</param> /// <returns>The index of the slot where item was stored.</returns> internal int Enqueue(T item) { int newIndex; // If there is a free slot, reuse it if (_freeIndex != TERMINATOR_INDEX) { Contract.Assert(0 <= _freeIndex && _freeIndex < _storage.Count, "Index is out of range."); newIndex = _freeIndex; _freeIndex = _storage[_freeIndex].Key; _storage[newIndex] = new KeyValuePair<int, T>(TERMINATOR_INDEX, item); } // If there is no free slot, add one else { newIndex = _storage.Count; _storage.Add(new KeyValuePair<int, T>(TERMINATOR_INDEX, item)); } if (_headIndex == TERMINATOR_INDEX) { // Point m_headIndex to newIndex if the queue was empty Contract.Assert(_tailIndex == TERMINATOR_INDEX, "If head indicates empty, so too should tail."); _headIndex = newIndex; } else { // Point the tail slot to newIndex if the queue was not empty Contract.Assert(_tailIndex != TERMINATOR_INDEX, "If head does not indicate empty, neither should tail."); _storage[_tailIndex] = new KeyValuePair<int, T>(newIndex, _storage[_tailIndex].Value); } // Point the tail slot newIndex _tailIndex = newIndex; return newIndex; } /// <summary>Tries to dequeue an item.</summary> /// <param name="item">The item that is dequeued.</param> internal bool TryDequeue(out T item) { // If the queue is empty, just initialize the output item and return false if (_headIndex == TERMINATOR_INDEX) { Contract.Assert(_tailIndex == TERMINATOR_INDEX, "If head indicates empty, so too should tail."); item = default(T); return false; } // If there are items in the queue, start with populating the output item Contract.Assert(0 <= _headIndex && _headIndex < _storage.Count, "Head is out of range."); item = _storage[_headIndex].Value; // Move the popped slot to the head of the free list int newHeadIndex = _storage[_headIndex].Key; _storage[_headIndex] = new KeyValuePair<int, T>(_freeIndex, default(T)); _freeIndex = _headIndex; _headIndex = newHeadIndex; if (_headIndex == TERMINATOR_INDEX) _tailIndex = TERMINATOR_INDEX; return true; } /// <summary>Replaces the item of a given slot.</summary> /// <param name="index">The index of the slot where the value should be replaced.</param> /// <param name="item">The item to be places.</param> internal void Replace(int index, T item) { Contract.Assert(0 <= index && index < _storage.Count, "Index is out of range."); #if DEBUG // Also assert that index does not belong to the list of free slots for (int idx = _freeIndex; idx != TERMINATOR_INDEX; idx = _storage[idx].Key) Contract.Assert(idx != index, "Index should not belong to the list of free slots."); #endif _storage[index] = new KeyValuePair<int, T>(_storage[index].Key, item); } internal void Clear() { _storage.Clear(); _headIndex = TERMINATOR_INDEX; _tailIndex = TERMINATOR_INDEX; _freeIndex = TERMINATOR_INDEX; } internal bool IsEmpty { get { return _headIndex == TERMINATOR_INDEX; } } public IEnumerator<T> GetEnumerator() { for (int index = _headIndex; index != TERMINATOR_INDEX; index = _storage[index].Key) yield return _storage[index].Value; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// <summary>The queue of elements.</summary> private readonly ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>> _queue; /// <summary>A map from key to index into the list.</summary> /// <remarks>The correctness of this map relies on the list only having elements removed from its end.</remarks> private readonly Dictionary<TKey, int> _mapKeyToIndex; /// <summary>Initializes the QueuedMap.</summary> internal QueuedMap() { _queue = new ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>>(); _mapKeyToIndex = new Dictionary<TKey, int>(); } /// <summary>Initializes the QueuedMap.</summary> /// <param name="capacity">The initial capacity of the data structure.</param> internal QueuedMap(int capacity) { _queue = new ArrayBasedLinkedQueue<KeyValuePair<TKey, TValue>>(capacity); _mapKeyToIndex = new Dictionary<TKey, int>(capacity); } /// <summary>Pushes a key/value pair into the data structure.</summary> /// <param name="key">The key for the pair.</param> /// <param name="value">The value for the pair.</param> internal void Push(TKey key, TValue value) { // Try to get the index of the key in the queue. If it's there, replace the value. int indexOfKeyInQueue; if (!_queue.IsEmpty && _mapKeyToIndex.TryGetValue(key, out indexOfKeyInQueue)) { _queue.Replace(indexOfKeyInQueue, new KeyValuePair<TKey, TValue>(key, value)); } // If it's not there, add it to the queue and then add the mapping. else { indexOfKeyInQueue = _queue.Enqueue(new KeyValuePair<TKey, TValue>(key, value)); _mapKeyToIndex.Add(key, indexOfKeyInQueue); } } /// <summary>Try to pop the next element from the data structure.</summary> /// <param name="item">The popped pair.</param> /// <returns>true if an item could be popped; otherwise, false.</returns> internal bool TryPop(out KeyValuePair<TKey, TValue> item) { bool popped = _queue.TryDequeue(out item); if (popped) _mapKeyToIndex.Remove(item.Key); return popped; } /// <summary>Tries to pop one or more elements from the data structure.</summary> /// <param name="items">The items array into which the popped elements should be stored.</param> /// <param name="arrayOffset">The offset into the array at which to start storing popped items.</param> /// <param name="count">The number of items to be popped.</param> /// <returns>The number of items popped, which may be less than the requested number if fewer existed in the data structure.</returns> internal int PopRange(KeyValuePair<TKey, TValue>[] items, int arrayOffset, int count) { // As this data structure is internal, only assert incorrect usage. // If this were to ever be made public, these would need to be real argument checks. Contract.Requires(items != null, "Requires non-null array to store into."); Contract.Requires(count >= 0 && arrayOffset >= 0, "Count and offset must be non-negative"); Contract.Requires(arrayOffset + count >= 0, "Offset plus count overflowed"); Contract.Requires(arrayOffset + count <= items.Length, "Range must be within array size"); int actualCount = 0; for (int i = arrayOffset; actualCount < count; i++, actualCount++) { KeyValuePair<TKey, TValue> item; if (TryPop(out item)) items[i] = item; else break; } return actualCount; } /// <summary>Removes all elements from the data structure.</summary> internal void Clear() { _queue.Clear(); _mapKeyToIndex.Clear(); } /// <summary>Gets the number of items in the data structure.</summary> internal int Count { get { return _mapKeyToIndex.Count; } } /// <summary>Gets an enumerator for the contents of the queued map.</summary> /// <returns>An enumerator for the contents of the queued map.</returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return _queue.GetEnumerator(); } /// <summary>Gets an enumerator for the contents of the queued map.</summary> /// <returns>An enumerator for the contents of the queued map.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using UnityEngine; using System.Collections.Generic; public class MegaLoftLayerCloneSplineSimple : MegaLoftLayerBase { public bool showstartparams = true; public bool showmainparams = true; public bool showendparams = true; public bool StartEnabled = true; public bool MainEnabled = true; public bool EndEnabled = true; public Vector3 StartScale = Vector3.one; public Vector3 MainScale = Vector3.one; public Vector3 EndScale = Vector3.one; public float Start = 0.0f; public float GlobalScale = 1.0f; public float StartGap = 0.0f; public float EndGap = 0.0f; public float Gap = 0.0f; public float RemoveDof = 1.0f; public int repeat = 1; public float Length = 0.0f; public float tangent = 0.1f; public MegaAxis axis = MegaAxis.X; public Vector3 rot = Vector3.zero; public Mesh startObj; public Mesh mainObj; public Mesh endObj; public float twist = 0.0f; public float damage = 0.0f; public int curve = 0; public bool useTwist = false; public AnimationCurve ScaleCrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0)); public AnimationCurve twistCrv = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0)); public Vector3 StartOff = Vector3.zero; public Vector3 MainOff = Vector3.zero; // If we have multi mains then each needs a value public Vector3 EndOff = Vector3.zero; public Vector3 rotPath = Vector3.zero; public Vector3 offPath = Vector3.zero; public Vector3 sclPath = Vector3.one; public bool snap = false; //public MegaAxis meshAxis = MegaAxis.Z; // normals as well Vector3[] sverts; Vector2[] suvs; int[] stris; Vector3[] mverts; Vector2[] muvs; int[] mtris; Vector3[] everts; Vector2[] euvs; int[] etris; Matrix4x4 meshtm; Matrix4x4 tm; Matrix4x4 mat; Quaternion meshrot; Quaternion tw; Matrix4x4 wtm; Matrix4x4 pathtm = Matrix4x4.identity; [ContextMenu("Help")] public void HelpCom() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=2159"); } public override bool Valid() { if ( LayerEnabled && layerPath && layerPath.splines != null ) { if ( startObj || mainObj || endObj ) return true; } return false; } void Init() { //transform.position = Vector3.zero; if ( startObj != null ) { sverts = startObj.vertices; suvs = startObj.uv; stris = startObj.triangles; } if ( endObj != null ) { everts = endObj.vertices; euvs = endObj.uv; etris = endObj.triangles; } if ( mainObj != null ) { mverts = mainObj.vertices; muvs = mainObj.uv; mtris = mainObj.triangles; } } public override Vector3 GetPos(MegaShapeLoft loft, float ca, float a) { return Vector3.zero; } public override bool PrepareLoft(MegaShapeLoft loft, int sc) { Init(); int vcount = 0; int tcount = 0; if ( startObj && StartEnabled ) { vcount += sverts.Length; tcount += stris.Length; } if ( endObj && EndEnabled ) { vcount += everts.Length; tcount += etris.Length; } if ( mainObj && MainEnabled ) { if ( Length != 0.0f ) { MegaShape path = layerPath; if ( path ) { float dist = path.splines[curve].length * Length; Vector3 scl = MainScale * GlobalScale; Vector3 size = Vector3.zero; size.x = (mainObj.bounds.size.x + Gap) * scl.x; size.y = (mainObj.bounds.size.y + Gap) * scl.y; size.z = (mainObj.bounds.size.z + Gap) * scl.z; repeat = (int)(dist / size[(int)axis]); if ( repeat < 0 ) repeat = 0; } } vcount += (mverts.Length * repeat); tcount += (mtris.Length * repeat); } if ( loftverts == null || loftverts.Length != vcount ) loftverts = new Vector3[vcount]; if ( loftuvs == null || loftuvs.Length != vcount ) loftuvs = new Vector2[vcount]; if ( lofttris == null || lofttris.Length != tcount ) lofttris = new int[tcount]; return true; } Vector3 Deform(Vector3 p, MegaShape path, float percent, float off, Vector3 scale, float removeDof, Vector3 locoff, Vector3 sploff) { p = tm.MultiplyPoint3x4(p); p.x *= scale.x; p.y *= scale.y; p.z *= scale.z; p.z += off; p += locoff; float alpha = (p.z / path.splines[curve].length) + percent; float tw1 = 0.0f; Vector3 ps = pathtm.MultiplyPoint(path.InterpCurve3D(curve, alpha, path.normalizedInterp, ref tw1) + sploff); Vector3 ps1 = pathtm.MultiplyPoint(path.InterpCurve3D(curve, alpha + (tangent * 0.001f), path.normalizedInterp) + sploff); if ( path.splines[curve].closed ) alpha = Mathf.Repeat(alpha, 1.0f); else alpha = Mathf.Clamp01(alpha); if ( useTwist ) { //float tw1 = path.splines[curve].GetTwist(alpha); tw = meshrot * Quaternion.AngleAxis((twist * twistCrv.Evaluate(alpha)) + tw1, Vector3.forward); } Vector3 relativePos = ps1 - ps; relativePos.y *= removeDof; Quaternion rotation = Quaternion.LookRotation(relativePos) * tw; // * meshrot; //wtm.SetTRS(ps, rotation, Vector3.one); MegaMatrix.SetTR(ref wtm, ps, rotation); wtm = mat * wtm; p.z = 0.0f; return wtm.MultiplyPoint3x4(p); } public override int BuildMesh(MegaShapeLoft loft, int triindex) { MegaShape path = layerPath; if ( tangent < 0.1f ) tangent = 0.1f; //if ( snaptopath ) //{ //mat = path.transform.worldToLocalMatrix * transform.localToWorldMatrix; // * transform.worldToLocalMatrix; //mat = surfaceLoft.transform.localToWorldMatrix; //mat = transform.localToWorldMatrix * layerPath.transform.worldToLocalMatrix; // * transform.worldToLocalMatrix; //mat = surfaceLoft.transform.localToWorldMatrix; //mat = layerPath.transform.worldToLocalMatrix; // * transform.localToWorldMatrix; // * transform.worldToLocalMatrix; //mat = surfaceLoft.transform.localToWorldMatrix; //} //else //{ mat = Matrix4x4.identity; //path.transform.localToWorldMatrix; //} //mat = Matrix4x4.identity; //transform.worldToLocalMatrix; //mat = transform.localToWorldMatrix * path.transform.worldToLocalMatrix; // * transform.worldToLocalMatrix; //mat = surfaceLoft.transform.localToWorldMatrix; //mat = path.transform.worldToLocalMatrix * transform.localToWorldMatrix; // * transform.worldToLocalMatrix; //mat = surfaceLoft.transform.localToWorldMatrix; tm = Matrix4x4.identity; switch ( axis ) { case MegaAxis.X: MegaMatrix.RotateY(ref tm, -Mathf.PI * 0.5f); break; case MegaAxis.Y: MegaMatrix.RotateX(ref tm, -Mathf.PI * 0.5f); break; case MegaAxis.Z: break; } meshtm = Matrix4x4.identity; MegaMatrix.Rotate(ref meshtm, Mathf.Deg2Rad * rot); meshrot = Quaternion.Euler(rot); tw = meshrot; pathtm.SetTRS(offPath, Quaternion.Euler(rotPath), sclPath); float off = 0.0f; int trioff = 0; int vi = 0; int fi = 0; Vector3 sploff = Vector3.zero; if ( snap ) sploff = path.splines[0].knots[0].p - path.splines[curve].knots[0].p; int ax = (int)axis; float palpha = Start; // * 0.01f; if ( startObj != null && StartEnabled ) { Vector3 sscl = StartScale * GlobalScale; Vector3 soff = Vector3.Scale(StartOff, sscl); off -= startObj.bounds.min[(int)axis] * sscl[ax]; for ( int i = 0; i < sverts.Length; i++ ) { Vector3 p = sverts[i]; p = Deform(p, path, palpha, off, sscl, RemoveDof, soff, sploff); // + sploff; loftverts[vi] = p; loftuvs[vi++] = suvs[i]; } for ( int i = 0; i < stris.Length; i++ ) lofttris[fi++] = stris[i] + triindex; off += startObj.bounds.max[(int)axis] * sscl[ax]; off += StartGap; trioff = vi; } if ( mainObj != null && MainEnabled ) { float mw = mainObj.bounds.size[(int)axis]; Vector3 mscl = MainScale * GlobalScale; Vector3 moff = Vector3.Scale(MainOff, mscl); off -= mainObj.bounds.min[(int)axis] * mscl[ax]; mw *= mscl[(int)axis]; for ( int r = 0; r < repeat; r++ ) { for ( int i = 0; i < mverts.Length; i++ ) { Vector3 p = mverts[i]; p = Deform(p, path, palpha, off, mscl, RemoveDof, moff, sploff); // + sploff; loftverts[vi] = p; loftuvs[vi++] = muvs[i]; } for ( int i = 0; i < mtris.Length; i++ ) lofttris[fi++] = mtris[i] + trioff + triindex; off += mw; off += Gap; trioff = vi; } off -= Gap; off += (mainObj.bounds.max[(int)axis] * mscl[ax]) - mw; } if ( endObj != null && EndEnabled ) { Vector3 escl = EndScale * GlobalScale; Vector3 eoff = Vector3.Scale(EndOff, escl); off -= endObj.bounds.min[(int)axis] * escl[ax]; off += EndGap; for ( int i = 0; i < everts.Length; i++ ) { Vector3 p = everts[i]; p = Deform(p, path, palpha, off, escl, RemoveDof, eoff, sploff); // + sploff; loftverts[vi] = p; loftuvs[vi++] = euvs[i]; } for ( int i = 0; i < etris.Length; i++ ) lofttris[fi++] = etris[i] + trioff + triindex; trioff += everts.Length; } if ( conform ) { CalcBounds(loftverts); DoConform(loft, loftverts); } return triindex; } public override MegaLoftLayerBase Copy(GameObject go) { MegaLoftLayerCloneSplineSimple layer = go.AddComponent<MegaLoftLayerCloneSplineSimple>(); Copy(this, layer); loftverts = null; loftuvs = null; loftcols = null; lofttris = null; return null; } // Conform public bool conform = false; public GameObject target; public Collider conformCollider; public float[] offsets; public float[] last; public float conformAmount = 1.0f; public float raystartoff = 0.0f; public float raydist = 10.0f; public float conformOffset = 0.0f; float minz = 0.0f; public bool showConformParams = false; public void SetTarget(GameObject targ) { target = targ; if ( target ) { conformCollider = target.GetComponent<Collider>(); } } void CalcBounds(Vector3[] verts) { minz = verts[0].y; for ( int i = 1; i < verts.Length; i++ ) { if ( verts[i].y < minz ) minz = verts[i].y; } } public void InitConform(Vector3[] verts) { if ( offsets == null || offsets.Length != verts.Length ) { offsets = new float[verts.Length]; last = new float[verts.Length]; for ( int i = 0; i < verts.Length; i++ ) offsets[i] = verts[i].y - minz; } // Only need to do this if target changes, move to SetTarget if ( target ) { //MeshFilter mf = target.GetComponent<MeshFilter>(); //targetMesh = mf.sharedMesh; conformCollider = target.GetComponent<Collider>(); } } // We could do a bary centric thing if we grid up the bounds void DoConform(MegaShapeLoft loft, Vector3[] verts) { InitConform(verts); if ( target && conformCollider ) { Matrix4x4 loctoworld = transform.localToWorldMatrix; Matrix4x4 tm = loctoworld; // * worldtoloc; Matrix4x4 invtm = tm.inverse; Ray ray = new Ray(); RaycastHit hit; float ca = conformAmount * loft.conformAmount; // When calculating alpha need to do caps sep for ( int i = 0; i < verts.Length; i++ ) { Vector3 origin = tm.MultiplyPoint(verts[i]); origin.y += raystartoff; ray.origin = origin; ray.direction = Vector3.down; //loftverts[i] = loftverts1[i]; if ( conformCollider.Raycast(ray, out hit, raydist) ) { Vector3 lochit = invtm.MultiplyPoint(hit.point); verts[i].y = Mathf.Lerp(verts[i].y, lochit.y + offsets[i] + conformOffset, ca); //conformAmount); last[i] = verts[i].y; } else { Vector3 ht = ray.origin; ht.y -= raydist; verts[i].y = last[i]; //lochit.z + offsets[i] + offset; } } } else { } } }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (c) 2003-2012 by AG-Software * * All Rights Reserved. * * Contact information for AG-Software is available at http://www.ag-software.de * * * * Licence: * * The agsXMPP SDK is released under a dual licence * * agsXMPP can be used under either of two licences * * * * A commercial licence which is probably the most appropriate for commercial * * corporate use and closed source projects. * * * * The GNU Public License (GPL) is probably most appropriate for inclusion in * * other open source projects. * * * * See README.html for details. * * * * For general enquiries visit our website at: * * http://www.ag-software.de * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ using System; using System.Text; using agsXMPP.Net; using agsXMPP.Xml.Dom; using agsXMPP.protocol; using agsXMPP.protocol.component; using agsXMPP.Xml; namespace agsXMPP { /// <summary> /// <para> /// use this class to write components that connect to a Jabebr/XMPP server /// </para> /// <para> /// http://www.xmpp.org/extensions/xep-0114.html /// </para> /// </summary> public class XmppComponentConnection : XmppConnection { // This route stuff is old undocumented jabberd(2) stuff. hopefully we can get rid of this one day // or somebody writes up and XEP public delegate void RouteHandler (object sender, Route r); private bool m_CleanUpDone; private bool m_StreamStarted; #region << Constructors >> /// <summary> /// Creates a new Component Connection to a given server and port /// </summary> public XmppComponentConnection() { m_IqGrabber = new IqGrabber(this); } /// <summary> /// Creates a new Component Connection to a given server and port /// </summary> /// <param name="server">host/ip of the listening server</param> /// <param name="port">port the server listens for the connection</param> public XmppComponentConnection(string server, int port) : this() { base.Server = server; base.Port = port; } /// <summary> /// Creates a new Component Connection to a given server, port and password (secret) /// </summary> /// <param name="server">host/ip of the listening server</param> /// <param name="port">port the server listens for the connection</param> /// <param name="password">password</param> public XmppComponentConnection(string server, int port, string password) : this(server,port) { this.Password = password; } #endregion #region << Properties and Member Variables >> private string m_Password = null; private bool m_Authenticated = false; private Jid m_ComponentJid = null; private IqGrabber m_IqGrabber = null; public string Password { get { return m_Password; } set { m_Password = value; } } /// <summary> /// Are we Authenticated to the server? This is readonly and set by the library /// </summary> public bool Authenticated { get { return m_Authenticated; } } /// <summary> /// The Domain of the component. /// <para> /// eg: <c>jabber.ag-software.de</c> /// </para> /// </summary> public Jid ComponentJid { get { return m_ComponentJid; } set { m_ComponentJid = value; } } public IqGrabber IqGrabber { get { return m_IqGrabber; } set { m_IqGrabber = value; } } #endregion #region << Events >> // public event ErrorHandler OnError; /// <summary> /// connection is authenticated now and ready for receiving Route, Log and Xdb Packets /// </summary> public event ObjectHandler OnLogin; public event ObjectHandler OnClose; /// <summary> /// handler for incoming routet packtes from the server /// </summary> public event RouteHandler OnRoute; /// <summary> /// Event that occurs on authentication errors /// e.g. wrong password, user doesnt exist etc... /// </summary> public event XmppElementHandler OnAuthError; /// <summary> /// Stream errors &lt;stream:error/&gt; /// </summary> public event XmppElementHandler OnStreamError; /// <summary> /// Event occurs on Socket Errors /// </summary> public event ErrorHandler OnSocketError; /// <summary> /// /// </summary> public event IqHandler OnIq; /// <summary> /// We received a message. This could be a chat message, headline, normal message or a groupchat message. /// There are also XMPP extension which are embedded in messages. /// e.g. X-Data forms. /// </summary> public event MessageHandler OnMessage; /// <summary> /// We received a presence from a contact or chatroom. /// Also subscriptions is handles in this event. /// </summary> public event PresenceHandler OnPresence; #endregion public void Open() { _Open(); } /// <summary> /// /// </summary> /// <param name="server"></param> /// <param name="port"></param> public void Open(string server, int port) { this.Server = server; this.Port = port; _Open(); } private void _Open() { m_CleanUpDone = false; m_StreamStarted = false; if (ConnectServer == null) SocketConnect(base.Server, base.Port); else SocketConnect(this.ConnectServer, base.Port); } private void SendOpenStream() { // <stream:stream // xmlns='jabber:component:accept' // xmlns:stream='http://etherx.jabber.org/streams' // to='shakespeare.lit'> StringBuilder sb = new StringBuilder(); //sb.Append("<?xml version='1.0'?>"); sb.Append("<stream:stream"); if (m_ComponentJid!=null) sb.Append(" to='" + m_ComponentJid.ToString() + "'"); sb.Append(" xmlns='" + Uri.ACCEPT + "'"); sb.Append(" xmlns:stream='" + Uri.STREAM + "'"); sb.Append(">"); Open(sb.ToString()); } private void Login() { // Send Handshake Send( new Handshake(this.m_Password, this.StreamId) ); } #region << Stream Parser events >> public override void StreamParserOnStreamStart(object sender, Node e) { base.StreamParserOnStreamStart (sender, e); m_StreamStarted = true; Login(); } public override void StreamParserOnStreamEnd(object sender, Node e) { base.StreamParserOnStreamEnd (sender, e); if(!m_CleanUpDone) CleanupSession(); } public override void StreamParserOnStreamElement(object sender, ElementEventArgs eventArgs) { base.StreamParserOnStreamElement (sender, eventArgs); var e = eventArgs.Element; if (e is Handshake) { m_Authenticated = true; if (OnLogin != null) OnLogin(this); if (KeepAlive) CreateKeepAliveTimer(); eventArgs.Handled = true; } else if (e is Route) { if (OnRoute != null) OnRoute(this, e as Route); eventArgs.Handled = true; } else if (e is protocol.Error) { protocol.Error streamErr = e as protocol.Error; switch (streamErr.Condition) { // Auth errors are important for the users here, so throw catch auth errors // in a separate event here case agsXMPP.protocol.StreamErrorCondition.NotAuthorized: // Authentication Error if (OnAuthError != null) OnAuthError(this, e as Element); break; default: if (OnStreamError != null) OnStreamError(this, e as Element); break; } eventArgs.Handled = true; } else if (e is Message) { if (OnMessage != null) { OnMessage(this, e as Message); eventArgs.Handled = true; } } else if (e is Presence) { if (OnPresence != null) { OnPresence(this, e as Presence); eventArgs.Handled = true; } } else if (e is IQ) { if (OnIq != null) { var iqEventArgs = new protocol.client.IQEventArgs((IQ)e); OnIq(this, iqEventArgs); if (iqEventArgs.Handled) { eventArgs.Handled = true; } } } } private void m_StreamParser_OnStreamError(object sender, Exception ex) { if(!m_CleanUpDone) CleanupSession(); } #endregion #region << ClientSocket Events >> public override void SocketOnConnect(object sender) { base.SocketOnConnect (sender); SendOpenStream(); } public override void SocketOnDisconnect(object sender) { base.SocketOnDisconnect (sender); if(!m_CleanUpDone) CleanupSession(); } public override void SocketOnError(object sender, Exception ex) { base.SocketOnError(sender, ex); if (m_StreamStarted && !m_CleanUpDone) CleanupSession(); if (OnSocketError != null) OnSocketError(this, ex); } #endregion public override void Send(Element e) { // this is a hack to not send the xmlns="jabber:component:accept" with all packets Element dummyEl = new Element("a"); dummyEl.Namespace = Uri.ACCEPT; dummyEl.AddChild(e); string toSend = dummyEl.ToString(); Send(toSend.Substring(35, toSend.Length - 35 - 4)); } private void CleanupSession() { // This cleanup has only to be done if we were able to connect and teh XMPP Stream was started DestroyKeepAliveTimer(); m_CleanUpDone = true; StreamParser.Reset(); m_IqGrabber.Clear(); if (OnClose!=null) OnClose(this); } } }
// 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. using Microsoft.Azure.Batch.Conventions.Files.Utilities; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.RetryPolicies; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Batch.Conventions.Files { /// <summary> /// Represents persistent storage for the outputs of an Azure Batch task. /// </summary> /// <remarks> /// Task outputs refer to output data logically associated with a specific task, rather than /// the job as a whole. For example, in a movie rendering job, if a task rendered a single frame, /// that frame would be a task output. Logs and other diagnostic information such as intermediate /// files may also be persisted as task outputs (see <see cref="TaskOutputKind"/> for a way to /// categorise these so that clients can distinguish between the main output and auxiliary data). /// </remarks> public class TaskOutputStorage { private readonly StoragePath _storagePath; /// <summary> /// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a task id and /// a URL representing the job output container. /// </summary> /// <param name="jobOutputContainerUri">The URL in Azure storage of the blob container to /// use for outputs associated with this job. This URL must contain a SAS (Shared Access /// Signature) granting access to the container, or the container must be public.</param> /// <param name="taskId">The id of the Azure Batch task.</param> /// <remarks>The container must already exist; the TaskOutputStorage class does not create /// it for you.</remarks> public TaskOutputStorage(Uri jobOutputContainerUri, string taskId) : this(CloudBlobContainerUtils.GetContainerReference(jobOutputContainerUri), taskId, null) { } /// <summary> /// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a storage account, /// job id, and task id. /// </summary> /// <param name="storageAccount">The storage account linked to the Azure Batch account.</param> /// <param name="jobId">The id of the Azure Batch job containing the task.</param> /// <param name="taskId">The id of the Azure Batch task.</param> /// <remarks>The job output container must already exist; the TaskOutputStorage class does not create /// it for you.</remarks> public TaskOutputStorage(CloudStorageAccount storageAccount, string jobId, string taskId) : this(CloudBlobContainerUtils.GetContainerReference(storageAccount, jobId), taskId, null) { } /// <summary> /// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a task id and /// a URL representing the job output container. /// </summary> /// <param name="jobOutputContainerUri">The URL in Azure storage of the blob container to /// use for outputs associated with this job. This URL must contain a SAS (Shared Access /// Signature) granting access to the container, or the container must be public.</param> /// <param name="taskId">The id of the Azure Batch task.</param> /// <param name="storageRetryPolicy">The retry policy for storage requests.</param> /// <remarks>The container must already exist; the TaskOutputStorage class does not create /// it for you.</remarks> public TaskOutputStorage(Uri jobOutputContainerUri, string taskId, IRetryPolicy storageRetryPolicy) : this(CloudBlobContainerUtils.GetContainerReference(jobOutputContainerUri), taskId, storageRetryPolicy) { } /// <summary> /// Initializes a new instance of the <see cref="JobOutputStorage"/> class from a storage account, /// job id, and task id. /// </summary> /// <param name="storageAccount">The storage account linked to the Azure Batch account.</param> /// <param name="jobId">The id of the Azure Batch job containing the task.</param> /// <param name="taskId">The id of the Azure Batch task.</param> /// <param name="storageRetryPolicy">The retry policy for storage requests.</param> /// <remarks>The job output container must already exist; the TaskOutputStorage class does not create /// it for you.</remarks> public TaskOutputStorage(CloudStorageAccount storageAccount, string jobId, string taskId, IRetryPolicy storageRetryPolicy) : this(CloudBlobContainerUtils.GetContainerReference(storageAccount, jobId), taskId, storageRetryPolicy) { } private TaskOutputStorage(CloudBlobContainer jobOutputContainer, string taskId, IRetryPolicy storageRetryPolicy) { if (jobOutputContainer == null) { throw new ArgumentNullException(nameof(jobOutputContainer)); } Validate.IsNotNullOrEmpty(taskId, nameof(taskId)); if (storageRetryPolicy != null) { jobOutputContainer.ServiceClient.DefaultRequestOptions.RetryPolicy = storageRetryPolicy; } _storagePath = new StoragePath.TaskStoragePath(jobOutputContainer, taskId); } /// <summary> /// Saves the specified file to persistent storage. /// </summary> /// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to /// store this file, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param> /// <param name="relativePath">The path of the file to save, relative to the current directory. /// If the file is in a subdirectory of the current directory, the relative path will be preserved /// in blob storage.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <remarks>If the file is outside the current directory, traversals up the directory tree are removed. /// For example, a <paramref name="relativePath"/> of "..\ProcessEnv.cmd" would be treated as "ProcessEnv.cmd" /// for the purposes of creating a blob name.</remarks> /// <exception cref="ArgumentNullException">The <paramref name="kind"/> or <paramref name="relativePath"/> argument is null.</exception> /// <exception cref="ArgumentException">The <paramref name="relativePath"/> argument is an absolute path, or is empty.</exception> public async Task SaveAsync( TaskOutputKind kind, string relativePath, CancellationToken cancellationToken = default(CancellationToken) ) => await SaveAsyncImpl(kind, new DirectoryInfo(Directory.GetCurrentDirectory()), relativePath, cancellationToken).ConfigureAwait(false); internal async Task SaveAsyncImpl( TaskOutputKind kind, DirectoryInfo baseFolder, string relativePath, CancellationToken cancellationToken = default(CancellationToken) ) => await _storagePath.SaveAsync(kind, baseFolder, relativePath, cancellationToken).ConfigureAwait(false); /// <summary> /// Saves the specified file to persistent storage. /// </summary> /// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to /// store this file, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param> /// <param name="sourcePath">The path of the file to save.</param> /// <param name="destinationRelativePath">The blob name under which to save the file. This may include a /// relative component, such as "pointclouds/pointcloud_0001.txt".</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <exception cref="ArgumentNullException">The <paramref name="kind"/>, <paramref name="sourcePath"/>, or <paramref name="destinationRelativePath"/> argument is null.</exception> /// <exception cref="ArgumentException">The <paramref name="sourcePath"/> or <paramref name="destinationRelativePath"/> argument is empty.</exception> public async Task SaveAsync( TaskOutputKind kind, string sourcePath, string destinationRelativePath, CancellationToken cancellationToken = default(CancellationToken) ) => await _storagePath.SaveAsync(kind, sourcePath, destinationRelativePath, cancellationToken).ConfigureAwait(false); /// <summary> /// Saves the specified text to persistent storage, without requiring you to create a local file. /// </summary> /// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to /// store this data, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param> /// <param name="text">The text to save.</param> /// <param name="destinationRelativePath">The blob name under which to save the text. This may include a /// relative component, such as "records/widget42.json".</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns> /// <exception cref="ArgumentNullException">The <paramref name="kind"/>, <paramref name="text"/>, or <paramref name="destinationRelativePath"/> argument is null.</exception> /// <exception cref="ArgumentException">The <paramref name="destinationRelativePath"/> argument is empty.</exception> public async Task SaveTextAsync( TaskOutputKind kind, string text, string destinationRelativePath, CancellationToken cancellationToken = default(CancellationToken) ) => await _storagePath.SaveTextAsync(kind, text, destinationRelativePath, cancellationToken).ConfigureAwait(false); /// <summary> /// Lists the task outputs of the specified kind. /// </summary> /// <param name="kind">A <see cref="TaskOutputKind"/> representing the category of outputs to /// list, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param> /// <returns>A list of persisted task outputs of the specified kind.</returns> /// <remarks>The list is retrieved lazily from Azure blob storage when it is enumerated.</remarks> public IEnumerable<OutputFileReference> ListOutputs(TaskOutputKind kind) => _storagePath.List(kind); /// <summary> /// Retrieves a task output from Azure blob storage by kind and path. /// </summary> /// <param name="kind">A <see cref="TaskOutputKind"/> representing the category of the output to /// retrieve, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param> /// <param name="filePath">The path under which the output was persisted in blob storage.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A reference to the requested file in Azure blob storage.</returns> public async Task<OutputFileReference> GetOutputAsync( TaskOutputKind kind, string filePath, CancellationToken cancellationToken = default(CancellationToken) ) => await _storagePath.GetOutputAsync(kind, filePath, cancellationToken).ConfigureAwait(false); /// <summary> /// Saves the specified file to persistent storage as a <see cref="TaskOutputKind.TaskLog"/>, /// and tracks subsequent appends to the file and appends them to the persistent copy too. /// </summary> /// <param name="relativePath">The path of the file to save, relative to the current directory. /// If the file is in a subdirectory of the current directory, the relative path will be preserved /// in blob storage.</param> /// <returns>An <see cref="ITrackedSaveOperation"/> which will save a file to blob storage and will periodically flush file /// appends to the blob until disposed. When disposed, all remaining appends are flushed to /// blob storage, and further tracking of file appends is stopped.</returns> /// <remarks> /// <para>Tracking supports only appends. That is, while a file is being tracked, any data added /// at the end is appended to the persistent storage. Changes to data that has already been uploaded /// will not be reflected to the persistent store. This method is therefore intended for use only /// with files such as (non-rotating) log files where data is only added at the end of the file. /// If the entire contents of a file can change, use <see cref="SaveAsync(TaskOutputKind, string, CancellationToken)"/> /// and call it periodically or after each change.</para> /// <para>If the file is outside the current directory, traversals up the directory tree are removed. /// For example, a <paramref name="relativePath"/> of "..\ProcessEnv.cmd" would be treated as "ProcessEnv.cmd" /// for the purposes of creating a blob name.</para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="relativePath"/> argument is null.</exception> /// <exception cref="ArgumentException">The <paramref name="relativePath"/> argument is an absolute path, or is empty.</exception> public async Task<ITrackedSaveOperation> SaveTrackedAsync(string relativePath) => await _storagePath.SaveTrackedAsync(TaskOutputKind.TaskLog, relativePath, TrackedFile.DefaultFlushInterval).ConfigureAwait(false); /// <summary> /// Saves the specified file to persistent storage, and tracks subsequent appends to the file /// and appends them to the persistent copy too. /// </summary> /// <param name="kind">A <see cref="TaskOutputKind"/> representing the category under which to /// store this file, for example <see cref="TaskOutputKind.TaskOutput"/> or <see cref="TaskOutputKind.TaskLog"/>.</param> /// <param name="sourcePath">The path of the file to save.</param> /// <param name="destinationRelativePath">The blob name under which to save the file. This may include a /// relative component, such as "pointclouds/pointcloud_0001.txt".</param> /// <param name="flushInterval">The interval at which to flush appends to persistent storage.</param> /// <returns>An <see cref="ITrackedSaveOperation"/> which will save a file to blob storage and will periodically flush file /// appends to the blob until disposed. When disposed, all remaining appends are flushed to /// blob storage, and further tracking of file appends is stopped.</returns> /// <remarks> /// <para>Tracking supports only appends. That is, while a file is being tracked, any data added /// at the end is appended to the persistent storage. Changes to data that has already been uploaded /// will not be reflected to the persistent store. This method is therefore intended for use only /// with files such as (non-rotating) log files where data is only added at the end of the file. /// If the entire contents of a file can change, use <see cref="SaveAsync(TaskOutputKind, string, string, CancellationToken)"/> /// and call it periodically or after each change.</para> /// </remarks> /// <exception cref="ArgumentNullException">The <paramref name="kind"/>, <paramref name="sourcePath"/>, or <paramref name="destinationRelativePath"/> argument is null.</exception> /// <exception cref="ArgumentException">The <paramref name="sourcePath"/> or <paramref name="destinationRelativePath"/> argument is empty.</exception> public async Task<ITrackedSaveOperation> SaveTrackedAsync( TaskOutputKind kind, string sourcePath, string destinationRelativePath, TimeSpan flushInterval ) => await _storagePath.SaveTrackedAsync(kind, sourcePath, destinationRelativePath, flushInterval).ConfigureAwait(false); /// <summary> /// Gets the Blob name prefix/folder where files of the given kind are stored /// </summary> /// <param name="kind">The output kind.</param> /// <returns>The Blob name prefix/folder where files of the given kind are stored.</returns> public string GetOutputStoragePath(TaskOutputKind kind) => _storagePath.BlobNamePrefix(kind); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace DDDSyd2016.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace SandcastleBuilder.Utils.Design { partial class PlugInConfigurationEditorDlg { /// <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) { if(components != null) components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PlugInConfigurationEditorDlg)); this.lbAvailablePlugIns = new System.Windows.Forms.ListBox(); this.btnClose = new System.Windows.Forms.Button(); this.statusBarTextProvider1 = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components); this.txtPlugInDescription = new System.Windows.Forms.TextBox(); this.txtPlugInCopyright = new System.Windows.Forms.TextBox(); this.txtPlugInVersion = new System.Windows.Forms.TextBox(); this.lbProjectPlugIns = new System.Windows.Forms.CheckedListBox(); this.btnDelete = new System.Windows.Forms.Button(); this.ilImages = new System.Windows.Forms.ImageList(this.components); this.btnAddPlugIn = new System.Windows.Forms.Button(); this.btnConfigure = new System.Windows.Forms.Button(); this.btnHelp = new System.Windows.Forms.Button(); this.gbAvailablePlugIns = new System.Windows.Forms.GroupBox(); this.gbProjectAddIns = new System.Windows.Forms.GroupBox(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.gbAvailablePlugIns.SuspendLayout(); this.gbProjectAddIns.SuspendLayout(); this.SuspendLayout(); // // lbAvailablePlugIns // this.lbAvailablePlugIns.IntegralHeight = false; this.lbAvailablePlugIns.ItemHeight = 16; this.lbAvailablePlugIns.Location = new System.Drawing.Point(6, 21); this.lbAvailablePlugIns.Name = "lbAvailablePlugIns"; this.lbAvailablePlugIns.Size = new System.Drawing.Size(290, 175); this.lbAvailablePlugIns.Sorted = true; this.statusBarTextProvider1.SetStatusBarText(this.lbAvailablePlugIns, "Select the plug-in to add to the project"); this.lbAvailablePlugIns.TabIndex = 0; this.lbAvailablePlugIns.SelectedIndexChanged += new System.EventHandler(this.lbAvailablePlugIns_SelectedIndexChanged); this.lbAvailablePlugIns.DoubleClick += new System.EventHandler(this.btnAddPlugIn_Click); // // btnClose // this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnClose.Location = new System.Drawing.Point(562, 427); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(88, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnClose, "Close: Close this form"); this.btnClose.TabIndex = 3; this.btnClose.Text = "Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new System.EventHandler(this.btnClose_Click); // // txtPlugInDescription // this.txtPlugInDescription.Location = new System.Drawing.Point(6, 296); this.txtPlugInDescription.Multiline = true; this.txtPlugInDescription.Name = "txtPlugInDescription"; this.txtPlugInDescription.ReadOnly = true; this.txtPlugInDescription.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtPlugInDescription.Size = new System.Drawing.Size(290, 105); this.statusBarTextProvider1.SetStatusBarText(this.txtPlugInDescription, "A description of the plug-in"); this.txtPlugInDescription.TabIndex = 3; // // txtPlugInCopyright // this.txtPlugInCopyright.Location = new System.Drawing.Point(6, 230); this.txtPlugInCopyright.Multiline = true; this.txtPlugInCopyright.Name = "txtPlugInCopyright"; this.txtPlugInCopyright.ReadOnly = true; this.txtPlugInCopyright.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtPlugInCopyright.Size = new System.Drawing.Size(290, 60); this.statusBarTextProvider1.SetStatusBarText(this.txtPlugInCopyright, "Plug-in copyright information"); this.txtPlugInCopyright.TabIndex = 2; // // txtPlugInVersion // this.txtPlugInVersion.Location = new System.Drawing.Point(6, 202); this.txtPlugInVersion.Name = "txtPlugInVersion"; this.txtPlugInVersion.ReadOnly = true; this.txtPlugInVersion.Size = new System.Drawing.Size(290, 22); this.statusBarTextProvider1.SetStatusBarText(this.txtPlugInVersion, "Plug-in version information"); this.txtPlugInVersion.TabIndex = 1; // // lbProjectPlugIns // this.lbProjectPlugIns.Font = new System.Drawing.Font("Tahoma", 8F); this.lbProjectPlugIns.IntegralHeight = false; this.lbProjectPlugIns.Location = new System.Drawing.Point(6, 21); this.lbProjectPlugIns.Name = "lbProjectPlugIns"; this.lbProjectPlugIns.Size = new System.Drawing.Size(318, 340); this.lbProjectPlugIns.Sorted = true; this.statusBarTextProvider1.SetStatusBarText(this.lbProjectPlugIns, "Select the plug-in to configure"); this.lbProjectPlugIns.TabIndex = 0; this.lbProjectPlugIns.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lbProjectPlugIns_ItemCheck); // // btnDelete // this.btnDelete.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnDelete.ImageIndex = 1; this.btnDelete.ImageList = this.ilImages; this.btnDelete.Location = new System.Drawing.Point(224, 367); this.btnDelete.Name = "btnDelete"; this.btnDelete.Padding = new System.Windows.Forms.Padding(10, 0, 10, 0); this.btnDelete.Size = new System.Drawing.Size(100, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnDelete, "Delete: Delete the selected plug-in from the project"); this.btnDelete.TabIndex = 3; this.btnDelete.Text = "&Delete"; this.btnDelete.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.toolTip1.SetToolTip(this.btnDelete, "Delete the selected plug-in from the project"); this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // ilImages // this.ilImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilImages.ImageStream"))); this.ilImages.TransparentColor = System.Drawing.Color.Magenta; this.ilImages.Images.SetKeyName(0, "PlugInAdd.png"); this.ilImages.Images.SetKeyName(1, "Delete.bmp"); this.ilImages.Images.SetKeyName(2, "MoveUp.bmp"); this.ilImages.Images.SetKeyName(3, "MoveDown.bmp"); this.ilImages.Images.SetKeyName(4, "Properties.bmp"); // // btnAddPlugIn // this.btnAddPlugIn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnAddPlugIn.ImageIndex = 0; this.btnAddPlugIn.ImageList = this.ilImages; this.btnAddPlugIn.Location = new System.Drawing.Point(6, 367); this.btnAddPlugIn.Name = "btnAddPlugIn"; this.btnAddPlugIn.Padding = new System.Windows.Forms.Padding(10, 0, 0, 0); this.btnAddPlugIn.Size = new System.Drawing.Size(100, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnAddPlugIn, "Add Plug-In: Add the selected plug-in to the project"); this.btnAddPlugIn.TabIndex = 1; this.btnAddPlugIn.Text = "&Add"; this.toolTip1.SetToolTip(this.btnAddPlugIn, "Add the selected plug-in to the project"); this.btnAddPlugIn.Click += new System.EventHandler(this.btnAddPlugIn_Click); // // btnConfigure // this.btnConfigure.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnConfigure.ImageIndex = 4; this.btnConfigure.ImageList = this.ilImages; this.btnConfigure.Location = new System.Drawing.Point(112, 367); this.btnConfigure.Name = "btnConfigure"; this.btnConfigure.Padding = new System.Windows.Forms.Padding(7, 0, 0, 0); this.btnConfigure.Size = new System.Drawing.Size(106, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnConfigure, "Configure: Configure the selected plug-in"); this.btnConfigure.TabIndex = 2; this.btnConfigure.Text = "&Configure"; this.btnConfigure.TextAlign = System.Drawing.ContentAlignment.MiddleRight; this.toolTip1.SetToolTip(this.btnConfigure, "Edit the selected plug-in\'s configuration"); this.btnConfigure.UseVisualStyleBackColor = true; this.btnConfigure.Click += new System.EventHandler(this.btnConfigure_Click); // // btnHelp // this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnHelp.Location = new System.Drawing.Point(468, 427); this.btnHelp.Name = "btnHelp"; this.btnHelp.Size = new System.Drawing.Size(88, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnHelp, "Help: View help for this form"); this.btnHelp.TabIndex = 2; this.btnHelp.Text = "&Help"; this.toolTip1.SetToolTip(this.btnHelp, "View help for this form"); this.btnHelp.UseVisualStyleBackColor = true; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // gbAvailablePlugIns // this.gbAvailablePlugIns.Controls.Add(this.txtPlugInVersion); this.gbAvailablePlugIns.Controls.Add(this.txtPlugInCopyright); this.gbAvailablePlugIns.Controls.Add(this.txtPlugInDescription); this.gbAvailablePlugIns.Controls.Add(this.lbAvailablePlugIns); this.gbAvailablePlugIns.Location = new System.Drawing.Point(12, 12); this.gbAvailablePlugIns.Name = "gbAvailablePlugIns"; this.gbAvailablePlugIns.Size = new System.Drawing.Size(302, 407); this.gbAvailablePlugIns.TabIndex = 0; this.gbAvailablePlugIns.TabStop = false; this.gbAvailablePlugIns.Text = "Available Plug-Ins"; // // gbProjectAddIns // this.gbProjectAddIns.Controls.Add(this.btnConfigure); this.gbProjectAddIns.Controls.Add(this.btnDelete); this.gbProjectAddIns.Controls.Add(this.btnAddPlugIn); this.gbProjectAddIns.Controls.Add(this.lbProjectPlugIns); this.gbProjectAddIns.Location = new System.Drawing.Point(320, 12); this.gbProjectAddIns.Name = "gbProjectAddIns"; this.gbProjectAddIns.Size = new System.Drawing.Size(330, 407); this.gbProjectAddIns.TabIndex = 1; this.gbProjectAddIns.TabStop = false; this.gbProjectAddIns.Text = "Plug-Ins in This Project"; // // PlugInConfigurationEditorDlg // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.CancelButton = this.btnClose; this.ClientSize = new System.Drawing.Size(662, 471); this.Controls.Add(this.btnHelp); this.Controls.Add(this.gbProjectAddIns); this.Controls.Add(this.gbAvailablePlugIns); this.Controls.Add(this.btnClose); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PlugInConfigurationEditorDlg"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Select and Configure Build Process Plug-Ins"; this.gbAvailablePlugIns.ResumeLayout(false); this.gbAvailablePlugIns.PerformLayout(); this.gbProjectAddIns.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListBox lbAvailablePlugIns; private SandcastleBuilder.Utils.Controls.StatusBarTextProvider statusBarTextProvider1; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.GroupBox gbAvailablePlugIns; private System.Windows.Forms.TextBox txtPlugInVersion; private System.Windows.Forms.TextBox txtPlugInCopyright; private System.Windows.Forms.TextBox txtPlugInDescription; private System.Windows.Forms.GroupBox gbProjectAddIns; private System.Windows.Forms.CheckedListBox lbProjectPlugIns; private System.Windows.Forms.ImageList ilImages; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnAddPlugIn; private System.Windows.Forms.Button btnConfigure; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button btnHelp; } }
/* * 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.Data; using System.Data.SqlClient; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MSSQL { /// <summary> /// A MSSQL interface for the inventory server /// </summary> public class MSSQLInventoryData : IInventoryDataPlugin { private const string _migrationStore = "InventoryStore"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The database manager /// </summary> private MSSQLManager database; #region IPlugin members [Obsolete("Cannot be default-initialized!")] public void Initialise() { m_log.Info("[MSSQLInventoryData]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } /// <summary> /// Loads and initialises the MSSQL inventory storage interface /// </summary> /// <param name="connectionString">connect string</param> /// <remarks>use mssql_connection.ini</remarks> public void Initialise(string connectionString) { if (!string.IsNullOrEmpty(connectionString)) { database = new MSSQLManager(connectionString); } else { IniFile gridDataMSSqlFile = new IniFile("mssql_connection.ini"); string settingDataSource = gridDataMSSqlFile.ParseFileReadValue("data_source"); string settingInitialCatalog = gridDataMSSqlFile.ParseFileReadValue("initial_catalog"); string settingPersistSecurityInfo = gridDataMSSqlFile.ParseFileReadValue("persist_security_info"); string settingUserId = gridDataMSSqlFile.ParseFileReadValue("user_id"); string settingPassword = gridDataMSSqlFile.ParseFileReadValue("password"); database = new MSSQLManager(settingDataSource, settingInitialCatalog, settingPersistSecurityInfo, settingUserId, settingPassword); } //New migrations check of store database.CheckMigration(_migrationStore); } /// <summary> /// The name of this DB provider /// </summary> /// <returns>A string containing the name of the DB provider</returns> public string Name { get { return "MSSQL Inventory Data Interface"; } } /// <summary> /// Closes this DB provider /// </summary> public void Dispose() { database = null; } /// <summary> /// Returns the version of this DB provider /// </summary> /// <returns>A string containing the DB provider</returns> public string Version { get { return database.getVersion(); } } #endregion #region Folder methods /// <summary> /// Returns a list of the root folders within a users inventory /// </summary> /// <param name="user">The user whos inventory is to be searched</param> /// <returns>A list of folder objects</returns> public List<InventoryFolderBase> getUserRootFolders(UUID user) { return getInventoryFolders(UUID.Zero, user); } /// <summary> /// see InventoryItemBase.getUserRootFolder /// </summary> /// <param name="user">the User UUID</param> /// <returns></returns> public InventoryFolderBase getUserRootFolder(UUID user) { List<InventoryFolderBase> items = getUserRootFolders(user); InventoryFolderBase rootFolder = null; // There should only ever be one root folder for a user. However, if there's more // than one we'll simply use the first one rather than failing. It would be even // nicer to print some message to this effect, but this feels like it's too low a // to put such a message out, and it's too minor right now to spare the time to // suitably refactor. if (items.Count > 0) { rootFolder = items[0]; } return rootFolder; } /// <summary> /// Returns a list of folders in a users inventory contained within the specified folder /// </summary> /// <param name="parentID">The folder to search</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getInventoryFolders(UUID parentID) { return getInventoryFolders(parentID, UUID.Zero); } /// <summary> /// Returns a specified inventory folder /// </summary> /// <param name="folderID">The folder to return</param> /// <returns>A folder class</returns> public InventoryFolderBase getInventoryFolder(UUID folderID) { using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryfolders WHERE folderID = @folderID")) { command.Parameters.Add(database.CreateParameter("folderID", folderID)); using (IDataReader reader = command.ExecuteReader()) { if (reader.Read()) { return readInventoryFolder(reader); } } } m_log.InfoFormat("[INVENTORY DB] : Found no inventory folder with ID : {0}", folderID); return null; } /// <summary> /// Returns all child folders in the hierarchy from the parent folder and down. /// Does not return the parent folder itself. /// </summary> /// <param name="parentID">The folder to get subfolders for</param> /// <returns>A list of inventory folders</returns> public List<InventoryFolderBase> getFolderHierarchy(UUID parentID) { //Note maybe change this to use a Dataset that loading in all folders of a user and then go throw it that way. //Note this is changed so it opens only one connection to the database and not everytime it wants to get data. List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID")) { command.Parameters.Add(database.CreateParameter("@parentID", parentID)); folders.AddRange(getInventoryFolders(command)); List<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>(); foreach (InventoryFolderBase folderBase in folders) { tempFolders.AddRange(getFolderHierarchy(folderBase.ID, command)); } if (tempFolders.Count > 0) { folders.AddRange(tempFolders); } } return folders; } /// <summary> /// Creates a new inventory folder /// </summary> /// <param name="folder">Folder to create</param> public void addInventoryFolder(InventoryFolderBase folder) { string sql = @"INSERT INTO inventoryfolders ([folderID], [agentID], [parentFolderID], [folderName], [type], [version]) VALUES (@folderID, @agentID, @parentFolderID, @folderName, @type, @version);"; string folderName = folder.Name; if (folderName.Length > 64) { folderName = folderName.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on add"); } using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("folderID", folder.ID)); command.Parameters.Add(database.CreateParameter("agentID", folder.Owner)); command.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); command.Parameters.Add(database.CreateParameter("folderName", folderName)); command.Parameters.Add(database.CreateParameter("type", folder.Type)); command.Parameters.Add(database.CreateParameter("version", folder.Version)); try { //IDbCommand result = database.Query(sql, param); command.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); } } } /// <summary> /// Updates an inventory folder /// </summary> /// <param name="folder">Folder to update</param> public void updateInventoryFolder(InventoryFolderBase folder) { string sql = @"UPDATE inventoryfolders SET folderID = @folderID, agentID = @agentID, parentFolderID = @parentFolderID, folderName = @folderName, type = @type, version = @version WHERE folderID = @keyFolderID"; string folderName = folder.Name; if (folderName.Length > 64) { folderName = folderName.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + folder.Name.Length.ToString() + " to " + folderName.Length + " characters on update"); } using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("folderID", folder.ID)); command.Parameters.Add(database.CreateParameter("agentID", folder.Owner)); command.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); command.Parameters.Add(database.CreateParameter("folderName", folderName)); command.Parameters.Add(database.CreateParameter("type", folder.Type)); command.Parameters.Add(database.CreateParameter("version", folder.Version)); command.Parameters.Add(database.CreateParameter("@keyFolderID", folder.ID)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); } } } /// <summary> /// Updates an inventory folder /// </summary> /// <param name="folder">Folder to update</param> public void moveInventoryFolder(InventoryFolderBase folder) { string sql = @"UPDATE inventoryfolders SET parentFolderID = @parentFolderID WHERE folderID = @folderID"; using (IDbCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("parentFolderID", folder.ParentID)); command.Parameters.Add(database.CreateParameter("@folderID", folder.ID)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.ErrorFormat("[INVENTORY DB]: Error : {0}", e.Message); } } } /// <summary> /// Delete an inventory folder /// </summary> /// <param name="folderID">Id of folder to delete</param> public void deleteInventoryFolder(UUID folderID) { using (SqlConnection connection = database.DatabaseConnection()) { List<InventoryFolderBase> subFolders; using (SqlCommand command = new SqlCommand("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID", connection)) { command.Parameters.Add(database.CreateParameter("@parentID", UUID.Zero)); AutoClosingSqlCommand autoCommand = new AutoClosingSqlCommand(command); subFolders = getFolderHierarchy(folderID, autoCommand); } //Delete all sub-folders foreach (InventoryFolderBase f in subFolders) { DeleteOneFolder(f.ID, connection); DeleteItemsInFolder(f.ID, connection); } //Delete the actual row DeleteOneFolder(folderID, connection); DeleteItemsInFolder(folderID, connection); connection.Close(); } } #endregion #region Item Methods /// <summary> /// Returns a list of items in a specified folder /// </summary> /// <param name="folderID">The folder to search</param> /// <returns>A list containing inventory items</returns> public List<InventoryItemBase> getInventoryInFolder(UUID folderID) { using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryitems WHERE parentFolderID = @parentFolderID")) { command.Parameters.Add(database.CreateParameter("parentFolderID", folderID)); List<InventoryItemBase> items = new List<InventoryItemBase>(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { items.Add(readInventoryItem(reader)); } } return items; } } /// <summary> /// Returns a specified inventory item /// </summary> /// <param name="itemID">The item ID</param> /// <returns>An inventory item</returns> public InventoryItemBase getInventoryItem(UUID itemID) { using (AutoClosingSqlCommand result = database.Query("SELECT * FROM inventoryitems WHERE inventoryID = @inventoryID")) { result.Parameters.Add(database.CreateParameter("inventoryID", itemID)); using (IDataReader reader = result.ExecuteReader()) { if (reader.Read()) { return readInventoryItem(reader); } } } m_log.InfoFormat("[INVENTORY DB]: Found no inventory item with ID : {0}", itemID); return null; } /// <summary> /// Adds a specified item to the database /// </summary> /// <param name="item">The inventory item</param> public void addInventoryItem(InventoryItemBase item) { if (getInventoryItem(item.ID) != null) { updateInventoryItem(item); return; } string sql = @"INSERT INTO inventoryitems ([inventoryID], [assetID], [assetType], [parentFolderID], [avatarID], [inventoryName], [inventoryDescription], [inventoryNextPermissions], [inventoryCurrentPermissions], [invType], [creatorID], [inventoryBasePermissions], [inventoryEveryOnePermissions], [inventoryGroupPermissions], [salePrice], [saleType], [creationDate], [groupID], [groupOwned], [flags]) VALUES (@inventoryID, @assetID, @assetType, @parentFolderID, @avatarID, @inventoryName, @inventoryDescription, @inventoryNextPermissions, @inventoryCurrentPermissions, @invType, @creatorID, @inventoryBasePermissions, @inventoryEveryOnePermissions, @inventoryGroupPermissions, @salePrice, @saleType, @creationDate, @groupID, @groupOwned, @flags)"; string itemName = item.Name; if (item.Name.Length > 64) { itemName = item.Name.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length.ToString() + " to " + itemName.Length.ToString() + " characters"); } string itemDesc = item.Description; if (item.Description.Length > 128) { itemDesc = item.Description.Substring(0, 128); m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters"); } using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("inventoryID", item.ID)); command.Parameters.Add(database.CreateParameter("assetID", item.AssetID)); command.Parameters.Add(database.CreateParameter("assetType", item.AssetType)); command.Parameters.Add(database.CreateParameter("parentFolderID", item.Folder)); command.Parameters.Add(database.CreateParameter("avatarID", item.Owner)); command.Parameters.Add(database.CreateParameter("inventoryName", itemName)); command.Parameters.Add(database.CreateParameter("inventoryDescription", itemDesc)); command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); command.Parameters.Add(database.CreateParameter("invType", item.InvType)); command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorId)); command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); command.Parameters.Add(database.CreateParameter("inventoryGroupPermissions", item.GroupPermissions)); command.Parameters.Add(database.CreateParameter("salePrice", item.SalePrice)); command.Parameters.Add(database.CreateParameter("saleType", item.SaleType)); command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); command.Parameters.Add(database.CreateParameter("flags", item.Flags)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB]: Error inserting item :" + e.Message); } } sql = "UPDATE inventoryfolders SET version = version + 1 WHERE folderID = @folderID"; using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("folderID", item.Folder.ToString())); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB] Error updating inventory folder for new item :" + e.Message); } } } /// <summary> /// Updates the specified inventory item /// </summary> /// <param name="item">Inventory item to update</param> public void updateInventoryItem(InventoryItemBase item) { string sql = @"UPDATE inventoryitems SET inventoryID = @inventoryID, assetID = @assetID, assetType = @assetType, parentFolderID = @parentFolderID, avatarID = @avatarID, inventoryName = @inventoryName, inventoryDescription = @inventoryDescription, inventoryNextPermissions = @inventoryNextPermissions, inventoryCurrentPermissions = @inventoryCurrentPermissions, invType = @invType, creatorID = @creatorID, inventoryBasePermissions = @inventoryBasePermissions, inventoryEveryOnePermissions = @inventoryEveryOnePermissions, salePrice = @salePrice, saleType = @saleType, creationDate = @creationDate, groupID = @groupID, groupOwned = @groupOwned, flags = @flags WHERE inventoryID = @keyInventoryID"; string itemName = item.Name; if (item.Name.Length > 64) { itemName = item.Name.Substring(0, 64); m_log.Warn("[INVENTORY DB]: Name field truncated from " + item.Name.Length.ToString() + " to " + itemName.Length.ToString() + " characters on update"); } string itemDesc = item.Description; if (item.Description.Length > 128) { itemDesc = item.Description.Substring(0, 128); m_log.Warn("[INVENTORY DB]: Description field truncated from " + item.Description.Length.ToString() + " to " + itemDesc.Length.ToString() + " characters on update"); } using (AutoClosingSqlCommand command = database.Query(sql)) { command.Parameters.Add(database.CreateParameter("inventoryID", item.ID)); command.Parameters.Add(database.CreateParameter("assetID", item.AssetID)); command.Parameters.Add(database.CreateParameter("assetType", item.AssetType)); command.Parameters.Add(database.CreateParameter("parentFolderID", item.Folder)); command.Parameters.Add(database.CreateParameter("avatarID", item.Owner)); command.Parameters.Add(database.CreateParameter("inventoryName", itemName)); command.Parameters.Add(database.CreateParameter("inventoryDescription", itemDesc)); command.Parameters.Add(database.CreateParameter("inventoryNextPermissions", item.NextPermissions)); command.Parameters.Add(database.CreateParameter("inventoryCurrentPermissions", item.CurrentPermissions)); command.Parameters.Add(database.CreateParameter("invType", item.InvType)); command.Parameters.Add(database.CreateParameter("creatorID", item.CreatorIdAsUuid)); command.Parameters.Add(database.CreateParameter("inventoryBasePermissions", item.BasePermissions)); command.Parameters.Add(database.CreateParameter("inventoryEveryOnePermissions", item.EveryOnePermissions)); command.Parameters.Add(database.CreateParameter("salePrice", item.SalePrice)); command.Parameters.Add(database.CreateParameter("saleType", item.SaleType)); command.Parameters.Add(database.CreateParameter("creationDate", item.CreationDate)); command.Parameters.Add(database.CreateParameter("groupID", item.GroupID)); command.Parameters.Add(database.CreateParameter("groupOwned", item.GroupOwned)); command.Parameters.Add(database.CreateParameter("flags", item.Flags)); command.Parameters.Add(database.CreateParameter("@keyInventoryID", item.ID)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB]: Error updating item :" + e.Message); } } } // See IInventoryDataPlugin /// <summary> /// Delete an item in inventory database /// </summary> /// <param name="itemID">the item UUID</param> public void deleteInventoryItem(UUID itemID) { using (AutoClosingSqlCommand command = database.Query("DELETE FROM inventoryitems WHERE inventoryID=@inventoryID")) { command.Parameters.Add(database.CreateParameter("inventoryID", itemID)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB]: Error deleting item :" + e.Message); } } } public InventoryItemBase queryInventoryItem(UUID itemID) { return getInventoryItem(itemID); } public InventoryFolderBase queryInventoryFolder(UUID folderID) { return getInventoryFolder(folderID); } /// <summary> /// Returns all activated gesture-items in the inventory of the specified avatar. /// </summary> /// <param name="avatarID">The <see cref="UUID"/> of the avatar</param> /// <returns> /// The list of gestures (<see cref="InventoryItemBase"/>s) /// </returns> public List<InventoryItemBase> fetchActiveGestures(UUID avatarID) { using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryitems WHERE avatarId = @uuid AND assetType = @assetType and flags = 1")) { command.Parameters.Add(database.CreateParameter("uuid", avatarID)); command.Parameters.Add(database.CreateParameter("assetType", (int)AssetType.Gesture)); using (IDataReader reader = command.ExecuteReader()) { List<InventoryItemBase> gestureList = new List<InventoryItemBase>(); while (reader.Read()) { gestureList.Add(readInventoryItem(reader)); } return gestureList; } } } #endregion #region Private methods /// <summary> /// Delete an item in inventory database /// </summary> /// <param name="folderID">the item ID</param> /// <param name="connection">connection to the database</param> private void DeleteItemsInFolder(UUID folderID, SqlConnection connection) { using (SqlCommand command = new SqlCommand("DELETE FROM inventoryitems WHERE parentFolderID=@parentFolderID", connection)) { command.Parameters.Add(database.CreateParameter("parentFolderID", folderID)); try { command.ExecuteNonQuery(); } catch (Exception e) { m_log.Error("[INVENTORY DB] Error deleting item :" + e.Message); } } } /// <summary> /// Gets the folder hierarchy in a loop. /// </summary> /// <param name="parentID">parent ID.</param> /// <param name="command">SQL command/connection to database</param> /// <returns></returns> private static List<InventoryFolderBase> getFolderHierarchy(UUID parentID, AutoClosingSqlCommand command) { command.Parameters["@parentID"].Value = parentID.Guid; //.ToString(); List<InventoryFolderBase> folders = getInventoryFolders(command); if (folders.Count > 0) { List<InventoryFolderBase> tempFolders = new List<InventoryFolderBase>(); foreach (InventoryFolderBase folderBase in folders) { tempFolders.AddRange(getFolderHierarchy(folderBase.ID, command)); } if (tempFolders.Count > 0) { folders.AddRange(tempFolders); } } return folders; } /// <summary> /// Gets the inventory folders. /// </summary> /// <param name="parentID">parentID, use UUID.Zero to get root</param> /// <param name="user">user id, use UUID.Zero, if you want all folders from a parentID.</param> /// <returns></returns> private List<InventoryFolderBase> getInventoryFolders(UUID parentID, UUID user) { using (AutoClosingSqlCommand command = database.Query("SELECT * FROM inventoryfolders WHERE parentFolderID = @parentID AND agentID LIKE @uuid")) { if (user == UUID.Zero) { command.Parameters.Add(database.CreateParameter("uuid", "%")); } else { command.Parameters.Add(database.CreateParameter("uuid", user)); } command.Parameters.Add(database.CreateParameter("parentID", parentID)); return getInventoryFolders(command); } } /// <summary> /// Gets the inventory folders. /// </summary> /// <param name="command">SQLcommand.</param> /// <returns></returns> private static List<InventoryFolderBase> getInventoryFolders(AutoClosingSqlCommand command) { using (IDataReader reader = command.ExecuteReader()) { List<InventoryFolderBase> items = new List<InventoryFolderBase>(); while (reader.Read()) { items.Add(readInventoryFolder(reader)); } return items; } } /// <summary> /// Reads a list of inventory folders returned by a query. /// </summary> /// <param name="reader">A MSSQL Data Reader</param> /// <returns>A List containing inventory folders</returns> protected static InventoryFolderBase readInventoryFolder(IDataReader reader) { try { InventoryFolderBase folder = new InventoryFolderBase(); folder.Owner = new UUID((Guid)reader["agentID"]); folder.ParentID = new UUID((Guid)reader["parentFolderID"]); folder.ID = new UUID((Guid)reader["folderID"]); folder.Name = (string)reader["folderName"]; folder.Type = (short)reader["type"]; folder.Version = Convert.ToUInt16(reader["version"]); return folder; } catch (Exception e) { m_log.Error("[INVENTORY DB] Error reading inventory folder :" + e.Message); } return null; } /// <summary> /// Reads a one item from an SQL result /// </summary> /// <param name="reader">The SQL Result</param> /// <returns>the item read</returns> private static InventoryItemBase readInventoryItem(IDataRecord reader) { try { InventoryItemBase item = new InventoryItemBase(); item.ID = new UUID((Guid)reader["inventoryID"]); item.AssetID = new UUID((Guid)reader["assetID"]); item.AssetType = Convert.ToInt32(reader["assetType"].ToString()); item.Folder = new UUID((Guid)reader["parentFolderID"]); item.Owner = new UUID((Guid)reader["avatarID"]); item.Name = reader["inventoryName"].ToString(); item.Description = reader["inventoryDescription"].ToString(); item.NextPermissions = Convert.ToUInt32(reader["inventoryNextPermissions"]); item.CurrentPermissions = Convert.ToUInt32(reader["inventoryCurrentPermissions"]); item.InvType = Convert.ToInt32(reader["invType"].ToString()); item.CreatorId = ((Guid)reader["creatorID"]).ToString(); item.BasePermissions = Convert.ToUInt32(reader["inventoryBasePermissions"]); item.EveryOnePermissions = Convert.ToUInt32(reader["inventoryEveryOnePermissions"]); item.GroupPermissions = Convert.ToUInt32(reader["inventoryGroupPermissions"]); item.SalePrice = Convert.ToInt32(reader["salePrice"]); item.SaleType = Convert.ToByte(reader["saleType"]); item.CreationDate = Convert.ToInt32(reader["creationDate"]); item.GroupID = new UUID((Guid)reader["groupID"]); item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]); item.Flags = Convert.ToUInt32(reader["flags"]); return item; } catch (SqlException e) { m_log.Error("[INVENTORY DB]: Error reading inventory item :" + e.Message); } return null; } /// <summary> /// Delete a folder in inventory databasae /// </summary> /// <param name="folderID">the folder UUID</param> /// <param name="connection">connection to database</param> private void DeleteOneFolder(UUID folderID, SqlConnection connection) { try { using (SqlCommand command = new SqlCommand("DELETE FROM inventoryfolders WHERE folderID=@folderID", connection)) { command.Parameters.Add(database.CreateParameter("folderID", folderID)); command.ExecuteNonQuery(); } } catch (SqlException e) { m_log.Error("[INVENTORY DB]: Error deleting folder :" + e.Message); } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ZooKeeperNet { using System; using System.Collections.Generic; using Org.Apache.Zookeeper.Data; public interface IZooKeeper { /// <summary> /// Unique ID representing the instance of the client /// </summary> Guid Id { get; set; } /// <summary> /// The session id for this ZooKeeper client instance. The value returned is /// not valid until the client connects to a server and may change after a /// re-connect. /// </summary> /// <value>The session id.</value> long SessionId { get; } /// <summary> /// The session password for this ZooKeeper client instance. The value /// returned is not valid until the client connects to a server and may /// change after a re-connect. /// /// This method is NOT thread safe /// </summary> /// <value>The sesion password.</value> byte[] SesionPassword { get; } /// <summary> /// The negotiated session timeout for this ZooKeeper client instance. The /// value returned is not valid until the client connects to a server and /// may change after a re-connect. /// /// This method is NOT thread safe /// </summary> /// <value>The session timeout.</value> TimeSpan SessionTimeout { get; } ZooKeeper.States State { get; } /// <summary> /// Add the specified scheme:auth information to this connection. /// /// This method is NOT thread safe /// </summary> /// <param name="scheme">The scheme.</param> /// <param name="auth">The auth.</param> void AddAuthInfo(string scheme, byte[] auth); /// <summary> /// Specify the default watcher for the connection (overrides the one /// specified during construction). /// </summary> /// <param name="watcher">The watcher.</param> void Register(IWatcher watcher); /// <summary> /// Create a node with the given path. The node data will be the given data, /// and node acl will be the given acl. /// /// The flags argument specifies whether the created node will be ephemeral /// or not. /// /// An ephemeral node will be removed by the ZooKeeper automatically when the /// session associated with the creation of the node expires. /// /// The flags argument can also specify to create a sequential node. The /// actual path name of a sequential node will be the given path plus a /// suffix "i" where i is the current sequential number of the node. The sequence /// number is always fixed length of 10 digits, 0 padded. Once /// such a node is created, the sequential number will be incremented by one. /// /// If a node with the same actual path already exists in the ZooKeeper, a /// KeeperException with error code KeeperException.NodeExists will be /// thrown. Note that since a different actual path is used for each /// invocation of creating sequential node with the same path argument, the /// call will never throw "file exists" KeeperException. /// /// If the parent node does not exist in the ZooKeeper, a KeeperException /// with error code KeeperException.NoNode will be thrown. /// /// An ephemeral node cannot have children. If the parent node of the given /// path is ephemeral, a KeeperException with error code /// KeeperException.NoChildrenForEphemerals will be thrown. /// /// This operation, if successful, will trigger all the watches left on the /// node of the given path by exists and getData API calls, and the watches /// left on the parent node by getChildren API calls. /// /// If a node is created successfully, the ZooKeeper server will trigger the /// watches on the path left by exists calls, and the watches on the parent /// of the node by getChildren calls. /// /// The maximum allowable size of the data array is 1 MB (1,048,576 bytes). /// Arrays larger than this will cause a KeeperExecption to be thrown. /// </summary> /// <param name="path">The path for the node.</param> /// <param name="data">The data for the node.</param> /// <param name="acl">The acl for the node.</param> /// <param name="createMode">specifying whether the node to be created is ephemeral and/or sequential.</param> /// <returns></returns> string Create(string path, byte[] data, IEnumerable<ACL> acl, CreateMode createMode); /// <summary> /// Delete the node with the given path. The call will succeed if such a node /// exists, and the given version matches the node's version (if the given /// version is -1, it matches any node's versions). /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if the nodes does not exist. /// /// A KeeperException with error code KeeperException.BadVersion will be /// thrown if the given version does not match the node's version. /// /// A KeeperException with error code KeeperException.NotEmpty will be thrown /// if the node has children. /// /// This operation, if successful, will trigger all the watches on the node /// of the given path left by exists API calls, and the watches on the parent /// node left by getChildren API calls. /// </summary> /// <param name="path">The path.</param> /// <param name="version">The version.</param> void Delete(string path, int version); /// <summary> /// Return the stat of the node of the given path. Return null if no such a /// node exists. /// /// If the watch is non-null and the call is successful (no exception is thrown), /// a watch will be left on the node with the given path. The watch will be /// triggered by a successful operation that creates/delete the node or sets /// the data on the node. /// </summary> /// <param name="path">The path.</param> /// <param name="watcher">The watcher.</param> /// <returns>the stat of the node of the given path; return null if no such a node exists.</returns> Stat Exists(string path, IWatcher watcher); /// <summary> /// Return the stat of the node of the given path. Return null if no such a /// node exists. /// /// If the watch is true and the call is successful (no exception is thrown), /// a watch will be left on the node with the given path. The watch will be /// triggered by a successful operation that creates/delete the node or sets /// the data on the node. /// @param path /// the node path /// @param watch /// whether need to watch this node /// @return the stat of the node of the given path; return null if no such a /// node exists. /// @throws KeeperException If the server signals an error /// @throws InterruptedException If the server transaction is interrupted. /// </summary> Stat Exists(string path, bool watch); /// <summary> /// Return the data and the stat of the node of the given path. /// /// If the watch is non-null and the call is successful (no exception is /// thrown), a watch will be left on the node with the given path. The watch /// will be triggered by a successful operation that sets data on the node, or /// deletes the node. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @param path the given path /// @param watcher explicit watcher /// @param stat the stat of the node /// @return the data of the node /// @throws KeeperException If the server signals an error with a non-zero error code /// @throws InterruptedException If the server transaction is interrupted. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> byte[] GetData(string path, IWatcher watcher, Stat stat); /// <summary> /// Return the data and the stat of the node of the given path. /// /// If the watch is true and the call is successful (no exception is /// thrown), a watch will be left on the node with the given path. The watch /// will be triggered by a successful operation that sets data on the node, or /// deletes the node. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @param path the given path /// @param watch whether need to watch this node /// @param stat the stat of the node /// @return the data of the node /// @throws KeeperException If the server signals an error with a non-zero error code /// @throws InterruptedException If the server transaction is interrupted. /// </summary> byte[] GetData(string path, bool watch, Stat stat); /// <summary> /// Set the data for the node of the given path if such a node exists and the /// given version matches the version of the node (if the given version is /// -1, it matches any node's versions). Return the stat of the node. /// /// This operation, if successful, will trigger all the watches on the node /// of the given path left by getData calls. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// /// A KeeperException with error code KeeperException.BadVersion will be /// thrown if the given version does not match the node's version. /// /// The maximum allowable size of the data array is 1 MB (1,048,576 bytes). /// Arrays larger than this will cause a KeeperExecption to be thrown. /// @param path /// the path of the node /// @param data /// the data to set /// @param version /// the expected matching version /// @return the state of the node /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero error code. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> Stat SetData(string path, byte[] data, int version); /// <summary> /// Return the ACL and stat of the node of the given path. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @param path /// the given path for the node /// @param stat /// the stat of the node will be copied to this parameter. /// @return the ACL array of the given node. /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero error code. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> IEnumerable<ACL> GetACL(string path, Stat stat); /// <summary> /// Set the ACL for the node of the given path if such a node exists and the /// given version matches the version of the node. Return the stat of the /// node. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// /// A KeeperException with error code KeeperException.BadVersion will be /// thrown if the given version does not match the node's version. /// @param path /// @param acl /// @param version /// @return the stat of the node. /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero error code. /// @throws org.apache.zookeeper.KeeperException.InvalidACLException If the acl is invalide. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> Stat SetACL(string path, IEnumerable<ACL> acl, int version); /// <summary> /// Return the list of the children of the node of the given path. /// /// If the watch is non-null and the call is successful (no exception is thrown), /// a watch will be left on the node with the given path. The watch willbe /// triggered by a successful operation that deletes the node of the given /// path or creates/delete a child under the node. /// /// The list of children returned is not sorted and no guarantee is provided /// as to its natural or lexical order. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @param path /// @param watcher explicit watcher /// @return an unordered array of children of the node with the given path /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero error code. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> IEnumerable<string> GetChildren(string path, IWatcher watcher); IEnumerable<string> GetChildren(string path, bool watch); /// <summary> /// For the given znode path return the stat and children list. /// /// If the watch is non-null and the call is successful (no exception is thrown), /// a watch will be left on the node with the given path. The watch willbe /// triggered by a successful operation that deletes the node of the given /// path or creates/delete a child under the node. /// /// The list of children returned is not sorted and no guarantee is provided /// as to its natural or lexical order. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @since 3.3.0 /// /// @param path /// @param watcher explicit watcher /// @param stat stat of the znode designated by path /// @return an unordered array of children of the node with the given path /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero error code. /// @throws IllegalArgumentException if an invalid path is specified /// </summary> IEnumerable<string> GetChildren(string path, IWatcher watcher, Stat stat); /// <summary> /// For the given znode path return the stat and children list. /// /// If the watch is true and the call is successful (no exception is thrown), /// a watch will be left on the node with the given path. The watch willbe /// triggered by a successful operation that deletes the node of the given /// path or creates/delete a child under the node. /// /// The list of children returned is not sorted and no guarantee is provided /// as to its natural or lexical order. /// /// A KeeperException with error code KeeperException.NoNode will be thrown /// if no node with the given path exists. /// @since 3.3.0 /// /// @param path /// @param watch /// @param stat stat of the znode designated by path /// @return an unordered array of children of the node with the given path /// @throws InterruptedException If the server transaction is interrupted. /// @throws KeeperException If the server signals an error with a non-zero /// error code. /// </summary> IEnumerable<string> GetChildren(string path, bool watch, Stat stat); /// <summary> /// Close this client object. Once the client is closed, its session becomes /// invalid. All the ephemeral nodes in the ZooKeeper server associated with /// the session will be removed. The watches left on those nodes (and on /// their parents) will be triggered. /// </summary> void Dispose(); /// <summary> /// string representation of this ZooKeeper client. Suitable for things /// like logging. /// /// Do NOT count on the format of this string, it may change without /// warning. /// /// @since 3.3.0 /// </summary> string ToString(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Tests; using System.Security.Principal; using Xunit; namespace System.Security.Claims { public class ClaimsPrincipalTests { [Fact] public void Ctor_Default() { var cp = new ClaimsPrincipal(); Assert.NotNull(cp.Identities); Assert.Equal(0, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(0, cp.Claims.Count()); Assert.Null(cp.Identity); } [Fact] public void Ctor_IIdentity() { var id = new ClaimsIdentity( new List<Claim> { new Claim("claim_type", "claim_value") }, ""); var cp = new ClaimsPrincipal(id); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.Same(id, cp.Identities.First()); Assert.Same(id, cp.Identity); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value")); } [Fact] public void Ctor_IIdentity_NonClaims() { var id = new NonClaimsIdentity() { Name = "NonClaimsIdentity_Name" }; var cp = new ClaimsPrincipal(id); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.NotSame(id, cp.Identities.First()); Assert.NotSame(id, cp.Identity); Assert.Equal(id.Name, cp.Identity.Name); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "NonClaimsIdentity_Name")); } [Fact] public void Ctor_IPrincipal() { var baseId = new ClaimsIdentity( new List<Claim> { new Claim("claim_type", "claim_value") }, ""); var basePrincipal = new ClaimsPrincipal(); basePrincipal.AddIdentity(baseId); var cp = new ClaimsPrincipal(basePrincipal); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.Same(baseId, cp.Identities.First()); Assert.Same(baseId, cp.Identity); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == "claim_type" && claim.Value == "claim_value"), "#7"); } [Fact] public void Ctor_NonClaimsIPrincipal_NonClaimsIdentity() { var id = new NonClaimsIdentity() { Name = "NonClaimsIdentity_Name" }; var basePrincipal = new NonClaimsPrincipal { Identity = id }; var cp = new ClaimsPrincipal(basePrincipal); Assert.NotNull(cp.Identities); Assert.Equal(1, cp.Identities.Count()); Assert.NotSame(id, cp.Identities.First()); Assert.NotSame(id, cp.Identity); Assert.Equal(id.Name, cp.Identity.Name); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "NonClaimsIdentity_Name")); } [Fact] public void Ctor_NonClaimsIPrincipal_NoIdentity() { var p = new ClaimsPrincipal(new NonClaimsPrincipal()); Assert.NotNull(p.Identities); Assert.Equal(1, p.Identities.Count()); Assert.NotNull(p.Claims); Assert.Equal(0, p.Claims.Count()); Assert.NotNull(p.Identity); Assert.False(p.Identity.IsAuthenticated); } [Fact] public void Ctor_IPrincipal_NoIdentity() { var cp = new ClaimsPrincipal(new ClaimsPrincipal()); Assert.NotNull(cp.Identities); Assert.Equal(0, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(0, cp.Claims.Count()); Assert.Null(cp.Identity); } [Fact] public void Ctor_IPrincipal_MultipleIdentities() { var baseId1 = new ClaimsIdentity("baseId1"); var baseId2 = new GenericIdentity("generic_name", "baseId2"); var baseId3 = new ClaimsIdentity("customType"); var basePrincipal = new ClaimsPrincipal(baseId1); basePrincipal.AddIdentity(baseId2); basePrincipal.AddIdentity(baseId3); var cp = new ClaimsPrincipal(basePrincipal); Assert.NotNull(cp.Identities); Assert.Equal(3, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(1, cp.Claims.Count()); Assert.Equal(baseId1, cp.Identity); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name")); Assert.Equal(baseId2.Claims.First(), cp.Claims.First()); } [Fact] public void Ctor_IEnumerableClaimsIdentity_Empty() { var cp = new ClaimsPrincipal(new ClaimsIdentity[0]); Assert.NotNull(cp.Identities); Assert.Equal(0, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(0, cp.Claims.Count()); Assert.Null(cp.Identity); } [Fact] public void Ctor_IEnumerableClaimsIdentity_Multiple() { var baseId1 = new ClaimsIdentity("baseId1"); var baseId2 = new GenericIdentity("generic_name2", "baseId2"); var baseId3 = new GenericIdentity("generic_name3", "baseId3"); var cp = new ClaimsPrincipal(new List<ClaimsIdentity> { baseId1, baseId2, baseId3 }); Assert.NotNull(cp.Identities); Assert.Equal(3, cp.Identities.Count()); Assert.NotNull(cp.Claims); Assert.Equal(2, cp.Claims.Count()); Assert.Equal(baseId1, cp.Identity); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name2")); Assert.True(cp.Claims.Any(claim => claim.Type == ClaimsIdentity.DefaultNameClaimType && claim.Value == "generic_name3")); Assert.Equal(baseId2.Claims.First(), cp.Claims.First()); Assert.Equal(baseId3.Claims.Last(), cp.Claims.Last()); } [Fact] public void Ctor_ArgumentValidation() { AssertExtensions.Throws<ArgumentNullException>("identities", () => new ClaimsPrincipal((IEnumerable<ClaimsIdentity>)null)); AssertExtensions.Throws<ArgumentNullException>("identity", () => new ClaimsPrincipal((IIdentity)null)); AssertExtensions.Throws<ArgumentNullException>("principal", () => new ClaimsPrincipal((IPrincipal)null)); AssertExtensions.Throws<ArgumentNullException>("reader", () => new ClaimsPrincipal((BinaryReader)null)); } [Fact] public void ClaimPrincipal_SerializeDeserialize_Roundtrip() { Assert.NotNull(BinaryFormatterHelpers.Clone(new ClaimsPrincipal())); } private class NonClaimsPrincipal : IPrincipal { public IIdentity Identity { get; set; } public bool IsInRole(string role) { throw new NotImplementedException(); } } } }
using System; using System.Data; using System.Data.SqlClient; using TarsimAvlCL; namespace TarsimAvlDAL { public class UserPermissionDAL : DB { public CLUserPermissionList GetList(ClUserPermissionFilter upPermission, LogParam logparam) { var cmd = new SqlCommand("PRC_UserPermission_GetList", ProjectConnection) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter(PAGEINDEX_PARAM, SqlDbType.Int)).Value = upPermission.PageIndex; cmd.Parameters.Add(new SqlParameter(PAGESIZE_PARAM, SqlDbType.Int)).Value = upPermission.PageSize; if (string.IsNullOrEmpty(upPermission.OrderBy)) upPermission.OrderBy = "UserPermissinID"; cmd.Parameters.Add(new SqlParameter(ORDERBY_PARAM, SqlDbType.NVarChar)).Value = upPermission.OrderBy; cmd.Parameters.Add(new SqlParameter(ORDER_PARAM, SqlDbType.NVarChar)).Value = upPermission.Order; cmd.Parameters.Add(new SqlParameter("UserPermissinID", SqlDbType.Int)).Value = upPermission.ClUserPermission.UserPermissinID; cmd.Parameters.Add(new SqlParameter("UserID", SqlDbType.Int)).Value = upPermission.ClUserPermission.UserID; cmd.Parameters.Add(new SqlParameter("PermissionID", SqlDbType.Int)).Value = (upPermission.ClUserPermission.PermissionID); cmd.Parameters.Add(new SqlParameter("CanView", SqlDbType.Bit)).Value = upPermission.ClUserPermission.CanView; cmd.Parameters.Add(new SqlParameter("CanUpdate", SqlDbType.Bit)).Value = (upPermission.ClUserPermission.CanUpdate); cmd.Parameters.Add(new SqlParameter("CanDel", SqlDbType.Bit)).Value = (upPermission.ClUserPermission.CanDel); cmd.Parameters.Add(new SqlParameter("CanInsert", SqlDbType.Bit)).Value = (upPermission.ClUserPermission.CanInsert); cmd.Parameters.Add(new SqlParameter("Result", SqlDbType.Int) {Direction = ParameterDirection.Output}); SqlDataReader dataReader = null; var userPermissionList = new CLUserPermissionList(); try { ProjectConnection.Open(); dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { if ((userPermissionList.RowCount == null || userPermissionList.RowCount == 0) && dataReader["ROW_COUNT"] != DBNull.Value) userPermissionList.RowCount = Convert.ToInt32(dataReader["ROW_COUNT"]); var metadatadb = new ClUserPermission(); if (dataReader["UserID"] != DBNull.Value) { //metadatadb.MetaDataID = Convert.ToInt32(dataReader[metadatadb.METADATAID_FIELD]); metadatadb.FillForObject(dataReader); userPermissionList.Rows.Add(metadatadb); } } //da.Fill(ds); dataReader.Close(); ProjectConnection.Close(); return userPermissionList; } catch (Exception ex) { return null; } finally { // ds.Dispose(); if (dataReader != null && !dataReader.IsClosed) dataReader.Close(); if (ProjectConnection.State != ConnectionState.Closed) ProjectConnection.Close(); } } public int AddPermissionPack(ClUserRole ur, LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_PermissionPack_Insert", ProjectConnection) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("RoleID", SqlDbType.NVarChar)).Value = ur.RoleID; cmd.Parameters.Add(new SqlParameter("UserID", SqlDbType.Int)).Value = ur.UserID; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int) {Direction = ParameterDirection.Output}; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } public int AddPermission(ClUserPermission up, LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_UserPermission_Insert", ProjectConnection) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("UserID", SqlDbType.Int)).Value = up.UserID; cmd.Parameters.Add(new SqlParameter("PermissionID", SqlDbType.Int)).Value = up.PermissionID; cmd.Parameters.Add(new SqlParameter("CanView", SqlDbType.Bit)).Value = up.CanView; cmd.Parameters.Add(new SqlParameter("CanUpdate", SqlDbType.Bit)).Value = up.CanUpdate; cmd.Parameters.Add(new SqlParameter("CanDel", SqlDbType.Bit)).Value = up.CanDel; cmd.Parameters.Add(new SqlParameter("CanInsert", SqlDbType.Bit)).Value = up.CanInsert; cmd.Parameters.Add(new SqlParameter("Log", SqlDbType.NVarChar)).Value = up.Log; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int) {Direction = ParameterDirection.Output}; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } public bool UpdateUserPermission(ClUserPermission userPermission, LogParam logparam) { bool flag = false; SqlCommand cmd = new SqlCommand("PRC_UserPermission_Update", ProjectConnection) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("UserPermissinID", SqlDbType.Int)).Value = userPermission.UserPermissinID; cmd.Parameters.Add(new SqlParameter("CanView", SqlDbType.Int)).Value = userPermission.CanView; cmd.Parameters.Add(new SqlParameter("CanInsert", SqlDbType.Int)).Value = userPermission.CanInsert; cmd.Parameters.Add(new SqlParameter("CanUpdate", SqlDbType.Int)).Value = userPermission.CanUpdate; cmd.Parameters.Add(new SqlParameter("CanDel", SqlDbType.Int)).Value = userPermission.CanDel; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int) { Direction = ParameterDirection.Output }; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); flag = Convert.ToInt32(prmResult.Value) > 0; } catch (Exception ex) { flag = false; } finally { ProjectConnection.Close(); } return flag; } public int DeletePermission(string userPermissionId, LogParam logparam) { SqlCommand cmd = new SqlCommand("PRC_UserPermission_Delete", ProjectConnection) { CommandType = CommandType.StoredProcedure }; cmd.Parameters.Add(new SqlParameter("UserIDLog", SqlDbType.NVarChar)).Value = logparam.UserID; cmd.Parameters.Add(new SqlParameter("IpLog", SqlDbType.NVarChar)).Value = logparam.IPAddress; cmd.Parameters.Add(new SqlParameter("OSLog", SqlDbType.NVarChar)).Value = logparam.OS; cmd.Parameters.Add(new SqlParameter("OSVerLog", SqlDbType.NVarChar)).Value = logparam.Browser; cmd.Parameters.Add(new SqlParameter("URLLog", SqlDbType.NVarChar)).Value = logparam.Url; cmd.Parameters.Add(new SqlParameter("UserPermissinID", SqlDbType.Int)).Value = userPermissionId; SqlParameter prmResult = new SqlParameter("Result", SqlDbType.Int) {Direction = ParameterDirection.Output}; cmd.Parameters.Add(prmResult); try { ProjectConnection.Open(); cmd.ExecuteNonQuery(); return Convert.ToInt32(prmResult.Value); } catch (Exception ex) { return 0; } finally { ProjectConnection.Close(); } } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Diagnostics; using System.IO; using System.Text; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.ML.Data.Buffer; using Encog.Util.File; namespace Encog.Util.Banchmark { /// <summary> /// Benchmark Encog with several network types. /// </summary> public class EncogBenchmark { /// <summary> /// Number of steps in all. /// </summary> private const int Steps = 3; /// <summary> /// The first step. /// </summary> private const int Step1 = 1; /// <summary> /// The third step. /// </summary> private const int Step2 = 2; /// <summary> /// The fourth step. /// </summary> private const int Step3 = 3; /// <summary> /// Report progress. /// </summary> private readonly IStatusReportable _report; /// <summary> /// The binary score. /// </summary> private int _binaryScore; /// <summary> /// The CPU score. /// </summary> private int _cpuScore; /// <summary> /// The memory score. /// </summary> private int _memoryScore; /// <summary> /// Construct a benchmark object. /// </summary> /// <param name="report">The object to report progress to.</param> public EncogBenchmark(IStatusReportable report) { _report = report; } /// <summary> /// The CPU score. /// </summary> public int CpuScore { get { return _cpuScore; } } /// <summary> /// The memory score. /// </summary> public int MemoryScore { get { return _memoryScore; } } /// <summary> /// The binary score. /// </summary> public int BinaryScore { get { return _binaryScore; } } /// <summary> /// Perform the benchmark. Returns the total amount of time for all of the /// benchmarks. Returns the final score. The lower the better for a score. /// </summary> /// <returns>The total time, which is the final Encog benchmark score.</returns> public String Process() { _report.Report(Steps, 0, "Beginning benchmark"); EvalCpu(); EvalMemory(); EvalBinary(); var result = new StringBuilder(); result.Append("Encog Benchmark: CPU:"); result.Append(Format.FormatInteger(_cpuScore)); result.Append(", Memory:"); result.Append(Format.FormatInteger(_memoryScore)); result.Append(", Disk:"); result.Append(Format.FormatInteger(_binaryScore)); _report.Report(Steps, Steps, result .ToString()); return result.ToString(); } /// <summary> /// Evaluate the CPU. /// </summary> private void EvalCpu() { int small = Evaluate.EvaluateTrain(2, 4, 0, 1); _report.Report(Steps, Step1, "Evaluate CPU, tiny= " + Format.FormatInteger(small/100)); int medium = Evaluate.EvaluateTrain(10, 20, 0, 1); _report.Report(Steps, Step1, "Evaluate CPU, small= " + Format.FormatInteger(medium/30)); int large = Evaluate.EvaluateTrain(100, 200, 40, 5); _report.Report(Steps, Step1, "Evaluate CPU, large= " + Format.FormatInteger(large)); int huge = Evaluate.EvaluateTrain(200, 300, 200, 50); _report.Report(Steps, Step1, "Evaluate CPU, huge= " + Format.FormatInteger(huge)); int result = (small/100) + (medium/30) + large + huge; _report.Report(Steps, Step1, "CPU result: " + result); _cpuScore = result; } /// <summary> /// Evaluate memory. /// </summary> private void EvalMemory() { BasicMLDataSet training = RandomTrainingFactory.Generate( 1000, 10000, 10, 10, -1, 1); const long stop = (10*Evaluate.Milis); int record = 0; IMLDataPair pair; int iterations = 0; var watch = new Stopwatch(); watch.Start(); while(true) { iterations++; pair = training[record++]; if(record >= training.Count) record = 0; if((iterations & 0xff) == 0 && watch.ElapsedMilliseconds >= stop) break; } iterations /= 100000; _report.Report(Steps, Step2, "Memory dataset, result: " + Format.FormatInteger(iterations)); _memoryScore = iterations; } /// <summary> /// Evaluate disk. /// </summary> private void EvalBinary() { FileInfo file = FileUtil.CombinePath( new FileInfo(Path.GetTempPath()), "temp.egb" ); BasicMLDataSet training = RandomTrainingFactory.Generate( 1000, 10000, 10, 10, -1, 1); // create the binary file if (file.Exists) { file.Delete(); } var training2 = new BufferedMLDataSet(file.ToString()); training2.Load(training); const long stop = (10*Evaluate.Milis); int record = 0; IMLDataPair pair; var watch = new Stopwatch(); watch.Start(); int iterations = 0; while(true) { iterations++; pair = training[record++]; if(record >= training.Count) record = 0; if((iterations & 0xff) == 0 && watch.ElapsedMilliseconds >= stop) break; } training2.Close(); iterations /= 100000; _report.Report(Steps, Step3, "Disk(binary) dataset, result: " + Format.FormatInteger(iterations)); if (file.Exists) { file.Delete(); } _binaryScore = iterations; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MultiTenantAccountManager.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Management.Automation; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.PowerShell.Commands { /// <summary> /// Response object for html content without DOM parsing. /// </summary> public class BasicHtmlWebResponseObject : WebResponseObject { #region Private Fields private static Regex s_attribNameValueRegex; private static Regex s_attribsRegex; private static Regex s_imageRegex; private static Regex s_inputFieldRegex; private static Regex s_linkRegex; private static Regex s_tagRegex; #endregion Private Fields #region Constructors /// <summary> /// Constructor for BasicHtmlWebResponseObject. /// </summary> /// <param name="response"></param> public BasicHtmlWebResponseObject(HttpResponseMessage response) : this(response, null) { } /// <summary> /// Constructor for HtmlWebResponseObject with memory stream. /// </summary> /// <param name="response"></param> /// <param name="contentStream"></param> public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream) : base(response, contentStream) { EnsureHtmlParser(); InitializeContent(); InitializeRawContent(response); } #endregion Constructors #region Properties /// <summary> /// Gets the Content property. /// </summary> public new string Content { get; private set; } /// <summary> /// Gets the Encoding that was used to decode the Content. /// </summary> /// <value> /// The Encoding used to decode the Content; otherwise, a null reference if the content is not text. /// </value> public Encoding Encoding { get; private set; } private WebCmdletElementCollection _inputFields; /// <summary> /// Gets the Fields property. /// </summary> public WebCmdletElementCollection InputFields { get { if (_inputFields == null) { EnsureHtmlParser(); List<PSObject> parsedFields = new List<PSObject>(); MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content); foreach (Match field in fieldMatch) { parsedFields.Add(CreateHtmlObject(field.Value, "INPUT")); } _inputFields = new WebCmdletElementCollection(parsedFields); } return _inputFields; } } private WebCmdletElementCollection _links; /// <summary> /// Gets the Links property. /// </summary> public WebCmdletElementCollection Links { get { if (_links == null) { EnsureHtmlParser(); List<PSObject> parsedLinks = new List<PSObject>(); MatchCollection linkMatch = s_linkRegex.Matches(Content); foreach (Match link in linkMatch) { parsedLinks.Add(CreateHtmlObject(link.Value, "A")); } _links = new WebCmdletElementCollection(parsedLinks); } return _links; } } private WebCmdletElementCollection _images; /// <summary> /// Gets the Images property. /// </summary> public WebCmdletElementCollection Images { get { if (_images == null) { EnsureHtmlParser(); List<PSObject> parsedImages = new List<PSObject>(); MatchCollection imageMatch = s_imageRegex.Matches(Content); foreach (Match image in imageMatch) { parsedImages.Add(CreateHtmlObject(image.Value, "IMG")); } _images = new WebCmdletElementCollection(parsedImages); } return _images; } } #endregion Properties #region Methods /// <summary> /// Reads the response content from the web response. /// </summary> protected void InitializeContent() { string contentType = ContentHelper.GetContentType(BaseResponse); if (ContentHelper.IsText(contentType)) { Encoding encoding = null; // fill the Content buffer string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); if (string.IsNullOrEmpty(characterSet) && ContentHelper.IsJson(contentType)) { characterSet = Encoding.UTF8.HeaderName; } this.Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out encoding); this.Encoding = encoding; } else { this.Content = string.Empty; } } private PSObject CreateHtmlObject(string html, string tagName) { PSObject elementObject = new PSObject(); elementObject.Properties.Add(new PSNoteProperty("outerHTML", html)); elementObject.Properties.Add(new PSNoteProperty("tagName", tagName)); ParseAttributes(html, elementObject); return elementObject; } private void EnsureHtmlParser() { if (s_tagRegex == null) { s_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } if (s_attribsRegex == null) { s_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } if (s_attribNameValueRegex == null) { s_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } if (s_inputFieldRegex == null) { s_inputFieldRegex = new Regex(@"<input\s+[^>]*(/>|>.*?</input>)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } if (s_linkRegex == null) { s_linkRegex = new Regex(@"<a\s+[^>]*(/>|>.*?</a>)", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } if (s_imageRegex == null) { s_imageRegex = new Regex(@"<img\s+[^>]*>", RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); } } private void InitializeRawContent(HttpResponseMessage baseResponse) { StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); raw.Append(Content); this.RawContent = raw.ToString(); } private void ParseAttributes(string outerHtml, PSObject elementObject) { // We might get an empty input for a directive from the HTML file if (!string.IsNullOrEmpty(outerHtml)) { // Extract just the opening tag of the HTML element (omitting the closing tag and any contents, // including contained HTML elements) var match = s_tagRegex.Match(outerHtml); // Extract all the attribute specifications within the HTML element opening tag var attribMatches = s_attribsRegex.Matches(match.Value); foreach (Match attribMatch in attribMatches) { // Extract the name and value for this attribute (allowing for variations like single/double/no // quotes, and no value at all) var nvMatches = s_attribNameValueRegex.Match(attribMatch.Value); Debug.Assert(nvMatches.Groups.Count == 5); // Name is always captured by group #1 string name = nvMatches.Groups[1].Value; // The value (if any) is captured by group #2, #3, or #4, depending on quoting or lack thereof string value = null; if (nvMatches.Groups[2].Success) { value = nvMatches.Groups[2].Value; } else if (nvMatches.Groups[3].Success) { value = nvMatches.Groups[3].Value; } else if (nvMatches.Groups[4].Success) { value = nvMatches.Groups[4].Value; } elementObject.Properties.Add(new PSNoteProperty(name, value)); } } } #endregion Methods } }
/* * 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 ds-2015-04-16.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.DirectoryService.Model; namespace Amazon.DirectoryService { /// <summary> /// Interface for accessing DirectoryService /// /// AWS Directory Service /// <para> /// This is the <i>AWS Directory Service API Reference</i>. This guide provides detailed /// information about AWS Directory Service operations, data types, parameters, and errors. /// </para> /// </summary> public partial interface IAmazonDirectoryService : IDisposable { #region ConnectDirectory /// <summary> /// Creates an AD Connector to connect an on-premises directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ConnectDirectory service method.</param> /// /// <returns>The response from the ConnectDirectory service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.DirectoryLimitExceededException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> ConnectDirectoryResponse ConnectDirectory(ConnectDirectoryRequest request); /// <summary> /// Initiates the asynchronous execution of the ConnectDirectory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ConnectDirectory operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ConnectDirectoryResponse> ConnectDirectoryAsync(ConnectDirectoryRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateAlias /// <summary> /// Creates an alias for a directory and assigns the alias to the directory. The alias /// is used to construct the access URL for the directory, such as <code>http://&#x3C;alias&#x3E;.awsapps.com</code>. /// /// <important> /// <para> /// After an alias has been created, it cannot be deleted or reused, so this operation /// should only be used when absolutely necessary. /// </para> /// </important> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateAlias service method.</param> /// /// <returns>The response from the CreateAlias service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> CreateAliasResponse CreateAlias(CreateAliasRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateAlias operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateAlias operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateAliasResponse> CreateAliasAsync(CreateAliasRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateComputer /// <summary> /// Creates a computer account in the specified directory, and joins the computer to the /// directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateComputer service method.</param> /// /// <returns>The response from the CreateComputer service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.DirectoryUnavailableException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.UnsupportedOperationException"> /// /// </exception> CreateComputerResponse CreateComputer(CreateComputerRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateComputer operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateComputer operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateComputerResponse> CreateComputerAsync(CreateComputerRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateDirectory /// <summary> /// Creates a Simple AD directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateDirectory service method.</param> /// /// <returns>The response from the CreateDirectory service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.DirectoryLimitExceededException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> CreateDirectoryResponse CreateDirectory(CreateDirectoryRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateDirectory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateDirectory operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateDirectoryResponse> CreateDirectoryAsync(CreateDirectoryRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region CreateSnapshot /// <summary> /// Creates a snapshot of an existing directory. /// /// /// <para> /// You cannot take snapshots of extended or connected directories. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateSnapshot service method.</param> /// /// <returns>The response from the CreateSnapshot service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.SnapshotLimitExceededException"> /// /// </exception> CreateSnapshotResponse CreateSnapshot(CreateSnapshotRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<CreateSnapshotResponse> CreateSnapshotAsync(CreateSnapshotRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteDirectory /// <summary> /// Deletes an AWS Directory Service directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteDirectory service method.</param> /// /// <returns>The response from the DeleteDirectory service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DeleteDirectoryResponse DeleteDirectory(DeleteDirectoryRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteDirectory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDirectory operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteDirectoryResponse> DeleteDirectoryAsync(DeleteDirectoryRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteSnapshot /// <summary> /// Deletes a directory snapshot. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot service method.</param> /// /// <returns>The response from the DeleteSnapshot service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DeleteSnapshotResponse DeleteSnapshot(DeleteSnapshotRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteSnapshotResponse> DeleteSnapshotAsync(DeleteSnapshotRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeDirectories /// <summary> /// Obtains information about the directories that belong to this account. /// /// /// <para> /// You can retrieve information about specific directories by passing the directory identifiers /// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the /// current account are returned. /// </para> /// /// <para> /// This operation supports pagination with the use of the <i>NextToken</i> request and /// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i> /// member contains a token that you pass in the next call to <a>DescribeDirectories</a> /// to retrieve the next set of items. /// </para> /// /// <para> /// You can also specify a maximum number of return results with the <i>Limit</i> parameter. /// </para> /// </summary> /// /// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DescribeDirectoriesResponse DescribeDirectories(); /// <summary> /// Obtains information about the directories that belong to this account. /// /// /// <para> /// You can retrieve information about specific directories by passing the directory identifiers /// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the /// current account are returned. /// </para> /// /// <para> /// This operation supports pagination with the use of the <i>NextToken</i> request and /// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i> /// member contains a token that you pass in the next call to <a>DescribeDirectories</a> /// to retrieve the next set of items. /// </para> /// /// <para> /// You can also specify a maximum number of return results with the <i>Limit</i> parameter. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeDirectories service method.</param> /// /// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DescribeDirectoriesResponse DescribeDirectories(DescribeDirectoriesRequest request); /// <summary> /// Obtains information about the directories that belong to this account. /// /// /// <para> /// You can retrieve information about specific directories by passing the directory identifiers /// in the <i>DirectoryIds</i> parameter. Otherwise, all directories that belong to the /// current account are returned. /// </para> /// /// <para> /// This operation supports pagination with the use of the <i>NextToken</i> request and /// response parameters. If more results are available, the <i>DescribeDirectoriesResult.NextToken</i> /// member contains a token that you pass in the next call to <a>DescribeDirectories</a> /// to retrieve the next set of items. /// </para> /// /// <para> /// You can also specify a maximum number of return results with the <i>Limit</i> parameter. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDirectories service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> Task<DescribeDirectoriesResponse> DescribeDirectoriesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeDirectories operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDirectories operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeDirectoriesResponse> DescribeDirectoriesAsync(DescribeDirectoriesRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeSnapshots /// <summary> /// Obtains information about the directory snapshots that belong to this account. /// /// /// <para> /// This operation supports pagination with the use of the <i>NextToken</i> request and /// response parameters. If more results are available, the <i>DescribeSnapshots.NextToken</i> /// member contains a token that you pass in the next call to <a>DescribeSnapshots</a> /// to retrieve the next set of items. /// </para> /// /// <para> /// You can also specify a maximum number of return results with the <i>Limit</i> parameter. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots service method.</param> /// /// <returns>The response from the DescribeSnapshots service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidNextTokenException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DescribeSnapshotsResponse DescribeSnapshots(DescribeSnapshotsRequest request); /// <summary> /// Initiates the asynchronous execution of the DescribeSnapshots operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeSnapshots operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeSnapshotsResponse> DescribeSnapshotsAsync(DescribeSnapshotsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DisableRadius /// <summary> /// Disables multi-factor authentication (MFA) with Remote Authentication Dial In User /// Service (RADIUS) for an AD Connector directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisableRadius service method.</param> /// /// <returns>The response from the DisableRadius service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DisableRadiusResponse DisableRadius(DisableRadiusRequest request); /// <summary> /// Initiates the asynchronous execution of the DisableRadius operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisableRadius operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DisableRadiusResponse> DisableRadiusAsync(DisableRadiusRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DisableSso /// <summary> /// Disables single-sign on for a directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the DisableSso service method.</param> /// /// <returns>The response from the DisableSso service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InsufficientPermissionsException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> DisableSsoResponse DisableSso(DisableSsoRequest request); /// <summary> /// Initiates the asynchronous execution of the DisableSso operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DisableSso operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DisableSsoResponse> DisableSsoAsync(DisableSsoRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region EnableRadius /// <summary> /// Enables multi-factor authentication (MFA) with Remote Authentication Dial In User /// Service (RADIUS) for an AD Connector directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the EnableRadius service method.</param> /// /// <returns>The response from the EnableRadius service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityAlreadyExistsException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> EnableRadiusResponse EnableRadius(EnableRadiusRequest request); /// <summary> /// Initiates the asynchronous execution of the EnableRadius operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EnableRadius operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<EnableRadiusResponse> EnableRadiusAsync(EnableRadiusRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region EnableSso /// <summary> /// Enables single-sign on for a directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the EnableSso service method.</param> /// /// <returns>The response from the EnableSso service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.AuthenticationFailedException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InsufficientPermissionsException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> EnableSsoResponse EnableSso(EnableSsoRequest request); /// <summary> /// Initiates the asynchronous execution of the EnableSso operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the EnableSso operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<EnableSsoResponse> EnableSsoAsync(EnableSsoRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetDirectoryLimits /// <summary> /// Obtains directory limit information for the current region. /// </summary> /// /// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> GetDirectoryLimitsResponse GetDirectoryLimits(); /// <summary> /// Obtains directory limit information for the current region. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetDirectoryLimits service method.</param> /// /// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> GetDirectoryLimitsResponse GetDirectoryLimits(GetDirectoryLimitsRequest request); /// <summary> /// Obtains directory limit information for the current region. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetDirectoryLimits service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> Task<GetDirectoryLimitsResponse> GetDirectoryLimitsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the GetDirectoryLimits operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetDirectoryLimits operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetDirectoryLimitsResponse> GetDirectoryLimitsAsync(GetDirectoryLimitsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSnapshotLimits /// <summary> /// Obtains the manual snapshot limits for a directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetSnapshotLimits service method.</param> /// /// <returns>The response from the GetSnapshotLimits service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> GetSnapshotLimitsResponse GetSnapshotLimits(GetSnapshotLimitsRequest request); /// <summary> /// Initiates the asynchronous execution of the GetSnapshotLimits operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSnapshotLimits operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetSnapshotLimitsResponse> GetSnapshotLimitsAsync(GetSnapshotLimitsRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region RestoreFromSnapshot /// <summary> /// Restores a directory using an existing directory snapshot. /// /// /// <para> /// When you restore a directory from a snapshot, any changes made to the directory after /// the snapshot date are overwritten. /// </para> /// /// <para> /// This action returns as soon as the restore operation is initiated. You can monitor /// the progress of the restore operation by calling the <a>DescribeDirectories</a> operation /// with the directory identifier. When the <b>DirectoryDescription.Stage</b> value changes /// to <code>Active</code>, the restore operation is complete. /// </para> /// </summary> /// <param name="request">Container for the necessary parameters to execute the RestoreFromSnapshot service method.</param> /// /// <returns>The response from the RestoreFromSnapshot service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> RestoreFromSnapshotResponse RestoreFromSnapshot(RestoreFromSnapshotRequest request); /// <summary> /// Initiates the asynchronous execution of the RestoreFromSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the RestoreFromSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<RestoreFromSnapshotResponse> RestoreFromSnapshotAsync(RestoreFromSnapshotRequest request, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region UpdateRadius /// <summary> /// Updates the Remote Authentication Dial In User Service (RADIUS) server information /// for an AD Connector directory. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateRadius service method.</param> /// /// <returns>The response from the UpdateRadius service method, as returned by DirectoryService.</returns> /// <exception cref="Amazon.DirectoryService.Model.ClientException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.EntityDoesNotExistException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.InvalidParameterException"> /// /// </exception> /// <exception cref="Amazon.DirectoryService.Model.ServiceException"> /// /// </exception> UpdateRadiusResponse UpdateRadius(UpdateRadiusRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateRadius operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateRadius operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<UpdateRadiusResponse> UpdateRadiusAsync(UpdateRadiusRequest request, CancellationToken cancellationToken = default(CancellationToken)); #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // Central spin logic used across the entire code-base. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using Internal.Runtime.Augments; namespace System.Threading { // SpinWait is just a little value type that encapsulates some common spinning // logic. It ensures we always yield on single-proc machines (instead of using busy // waits), and that we work well on HT. It encapsulates a good mixture of spinning // and real yielding. It's a value type so that various areas of the engine can use // one by allocating it on the stack w/out unnecessary GC allocation overhead, e.g.: // // void f() { // SpinWait wait = new SpinWait(); // while (!p) { wait.SpinOnce(); } // ... // } // // Internally it just maintains a counter that is used to decide when to yield, etc. // // A common usage is to spin before blocking. In those cases, the NextSpinWillYield // property allows a user to decide to fall back to waiting once it returns true: // // void f() { // SpinWait wait = new SpinWait(); // while (!p) { // if (wait.NextSpinWillYield) { /* block! */ } // else { wait.SpinOnce(); } // } // ... // } /// <summary> /// Provides support for spin-based waiting. /// </summary> /// <remarks> /// <para> /// <see cref="SpinWait"/> encapsulates common spinning logic. On single-processor machines, yields are /// always used instead of busy waits, and on computers with Intel(R) processors employing Hyper-Threading /// technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of /// spinning and true yielding. /// </para> /// <para> /// <see cref="SpinWait"/> is a value type, which means that low-level code can utilize SpinWait without /// fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications. /// In most cases, you should use the synchronization classes provided by the .NET Framework, such as /// <see cref="System.Threading.Monitor"/>. For most purposes where spin waiting is required, however, /// the <see cref="SpinWait"/> type should be preferred over the <see /// cref="System.Threading.Thread.SpinWait"/> method. /// </para> /// <para> /// While SpinWait is designed to be used in concurrent applications, it is not designed to be /// used from multiple threads concurrently. SpinWait's members are not thread-safe. If multiple /// threads must spin, each should use its own instance of SpinWait. /// </para> /// </remarks> public struct SpinWait { // These constants determine the frequency of yields versus spinning. The // numbers may seem fairly arbitrary, but were derived with at least some // thought in the design document. I fully expect they will need to change // over time as we gain more experience with performance. internal const int YIELD_THRESHOLD = 10; // When to switch over to a true yield. internal const int SLEEP_0_EVERY_HOW_MANY_TIMES = 5; // After how many yields should we Sleep(0)? internal const int SLEEP_1_EVERY_HOW_MANY_TIMES = 20; // After how many yields should we Sleep(1)? // The number of times we've spun already. private int _count; /// <summary> /// Gets the number of times <see cref="SpinOnce"/> has been called on this instance. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets whether the next call to <see cref="SpinOnce"/> will yield the processor, triggering a /// forced context switch. /// </summary> /// <value>Whether the next call to <see cref="SpinOnce"/> will yield the processor, triggering a /// forced context switch.</value> /// <remarks> /// On a single-CPU machine, <see cref="SpinOnce"/> always yields the processor. On machines with /// multiple CPUs, <see cref="SpinOnce"/> may yield after an unspecified number of calls. /// </remarks> public bool NextSpinWillYield { get { return _count > YIELD_THRESHOLD || PlatformHelper.IsSingleProcessor; } } /// <summary> /// Performs a single spin. /// </summary> /// <remarks> /// This is typically called in a loop, and may change in behavior based on the number of times a /// <see cref="SpinOnce"/> has been called thus far on this instance. /// </remarks> public void SpinOnce() { if (NextSpinWillYield) { // // We must yield. // // We prefer to call Thread.Yield first, triggering a SwitchToThread. This // unfortunately doesn't consider all runnable threads on all OS SKUs. In // some cases, it may only consult the runnable threads whose ideal processor // is the one currently executing code. Thus we occasionally issue a call to // Sleep(0), which considers all runnable threads at equal priority. Even this // is insufficient since we may be spin waiting for lower priority threads to // execute; we therefore must call Sleep(1) once in a while too, which considers // all runnable threads, regardless of ideal processor and priority, but may // remove the thread from the scheduler's queue for 10+ms, if the system is // configured to use the (default) coarse-grained system timer. // int yieldsSoFar = (_count >= YIELD_THRESHOLD ? _count - YIELD_THRESHOLD : _count); if ((yieldsSoFar % SLEEP_1_EVERY_HOW_MANY_TIMES) == (SLEEP_1_EVERY_HOW_MANY_TIMES - 1)) { RuntimeThread.Sleep(1); } else if ((yieldsSoFar % SLEEP_0_EVERY_HOW_MANY_TIMES) == (SLEEP_0_EVERY_HOW_MANY_TIMES - 1)) { RuntimeThread.Sleep(0); } else { RuntimeThread.Yield(); } } else { // // Otherwise, we will spin. // // We do this using the CLR's SpinWait API, which is just a busy loop that // issues YIELD/PAUSE instructions to ensure multi-threaded CPUs can react // intelligently to avoid starving. (These are NOOPs on other CPUs.) We // choose a number for the loop iteration count such that each successive // call spins for longer, to reduce cache contention. We cap the total // number of spins we are willing to tolerate to reduce delay to the caller, // since we expect most callers will eventually block anyway. // RuntimeThread.SpinWait(4 << _count); } // Finally, increment our spin counter. _count = (_count == int.MaxValue ? YIELD_THRESHOLD : _count + 1); } /// <summary> /// Resets the spin counter. /// </summary> /// <remarks> /// This makes <see cref="SpinOnce"/> and <see cref="NextSpinWillYield"/> behave as though no calls /// to <see cref="SpinOnce"/> had been issued on this instance. If a <see cref="SpinWait"/> instance /// is reused many times, it may be useful to reset it to avoid yielding too soon. /// </remarks> public void Reset() { _count = 0; } #region Static Methods /// <summary> /// Spins until the specified condition is satisfied. /// </summary> /// <param name="condition">A delegate to be executed over and over until it returns true.</param> /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception> public static void SpinUntil(Func<bool> condition) { #if DEBUG bool result = #endif SpinUntil(condition, Timeout.Infinite); #if DEBUG Debug.Assert(result); #endif } /// <summary> /// Spins until the specified condition is satisfied or until the specified timeout is expired. /// </summary> /// <param name="condition">A delegate to be executed over and over until it returns true.</param> /// <param name="timeout"> /// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait, /// or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param> /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns> /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative number /// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than /// <see cref="System.Int32.MaxValue"/>.</exception> public static bool SpinUntil(Func<bool> condition, TimeSpan timeout) { // Validate the timeout long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException( nameof(timeout), timeout, SR.SpinWait_SpinUntil_TimeoutWrong); } // Call wait with the timeout milliseconds return SpinUntil(condition, (int)totalMilliseconds); } /// <summary> /// Spins until the specified condition is satisfied or until the specified timeout is expired. /// </summary> /// <param name="condition">A delegate to be executed over and over until it returns true.</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param> /// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns> /// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout) { if (millisecondsTimeout < Timeout.Infinite) { throw new ArgumentOutOfRangeException( nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong); } if (condition == null) { throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull); } uint startTime = 0; if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite) { startTime = TimeoutHelper.GetTime(); } SpinWait spinner = new SpinWait(); while (!condition()) { if (millisecondsTimeout == 0) { return false; } spinner.SpinOnce(); if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield) { if (millisecondsTimeout <= (TimeoutHelper.GetTime() - startTime)) { return false; } } } return true; } #endregion } /// <summary> /// A helper class to get the number of processors, it updates the numbers of processors every sampling interval. /// </summary> internal static class PlatformHelper { private const int PROCESSOR_COUNT_REFRESH_INTERVAL_MS = 30000; // How often to refresh the count, in milliseconds. private static volatile int s_processorCount; // The last count seen. private static volatile int s_lastProcessorCountRefreshTicks; // The last time we refreshed. /// <summary> /// Gets the number of available processors /// </summary> internal static int ProcessorCount { get { int now = Environment.TickCount; int procCount = s_processorCount; if (procCount == 0 || (now - s_lastProcessorCountRefreshTicks) >= PROCESSOR_COUNT_REFRESH_INTERVAL_MS) { s_processorCount = procCount = Environment.ProcessorCount; s_lastProcessorCountRefreshTicks = now; } Debug.Assert(procCount > 0, "Processor count should be greater than 0."); return procCount; } } /// <summary> /// Gets whether the current machine has only a single processor. /// </summary> internal static bool IsSingleProcessor { get { return ProcessorCount == 1; } } } }
//------------------------------------------------------------------------------ // <copyright file="LinqDataSourceView.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web.Compilation; using System.Web.Query.Dynamic; using System.Web.Resources; using System.Security; using System.Security.Permissions; using DynamicValidatorEventArgs = System.Web.DynamicData.DynamicValidatorEventArgs; using DynamicDataSourceOperation = System.Web.DynamicData.DynamicDataSourceOperation; public partial class LinqDataSourceView : ContextDataSourceView { private static readonly object EventDeleted = new object(); private static readonly object EventDeleting = new object(); private static readonly object EventException = new object(); private static readonly object EventInserted = new object(); private static readonly object EventInserting = new object(); private static readonly object EventUpdated = new object(); private static readonly object EventUpdating = new object(); private HttpContext _context; private Type _contextType; private string _contextTypeName; private LinqDataSource _owner; private List<ContextDataSourceContextData> _selectContexts; private bool _enableDelete; private bool _enableInsert; private bool _enableObjectTracking = true; private bool _enableUpdate; private bool _isNewContext; private ILinqToSql _linqToSql; private bool _reuseSelectContext; private bool _storeOriginalValuesInViewState = true; private bool _storeOriginalValues; private object _selectResult; public LinqDataSourceView(LinqDataSource owner, string name, HttpContext context) : this(owner, name, context, new DynamicQueryableWrapper(), new LinqToSqlWrapper()) { } // internal constructor that takes mocks for unit tests. internal LinqDataSourceView(LinqDataSource owner, string name, HttpContext context, IDynamicQueryable dynamicQueryable, ILinqToSql linqToSql) : base(owner, name, context, dynamicQueryable) { _context = context; _owner = owner; _linqToSql = linqToSql; } public override bool CanDelete { get { return EnableDelete; } } public override bool CanInsert { get { return EnableInsert; } } // When AutoPage is false the user should manually page in the Selecting event. public override bool CanPage { get { return true; } } // When AutoPage is false the user must set the total row count in the Selecting event. public override bool CanRetrieveTotalRowCount { get { return true; } } // When AutoSort is false the user should manually sort in the Selecting event. public override bool CanSort { get { return true; } } public override bool CanUpdate { get { return EnableUpdate; } } public override Type ContextType { [SecuritySafeCritical] get { if (_contextType == null) { string typeName = ContextTypeName; if (String.IsNullOrEmpty(typeName)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ContextTypeNameNotSpecified, _owner.ID)); } try { _contextType = BuildManager.GetType(typeName, /*throwOnFail*/true, /*ignoreCase*/true); } catch (Exception e) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ContextTypeNameNotFound, _owner.ID), e); } } return _contextType; } } public override string ContextTypeName { get { return _contextTypeName ?? String.Empty; } set { if (_contextTypeName != value) { if (_reuseSelectContext) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ContextTypeNameChanged, _owner.ID)); } _contextTypeName = value; _contextType = null; OnDataSourceViewChanged(EventArgs.Empty); } } } public bool EnableDelete { get { return _enableDelete; } set { if (_enableDelete != value) { _enableDelete = value; OnDataSourceViewChanged(EventArgs.Empty); } } } public bool EnableInsert { get { return _enableInsert; } set { if (_enableInsert != value) { _enableInsert = value; OnDataSourceViewChanged(EventArgs.Empty); } } } public bool EnableObjectTracking { get { return _enableObjectTracking; } set { if (_enableObjectTracking != value) { if (_reuseSelectContext) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_EnableObjectTrackingChanged, _owner.ID)); } _enableObjectTracking = value; } } } public bool EnableUpdate { get { return _enableUpdate; } set { if (_enableUpdate != value) { _enableUpdate = value; OnDataSourceViewChanged(EventArgs.Empty); } } } public bool StoreOriginalValuesInViewState { get { return _storeOriginalValuesInViewState; } set { if (_storeOriginalValuesInViewState != value) { _storeOriginalValuesInViewState = value; OnDataSourceViewChanged(EventArgs.Empty); } } } public string TableName { get { return EntitySetName; } set { if (EntitySetName != value) { if (_reuseSelectContext) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableNameChanged, _owner.ID)); } EntitySetName = value; } } } public event EventHandler<LinqDataSourceStatusEventArgs> ContextCreated { add { Events.AddHandler(EventContextCreated, value); } remove { Events.RemoveHandler(EventContextCreated, value); } } public event EventHandler<LinqDataSourceContextEventArgs> ContextCreating { add { Events.AddHandler(EventContextCreating, value); } remove { Events.RemoveHandler(EventContextCreating, value); } } public event EventHandler<LinqDataSourceDisposeEventArgs> ContextDisposing { add { Events.AddHandler(EventContextDisposing, value); } remove { Events.RemoveHandler(EventContextDisposing, value); } } public event EventHandler<LinqDataSourceStatusEventArgs> Deleted { add { Events.AddHandler(EventDeleted, value); } remove { Events.RemoveHandler(EventDeleted, value); } } public event EventHandler<LinqDataSourceDeleteEventArgs> Deleting { add { Events.AddHandler(EventDeleting, value); } remove { Events.RemoveHandler(EventDeleting, value); } } internal event EventHandler<DynamicValidatorEventArgs> Exception { add { Events.AddHandler(EventException, value); } remove { Events.RemoveHandler(EventException, value); } } public event EventHandler<LinqDataSourceStatusEventArgs> Inserted { add { Events.AddHandler(EventInserted, value); } remove { Events.RemoveHandler(EventInserted, value); } } public event EventHandler<LinqDataSourceInsertEventArgs> Inserting { add { Events.AddHandler(EventInserting, value); } remove { Events.RemoveHandler(EventInserting, value); } } public event EventHandler<LinqDataSourceStatusEventArgs> Selected { add { Events.AddHandler(EventSelected, value); } remove { Events.RemoveHandler(EventSelected, value); } } public event EventHandler<LinqDataSourceSelectEventArgs> Selecting { add { Events.AddHandler(EventSelecting, value); } remove { Events.RemoveHandler(EventSelecting, value); } } public event EventHandler<LinqDataSourceStatusEventArgs> Updated { add { Events.AddHandler(EventUpdated, value); } remove { Events.RemoveHandler(EventUpdated, value); } } public event EventHandler<LinqDataSourceUpdateEventArgs> Updating { add { Events.AddHandler(EventUpdating, value); } remove { Events.RemoveHandler(EventUpdating, value); } } protected virtual object CreateContext(Type contextType) { return DataSourceHelper.CreateObjectInstance(contextType); } protected override ContextDataSourceContextData CreateContext(DataSourceOperation operation) { if (operation == DataSourceOperation.Select) { return CreateContextAndTableForSelect(); } return CreateContextAndTableForEdit(operation); } private ContextDataSourceContextData CreateContextAndTable(DataSourceOperation operation) { ContextDataSourceContextData contextData = null; bool eventFired = false; try { LinqDataSourceContextEventArgs contextEventArgs = new LinqDataSourceContextEventArgs(operation); OnContextCreating(contextEventArgs); contextData = new ContextDataSourceContextData(contextEventArgs.ObjectInstance); Type contextType = null; MemberInfo tableMemberInfo = null; if (contextData.Context == null) { // construct the context unless accessing a static table for Select. contextType = ContextType; tableMemberInfo = GetTableMemberInfo(contextType); if (tableMemberInfo != null) { if (MemberIsStatic(tableMemberInfo)) { if (operation != DataSourceOperation.Select) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableCannotBeStatic, TableName, contextType.Name, _owner.ID)); } } else { contextData.Context = CreateContext(contextType); _isNewContext = true; } } } else { // use the manually constructed context. tableMemberInfo = GetTableMemberInfo(contextData.Context.GetType()); } // fetch the table from the context. if (tableMemberInfo != null) { FieldInfo field = tableMemberInfo as FieldInfo; if (field != null) { contextData.EntitySet = field.GetValue(contextData.Context); } PropertyInfo property = tableMemberInfo as PropertyInfo; if (property != null) { contextData.EntitySet = property.GetValue(contextData.Context, null); } } if (contextData.EntitySet == null) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableNameNotFound, TableName, contextType.Name, _owner.ID)); } } catch (Exception e) { eventFired = true; LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(e); OnContextCreated(createdEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.ContextCreate)); // CreateContextAndTable will return null if this exception is handled. if (!createdEventArgs.ExceptionHandled) { throw; } } finally { if (!eventFired) { // contextData can be null if exception thrown from ContextCreating handler. object context = (contextData == null) ? null : contextData.Context; LinqDataSourceStatusEventArgs createdEventArgs = new LinqDataSourceStatusEventArgs(context); OnContextCreated(createdEventArgs); } } return contextData; } private ContextDataSourceContextData CreateContextAndTableForEdit(DataSourceOperation operation) { ContextDataSourceContextData contextData = CreateContextAndTable(operation); // context data may be null or incomplete if an exception was handled if (contextData != null) { if (contextData.Context == null) { return null; } if (contextData.EntitySet == null) { DisposeContext(contextData.Context); return null; } ValidateContextType(contextData.Context.GetType(), false); ValidateTableType(contextData.EntitySet.GetType(), false); } return contextData; } private ContextDataSourceContextData CreateContextAndTableForSelect() { _isNewContext = false; if (_selectContexts == null) { _selectContexts = new List<ContextDataSourceContextData>(); } else if (_reuseSelectContext && _selectContexts.Count > 0) { return _selectContexts[_selectContexts.Count - 1]; } // context data may be null if an exception was handled ContextDataSourceContextData contextData = CreateContextAndTable(DataSourceOperation.Select); if (contextData != null) { if (contextData.Context != null) { ValidateContextType(contextData.Context.GetType(), true); } if (contextData.EntitySet != null) { ValidateTableType(contextData.EntitySet.GetType(), true); } _selectContexts.Add(contextData); // context may not be dlinq context or may be null if table was static. DataContext dlinqContext = contextData.Context as DataContext; if ((dlinqContext != null) && _isNewContext) { dlinqContext.ObjectTrackingEnabled = EnableObjectTracking; } // don't reuse dlinq contexts that cache data or exterior changes will not be reflected. _reuseSelectContext = (dlinqContext == null) || !EnableObjectTracking; } return contextData; } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object", Justification = "Names are consistent with those used in the ObjectDataSource classes")] protected virtual void DeleteDataObject(object dataContext, object table, object oldDataObject) { _linqToSql.Attach((ITable)table, oldDataObject); _linqToSql.Remove((ITable)table, oldDataObject); _linqToSql.SubmitChanges((DataContext)dataContext); } protected override int DeleteObject(object oldEntity) { LinqDataSourceDeleteEventArgs deleteEventArgs = new LinqDataSourceDeleteEventArgs(oldEntity); OnDeleting(deleteEventArgs); if (deleteEventArgs.Cancel) { return -1; } LinqDataSourceStatusEventArgs deletedEventArgs = null; try { DeleteDataObject(Context, EntitySet, deleteEventArgs.OriginalObject); } catch (Exception e) { // allow user to handle dlinq exceptions including OnValidate validation. deletedEventArgs = new LinqDataSourceStatusEventArgs(e); OnDeleted(deletedEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Delete)); if (deletedEventArgs.ExceptionHandled) { return -1; } throw; } deletedEventArgs = new LinqDataSourceStatusEventArgs(deleteEventArgs.OriginalObject); OnDeleted(deletedEventArgs); return 1; } protected override void DisposeContext(object dataContext) { if (dataContext != null) { LinqDataSourceDisposeEventArgs disposingEventArgs = new LinqDataSourceDisposeEventArgs(dataContext); OnContextDisposing(disposingEventArgs); if (!disposingEventArgs.Cancel) { base.DisposeContext(dataContext); } } } protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues) { ValidateDeleteSupported(keys, oldValues); return base.ExecuteDelete(keys, oldValues); } protected override int ExecuteInsert(IDictionary values) { ValidateInsertSupported(values); return base.ExecuteInsert(values); } protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) { ValidateUpdateSupported(keys, values, oldValues); return base.ExecuteUpdate(keys, values, oldValues); } protected internal override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments) { ClearOriginalValues(); QueryContext queryContext = CreateQueryContext(arguments); object table = GetSource(queryContext); IList result = null; if (_selectResult != null) { try { IQueryable query = QueryableDataSourceHelper.AsQueryable(_selectResult); query = ExecuteQuery(query, queryContext); Type dataObjectType = GetDataObjectType(query.GetType()); result = query.ToList(dataObjectType); if (_storeOriginalValues) { ITable dlinqTable = table as ITable; // We can store original values if the type is exact or derived if ((dlinqTable != null) && dataObjectType.IsAssignableFrom(EntityType)) { StoreOriginalValues(result); } } } catch (Exception e) { result = null; LinqDataSourceStatusEventArgs selectedEventArgs = new LinqDataSourceStatusEventArgs(e); OnSelected(selectedEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Select)); if (!selectedEventArgs.ExceptionHandled) { throw; } } finally { if (result != null) { int totalRowCount = -1; // paging performed, but row count not available. if (arguments.RetrieveTotalRowCount) { totalRowCount = arguments.TotalRowCount; } else if (!AutoPage) { totalRowCount = result.Count; } LinqDataSourceStatusEventArgs selectedEventArgs = new LinqDataSourceStatusEventArgs(result, totalRowCount); OnSelected(selectedEventArgs); } } // Null out the select context Context = null; } return result; } protected override object GetSource(QueryContext context) { LinqDataSourceSelectEventArgs selectEventArgs = new LinqDataSourceSelectEventArgs( context.Arguments, context.WhereParameters, context.OrderByParameters, context.GroupByParameters, context.OrderGroupsByParameters, context.SelectParameters); OnSelecting(selectEventArgs); if (selectEventArgs.Cancel) { return null; } _selectResult = selectEventArgs.Result; object table = _selectResult; // Original values should only be stored for valid delete and update scenarios. _storeOriginalValues = StoreOriginalValuesInViewState && (CanDelete || CanUpdate) && String.IsNullOrEmpty(GroupBy) && String.IsNullOrEmpty(SelectNew); if (_selectResult == null) { table = base.GetSource(context); _selectResult = table; } // If the provided select result was not a DLinq table and we need to store // original values then we must get the table and create a new data context // instance so that we can access the column metadata. else if (!(table is ITable) && _storeOriginalValues) { table = base.GetSource(context); } return table; } protected virtual MemberInfo GetTableMemberInfo(Type contextType) { string tableName = TableName; if (String.IsNullOrEmpty(tableName)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_TableNameNotSpecified, _owner.ID)); } MemberInfo[] members = contextType.FindMembers(MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static, /*filter*/null, /*filterCriteria*/null); for (int i = 0; i < members.Length; i++) { if (String.Equals(members[i].Name, tableName, StringComparison.OrdinalIgnoreCase)) { return members[i]; } } return null; } private ReadOnlyCollection<MetaDataMember> GetTableMetaDataMembers(ITable table, Type dataObjectType) { DataContext context = ((ITable)table).Context; MetaModel contextMetaData = context.Mapping; MetaTable tableMetaData = contextMetaData.GetTable(dataObjectType); MetaType rowMetaData = tableMetaData.Model.GetMetaType(dataObjectType); return rowMetaData.DataMembers; } protected override void HandleValidationErrors(IDictionary<string, Exception> errors, DataSourceOperation operation) { LinqDataSourceValidationException exception = new LinqDataSourceValidationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ValidationFailed, EntityType, errors.Values.First().Message), errors); bool exceptionHandled = false; switch (operation) { case DataSourceOperation.Delete: LinqDataSourceDeleteEventArgs deleteEventArgs = new LinqDataSourceDeleteEventArgs(exception); OnDeleting(deleteEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Delete)); exceptionHandled = deleteEventArgs.ExceptionHandled; break; case DataSourceOperation.Insert: LinqDataSourceInsertEventArgs insertEventArgs = new LinqDataSourceInsertEventArgs(exception); OnInserting(insertEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Insert)); exceptionHandled = insertEventArgs.ExceptionHandled; break; case DataSourceOperation.Update: // allow user to handle conversion or dlinq property validation exceptions. LinqDataSourceUpdateEventArgs updateEventArgs = new LinqDataSourceUpdateEventArgs(exception); OnUpdating(updateEventArgs); OnException(new DynamicValidatorEventArgs(exception, DynamicDataSourceOperation.Update)); exceptionHandled = updateEventArgs.ExceptionHandled; break; } if (!exceptionHandled) { throw exception; } } [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object", Justification = "Names are consistent with those used in the ObjectDataSource classes")] protected virtual void InsertDataObject(object dataContext, object table, object newDataObject) { _linqToSql.Add((ITable)table, newDataObject); _linqToSql.SubmitChanges((DataContext)dataContext); } protected override int InsertObject(object newEntity) { LinqDataSourceInsertEventArgs insertEventArgs = new LinqDataSourceInsertEventArgs(newEntity); OnInserting(insertEventArgs); if (insertEventArgs.Cancel) { return -1; } LinqDataSourceStatusEventArgs insertedEventArgs = null; try { InsertDataObject(Context, EntitySet, insertEventArgs.NewObject); } catch (Exception e) { // allow user to handle dlinq exceptions including OnValidate validation. insertedEventArgs = new LinqDataSourceStatusEventArgs(e); OnInserted(insertedEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Insert)); if (insertedEventArgs.ExceptionHandled) { return -1; } throw; } insertedEventArgs = new LinqDataSourceStatusEventArgs(insertEventArgs.NewObject); OnInserted(insertedEventArgs); return 1; } private static bool MemberIsStatic(MemberInfo member) { FieldInfo field = member as FieldInfo; if (field != null) { return field.IsStatic; } PropertyInfo property = member as PropertyInfo; if (property != null) { MethodInfo propertyGetter = property.GetGetMethod(); return ((propertyGetter != null) && propertyGetter.IsStatic); } return false; } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnContextCreated(LinqDataSourceStatusEventArgs e) { EventHandler<LinqDataSourceStatusEventArgs> handler = (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventContextCreated]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnContextCreating(LinqDataSourceContextEventArgs e) { EventHandler<LinqDataSourceContextEventArgs> handler = (EventHandler<LinqDataSourceContextEventArgs>)Events[EventContextCreating]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnContextDisposing(LinqDataSourceDisposeEventArgs e) { EventHandler<LinqDataSourceDisposeEventArgs> handler = (EventHandler<LinqDataSourceDisposeEventArgs>)Events[EventContextDisposing]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnDeleted(LinqDataSourceStatusEventArgs e) { EventHandler<LinqDataSourceStatusEventArgs> handler = (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventDeleted]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnDeleting(LinqDataSourceDeleteEventArgs e) { EventHandler<LinqDataSourceDeleteEventArgs> handler = (EventHandler<LinqDataSourceDeleteEventArgs>)Events[EventDeleting]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnException(DynamicValidatorEventArgs e) { EventHandler<DynamicValidatorEventArgs> handler = (EventHandler<DynamicValidatorEventArgs>)Events[EventException]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnInserted(LinqDataSourceStatusEventArgs e) { EventHandler<LinqDataSourceStatusEventArgs> handler = (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventInserted]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnInserting(LinqDataSourceInsertEventArgs e) { EventHandler<LinqDataSourceInsertEventArgs> handler = (EventHandler<LinqDataSourceInsertEventArgs>)Events[EventInserting]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnSelected(LinqDataSourceStatusEventArgs e) { EventHandler<LinqDataSourceStatusEventArgs> handler = (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventSelected]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnSelecting(LinqDataSourceSelectEventArgs e) { EventHandler<LinqDataSourceSelectEventArgs> handler = (EventHandler<LinqDataSourceSelectEventArgs>)Events[EventSelecting]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnUpdated(LinqDataSourceStatusEventArgs e) { EventHandler<LinqDataSourceStatusEventArgs> handler = (EventHandler<LinqDataSourceStatusEventArgs>)Events[EventUpdated]; if (handler != null) { handler(this, e); } } [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#")] protected virtual void OnUpdating(LinqDataSourceUpdateEventArgs e) { EventHandler<LinqDataSourceUpdateEventArgs> handler = (EventHandler<LinqDataSourceUpdateEventArgs>)Events[EventUpdating]; if (handler != null) { handler(this, e); } } internal void ReleaseSelectContexts() { if (_selectContexts != null) { foreach (ContextDataSourceContextData contextData in _selectContexts) { DisposeContext(contextData.Context); } } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", Justification = "Names are consistent with those used in the ObjectDataSource classes")] protected virtual void ResetDataObject(object table, object dataObject) { // DevDiv Bugs 187705, and 114508: Resetting is no longer necessary because // select has it's own context, but this method is kept for compatibility purposes. // no-op } public IEnumerable Select(DataSourceSelectArguments arguments) { return ExecuteSelect(arguments); } private Dictionary<string, Exception> SetDataObjectProperties(object oldDataObject, object newDataObject) { Dictionary<string, Exception> validateExceptions = null; PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(oldDataObject); foreach (PropertyDescriptor property in properties) { if (property.PropertyType.IsSerializable && !property.IsReadOnly) { object newValue = property.GetValue(newDataObject); try { property.SetValue(oldDataObject, newValue); } catch (Exception e) { if (validateExceptions == null) { validateExceptions = new Dictionary<string, Exception>(StringComparer.OrdinalIgnoreCase); } validateExceptions[property.Name] = e; } } } return validateExceptions; } [SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods", Justification = "System.Data.Linq assembly will be changing to support partial trust.")] protected override void StoreOriginalValues(IList results) { Type entityType = EntityType; IDictionary<string, MetaDataMember> columns = GetTableMetaDataMembers((ITable)EntitySet, entityType).ToDictionary(c => c.Member.Name); StoreOriginalValues(results, p => columns.ContainsKey(p.Name) && (columns[p.Name].IsPrimaryKey || columns[p.Name].IsVersion || (columns[p.Name].UpdateCheck != UpdateCheck.Never))); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", Justification = "Names are consistent with those used in the ObjectDataSource classes")] protected virtual void UpdateDataObject(object dataContext, object table, object oldDataObject, object newDataObject) { _linqToSql.Attach((ITable)table, oldDataObject); Dictionary<string, Exception> validateExceptions = SetDataObjectProperties(oldDataObject, newDataObject); // package up dlinq validation exceptions into single exception. if (validateExceptions != null) { throw new LinqDataSourceValidationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_ValidationFailed, oldDataObject.GetType(), validateExceptions.Values.First().Message), validateExceptions); } _linqToSql.SubmitChanges((DataContext)dataContext); } protected override int UpdateObject(object oldEntity, object newEntity) { LinqDataSourceUpdateEventArgs updateEventArgs = new LinqDataSourceUpdateEventArgs(oldEntity, newEntity); OnUpdating(updateEventArgs); if (updateEventArgs.Cancel) { return -1; } LinqDataSourceStatusEventArgs updatedEventArgs = null; try { UpdateDataObject(Context, EntitySet, updateEventArgs.OriginalObject, updateEventArgs.NewObject); } catch (Exception e) { ResetDataObject(EntitySet, updateEventArgs.OriginalObject); // allow user to handle dlinq exceptions including OnValidate validation. updatedEventArgs = new LinqDataSourceStatusEventArgs(e); OnUpdated(updatedEventArgs); OnException(new DynamicValidatorEventArgs(e, DynamicDataSourceOperation.Update)); if (updatedEventArgs.ExceptionHandled) { return -1; } throw; } updatedEventArgs = new LinqDataSourceStatusEventArgs(updateEventArgs.NewObject); OnUpdated(updatedEventArgs); return 1; } protected virtual void ValidateContextType(Type contextType, bool selecting) { if (!selecting && !typeof(DataContext).IsAssignableFrom(contextType)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_InvalidContextType, _owner.ID)); } } protected virtual void ValidateDeleteSupported(IDictionary keys, IDictionary oldValues) { if (!CanDelete) { throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_DeleteNotSupported, _owner.ID)); } ValidateEditSupported(); } protected virtual void ValidateEditSupported() { if (!String.IsNullOrEmpty(GroupBy)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_GroupByNotSupportedOnEdit, _owner.ID)); } if (!String.IsNullOrEmpty(SelectNew)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_SelectNewNotSupportedOnEdit, _owner.ID)); } } protected virtual void ValidateInsertSupported(IDictionary values) { if (!CanInsert) { throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_InsertNotSupported, _owner.ID)); } ValidateEditSupported(); if ((values == null) || (values.Count == 0)) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_InsertRequiresValues, _owner.ID)); } } protected virtual void ValidateTableType(Type tableType, bool selecting) { if (!selecting) { if (!(tableType.IsGenericType && tableType.GetGenericArguments().Length == 1 && typeof(ITable).IsAssignableFrom(tableType))) { throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_InvalidTablePropertyType, _owner.ID)); } } } protected virtual void ValidateUpdateSupported(IDictionary keys, IDictionary values, IDictionary oldValues) { if (!CanUpdate) { throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture, AtlasWeb.LinqDataSourceView_UpdateNotSupported, _owner.ID)); } ValidateEditSupported(); } } }
// 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. // <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/events/firebase/remoteconfig/v1/data.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Events.Protobuf.Firebase.RemoteConfig.V1 { /// <summary>Holder for reflection information generated from google/events/firebase/remoteconfig/v1/data.proto</summary> public static partial class DataReflection { #region Descriptor /// <summary>File descriptor for google/events/firebase/remoteconfig/v1/data.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static DataReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjFnb29nbGUvZXZlbnRzL2ZpcmViYXNlL3JlbW90ZWNvbmZpZy92MS9kYXRh", "LnByb3RvEiZnb29nbGUuZXZlbnRzLmZpcmViYXNlLnJlbW90ZWNvbmZpZy52", "MRofZ29vZ2xlL3Byb3RvYnVmL3RpbWVzdGFtcC5wcm90byKLAwoVUmVtb3Rl", "Q29uZmlnRXZlbnREYXRhEhYKDnZlcnNpb25fbnVtYmVyGAEgASgDEi8KC3Vw", "ZGF0ZV90aW1lGAIgASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBJN", "Cgt1cGRhdGVfdXNlchgDIAEoCzI4Lmdvb2dsZS5ldmVudHMuZmlyZWJhc2Uu", "cmVtb3RlY29uZmlnLnYxLlJlbW90ZUNvbmZpZ1VzZXISEwoLZGVzY3JpcHRp", "b24YBCABKAkSVwoNdXBkYXRlX29yaWdpbhgFIAEoDjJALmdvb2dsZS5ldmVu", "dHMuZmlyZWJhc2UucmVtb3RlY29uZmlnLnYxLlJlbW90ZUNvbmZpZ1VwZGF0", "ZU9yaWdpbhJTCgt1cGRhdGVfdHlwZRgGIAEoDjI+Lmdvb2dsZS5ldmVudHMu", "ZmlyZWJhc2UucmVtb3RlY29uZmlnLnYxLlJlbW90ZUNvbmZpZ1VwZGF0ZVR5", "cGUSFwoPcm9sbGJhY2tfc291cmNlGAcgASgDIkIKEFJlbW90ZUNvbmZpZ1Vz", "ZXISDAoEbmFtZRgBIAEoCRINCgVlbWFpbBgCIAEoCRIRCglpbWFnZV91cmwY", "AyABKAkqdgoYUmVtb3RlQ29uZmlnVXBkYXRlT3JpZ2luEisKJ1JFTU9URV9D", "T05GSUdfVVBEQVRFX09SSUdJTl9VTlNQRUNJRklFRBAAEgsKB0NPTlNPTEUQ", "ARIMCghSRVNUX0FQSRACEhIKDkFETUlOX1NES19OT0RFEAMqfAoWUmVtb3Rl", "Q29uZmlnVXBkYXRlVHlwZRIpCiVSRU1PVEVfQ09ORklHX1VQREFURV9UWVBF", "X1VOU1BFQ0lGSUVEEAASFgoSSU5DUkVNRU5UQUxfVVBEQVRFEAESEQoNRk9S", "Q0VEX1VQREFURRACEgwKCFJPTExCQUNLEANCaQoqY29tLmdvb2dsZS5ldmVu", "dHMuZmlyZWJhc2UucmVtb3RlY29uZmlnLnYxQglEYXRhUHJvdG+qAi9Hb29n", "bGUuRXZlbnRzLlByb3RvYnVmLkZpcmViYXNlLlJlbW90ZUNvbmZpZy5WMWIG", "cHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin), typeof(global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType), }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigEventData), global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigEventData.Parser, new[]{ "VersionNumber", "UpdateTime", "UpdateUser", "Description", "UpdateOrigin", "UpdateType", "RollbackSource" }, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser), global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser.Parser, new[]{ "Name", "Email", "ImageUrl" }, null, null, null, null) })); } #endregion } #region Enums /// <summary> /// What type of update was associated with the Remote Config template version. /// </summary> public enum RemoteConfigUpdateOrigin { /// <summary> /// Catch-all for unrecognized values. /// </summary> [pbr::OriginalName("REMOTE_CONFIG_UPDATE_ORIGIN_UNSPECIFIED")] Unspecified = 0, /// <summary> /// The update came from the Firebase UI. /// </summary> [pbr::OriginalName("CONSOLE")] Console = 1, /// <summary> /// The update came from the Remote Config REST API. /// </summary> [pbr::OriginalName("REST_API")] RestApi = 2, /// <summary> /// The update came from the Firebase Admin Node SDK. /// </summary> [pbr::OriginalName("ADMIN_SDK_NODE")] AdminSdkNode = 3, } /// <summary> /// Where the Remote Config update action originated. /// </summary> public enum RemoteConfigUpdateType { /// <summary> /// Catch-all for unrecognized enum values. /// </summary> [pbr::OriginalName("REMOTE_CONFIG_UPDATE_TYPE_UNSPECIFIED")] Unspecified = 0, /// <summary> /// A regular incremental update. /// </summary> [pbr::OriginalName("INCREMENTAL_UPDATE")] IncrementalUpdate = 1, /// <summary> /// A forced update. /// The ETag was specified as "*" in an UpdateRemoteConfigRequest /// request or the "Force Update" button was pressed on the console. /// </summary> [pbr::OriginalName("FORCED_UPDATE")] ForcedUpdate = 2, /// <summary> /// A rollback to a previous Remote Config template. /// </summary> [pbr::OriginalName("ROLLBACK")] Rollback = 3, } #endregion #region Messages /// <summary> /// The data within all Firebase Remote Config events. /// </summary> public sealed partial class RemoteConfigEventData : pb::IMessage<RemoteConfigEventData> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RemoteConfigEventData> _parser = new pb::MessageParser<RemoteConfigEventData>(() => new RemoteConfigEventData()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RemoteConfigEventData> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.DataReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RemoteConfigEventData() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RemoteConfigEventData(RemoteConfigEventData other) : this() { versionNumber_ = other.versionNumber_; updateTime_ = other.updateTime_ != null ? other.updateTime_.Clone() : null; updateUser_ = other.updateUser_ != null ? other.updateUser_.Clone() : null; description_ = other.description_; updateOrigin_ = other.updateOrigin_; updateType_ = other.updateType_; rollbackSource_ = other.rollbackSource_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RemoteConfigEventData Clone() { return new RemoteConfigEventData(this); } /// <summary>Field number for the "version_number" field.</summary> public const int VersionNumberFieldNumber = 1; private long versionNumber_; /// <summary> /// The version number of the version's corresponding Remote Config template. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long VersionNumber { get { return versionNumber_; } set { versionNumber_ = value; } } /// <summary>Field number for the "update_time" field.</summary> public const int UpdateTimeFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp updateTime_; /// <summary> /// When the Remote Config template was written to the Remote Config server. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Protobuf.WellKnownTypes.Timestamp UpdateTime { get { return updateTime_; } set { updateTime_ = value; } } /// <summary>Field number for the "update_user" field.</summary> public const int UpdateUserFieldNumber = 3; private global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser updateUser_; /// <summary> /// Aggregation of all metadata fields about the account that performed the /// update. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser UpdateUser { get { return updateUser_; } set { updateUser_ = value; } } /// <summary>Field number for the "description" field.</summary> public const int DescriptionFieldNumber = 4; private string description_ = ""; /// <summary> /// The user-provided description of the corresponding Remote Config template. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Description { get { return description_; } set { description_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "update_origin" field.</summary> public const int UpdateOriginFieldNumber = 5; private global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin updateOrigin_ = global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin.Unspecified; /// <summary> /// Where the update action originated. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin UpdateOrigin { get { return updateOrigin_; } set { updateOrigin_ = value; } } /// <summary>Field number for the "update_type" field.</summary> public const int UpdateTypeFieldNumber = 6; private global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType updateType_ = global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType.Unspecified; /// <summary> /// What type of update was made. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType UpdateType { get { return updateType_; } set { updateType_ = value; } } /// <summary>Field number for the "rollback_source" field.</summary> public const int RollbackSourceFieldNumber = 7; private long rollbackSource_; /// <summary> /// Only present if this version is the result of a rollback, and will be the /// version number of the Remote Config template that was rolled-back to. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public long RollbackSource { get { return rollbackSource_; } set { rollbackSource_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RemoteConfigEventData); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RemoteConfigEventData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (VersionNumber != other.VersionNumber) return false; if (!object.Equals(UpdateTime, other.UpdateTime)) return false; if (!object.Equals(UpdateUser, other.UpdateUser)) return false; if (Description != other.Description) return false; if (UpdateOrigin != other.UpdateOrigin) return false; if (UpdateType != other.UpdateType) return false; if (RollbackSource != other.RollbackSource) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (VersionNumber != 0L) hash ^= VersionNumber.GetHashCode(); if (updateTime_ != null) hash ^= UpdateTime.GetHashCode(); if (updateUser_ != null) hash ^= UpdateUser.GetHashCode(); if (Description.Length != 0) hash ^= Description.GetHashCode(); if (UpdateOrigin != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin.Unspecified) hash ^= UpdateOrigin.GetHashCode(); if (UpdateType != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType.Unspecified) hash ^= UpdateType.GetHashCode(); if (RollbackSource != 0L) hash ^= RollbackSource.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (VersionNumber != 0L) { output.WriteRawTag(8); output.WriteInt64(VersionNumber); } if (updateTime_ != null) { output.WriteRawTag(18); output.WriteMessage(UpdateTime); } if (updateUser_ != null) { output.WriteRawTag(26); output.WriteMessage(UpdateUser); } if (Description.Length != 0) { output.WriteRawTag(34); output.WriteString(Description); } if (UpdateOrigin != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin.Unspecified) { output.WriteRawTag(40); output.WriteEnum((int) UpdateOrigin); } if (UpdateType != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType.Unspecified) { output.WriteRawTag(48); output.WriteEnum((int) UpdateType); } if (RollbackSource != 0L) { output.WriteRawTag(56); output.WriteInt64(RollbackSource); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (VersionNumber != 0L) { output.WriteRawTag(8); output.WriteInt64(VersionNumber); } if (updateTime_ != null) { output.WriteRawTag(18); output.WriteMessage(UpdateTime); } if (updateUser_ != null) { output.WriteRawTag(26); output.WriteMessage(UpdateUser); } if (Description.Length != 0) { output.WriteRawTag(34); output.WriteString(Description); } if (UpdateOrigin != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin.Unspecified) { output.WriteRawTag(40); output.WriteEnum((int) UpdateOrigin); } if (UpdateType != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType.Unspecified) { output.WriteRawTag(48); output.WriteEnum((int) UpdateType); } if (RollbackSource != 0L) { output.WriteRawTag(56); output.WriteInt64(RollbackSource); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (VersionNumber != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(VersionNumber); } if (updateTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateTime); } if (updateUser_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(UpdateUser); } if (Description.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Description); } if (UpdateOrigin != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UpdateOrigin); } if (UpdateType != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType.Unspecified) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) UpdateType); } if (RollbackSource != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(RollbackSource); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RemoteConfigEventData other) { if (other == null) { return; } if (other.VersionNumber != 0L) { VersionNumber = other.VersionNumber; } if (other.updateTime_ != null) { if (updateTime_ == null) { UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } UpdateTime.MergeFrom(other.UpdateTime); } if (other.updateUser_ != null) { if (updateUser_ == null) { UpdateUser = new global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser(); } UpdateUser.MergeFrom(other.UpdateUser); } if (other.Description.Length != 0) { Description = other.Description; } if (other.UpdateOrigin != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin.Unspecified) { UpdateOrigin = other.UpdateOrigin; } if (other.UpdateType != global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType.Unspecified) { UpdateType = other.UpdateType; } if (other.RollbackSource != 0L) { RollbackSource = other.RollbackSource; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { VersionNumber = input.ReadInt64(); break; } case 18: { if (updateTime_ == null) { UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(UpdateTime); break; } case 26: { if (updateUser_ == null) { UpdateUser = new global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser(); } input.ReadMessage(UpdateUser); break; } case 34: { Description = input.ReadString(); break; } case 40: { UpdateOrigin = (global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin) input.ReadEnum(); break; } case 48: { UpdateType = (global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType) input.ReadEnum(); break; } case 56: { RollbackSource = input.ReadInt64(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { VersionNumber = input.ReadInt64(); break; } case 18: { if (updateTime_ == null) { UpdateTime = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(UpdateTime); break; } case 26: { if (updateUser_ == null) { UpdateUser = new global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUser(); } input.ReadMessage(UpdateUser); break; } case 34: { Description = input.ReadString(); break; } case 40: { UpdateOrigin = (global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateOrigin) input.ReadEnum(); break; } case 48: { UpdateType = (global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.RemoteConfigUpdateType) input.ReadEnum(); break; } case 56: { RollbackSource = input.ReadInt64(); break; } } } } #endif } /// <summary> /// All the fields associated with the person/service account /// that wrote a Remote Config template. /// </summary> public sealed partial class RemoteConfigUser : pb::IMessage<RemoteConfigUser> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<RemoteConfigUser> _parser = new pb::MessageParser<RemoteConfigUser>(() => new RemoteConfigUser()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<RemoteConfigUser> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Events.Protobuf.Firebase.RemoteConfig.V1.DataReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RemoteConfigUser() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RemoteConfigUser(RemoteConfigUser other) : this() { name_ = other.name_; email_ = other.email_; imageUrl_ = other.imageUrl_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public RemoteConfigUser Clone() { return new RemoteConfigUser(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Display name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "email" field.</summary> public const int EmailFieldNumber = 2; private string email_ = ""; /// <summary> /// Email address. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Email { get { return email_; } set { email_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "image_url" field.</summary> public const int ImageUrlFieldNumber = 3; private string imageUrl_ = ""; /// <summary> /// Image URL. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string ImageUrl { get { return imageUrl_; } set { imageUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as RemoteConfigUser); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(RemoteConfigUser other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Email != other.Email) return false; if (ImageUrl != other.ImageUrl) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Email.Length != 0) hash ^= Email.GetHashCode(); if (ImageUrl.Length != 0) hash ^= ImageUrl.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Email.Length != 0) { output.WriteRawTag(18); output.WriteString(Email); } if (ImageUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(ImageUrl); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Email.Length != 0) { output.WriteRawTag(18); output.WriteString(Email); } if (ImageUrl.Length != 0) { output.WriteRawTag(26); output.WriteString(ImageUrl); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Email.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } if (ImageUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ImageUrl); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(RemoteConfigUser other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Email.Length != 0) { Email = other.Email; } if (other.ImageUrl.Length != 0) { ImageUrl = other.ImageUrl; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { Name = input.ReadString(); break; } case 18: { Email = input.ReadString(); break; } case 26: { ImageUrl = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 10: { Name = input.ReadString(); break; } case 18: { Email = input.ReadString(); break; } case 26: { ImageUrl = input.ReadString(); break; } } } } #endif } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection.Emit { using System.Text; using System; using CultureInfo = System.Globalization.CultureInfo; using System.Diagnostics.SymbolStore; using System.Reflection; using System.Security; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Diagnostics; public sealed class MethodBuilder : MethodInfo { #region Private Data Members // Identity internal String m_strName; // The name of the method private MethodToken m_tkMethod; // The token of this method private ModuleBuilder m_module; internal TypeBuilder m_containingType; // IL private int[] m_mdMethodFixups; // The location of all of the token fixups. Null means no fixups. private byte[] m_localSignature; // Local signature if set explicitly via DefineBody. Null otherwise. internal LocalSymInfo m_localSymInfo; // keep track debugging local information internal ILGenerator m_ilGenerator; // Null if not used. private byte[] m_ubBody; // The IL for the method private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none. private const int DefaultMaxStack = 16; private int m_maxStack = DefaultMaxStack; // Flags internal bool m_bIsBaked; private bool m_bIsGlobalMethod; private bool m_fInitLocals; // indicating if the method stack frame will be zero initialized or not. // Attributes private MethodAttributes m_iAttributes; private CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; // Parameters private SignatureHelper m_signature; internal Type[] m_parameterTypes; private ParameterBuilder m_retParam; private Type m_returnType; private Type[] m_returnTypeRequiredCustomModifiers; private Type[] m_returnTypeOptionalCustomModifiers; private Type[][] m_parameterTypeRequiredCustomModifiers; private Type[][] m_parameterTypeOptionalCustomModifiers; // Generics private GenericTypeParameterBuilder[] m_inst; private bool m_bIsGenMethDef; #endregion #region Constructor internal MethodBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { Init(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, mod, type, bIsGlobalMethod); } private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) throw new ArgumentException(SR.Argument_EmptyName, nameof(name)); if (name[0] == '\0') throw new ArgumentException(SR.Argument_IllegalName, nameof(name)); if (mod == null) throw new ArgumentNullException(nameof(mod)); if (parameterTypes != null) { foreach (Type t in parameterTypes) { if (t == null) throw new ArgumentNullException(nameof(parameterTypes)); } } m_strName = name; m_module = mod; m_containingType = type; // //if (returnType == null) //{ // m_returnType = typeof(void); //} //else { m_returnType = returnType; } if ((attributes & MethodAttributes.Static) == 0) { // turn on the has this calling convention callingConvention = callingConvention | CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0) { // A method can't be both static and virtual throw new ArgumentException(SR.Arg_NoStaticVirtual); } if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName) { if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface) { // methods on interface have to be abstract + virtual except special name methods such as type initializer if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) != (MethodAttributes.Abstract | MethodAttributes.Virtual) && (attributes & MethodAttributes.Static) == 0) throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod); } } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention, // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); m_iAttributes = attributes; m_bIsGlobalMethod = bIsGlobalMethod; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; // Default is managed IL. Manged IL has bit flag 0x0020 set off m_dwMethodImplFlags = MethodImplAttributes.IL; } #endregion #region Internal Members internal void CheckContext(params Type[][] typess) { m_module.CheckContext(typess); } internal void CheckContext(params Type[] types) { m_module.CheckContext(types); } internal void CreateMethodBodyHelper(ILGenerator il) { // Sets the IL of the method. An ILGenerator is passed as an argument and the method // queries this instance to get all of the information which it needs. if (il == null) { throw new ArgumentNullException(nameof(il)); } __ExceptionInfo[] excp; int counter = 0; int[] filterAddrs; int[] catchAddrs; int[] catchEndAddrs; Type[] catchClass; int[] type; int numCatch; int start, end; ModuleBuilder dynMod = (ModuleBuilder)m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { // you don't need to call DefineBody when you get your ILGenerator // through MethodBuilder::GetILGenerator. // throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { // There are still unclosed local scope throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); //Okay, now the fun part. Calculate all of the exceptions. excp = il.GetExceptions(); int numExceptions = CalculateNumberOfExceptions(excp); if (numExceptions > 0) { m_exceptions = new ExceptionHandler[numExceptions]; for (int i = 0; i < excp.Length; i++) { filterAddrs = excp[i].GetFilterAddresses(); catchAddrs = excp[i].GetCatchAddresses(); catchEndAddrs = excp[i].GetCatchEndAddresses(); catchClass = excp[i].GetCatchClass(); numCatch = excp[i].GetNumberOfCatches(); start = excp[i].GetStartAddress(); end = excp[i].GetEndAddress(); type = excp[i].GetExceptionTypes(); for (int j = 0; j < numCatch; j++) { int tkExceptionClass = 0; if (catchClass[j] != null) { tkExceptionClass = dynMod.GetTypeTokenInternal(catchClass[j]).Token; } switch (type[j]) { case __ExceptionInfo.None: case __ExceptionInfo.Fault: case __ExceptionInfo.Filter: m_exceptions[counter++] = new ExceptionHandler(start, end, filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; case __ExceptionInfo.Finally: m_exceptions[counter++] = new ExceptionHandler(start, excp[i].GetFinallyEndAddress(), filterAddrs[j], catchAddrs[j], catchEndAddrs[j], type[j], tkExceptionClass); break; } } } } m_bIsBaked = true; if (dynMod.GetSymWriter() != null) { // set the debugging information such as scope and line number // if it is in a debug module // SymbolToken tk = new SymbolToken(MetadataTokenInternal); ISymbolWriter symWriter = dynMod.GetSymWriter(); // call OpenMethod to make this method the current method symWriter.OpenMethod(tk); // call OpenScope because OpenMethod no longer implicitly creating // the top-levelsmethod scope // symWriter.OpenScope(0); if (m_symCustomAttrs != null) { foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs) dynMod.GetSymWriter().SetSymAttribute( new SymbolToken(MetadataTokenInternal), symCustomAttr.m_name, symCustomAttr.m_data); } if (m_localSymInfo != null) m_localSymInfo.EmitLocalSymInfo(symWriter); il.m_ScopeTree.EmitScopeTree(symWriter); il.m_LineNumberInfo.EmitLineNumberInfo(symWriter); symWriter.CloseScope(il.ILOffset); symWriter.CloseMethod(); } } // This is only called from TypeBuilder.CreateType after the method has been created internal void ReleaseBakedStructures() { if (!m_bIsBaked) { // We don't need to do anything here if we didn't baked the method body return; } m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } internal override Type[] GetParameterTypes() { if (m_parameterTypes == null) m_parameterTypes = Array.Empty<Type>(); return m_parameterTypes; } internal static Type GetMethodBaseReturnType(MethodBase method) { MethodInfo mi = null; ConstructorInfo ci = null; if ((mi = method as MethodInfo) != null) { return mi.ReturnType; } else if ((ci = method as ConstructorInfo) != null) { return ci.GetReturnType(); } else { Debug.Assert(false, "We should never get here!"); return null; } } internal byte[] GetBody() { // Returns the il bytes of this method. // This il is not valid until somebody has called BakeByteArray return m_ubBody; } internal int[] GetTokenFixups() { return m_mdMethodFixups; } internal SignatureHelper GetMethodSignature() { if (m_parameterTypes == null) m_parameterTypes = Array.Empty<Type>(); m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0, m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } // Returns a buffer whose initial signatureLength bytes contain encoded local signature. internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null) { if (m_ilGenerator.m_localCount != 0) { // If user is using ILGenerator::DeclareLocal, then get local signaturefrom there. return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } else { // this is the case when client provide an array of IL byte stream rather than going through ILGenerator. return m_maxStack; } } internal ExceptionHandler[] GetExceptionHandlers() { return m_exceptions; } internal int ExceptionHandlerCount { get { return m_exceptions != null ? m_exceptions.Length : 0; } } internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) { return 0; } for (int i = 0; i < excp.Length; i++) { num += excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { return (m_containingType != null && m_containingType.IsCreated()); } internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } #endregion #region Object Overrides public override bool Equals(Object obj) { if (!(obj is MethodBuilder)) { return false; } if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) { return false; } if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes)) { return false; } SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature(); if (thatSig.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return this.m_strName.GetHashCode(); } public override String ToString() { StringBuilder sb = new StringBuilder(1000); sb.Append("Name: " + m_strName + " " + Environment.NewLine); sb.Append("Attributes: " + (int)m_iAttributes + Environment.NewLine); sb.Append("Method Signature: " + GetMethodSignature() + Environment.NewLine); sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #region MemberInfo Overrides public override String Name { get { return m_strName; } } internal int MetadataTokenInternal { get { return GetToken().Token; } } public override Module Module { get { return m_containingType.Module; } } public override Type DeclaringType { get { if (m_containingType.m_isHiddenGlobalType == true) return null; return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return null; } } public override Type ReflectedType { get { return DeclaringType; } } #endregion #region MethodBase Overrides public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodAttributes Attributes { get { return m_iAttributes; } } public override CallingConventions CallingConvention { get { return m_callingConvention; } } public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override bool IsSecurityCritical { get { return true; } } public override bool IsSecuritySafeCritical { get { return false; } } public override bool IsSecurityTransparent { get { return false; } } #endregion #region MethodInfo Overrides public override MethodInfo GetBaseDefinition() { return this; } public override Type ReturnType { get { return m_returnType; } } public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.GetParameters(); } public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated); MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes); return rmi.ReturnParameter; } } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } #endregion #region Generic Members public override bool IsGenericMethodDefinition { get { return m_bIsGenMethDef; } } public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; } public override bool IsGenericMethod { get { return m_inst != null; } } public override Type[] GetGenericArguments() { return m_inst; } public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { if (names == null) throw new ArgumentNullException(nameof(names)); if (names.Length == 0) throw new ArgumentException(SR.Arg_EmptyArray, nameof(names)); if (m_inst != null) throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); for (int i = 0; i < names.Length; i++) if (names[i] == null) throw new ArgumentNullException(nameof(names)); if (m_tkMethod.Token != 0) throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked); m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int i = 0; i < names.Length; i++) m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this)); return m_inst; } internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); } #endregion #region Public Members public MethodToken GetToken() { // We used to always "tokenize" a MethodBuilder when it is constructed. After change list 709498 // we only "tokenize" a method when requested. But the order in which the methods are tokenized // didn't change: the same order the MethodBuilders are constructed. The recursion introduced // will overflow the stack when there are many methods on the same type (10000 in my experiment). // The change also introduced race conditions. Before the code change GetToken is called from // the MethodBuilder .ctor which is protected by lock(ModuleBuilder.SyncRoot). Now it // could be called more than once on the the same method introducing duplicate (invalid) tokens. // I don't fully understand this change. So I will keep the logic and only fix the recursion and // the race condition. if (m_tkMethod.Token != 0) { return m_tkMethod; } MethodBuilder currentMethod = null; MethodToken currentToken = new MethodToken(0); int i; // We need to lock here to prevent a method from being "tokenized" twice. // We don't need to synchronize this with Type.DefineMethod because it only appends newly // constructed MethodBuilders to the end of m_listMethods lock (m_containingType.m_listMethods) { if (m_tkMethod.Token != 0) { return m_tkMethod; } // If m_tkMethod is still 0 when we obtain the lock, m_lastTokenizedMethod must be smaller // than the index of the current method. for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; ++i) { currentMethod = m_containingType.m_listMethods[i]; currentToken = currentMethod.GetTokenNoLock(); if (currentMethod == this) break; } m_containingType.m_lastTokenizedMethod = i; } Debug.Assert(currentMethod == this, "We should have found this method in m_containingType.m_listMethods"); Debug.Assert(currentToken.Token != 0, "The token should not be 0"); return currentToken; } private MethodToken GetTokenNoLock() { Debug.Assert(m_tkMethod.Token == 0, "m_tkMethod should not have been initialized"); int sigLength; byte[] sigBytes = GetMethodSignature().InternalGetSignature(out sigLength); int token = TypeBuilder.DefineMethod(m_module.GetNativeHandle(), m_containingType.MetadataTokenInternal, m_strName, sigBytes, sigLength, Attributes); m_tkMethod = new MethodToken(token); if (m_inst != null) foreach (GenericTypeParameterBuilder tb in m_inst) if (!tb.m_type.IsCreated()) tb.m_type.CreateType(); TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), token, m_dwMethodImplFlags); return m_tkMethod; } public void SetParameters(params Type[] parameterTypes) { CheckContext(parameterTypes); SetSignature(null, null, null, parameterTypes, null, null); } public void SetReturnType(Type returnType) { CheckContext(returnType); SetSignature(returnType, null, null, null, null, null); } public void SetSignature( Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { // We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked. // But we cannot because that would be a breaking change from V2. if (m_tkMethod.Token != 0) return; CheckContext(returnType); CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); CheckContext(parameterTypeRequiredCustomModifiers); CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName) { if (position < 0) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); ThrowIfGeneric(); m_containingType.ThrowIfCreated(); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); attributes = attributes & ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } private List<SymCustomAttr> m_symCustomAttrs; private struct SymCustomAttr { public String m_name; public byte[] m_data; } public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric(); m_containingType.ThrowIfCreated(); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes); } public ILGenerator GetILGenerator() { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this); return m_ilGenerator; } public ILGenerator GetILGenerator(int size) { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); if (m_ilGenerator == null) m_ilGenerator = new ILGenerator(this, size); return m_ilGenerator; } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL || (m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { // cannot attach method body if methodimpl is marked not marked as managed IL // throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody); } } public bool InitLocals { // Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false. get { ThrowIfGeneric(); return m_fInitLocals; } set { ThrowIfGeneric(); m_fInitLocals = value; } } public Module GetModule() { return GetModuleBuilder(); } public String Signature { get { return GetMethodSignature().ToString(); } } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) throw new ArgumentNullException(nameof(con)); if (binaryAttribute == null) throw new ArgumentNullException(nameof(binaryAttribute)); ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataTokenInternal, ((ModuleBuilder)m_module).GetConstructorToken(con).Token, binaryAttribute, false, false); if (IsKnownCA(con)) ParseCA(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) throw new ArgumentNullException(nameof(customBuilder)); ThrowIfGeneric(); customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal); if (IsKnownCA(customBuilder.m_con)) ParseCA(customBuilder.m_con, customBuilder.m_blob); } // this method should return true for any and every ca that requires more work // than just setting the ca private bool IsKnownCA(ConstructorInfo con) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) return true; else if (caType == typeof(DllImportAttribute)) return true; else return false; } private void ParseCA(ConstructorInfo con, byte[] blob) { Type caType = con.DeclaringType; if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute)) { // dig through the blob looking for the MethodImplAttributes flag // that must be in the MethodCodeType field // for now we simply set a flag that relaxes the check when saving and // allows this method to have no body when any kind of MethodImplAttribute is present m_canBeRuntimeImpl = true; } else if (caType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } internal bool m_canBeRuntimeImpl = false; internal bool m_isDllImport = false; #endregion } internal class LocalSymInfo { // This class tracks the local variable's debugging information // and namespace information with a given active lexical scope. #region Internal Data Members internal String[] m_strName; internal byte[][] m_ubSignature; internal int[] m_iLocalSlot; internal int[] m_iStartOffset; internal int[] m_iEndOffset; internal int m_iLocalSymCount; // how many entries in the arrays are occupied internal String[] m_namespace; internal int m_iNameSpaceCount; internal const int InitialSize = 16; #endregion #region Constructor internal LocalSymInfo() { // initialize data variables m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } #endregion #region Private Members private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new String[InitialSize]; } else if (m_iNameSpaceCount == m_namespace.Length) { String[] strTemp = new String[checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, 0, strTemp, 0, m_iNameSpaceCount); m_namespace = strTemp; } } private void EnsureCapacity() { if (m_iLocalSymCount == 0) { // First time. Allocate the arrays. m_strName = new String[InitialSize]; m_ubSignature = new byte[InitialSize][]; m_iLocalSlot = new int[InitialSize]; m_iStartOffset = new int[InitialSize]; m_iEndOffset = new int[InitialSize]; } else if (m_iLocalSymCount == m_strName.Length) { // the arrays are full. Enlarge the arrays // why aren't we just using lists here? int newSize = checked(m_iLocalSymCount * 2); int[] temp = new int[newSize]; Array.Copy(m_iLocalSlot, 0, temp, 0, m_iLocalSymCount); m_iLocalSlot = temp; temp = new int[newSize]; Array.Copy(m_iStartOffset, 0, temp, 0, m_iLocalSymCount); m_iStartOffset = temp; temp = new int[newSize]; Array.Copy(m_iEndOffset, 0, temp, 0, m_iLocalSymCount); m_iEndOffset = temp; String[] strTemp = new String[newSize]; Array.Copy(m_strName, 0, strTemp, 0, m_iLocalSymCount); m_strName = strTemp; byte[][] ubTemp = new byte[newSize][]; Array.Copy(m_ubSignature, 0, ubTemp, 0, m_iLocalSymCount); m_ubSignature = ubTemp; } } #endregion #region Internal Members internal void AddLocalSymInfo(String strName, byte[] signature, int slot, int startOffset, int endOffset) { // make sure that arrays are large enough to hold addition info EnsureCapacity(); m_iStartOffset[m_iLocalSymCount] = startOffset; m_iEndOffset[m_iLocalSymCount] = endOffset; m_iLocalSlot[m_iLocalSymCount] = slot; m_strName[m_iLocalSymCount] = strName; m_ubSignature[m_iLocalSymCount] = signature; checked { m_iLocalSymCount++; } } internal void AddUsingNamespace(String strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter) { int i; for (i = 0; i < m_iLocalSymCount; i++) { symWriter.DefineLocalVariable( m_strName[i], FieldAttributes.PrivateScope, m_ubSignature[i], SymAddressKind.ILOffset, m_iLocalSlot[i], 0, // addr2 is not used yet 0, // addr3 is not used m_iStartOffset[i], m_iEndOffset[i]); } for (i = 0; i < m_iNameSpaceCount; i++) { symWriter.UsingNamespace(m_namespace[i]); } } #endregion } /// <summary> /// Describes exception handler in a method body. /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct ExceptionHandler : IEquatable<ExceptionHandler> { // Keep in sync with unmanged structure. internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; #region Constructors internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { Debug.Assert(tryStartOffset >= 0); Debug.Assert(tryEndOffset >= 0); Debug.Assert(filterOffset >= 0); Debug.Assert(handlerStartOffset >= 0); Debug.Assert(handlerEndOffset >= 0); Debug.Assert(IsValidKind((ExceptionHandlingClauseOptions)kind)); Debug.Assert(kind != (int)ExceptionHandlingClauseOptions.Clause || (exceptionTypeToken & 0x00FFFFFF) != 0); m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } private static bool IsValidKind(ExceptionHandlingClauseOptions kind) { switch (kind) { case ExceptionHandlingClauseOptions.Clause: case ExceptionHandlingClauseOptions.Filter: case ExceptionHandlingClauseOptions.Finally: case ExceptionHandlingClauseOptions.Fault: return true; default: return false; } } #endregion #region Equality public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(Object obj) { return obj is ExceptionHandler && Equals((ExceptionHandler)obj); } public bool Equals(ExceptionHandler other) { return other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset && other.m_kind == m_kind; } public static bool operator ==(ExceptionHandler left, ExceptionHandler right) { return left.Equals(right); } public static bool operator !=(ExceptionHandler left, ExceptionHandler right) { return !left.Equals(right); } #endregion } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation #endregion namespace FluentValidation.Tests { using System; using System.Linq; using Xunit; public class EnumValidatorTests { TestValidator validator; public EnumValidatorTests() { CultureScope.SetDefaultCulture(); validator = new TestValidator { v => v.RuleFor(x => x.Gender).IsInEnum() }; } [Fact] public void IsValidTests() { validator.Validate(new Person { Gender = EnumGender.Female }).IsValid.ShouldBeTrue(); // Simplest valid value validator.Validate(new Person { Gender = EnumGender.Male }).IsValid.ShouldBeTrue(); // Other valid value validator.Validate(new Person { Gender = (EnumGender)1 }).IsValid.ShouldBeTrue(); // Casting with valid value } [Fact] public void When_the_enum_is_not_initialized_with_valid_value_then_the_validator_should_fail() { var result = validator.Validate(new Person()); // Default value 0 is not defined in Enum result.IsValid.ShouldBeFalse(); } [Fact] public void When_the_enum_is_initialized_with_invalid_value_then_the_validator_should_fail() { var result = validator.Validate(new Person { Gender = (EnumGender)3 }); // 3 in not defined in Enum result.IsValid.ShouldBeFalse(); } [Fact] public void When_validation_fails_the_default_error_should_be_set() { var result = validator.Validate(new Person()); result.Errors.Single().ErrorMessage.ShouldEqual("'Gender' has a range of values which does not include '0'."); } [Fact] public void Nullable_enum_valid_when_property_value_is_null() { var validator = new InlineValidator<Foo>(); validator.RuleFor(x => x.Gender).IsInEnum(); var result = validator.Validate(new Foo()); result.IsValid.ShouldBeTrue(); } [Fact] public void Nullable_enum_valid_when_value_specified() { var validator = new InlineValidator<Foo>(); validator.RuleFor(x => x.Gender).IsInEnum(); var result = validator.Validate(new Foo() { Gender = EnumGender.Male }); result.IsValid.ShouldBeTrue(); } [Fact] public void Nullable_enum_invalid_when_bad_value_specified() { var validator = new InlineValidator<Foo>(); validator.RuleFor(x => x.Gender).IsInEnum(); var result = validator.Validate(new Foo() { Gender = (EnumGender)42 }); result.IsValid.ShouldBeFalse(); } [Fact] public void Flags_enum_valid_when_using_bitwise_value() { var inlineValidator = new InlineValidator<FlagsEnumPoco>(); inlineValidator.RuleFor(x => x.SByteValue).IsInEnum(); inlineValidator.RuleFor(x => x.ByteValue).IsInEnum(); inlineValidator.RuleFor(x => x.Int16Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt16Value).IsInEnum(); inlineValidator.RuleFor(x => x.Int32Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt32Value).IsInEnum(); inlineValidator.RuleFor(x => x.Int64Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt64Value).IsInEnum(); var poco = new FlagsEnumPoco(); poco.PopulateWithValidValues(); var result = inlineValidator.Validate(poco); result.IsValid.ShouldBeTrue(); } [Fact] public void Flags_enum_invalid_when_using_outofrange_positive_value() { var inlineValidator = new InlineValidator<FlagsEnumPoco>(); inlineValidator.RuleFor(x => x.SByteValue).IsInEnum(); inlineValidator.RuleFor(x => x.ByteValue).IsInEnum(); inlineValidator.RuleFor(x => x.Int16Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt16Value).IsInEnum(); inlineValidator.RuleFor(x => x.Int32Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt32Value).IsInEnum(); inlineValidator.RuleFor(x => x.Int64Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt64Value).IsInEnum(); var poco = new FlagsEnumPoco(); poco.PopulateWithInvalidPositiveValues(); var result = inlineValidator.Validate(poco); result.IsValid.ShouldBeFalse(); result.Errors.SingleOrDefault(x => x.PropertyName == "ByteValue").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "SByteValue").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "Int16Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "UInt16Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "Int32Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "UInt32Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "Int64Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "UInt64Value").ShouldNotBeNull(); } [Fact] public void Flags_enum_invalid_when_using_outofrange_negative_value() { var inlineValidator = new InlineValidator<FlagsEnumPoco>(); inlineValidator.RuleFor(x => x.SByteValue).IsInEnum(); inlineValidator.RuleFor(x => x.ByteValue).IsInEnum(); inlineValidator.RuleFor(x => x.Int16Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt16Value).IsInEnum(); inlineValidator.RuleFor(x => x.Int32Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt32Value).IsInEnum(); inlineValidator.RuleFor(x => x.Int64Value).IsInEnum(); inlineValidator.RuleFor(x => x.UInt64Value).IsInEnum(); var poco = new FlagsEnumPoco(); poco.PopulateWithInvalidNegativeValues(); var result = inlineValidator.Validate(poco); result.IsValid.ShouldBeFalse(); result.Errors.SingleOrDefault(x => x.PropertyName == "SByteValue").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "Int16Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "Int32Value").ShouldNotBeNull(); result.Errors.SingleOrDefault(x => x.PropertyName == "Int64Value").ShouldNotBeNull(); } private class Foo { public EnumGender? Gender { get; set; } } #region Flag enum helpers private class FlagsEnumPoco { public SByteEnum SByteValue { get; set; } public ByteEnum ByteValue { get; set; } public Int16Enum Int16Value { get; set; } public UInt16Enum UInt16Value { get; set; } public Int32Enum Int32Value { get; set; } public UInt32Enum UInt32Value { get; set; } public Int64Enum Int64Value { get; set; } public UInt64Enum UInt64Value { get; set; } public void PopulateWithValidValues() { SByteValue = SByteEnum.B | SByteEnum.C; ByteValue = ByteEnum.B | ByteEnum.C; Int16Value = Int16Enum.B | Int16Enum.C; UInt16Value = UInt16Enum.B | UInt16Enum.C; Int32Value = Int32Enum.B | Int32Enum.C; UInt32Value = UInt32Enum.B | UInt32Enum.C; Int64Value = Int64Enum.B | Int64Enum.C; UInt64Value = UInt64Enum.B | UInt64Enum.C; } public void PopulateWithInvalidPositiveValues() { SByteValue = (SByteEnum)123; ByteValue = (ByteEnum)123; Int16Value = (Int16Enum)123; UInt16Value = (UInt16Enum)123; Int32Value = (Int32Enum)123; UInt32Value = (UInt32Enum)123; Int64Value = (Int64Enum)123; UInt64Value = (UInt64Enum)123; } public void PopulateWithInvalidNegativeValues() { SByteValue = (SByteEnum)(-123); Int16Value = (Int16Enum)(-123); Int32Value = (Int32Enum)(-123); Int64Value = (Int64Enum)(-123); } } [Flags] private enum SByteEnum : sbyte { A = 0, B = 1, C = 2 } [Flags] private enum ByteEnum : byte { A = 0, B = 1, C = 2 } [Flags] private enum Int16Enum : short { A = 0, B = 1, C = 2 } [Flags] private enum UInt16Enum : ushort { A = 0, B = 1, C = 2 } [Flags] private enum Int32Enum : int { A = 0, B = 1, C = 2 } [Flags] private enum UInt32Enum : uint { A = 0, B = 1, C = 2 } [Flags] private enum Int64Enum : long { A = 0, B = 1, C = 2 } [Flags] private enum UInt64Enum : ulong { A = 0, B = 1, C = 2 } #endregion } }
// // Copyright (C) DataStax 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.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Cassandra.Mapping; using Cassandra.Mapping.Statements; namespace Cassandra.Data.Linq { /// <summary> /// A Linq IQueryProvider that represents a table in Cassandra /// </summary> /// <typeparam name="TEntity"></typeparam> public class Table<TEntity> : CqlQuery<TEntity>, ITable { private readonly ISession _session; private readonly string _name; private readonly string _keyspaceName; /// <summary> /// Gets the name of the Table in Cassandra /// </summary> public string Name { get { return _name ?? PocoData.TableName; } } /// <summary> /// Gets the name of the keyspace used. If null, it uses the active session keyspace. /// </summary> public string KeyspaceName { get { return _keyspaceName ?? PocoData.KeyspaceName; } } /// <summary> /// <para>Creates a new instance of the Linq IQueryProvider that represents a table in Cassandra using the mapping configuration provided.</para> /// <para>Use this constructor if you want to use a different table and keyspace names than the ones defined in the mapping configuration.</para> /// <para>Fluent configuration or attributes can be used to define mapping information.</para> /// </summary> /// <remarks> /// In case no mapping information is defined, case-insensitive class and method names will be used. /// </remarks> /// <param name="session">Session instance to be used to execute the statements</param> /// <param name="config">Mapping configuration</param> /// <param name="tableName">Name of the table</param> /// <param name="keyspaceName">Name of the keyspace were the table was created.</param> public Table(ISession session, MappingConfiguration config, string tableName, string keyspaceName) { _session = session; _name = tableName; _keyspaceName = keyspaceName; //In case no mapping has been defined for the type, determine if the attributes used are Linq or Cassandra.Mapping //Linq attributes are marked as Obsolete #pragma warning disable 612 config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(TEntity), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(TEntity))); #pragma warning restore 612 var pocoData = config.MapperFactory.GetPocoData<TEntity>(); InternalInitialize(Expression.Constant(this), this, config.MapperFactory, config.StatementFactory, pocoData); } /// <summary> /// <para>Creates a new instance of the Linq IQueryProvider that represents a table in Cassandra using the mapping configuration provided.</para> /// <para>Use this constructor if you want to use a different table name than the one defined in the mapping configuration.</para> /// <para>Fluent configuration or attributes can be used to define mapping information.</para> /// </summary> /// <remarks> /// In case no mapping information is defined, case-insensitive class and method names will be used. /// </remarks> /// <param name="session">Session instance to be used to execute the statements</param> /// <param name="config">Mapping configuration</param> /// <param name="tableName">Name of the table</param> public Table(ISession session, MappingConfiguration config, string tableName) : this(session, config, tableName, null) { } /// <summary> /// <para>Creates a new instance of the Linq IQueryProvider that represents a table in Cassandra using the mapping configuration provided.</para> /// <para>Fluent configuration or attributes can be used to define mapping information.</para> /// </summary> /// <remarks> /// In case no mapping information is defined, case-insensitive class and method names will be used. /// </remarks> /// <param name="session">Session instance to be used to execute the statements</param> /// <param name="config">Mapping configuration</param> public Table(ISession session, MappingConfiguration config) : this(session, config, null, null) { } /// <summary> /// Creates a new instance of the Linq IQueryProvider that represents a table in Cassandra using <see cref="MappingConfiguration.Global"/> configuration. /// </summary> /// <param name="session">Session instance to be used to execute the statements</param> public Table(ISession session) : this(session, MappingConfiguration.Global) { _session = session; } /// <summary> /// Creates a <see cref="CqlQuery&lt;T&gt;"/> /// </summary> public IQueryable<TElement> CreateQuery<TElement>(Expression expression) { return new CqlQuery<TElement>(expression, this, MapperFactory, StatementFactory, PocoData); } IQueryable IQueryProvider.CreateQuery(Expression expression) { //Implementation of IQueryProvider throw new NotImplementedException(); } TResult IQueryProvider.Execute<TResult>(Expression expression) { //Implementation of IQueryProvider throw new NotImplementedException(); } object IQueryProvider.Execute(Expression expression) { //Implementation of IQueryProvider throw new NotImplementedException(); } public Type GetEntityType() { return typeof (TEntity); } public void Create() { var serializer = _session.Cluster.Metadata.ControlConnection.Serializer.GetCurrentSerializer(); var cqlQueries = CqlGenerator.GetCreate(serializer, PocoData, Name, KeyspaceName, false); foreach (var cql in cqlQueries) { _session.Execute(cql); } } public void CreateIfNotExists() { try { Create(); } catch (AlreadyExistsException) { //do nothing } } public async Task CreateAsync() { var serializer = _session.Cluster.Metadata.ControlConnection.Serializer.GetCurrentSerializer(); var cqlQueries = CqlGenerator.GetCreate(serializer, PocoData, Name, KeyspaceName, false); foreach (var cql in cqlQueries) { await _session.ExecuteAsync(new SimpleStatement(cql)).ConfigureAwait(false); } } public async Task CreateIfNotExistsAsync() { try { await CreateAsync().ConfigureAwait(false); } catch (AlreadyExistsException) { //do nothing } } public ISession GetSession() { return _session; } public TableType GetTableType() { return PocoData.Columns.Any(c => c.IsCounter) ? TableType.Counter : TableType.Standard; } /// <summary> /// Returns a new <see cref="CqlInsert{TEntity}"/> command. Use /// <see cref="CqlCommand.Execute()"/> method to execute the query. /// </summary> public CqlInsert<TEntity> Insert(TEntity entity) { return Insert(entity, true); } /// <summary> /// Returns a new <see cref="CqlInsert{TEntity}"/> command. Use /// <see cref="CqlCommand.Execute()"/> method to execute the query. /// </summary> /// <param name="entity">The entity to insert</param> /// <param name="insertNulls"> /// Determines if the query must be generated using <c>NULL</c> values for <c>null</c> /// entity members. /// <para> /// Use <c>false</c> if you don't want to consider <c>null</c> values for the INSERT /// operation (recommended). /// </para> /// <para> /// Use <c>true</c> if you want to override all the values in the table, /// generating tombstones for null values. /// </para> /// </param> public CqlInsert<TEntity> Insert(TEntity entity, bool insertNulls) { return new CqlInsert<TEntity>(entity, insertNulls, this, StatementFactory, MapperFactory); } } }
// 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.16.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; /// <summary> /// Extension methods for NetworkSecurityGroupsOperations. /// </summary> public static partial class NetworkSecurityGroupsOperationsExtensions { /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> public static void Delete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName) { Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).DeleteAsync(resourceGroupName, networkSecurityGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> public static void BeginDelete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName) { Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).BeginDeleteAsync(resourceGroupName, networkSecurityGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Delete NetworkSecurityGroup operation deletes the specifed network /// security 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// The Get NetworkSecurityGroups operation retrieves information about the /// specified network security 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// expand references resources. /// </param> public static NetworkSecurityGroup Get(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string)) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).GetAsync(resourceGroupName, networkSecurityGroupName, expand), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get NetworkSecurityGroups operation retrieves information about the /// specified network security 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='expand'> /// expand references resources. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> GetAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, expand, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> public static NetworkSecurityGroup CreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> CreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> public static NetworkSecurityGroup BeginCreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Put NetworkSecurityGroup operation creates/updates a network security /// groupin the specified 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='networkSecurityGroupName'> /// The name of the network security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update Network Security Group operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NetworkSecurityGroup> BeginCreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The list NetworkSecurityGroups returns all network security groups in a /// subscription /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NetworkSecurityGroup> ListAll(this INetworkSecurityGroupsOperations operations) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup>> ListAllAsync(this INetworkSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup> List(this INetworkSecurityGroupsOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup>> ListAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup> ListAllNext(this INetworkSecurityGroupsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup>> ListAllNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup> ListNext(this INetworkSecurityGroupsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((INetworkSecurityGroupsOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The list NetworkSecurityGroups returns all network security groups 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<NetworkSecurityGroup>> ListNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.MessageTemplates { using System; using NLog.MessageTemplates; using Xunit; using Xunit.Extensions; public class ParserTests { [Theory] [InlineData("")] [InlineData("Hello {0}")] [InlineData("I like my {car}")] [InlineData("But when Im drunk I need a {cool} bike")] [InlineData("I have {0} {1} {2} parameters")] [InlineData("{0} on front")] [InlineData(" {0} on front")] [InlineData("end {1}")] [InlineData("end {1} ")] [InlineData("{name} is my name")] [InlineData(" {name} is my name")] [InlineData("{multiple}{parameters}")] [InlineData("I have {{text}} and {{0}}")] [InlineData("{{text}}{{0}}")] [InlineData(" {{text}}{{0}} ")] [InlineData(" {0} ")] [InlineData(" {1} ")] [InlineData(" {2} ")] [InlineData(" {3} {4} {9} {8} {5} {6} {7}")] [InlineData(" {{ ")] [InlineData("{{ ")] [InlineData(" {{")] [InlineData(" }} ")] [InlineData("}} ")] [InlineData(" }}")] [InlineData("{0:000}")] [InlineData("{aaa:000}")] [InlineData(" {@serialize} ")] [InlineData(" {$stringify} ")] [InlineData(" {alignment,-10} ")] [InlineData(" {alignment,10} ")] [InlineData(" {0,10} ")] [InlineData(" {0,-10} ")] [InlineData(" {0,-10:test} ")] [InlineData("{{{0:d}}}")] [InlineData("{{{0:0{{}")] public void ParseAndPrint(string input) { var template = TemplateParser.Parse(input); Assert.Equal(input, template.Rebuild()); } [Theory] [InlineData("{0}", 0, null)] [InlineData("{001}", 1, null)] [InlineData("{9}", 9, null)] [InlineData("{1 }", 1, null)] [InlineData("{1} {2}", 1, null)] [InlineData("{@3} {$4}", 3, null)] [InlineData("{3,6}", 3, null)] [InlineData("{5:R}", 5, "R")] [InlineData("{0:0}", 0, "0")] public void ParsePositional(string input, int index, string format) { var template = TemplateParser.Parse(input); Assert.True(template.IsPositional); Assert.Equal(format, template.Holes[0].Format); Assert.Equal(index, template.Holes[0].Index); } [Theory] [InlineData("{ 0}")] [InlineData("{-1}")] [InlineData("{1.2}")] [InlineData("{42r}")] [InlineData("{6} {x}")] [InlineData("{a} {x}")] public void ParseNominal(string input) { var template = TemplateParser.Parse(input); Assert.False(template.IsPositional); } [Theory] [InlineData("{hello}", "hello")] [InlineData("{@hello}", "hello")] [InlineData("{$hello}", "hello")] [InlineData("{#hello}", "#hello")] [InlineData("{ spaces ,-3}", " spaces ")] [InlineData("{special!:G})", "special!")] [InlineData("{noescape_in_name}}}", "noescape_in_name")] [InlineData("{noescape_in_name{{}", "noescape_in_name{{")] [InlineData("{0}", "0")] [InlineData("{18 }", "18 ")] public void ParseName(string input, string name) { var template = TemplateParser.Parse(input); Assert.Equal(name, template.Holes[0].Name); } [Theory] [InlineData("{aaa}", "")] [InlineData("{@a}", "@")] [InlineData("{@A}", "@")] [InlineData("{@8}", "@")] [InlineData("{@aaa}", "@")] [InlineData("{$a}", "$")] [InlineData("{$A}", "$")] [InlineData("{$9}", "$")] [InlineData("{$aaa}", "$")] public void ParseHoleType(string input, string holeType) { var template = TemplateParser.Parse(input); Assert.Single(template.Holes); CaptureType captureType = CaptureType.Normal; if (holeType == "@") captureType = CaptureType.Serialize; else if (holeType == "$") captureType = CaptureType.Stringify; Assert.Equal(captureType, template.Holes[0].CaptureType); } [Theory] [InlineData(" {0,-10:nl-nl} ", -10, "nl-nl")] [InlineData(" {0,-10} ", -10, null)] [InlineData("{0, 36 }", 36, null)] [InlineData("{0,-36 :x}", -36, "x")] [InlineData(" {0:nl-nl} ", 0, "nl-nl")] [InlineData(" {0} ", 0, null)] public void ParseFormatAndAlignment_numeric(string input, int aligment, string format) { var templates = TemplateParser.Parse(input); var hole = templates.Holes[0]; Assert.Equal("0", hole.Name); Assert.Equal(0, hole.Index); Assert.Equal(aligment, hole.Alignment); Assert.Equal(format, hole.Format); } [Theory] [InlineData(" {car,-10:nl-nl} ", -10, "nl-nl")] [InlineData(" {car,-10} ", -10, null)] [InlineData(" {car:nl-nl} ", 0, "nl-nl")] [InlineData(" {car} ", 0, null)] public void ParseFormatAndAlignment_text(string input, int aligment, string format) { var template = TemplateParser.Parse(input); var hole = template.Holes[0]; Assert.False(template.IsPositional); Assert.Equal("car", hole.Name); Assert.Equal(aligment, hole.Alignment); Assert.Equal(format, hole.Format); } [Theory] [InlineData("Hello {0")] [InlineData("Hello 0}")] [InlineData("Hello {a:")] [InlineData("Hello {a")] [InlineData("Hello {a,")] [InlineData("Hello {a,1")] [InlineData("{")] [InlineData("}")] [InlineData("}}}")] [InlineData("}}}{")] [InlineData("{}}{")] [InlineData("{a,-3.5}")] [InlineData("{a,2x}")] [InlineData("{a,--2}")] [InlineData("{a,-2")] [InlineData("{a,-2 :N0")] [InlineData("{a,-2.0")] [InlineData("{a,:N0}")] [InlineData("{a,}")] [InlineData("{a,{}")] [InlineData("{a:{}")] [InlineData("{a,d{e}")] [InlineData("{a:d{e}")] public void ThrowsTemplateParserException(string input) { Assert.Throws<TemplateParserException>(() => TemplateParser.Parse(input)); } [Theory] [InlineData(null)] public void ThrowsArgumentNullException(string input) { Assert.Throws<ArgumentNullException>(() => TemplateParser.Parse(input)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; namespace System.Globalization { /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/02/18 2051/02/10 ** TaiwanLunisolar 1912/01/01 2050/13/29 */ public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. internal static EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1912; internal const int MAX_LUNISOLAR_YEAR = 2050; internal const int MIN_GREGORIAN_YEAR = 1912; internal const int MIN_GREGORIAN_MONTH = 2; internal const int MIN_GREGORIAN_DAY = 18; internal const int MAX_GREGORIAN_YEAR = 2051; internal const int MAX_GREGORIAN_MONTH = 2; internal const int MAX_GREGORIAN_DAY = 10; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1911 from ChineseLunisolarCalendar return 384; } } private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1912 */ { 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 */}; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (taiwanLunisolarEraInfo); } } internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MIN_LUNISOLAR_YEAR) || (lunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } Contract.EndContractBlock(); return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.TAIWAN); } } internal override CalendarId ID { get { return (CalendarId.TAIWANLUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System.Collections.Generic; using System.Runtime; abstract class JumpOpcode : Opcode { Opcode jump; internal JumpOpcode(OpcodeID id, Opcode jump) : base(id) { this.Jump = jump; this.flags |= OpcodeFlags.Jump; } internal Opcode Jump { get { return this.jump; } set { Fx.Assert(value.ID == OpcodeID.BlockEnd, ""); this.AddJump((BlockEndOpcode)value); } } internal void AddJump(BlockEndOpcode jumpTo) { bool conditional = this.IsReachableFromConditional(); if (conditional) { this.prev.DelinkFromConditional(this); } if (null == this.jump) { this.jump = jumpTo; } else { BranchOpcode jumpBranch; if (this.jump.ID == OpcodeID.Branch) { // already a branch jumpBranch = (BranchOpcode)this.jump; } else { BlockEndOpcode currentJump = (BlockEndOpcode)this.jump; jumpBranch = new BranchOpcode(); jumpBranch.Branches.Add(currentJump); this.jump = jumpBranch; } jumpBranch.Branches.Add(jumpTo); } jumpTo.LinkJump(this); if (conditional && null != this.jump) { this.prev.LinkToConditional(this); } } internal override void Remove() { if (null == this.jump) { base.Remove(); } } internal void RemoveJump(BlockEndOpcode jumpTo) { Fx.Assert(null != this.jump, ""); bool conditional = this.IsReachableFromConditional(); if (conditional) { this.prev.DelinkFromConditional(this); } if (this.jump.ID == OpcodeID.Branch) { BranchOpcode jumpBranch = (BranchOpcode)this.jump; jumpTo.DeLinkJump(this); jumpBranch.RemoveChild(jumpTo); if (0 == jumpBranch.Branches.Count) { this.jump = null; } } else { Fx.Assert(object.ReferenceEquals(jumpTo, this.jump), ""); jumpTo.DeLinkJump(this); this.jump = null; } if (conditional && null != this.jump) { this.prev.LinkToConditional(this); } } internal override void Trim() { if (this.jump.ID == OpcodeID.Branch) { this.jump.Trim(); } } } class JumpIfOpcode : JumpOpcode { protected bool test; internal JumpIfOpcode(Opcode jump, bool test) : this(OpcodeID.JumpIfNot, jump, test) { } protected JumpIfOpcode(OpcodeID id, Opcode jump, bool test) : base(id, jump) { this.test = test; } internal bool Test { get { return this.test; } } internal override bool Equals(Opcode op) { if (base.Equals(op)) { return (this.test == ((JumpIfOpcode)op).test); } return false; } internal override Opcode Eval(ProcessingContext context) { Fx.Assert(null != context, ""); StackFrame arg = context.TopArg; for (int i = arg.basePtr; i <= arg.endPtr; ++i) { Fx.Assert(context.Values[i].IsType(ValueDataType.Boolean), ""); if (this.test == context.Values[i].Boolean) { // At least one result satisfies the test. Don't branch return this.next; } } // Jump, since no result is satisfactory.. return this.Jump; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} {1}", base.ToString(), this.test); } #endif } class ApplyBooleanOpcode : JumpIfOpcode { internal ApplyBooleanOpcode(Opcode jump, bool test) : this(OpcodeID.ApplyBoolean, jump, test) { } protected ApplyBooleanOpcode(OpcodeID id, Opcode jump, bool test) : base(id, jump, test) { } internal override Opcode Eval(ProcessingContext context) { int matchCount = this.UpdateResultMask(context); context.PopFrame(); if (0 == matchCount) { return this.Jump; } return this.next; } protected int UpdateResultMask(ProcessingContext context) { StackFrame results = context.TopArg; StackFrame resultMask = context.SecondArg; Value[] values = context.Values; int testCount = 0; for (int maskIndex = resultMask.basePtr, resultIndex = results.basePtr; maskIndex <= resultMask.endPtr; ++maskIndex) { if (this.test == values[maskIndex].Boolean) { bool boolResult = values[resultIndex].Boolean; if (this.test == boolResult) { testCount++; } values[maskIndex].Boolean = boolResult; ++resultIndex; } } return testCount; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} {1}", base.ToString(), this.test); } #endif } // 'And' booleans: test is true // 'Or' booleans: test is false class StartBooleanOpcode : Opcode { bool test; internal StartBooleanOpcode(bool test) : base(OpcodeID.StartBoolean) { this.test = test; } internal override bool Equals(Opcode op) { if (base.Equals(op)) { return (((StartBooleanOpcode)op).test == this.test); } return false; } internal override Opcode Eval(ProcessingContext context) { StackFrame sequences = context.TopSequenceArg; Value[] values = context.Values; StackFrame resultMask = context.TopArg; Value[] sequenceBuffer = context.Sequences; context.PushSequenceFrame(); for (int seqIndex = sequences.basePtr; seqIndex <= sequences.endPtr; ++seqIndex) { NodeSequence sourceSeq = sequenceBuffer[seqIndex].Sequence; if (sourceSeq.Count > 0) { NodeSequenceItem[] items = sourceSeq.Items; NodeSequence newSeq = null; // Loop over the sequence, selecting those items for which the previous expression returned a result that // matches the test value. Only those items will be processed further // Note that the original position and size information is retained. for (int i = resultMask.basePtr, n = 0; i <= resultMask.endPtr; ++i, ++n) { if (this.test == values[i].Boolean) { if (null == newSeq) { newSeq = context.CreateSequence(); } newSeq.AddCopy(ref items[n], NodeSequence.GetContextSize(sourceSeq, n)); } else { if (items[n].Last && null != newSeq) { newSeq.Items[newSeq.Count - 1].Last = true; // maintain nodeset boundaries... } } } context.PushSequence((null == newSeq) ? NodeSequence.Empty : newSeq); newSeq = null; } } return this.next; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} {1}", base.ToString(), this.test); } #endif } // 'And' booleans: test is true // 'Or' booleans: test is false class EndBooleanOpcode : ApplyBooleanOpcode { internal EndBooleanOpcode(Opcode jump, bool test) : base(OpcodeID.EndBoolean, jump, test) { } internal override Opcode Eval(ProcessingContext context) { int matchCount = this.UpdateResultMask(context); context.PopFrame(); context.PopSequenceFrame(); if (0 == matchCount) { return this.Jump; } return this.next; } } class NoOpOpcode : Opcode { internal NoOpOpcode(OpcodeID id) : base(id) { } } class BlockEndOpcode : Opcode { QueryBuffer<Opcode> sourceJumps; internal BlockEndOpcode() : base(OpcodeID.BlockEnd) { this.sourceJumps = new QueryBuffer<Opcode>(1); } internal void DeLinkJump(Opcode jump) { this.sourceJumps.Remove(jump); } internal void LinkJump(Opcode jump) { this.sourceJumps.Add(jump); } internal override void Remove() { // Before we can remove this blockEnd from the query tree, we have delink all jumps to it while (this.sourceJumps.Count > 0) { ((JumpOpcode)this.sourceJumps[0]).RemoveJump(this); } base.Remove(); } } class TypecastOpcode : Opcode { ValueDataType newType; #if NO internal TypecastOpcode(OpcodeID opcode, ValueDataType newType) : base(opcode) { this.newType = newType; } #endif internal TypecastOpcode(ValueDataType newType) : base(OpcodeID.Cast) { this.newType = newType; } internal override bool Equals(Opcode op) { if (base.Equals(op)) { return (this.newType == ((TypecastOpcode)op).newType); } return false; } internal override Opcode Eval(ProcessingContext context) { StackFrame frame = context.TopArg; Value[] values = context.Values; for (int i = frame.basePtr; i <= frame.endPtr; ++i) { values[i].ConvertTo(context, newType); } return this.next; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} {1}", base.ToString(), this.newType.ToString()); } #endif } struct BranchContext { ProcessingContext branchContext; ProcessingContext sourceContext; internal BranchContext(ProcessingContext context) { this.sourceContext = context; this.branchContext = null; } internal ProcessingContext Create() { if (null == this.branchContext) { this.branchContext = this.sourceContext.Clone(); } else { this.branchContext.CopyFrom(this.sourceContext); } return this.branchContext; } internal void Release() { if (null != this.branchContext) { this.branchContext.Release(); } } } class QueryBranch { internal Opcode branch; internal int id; #if NO internal QueryBranch(Opcode branch) : this(branch, int.MinValue) { } #endif internal QueryBranch(Opcode branch, int id) { this.branch = branch; this.id = id; } internal Opcode Branch { get { return this.branch; } #if NO set { this.branch = value; } #endif } internal int ID { get { return this.id; } } } class QueryBranchTable { int count; QueryBranch[] branches; internal QueryBranchTable() : this(1) { } internal QueryBranchTable(int capacity) { this.branches = new QueryBranch[capacity]; } internal int Count { get { return this.count; } } internal QueryBranch this[int index] { get { return this.branches[index]; } } #if NO internal void Add(QueryBranch entry) { Fx.Assert(null != entry, ""); this.InsertAt(this.count, entry); } #endif internal void AddInOrder(QueryBranch branch) { // Insert in sorted order always int index; for (index = 0; index < this.count; ++index) { // if current node is >= key, we've found the spot if (this.branches[index].ID >= branch.ID) { break; } } this.InsertAt(index, branch); } void Grow() { QueryBranch[] branches = new QueryBranch[this.branches.Length + 1]; Array.Copy(this.branches, branches, this.branches.Length); this.branches = branches; } public int IndexOf(Opcode opcode) { for (int i = 0; i < this.count; ++i) { if (object.ReferenceEquals(opcode, this.branches[i].Branch)) { return i; } } return -1; } public int IndexOfID(int id) { for (int i = 0; i < this.count; ++i) { if (this.branches[i].ID == id) { return i; } } return -1; } #if NO public int IndexOfEquals(Opcode opcode) { for (int i = 0; i < this.count; ++i) { if (this.branches[i].Branch.Equals(opcode)) { return i; } } return -1; } #endif internal void InsertAt(int index, QueryBranch branch) { if (this.count == this.branches.Length) { this.Grow(); } if (index < this.count) { Array.Copy(this.branches, index, this.branches, index + 1, this.count - index); } this.branches[index] = branch; this.count++; } internal bool Remove(Opcode branch) { Fx.Assert(null != branch, ""); int index = this.IndexOf(branch); if (index >= 0) { this.RemoveAt(index); return true; } return false; } internal void RemoveAt(int index) { Fx.Assert(index < this.count, ""); if (index < this.count - 1) { Array.Copy(this.branches, index + 1, this.branches, index, this.count - index - 1); } else { this.branches[index] = null; } this.count--; } internal void Trim() { if (this.count < this.branches.Length) { QueryBranch[] branches = new QueryBranch[this.count]; Array.Copy(this.branches, branches, this.count); this.branches = branches; } for (int i = 0; i < this.branches.Length; ++i) { if (this.branches[i] != null && this.branches[i].Branch != null) { this.branches[i].Branch.Trim(); } } } } class BranchOpcode : Opcode { OpcodeList branches; internal BranchOpcode() : this(OpcodeID.Branch) { } internal BranchOpcode(OpcodeID id) : base(id) { this.flags |= OpcodeFlags.Branch; this.branches = new OpcodeList(2); } internal OpcodeList Branches { get { return this.branches; } } internal override void Add(Opcode opcode) { // Add with maximum affinity.. find a similar opcode, if we can, and call its Add method for (int i = 0; i < this.branches.Count; ++i) { if (this.branches[i].IsEquivalentForAdd(opcode)) { this.branches[i].Add(opcode); return; } } // Ok.. no similar opcode. Add it just like any other branch this.AddBranch(opcode); } internal override void AddBranch(Opcode opcode) { Fx.Assert(null != opcode, ""); // Make sure the same opcode doesn't already exist.. Fx.Assert(-1 == this.branches.IndexOf(opcode), ""); this.branches.Add(opcode); opcode.Prev = this; // If this branch is in a conditional, then this new opcode must be added to that conditional.. if (this.IsInConditional()) { this.LinkToConditional(opcode); } } internal override void CollectXPathFilters(ICollection<MessageFilter> filters) { for (int i = 0; i < this.branches.Count; ++i) { this.branches[i].CollectXPathFilters(filters); } } internal override void DelinkFromConditional(Opcode child) { if (null != this.prev) { this.prev.DelinkFromConditional(child); } } internal override Opcode Eval(ProcessingContext context) { QueryProcessor processor = context.Processor; SeekableXPathNavigator contextNode = processor.ContextNode; int marker = processor.CounterMarker; long pos = contextNode.CurrentPosition; Opcode branch; int i = 0; int branchCount = this.branches.Count; try { if (context.StacksInUse) { // If we have N branches, eval N-1 in a cloned context and the remainder in the // original one if (--branchCount > 0) { // Evaluate all but the first branch with a clone of the current context // The first branch (right most) can be evaluated with the current context BranchContext branchContext = new BranchContext(context); // struct. fast for (; i < branchCount; ++i) { branch = this.branches[i]; if (0 != (branch.Flags & OpcodeFlags.Fx)) { branch.Eval(context); } else { // This allocates a solitary context and then reuses it repeatedly ProcessingContext newContext = branchContext.Create(); while (null != branch) { branch = branch.Eval(newContext); } } contextNode.CurrentPosition = pos; // restore the navigator to its original position processor.CounterMarker = marker; // and the node count marker } branchContext.Release(); } // Do the final branch with the existing context branch = branches[i]; while (null != branch) { branch = branch.Eval(context); } } else // since there is nothing on the stack, there is nothing to clone { int nodeCountSav = context.NodeCount; for (; i < branchCount; ++i) { branch = branches[i]; // Evaluate this branch while (null != branch) { branch = branch.Eval(context); } // Restore the current context to its pristine state, so we can reuse it context.ClearContext(); context.NodeCount = nodeCountSav; contextNode.CurrentPosition = pos; processor.CounterMarker = marker; } } } catch (XPathNavigatorException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branches[i])); } catch (NavigatorInvalidBodyAccessException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branches[i])); } processor.CounterMarker = marker; return this.next; } internal override bool IsInConditional() { if (null != this.prev) { return this.prev.IsInConditional(); } return true; } internal override void LinkToConditional(Opcode child) { if (null != this.prev) { this.prev.LinkToConditional(child); } } /// <summary> /// Loop over all branches, trying to locate one that is equal to the given opcode /// If the branch is a branch itself, perform the locate recursively. /// </summary> /// <param name="opcode"></param> /// <returns></returns> internal override Opcode Locate(Opcode opcode) { Fx.Assert(!opcode.TestFlag(OpcodeFlags.Branch), ""); for (int i = 0, count = this.branches.Count; i < count; ++i) { Opcode branch = this.branches[i]; if (branch.TestFlag(OpcodeFlags.Branch)) { // The branch is itself a branch. Since branch opcodes serve as branches in the exection // path for a query, but don't comprise one of the opcodes used to actually perform it, we // recursively try to locate an equivalent opcode inside the branch Opcode subBranch = branch.Locate(opcode); if (null != subBranch) { return subBranch; } } else if (branch.Equals(opcode)) { return branch; } } return null; } internal override void Remove() { if (0 == this.branches.Count) { base.Remove(); } } internal override void RemoveChild(Opcode opcode) { Fx.Assert(null != opcode, ""); if (this.IsInConditional()) { this.DelinkFromConditional(opcode); } this.branches.Remove(opcode); this.branches.Trim(); } internal override void Replace(Opcode replace, Opcode with) { int i = this.branches.IndexOf(replace); if (i >= 0) { replace.Prev = null; this.branches[i] = with; with.Prev = this; } } internal override void Trim() { this.branches.Trim(); for (int i = 0; i < this.branches.Count; ++i) { this.branches[i].Trim(); } } } struct QueryBranchResult { internal QueryBranch branch; int valIndex; internal QueryBranchResult(QueryBranch branch, int valIndex) { this.branch = branch; this.valIndex = valIndex; } internal QueryBranch Branch { get { return this.branch; } } internal int ValIndex { get { return this.valIndex; } } #if NO internal void Set(QueryBranch branch, int valIndex) { this.branch = branch; this.valIndex = valIndex; } #endif } internal class QueryBranchResultSet { QueryBuffer<QueryBranchResult> results; QueryBranchResultSet next; internal static SortComparer comparer = new SortComparer(); internal QueryBranchResultSet() : this(2) { } internal QueryBranchResultSet(int capacity) { this.results = new QueryBuffer<QueryBranchResult>(capacity); } internal int Count { get { return this.results.count; } } internal QueryBranchResult this[int index] { get { return this.results[index]; } } internal QueryBranchResultSet Next { get { return this.next; } set { this.next = value; } } internal void Add(QueryBranch branch, int valIndex) { this.results.Add(new QueryBranchResult(branch, valIndex)); } internal void Clear() { this.results.count = 0; } internal void Sort() { this.results.Sort(QueryBranchResultSet.comparer); } internal class SortComparer : IComparer<QueryBranchResult> { public bool Equals(QueryBranchResult x, QueryBranchResult y) { return x.branch.id == y.branch.id; } public int Compare(QueryBranchResult x, QueryBranchResult y) { return x.branch.id - y.branch.id; } public int GetHashCode(QueryBranchResult obj) { return obj.branch.id; } } } struct BranchMatcher { int resultCount; QueryBranchResultSet resultTable; internal BranchMatcher(int resultCount, QueryBranchResultSet resultTable) { this.resultCount = resultCount; this.resultTable = resultTable; } internal QueryBranchResultSet ResultTable { get { return this.resultTable; } } void InitResults(ProcessingContext context) { context.PushFrame(); // Push this.resultsCount booleans onto the stack, all set to false context.Push(false, this.resultCount); } internal void InvokeMatches(ProcessingContext context) { Fx.Assert(null != context, ""); switch (this.resultTable.Count) { default: this.InvokeMultiMatch(context); break; case 0: break; case 1: this.InvokeSingleMatch(context); break; } } void InvokeMultiMatch(ProcessingContext context) { int marker = context.Processor.CounterMarker; BranchContext branchContext = new BranchContext(context); // struct. quick. int resultTableCount = this.resultTable.Count; for (int i = 0; i < resultTableCount; ) { QueryBranchResult result = this.resultTable[i]; QueryBranch branch = result.Branch; // Branches can arbitrarily alter context stacks, rendering them unuseable to other branches. // Therefore, before following a branch, we have to clone the context. Cloning is relatively efficient because // can avoid allocating memory in most cases. We cannot, unfortunately, avoid Array copies. // // Optimization: // We can avoid cloning altogether when we can predict that the branch does NOT tamper with the stack, // or does so in a predictable way. If we are sure that we can restore the stack easily after the branch // completes, we have no reason to copy the stack. ProcessingContext newContext; Opcode nextOpcode = branch.Branch.Next; if (nextOpcode.TestFlag(OpcodeFlags.NoContextCopy)) { newContext = context; } else { newContext = branchContext.Create(); } this.InitResults(newContext); // // Matches are sorted by their branch ID. // It is very possible that the a literal matches multiple times, especially when the value being // compared is a sequence. A literal may match multiple items in a single sequence // OR multiple items in multiple sequences. If there were 4 context sequences, the literal may have // matched one item each in 3 of them. The branchID for that literal will be present 3 times in the // resultTable. // Sorting the matches groups them by their branch Ids. We only want to take the branch ONCE, so now we // iterate over all the duplicate matches.. // result.ValIndex will give us the index of the value that was matched. Thus if the 3rd sequence // matched, ValIndex == 2 (0 based) newContext.Values[newContext.TopArg[result.ValIndex]].Boolean = true; while (++i < resultTableCount) { result = this.resultTable[i]; if (branch.ID == result.Branch.ID) { newContext.Values[newContext.TopArg[result.ValIndex]].Boolean = true; } else { break; } } try { newContext.EvalCodeBlock(nextOpcode); } catch (XPathNavigatorException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(nextOpcode)); } catch (NavigatorInvalidBodyAccessException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(nextOpcode)); } context.Processor.CounterMarker = marker; } branchContext.Release(); } internal void InvokeNonMatches(ProcessingContext context, QueryBranchTable nonMatchTable) { Fx.Assert(null != context && null != nonMatchTable, ""); int marker = context.Processor.CounterMarker; BranchContext branchContext = new BranchContext(context); int nonMatchIndex = 0; int matchIndex = 0; while (matchIndex < this.resultTable.Count && nonMatchIndex < nonMatchTable.Count) { int compare = this.resultTable[matchIndex].Branch.ID - nonMatchTable[nonMatchIndex].ID; if (compare > 0) { // Nonmatch < match // Invoke.. ProcessingContext newContext = branchContext.Create(); this.InvokeNonMatch(newContext, nonMatchTable[nonMatchIndex]); context.Processor.CounterMarker = marker; ++nonMatchIndex; } else if (0 == compare) { ++nonMatchIndex; } else { ++matchIndex; } } // Add remaining while (nonMatchIndex < nonMatchTable.Count) { ProcessingContext newContext = branchContext.Create(); this.InvokeNonMatch(newContext, nonMatchTable[nonMatchIndex]); context.Processor.CounterMarker = marker; ++nonMatchIndex; } branchContext.Release(); } void InvokeNonMatch(ProcessingContext context, QueryBranch branch) { context.PushFrame(); context.Push(false, this.resultCount); try { context.EvalCodeBlock(branch.Branch); } catch (XPathNavigatorException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branch.Branch)); } catch (NavigatorInvalidBodyAccessException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(branch.Branch)); } } void InvokeSingleMatch(ProcessingContext context) { int marker = context.Processor.CounterMarker; QueryBranchResult result = this.resultTable[0]; this.InitResults(context); context.Values[context.TopArg[result.ValIndex]].Boolean = true; try { context.EvalCodeBlock(result.Branch.Branch.Next); } catch (XPathNavigatorException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(result.Branch.Branch.Next)); } catch (NavigatorInvalidBodyAccessException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(result.Branch.Branch.Next)); } context.Processor.CounterMarker = marker; } internal void Release(ProcessingContext context) { context.Processor.ReleaseResults(this.resultTable); } } abstract class QueryBranchIndex { internal abstract int Count { get; } internal abstract QueryBranch this[object key] { get; set; } internal abstract void CollectXPathFilters(ICollection<MessageFilter> filters); #if NO internal abstract IEnumerator GetEnumerator(); #endif internal abstract void Match(int valIndex, ref Value val, QueryBranchResultSet results); internal abstract void Remove(object key); internal abstract void Trim(); } class QueryConditionalBranchOpcode : Opcode { QueryBranchTable alwaysBranches; QueryBranchIndex branchIndex; int nextID; internal QueryConditionalBranchOpcode(OpcodeID id, QueryBranchIndex branchIndex) : base(id) { Fx.Assert(null != branchIndex, ""); this.flags |= OpcodeFlags.Branch; this.branchIndex = branchIndex; this.nextID = 0; } internal QueryBranchTable AlwaysBranches { get { if (null == this.alwaysBranches) { this.alwaysBranches = new QueryBranchTable(); } return this.alwaysBranches; } } #if NO internal QueryBranchIndex BranchIndex { get { return this.branchIndex; } } #endif internal override void Add(Opcode opcode) { LiteralRelationOpcode literal = this.ValidateOpcode(opcode); if (null == literal) { base.Add(opcode); return; } // Was this literal already added to the index? QueryBranch queryBranch = this.branchIndex[literal.Literal]; if (null == queryBranch) { // First time. New branch this.nextID++; queryBranch = new QueryBranch(literal, this.nextID); literal.Prev = this; this.branchIndex[literal.Literal] = queryBranch; } else { Fx.Assert(!object.ReferenceEquals(queryBranch.Branch, literal), ""); Fx.Assert(literal.ID == queryBranch.Branch.ID, ""); // literal already exists.. but what follows the literal must be branched // Should never get here, but just in case queryBranch.Branch.Next.Add(literal.Next); } literal.Flags |= OpcodeFlags.InConditional; this.AddAlwaysBranch(queryBranch, literal.Next); } internal void AddAlwaysBranch(Opcode literal, Opcode next) { LiteralRelationOpcode literalOp = this.ValidateOpcode(literal); Fx.Assert(null != literalOp, ""); if (null != literalOp) { this.AddAlwaysBranch(literalOp, next); } } // Whether or not the given literal matches, we must always take the branch rooted at 'next' // Add to the AlwaysBranches table if not already there.. internal void AddAlwaysBranch(LiteralRelationOpcode literal, Opcode next) { Fx.Assert(null != literal && null != next, ""); QueryBranch literalBranch = this.branchIndex[literal.Literal]; Fx.Assert(null != literalBranch, ""); this.AddAlwaysBranch(literalBranch, next); } void AddAlwaysBranch(QueryBranch literalBranch, Opcode next) { if (OpcodeID.Branch == next.ID) { BranchOpcode opcode = (BranchOpcode)next; OpcodeList branches = opcode.Branches; for (int i = 0; i < branches.Count; ++i) { Opcode branch = branches[i]; if (this.IsAlwaysBranch(branch)) { this.AlwaysBranches.AddInOrder(new QueryBranch(branch, literalBranch.ID)); } else { branch.Flags |= OpcodeFlags.NoContextCopy; } } } else { Fx.Assert(!next.TestFlag(OpcodeFlags.Branch), ""); if (this.IsAlwaysBranch(next)) { this.AlwaysBranches.AddInOrder(new QueryBranch(next, literalBranch.ID)); } else { next.Flags |= OpcodeFlags.NoContextCopy; } } } internal virtual void CollectMatches(int valIndex, ref Value val, QueryBranchResultSet results) { this.branchIndex.Match(valIndex, ref val, results); } internal override void CollectXPathFilters(ICollection<MessageFilter> filters) { if (this.alwaysBranches != null) { for (int i = 0; i < this.alwaysBranches.Count; ++i) { this.alwaysBranches[i].Branch.CollectXPathFilters(filters); } } this.branchIndex.CollectXPathFilters(filters); } internal override Opcode Eval(ProcessingContext context) { StackFrame arg = context.TopArg; int argCount = arg.Count; if (argCount > 0) { QueryBranchResultSet resultSet = context.Processor.CreateResultSet(); BranchMatcher matcher = new BranchMatcher(argCount, resultSet); // Operate on values at the the top frame of the value stack // For each source value, find the branch that could be taken for (int i = 0; i < argCount; ++i) { this.CollectMatches(i, ref context.Values[arg[i]], resultSet); } // Done with whatever we were testing equality against context.PopFrame(); if (resultSet.Count > 1) { // Sort results resultSet.Sort(); } // First, do non-true branches.. if (null != this.alwaysBranches && this.alwaysBranches.Count > 0) { matcher.InvokeNonMatches(context, this.alwaysBranches); } // Iterate through matches, invoking each matched branch matcher.InvokeMatches(context); matcher.Release(context); } else { context.PopFrame(); } return this.next; } internal QueryBranch GetBranch(Opcode op) { if (op.TestFlag(OpcodeFlags.Literal)) { LiteralRelationOpcode relOp = this.ValidateOpcode(op); if (null != relOp) { QueryBranch branch = this.branchIndex[relOp.Literal]; if (null != branch && branch.Branch.ID == op.ID) { return branch; } } } return null; } bool IsAlwaysBranch(Opcode next) { Fx.Assert(null != next, ""); // Opcodes subsequent to matching literals must obviously be branched to. // The question is whether we should branch to the opcodes following those literals that do *not* match. // Naturally, the answer depends on the sort of opcode that succeeds the literal. // // If the literal is within a boolean conjunction, the succeeding opcode will either be a JumpIfNot // Or a BlockEnd. // // -If the JumpIfNot is multiway, then always evaluate if it contains ANY non-result only opcodes. // -If JumpIfNot(False) -i.e. AND - only evaluate if the opcode succeeding the jump is NOT a result opcode. // -If JumpIfNot(True) - i.e. OR - always evaluate // // -If BlockEnd - evaluate only if not followed by a result // // When branching for matching literals, we push trues onto the ValueStack corresponding to the items that // matched. When branching for non-matching literals, we push ALL FALSE values... and then eval. // is it a the termination of a conditional? JumpIfOpcode jump = next as JumpIfOpcode; if (null != jump) { // Is the conditional JumpIfNot(False) = i.e. OR? if (!jump.Test) { return true; } // Does the conditional actually jump to anything? Should never be the case, but paranoia demands.. Opcode jumpTo = jump.Jump; if (null == jumpTo) { return false; } // Lets see where the jump will take us Opcode postJump; if (jumpTo.TestFlag(OpcodeFlags.Branch)) { // Multiway jump OpcodeList branches = ((BranchOpcode)jumpTo).Branches; for (int i = 0; i < branches.Count; ++i) { postJump = branches[i].Next; if (null != postJump && !postJump.TestFlag(OpcodeFlags.Result)) { // There is at least one jump here that leads to a non-result. // For now, this dooms everybody to being branched to, whether or not their respective literals // matched return true; } } return false; } // single jump postJump = jump.Jump.Next; if (null != postJump && postJump.TestFlag(OpcodeFlags.Result)) { return false; } return true; } // If the next opcode is a BlockEnd, then only bother processing if what follows the block is not a result if (OpcodeID.BlockEnd == next.ID) { Fx.Assert(null != next.Next, ""); return (!next.Next.TestFlag(OpcodeFlags.Result)); } // The literal is not inside a boolean conjunction // If the literal is not followed by a result, then we must do further processing after the branch return (!next.TestFlag(OpcodeFlags.Result)); } /// <summary> /// Returns true if this branch can accept 'opcode' being added to it /// </summary> internal override bool IsEquivalentForAdd(Opcode opcode) { if (null != this.ValidateOpcode(opcode)) { return true; } return base.IsEquivalentForAdd(opcode); } internal override Opcode Locate(Opcode opcode) { QueryBranch queryBranch = this.GetBranch(opcode); if (null != queryBranch) { return queryBranch.Branch; } return null; } internal override void Remove() { if (null == this.branchIndex || 0 == this.branchIndex.Count) { base.Remove(); } } internal override void RemoveChild(Opcode opcode) { LiteralRelationOpcode literal = this.ValidateOpcode(opcode); Fx.Assert(null != literal, ""); QueryBranch branch = this.branchIndex[literal.Literal]; Fx.Assert(null != branch, ""); this.branchIndex.Remove(literal.Literal); branch.Branch.Flags &= (~OpcodeFlags.NoContextCopy); if (null != this.alwaysBranches) { int removeAt = this.alwaysBranches.IndexOfID(branch.ID); if (removeAt >= 0) { this.alwaysBranches.RemoveAt(removeAt); if (0 == this.alwaysBranches.Count) { this.alwaysBranches = null; } } } } internal void RemoveAlwaysBranch(Opcode opcode) { if (null == this.alwaysBranches) { return; } // Note: if the opcodes below are not in the alwaysBranches table, nothing will happen // So arbitrary calls are safe - just makes the removal processor slower (we'll speed it up if necessary) if (OpcodeID.Branch == opcode.ID) { OpcodeList branches = ((BranchOpcode)opcode).Branches; for (int i = 0; i < branches.Count; ++i) { this.alwaysBranches.Remove(branches[i]); } } else { this.alwaysBranches.Remove(opcode); } if (0 == this.alwaysBranches.Count) { this.alwaysBranches = null; } } internal override void Replace(Opcode replace, Opcode with) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperCritical(new NotImplementedException(SR.GetString(SR.FilterUnexpectedError))); } internal override void Trim() { if (this.alwaysBranches != null) { this.alwaysBranches.Trim(); } this.branchIndex.Trim(); } internal virtual LiteralRelationOpcode ValidateOpcode(Opcode opcode) { return opcode as LiteralRelationOpcode; } } }
namespace MarioLevelEditor { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.pictureLevel = new System.Windows.Forms.PictureBox(); this.pRight = new System.Windows.Forms.Panel(); this.pLeft = new System.Windows.Forms.Panel(); this.pSelected = new System.Windows.Forms.PictureBox(); this.list = new System.Windows.Forms.ListView(); this.menu = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mOpen = new System.Windows.Forms.ToolStripMenuItem(); this.mSave = new System.Windows.Forms.ToolStripMenuItem(); this.mSaveAs = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator(); this.mExit = new System.Windows.Forms.ToolStripMenuItem(); this.actiondToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.offsetXSelectedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.offsetYSelectedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.images = new System.Windows.Forms.ImageList(this.components); this.PTop = new System.Windows.Forms.Panel(); this.PRest = new System.Windows.Forms.Panel(); this.dOpen = new System.Windows.Forms.OpenFileDialog(); this.dSave = new System.Windows.Forms.SaveFileDialog(); this.pButtom = new System.Windows.Forms.Panel(); this.status = new System.Windows.Forms.StatusStrip(); this.labelx = new System.Windows.Forms.ToolStripStatusLabel(); this.labely = new System.Windows.Forms.ToolStripStatusLabel(); this.objectnamelabel = new System.Windows.Forms.ToolStripStatusLabel(); this.timerobject = new System.Windows.Forms.Timer(this.components); ((System.ComponentModel.ISupportInitialize)(this.pictureLevel)).BeginInit(); this.pRight.SuspendLayout(); this.pLeft.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pSelected)).BeginInit(); this.menu.SuspendLayout(); this.PTop.SuspendLayout(); this.PRest.SuspendLayout(); this.pButtom.SuspendLayout(); this.status.SuspendLayout(); this.SuspendLayout(); // // pictureLevel // this.pictureLevel.Cursor = System.Windows.Forms.Cursors.Default; this.pictureLevel.Image = ((System.Drawing.Image)(resources.GetObject("pictureLevel.Image"))); this.pictureLevel.Location = new System.Drawing.Point(6, 6); this.pictureLevel.Name = "pictureLevel"; this.pictureLevel.Size = new System.Drawing.Size(1024, 464); this.pictureLevel.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureLevel.TabIndex = 0; this.pictureLevel.TabStop = false; this.pictureLevel.MouseLeave += new System.EventHandler(this.pictureLevel_MouseLeave); this.pictureLevel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pictureLevel_MouseMove); this.pictureLevel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.pictureLevel_MouseDown); this.pictureLevel.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureLevel_Paint); this.pictureLevel.MouseEnter += new System.EventHandler(this.pictureLevel_MouseEnter); // // pRight // this.pRight.AutoScroll = true; this.pRight.BackColor = System.Drawing.Color.Gold; this.pRight.Controls.Add(this.pictureLevel); this.pRight.Dock = System.Windows.Forms.DockStyle.Fill; this.pRight.Location = new System.Drawing.Point(141, 0); this.pRight.Name = "pRight"; this.pRight.Size = new System.Drawing.Size(631, 490); this.pRight.TabIndex = 1; // // pLeft // this.pLeft.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.pLeft.Controls.Add(this.pSelected); this.pLeft.Controls.Add(this.list); this.pLeft.Dock = System.Windows.Forms.DockStyle.Left; this.pLeft.Location = new System.Drawing.Point(0, 0); this.pLeft.Name = "pLeft"; this.pLeft.Size = new System.Drawing.Size(141, 490); this.pLeft.TabIndex = 2; // // pSelected // this.pSelected.Image = global::MarioLevelEditor.Properties.Resources.Selected; this.pSelected.Location = new System.Drawing.Point(3, 448); this.pSelected.Name = "pSelected"; this.pSelected.Size = new System.Drawing.Size(45, 40); this.pSelected.TabIndex = 2; this.pSelected.TabStop = false; this.pSelected.Visible = false; // // list // this.list.Dock = System.Windows.Forms.DockStyle.Left; this.list.FullRowSelect = true; this.list.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.list.Location = new System.Drawing.Point(0, 0); this.list.Name = "list"; this.list.Size = new System.Drawing.Size(138, 490); this.list.TabIndex = 1; this.list.UseCompatibleStateImageBehavior = false; this.list.View = System.Windows.Forms.View.SmallIcon; this.list.ItemActivate += new System.EventHandler(this.list_ItemActivate); this.list.KeyDown += new System.Windows.Forms.KeyEventHandler(this.list_KeyDown); // // menu // this.menu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.actiondToolStripMenuItem, this.aboutToolStripMenuItem}); this.menu.Location = new System.Drawing.Point(0, 0); this.menu.Name = "menu"; this.menu.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.menu.Size = new System.Drawing.Size(772, 24); this.menu.TabIndex = 2; this.menu.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mOpen, this.mSave, this.mSaveAs, this.toolStripMenuItem1, this.mExit}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "File"; // // mOpen // this.mOpen.Name = "mOpen"; this.mOpen.Size = new System.Drawing.Size(124, 22); this.mOpen.Text = "Open..."; this.mOpen.Click += new System.EventHandler(this.mOpen_Click); // // mSave // this.mSave.Name = "mSave"; this.mSave.Size = new System.Drawing.Size(124, 22); this.mSave.Text = "Save"; this.mSave.Click += new System.EventHandler(this.mSave_Click); // // mSaveAs // this.mSaveAs.Name = "mSaveAs"; this.mSaveAs.Size = new System.Drawing.Size(124, 22); this.mSaveAs.Text = "Save as..."; this.mSaveAs.Click += new System.EventHandler(this.mSaveAs_Click); // // toolStripMenuItem1 // this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(121, 6); // // mExit // this.mExit.Name = "mExit"; this.mExit.Size = new System.Drawing.Size(124, 22); this.mExit.Text = "Exit"; // // actiondToolStripMenuItem // this.actiondToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.offsetXSelectedToolStripMenuItem, this.offsetYSelectedToolStripMenuItem}); this.actiondToolStripMenuItem.Name = "actiondToolStripMenuItem"; this.actiondToolStripMenuItem.Size = new System.Drawing.Size(54, 20); this.actiondToolStripMenuItem.Text = "Actions"; // // offsetXSelectedToolStripMenuItem // this.offsetXSelectedToolStripMenuItem.Name = "offsetXSelectedToolStripMenuItem"; this.offsetXSelectedToolStripMenuItem.Size = new System.Drawing.Size(155, 22); this.offsetXSelectedToolStripMenuItem.Text = "OffsetX Selected"; this.offsetXSelectedToolStripMenuItem.Click += new System.EventHandler(this.offsetXSelectedToolStripMenuItem_Click); // // offsetYSelectedToolStripMenuItem // this.offsetYSelectedToolStripMenuItem.Name = "offsetYSelectedToolStripMenuItem"; this.offsetYSelectedToolStripMenuItem.Size = new System.Drawing.Size(155, 22); this.offsetYSelectedToolStripMenuItem.Text = "OffsetY Selected"; this.offsetYSelectedToolStripMenuItem.Click += new System.EventHandler(this.offsetYSelectedToolStripMenuItem_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(48, 20); this.aboutToolStripMenuItem.Text = "About"; // // images // this.images.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit; this.images.ImageSize = new System.Drawing.Size(32, 32); this.images.TransparentColor = System.Drawing.Color.Transparent; // // PTop // this.PTop.BackColor = System.Drawing.Color.Red; this.PTop.Controls.Add(this.menu); this.PTop.Dock = System.Windows.Forms.DockStyle.Top; this.PTop.Location = new System.Drawing.Point(0, 0); this.PTop.Name = "PTop"; this.PTop.Size = new System.Drawing.Size(772, 24); this.PTop.TabIndex = 2; // // PRest // this.PRest.BackColor = System.Drawing.Color.Olive; this.PRest.Controls.Add(this.pRight); this.PRest.Controls.Add(this.pLeft); this.PRest.Dock = System.Windows.Forms.DockStyle.Fill; this.PRest.Location = new System.Drawing.Point(0, 24); this.PRest.Name = "PRest"; this.PRest.Size = new System.Drawing.Size(772, 490); this.PRest.TabIndex = 3; // // dOpen // this.dOpen.Filter = "Mario Levels | *.xml"; // // dSave // this.dSave.Filter = "Mario Levels | *.xml"; // // pButtom // this.pButtom.BackColor = System.Drawing.Color.Thistle; this.pButtom.Controls.Add(this.status); this.pButtom.Dock = System.Windows.Forms.DockStyle.Bottom; this.pButtom.Location = new System.Drawing.Point(0, 514); this.pButtom.Name = "pButtom"; this.pButtom.Size = new System.Drawing.Size(772, 25); this.pButtom.TabIndex = 1; // // status // this.status.Dock = System.Windows.Forms.DockStyle.Fill; this.status.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.labelx, this.labely, this.objectnamelabel}); this.status.Location = new System.Drawing.Point(0, 0); this.status.Name = "status"; this.status.Size = new System.Drawing.Size(772, 25); this.status.TabIndex = 0; this.status.Text = "statusStrip1"; // // labelx // this.labelx.AutoSize = false; this.labelx.BackColor = System.Drawing.SystemColors.ButtonFace; this.labelx.Name = "labelx"; this.labelx.Size = new System.Drawing.Size(50, 20); this.labelx.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labely // this.labely.AutoSize = false; this.labely.BackColor = System.Drawing.SystemColors.ButtonFace; this.labely.Name = "labely"; this.labely.Size = new System.Drawing.Size(50, 20); this.labely.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // objectnamelabel // this.objectnamelabel.AutoSize = false; this.objectnamelabel.BackColor = System.Drawing.SystemColors.ButtonFace; this.objectnamelabel.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.objectnamelabel.Name = "objectnamelabel"; this.objectnamelabel.Size = new System.Drawing.Size(100, 20); this.objectnamelabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // timerobject // this.timerobject.Enabled = true; this.timerobject.Tick += new System.EventHandler(this.timerobject_Tick); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(772, 539); this.Controls.Add(this.PRest); this.Controls.Add(this.PTop); this.Controls.Add(this.pButtom); this.DoubleBuffered = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Level Editor"; this.Load += new System.EventHandler(this.MainForm_Load); this.Paint += new System.Windows.Forms.PaintEventHandler(this.MainForm_Paint); ((System.ComponentModel.ISupportInitialize)(this.pictureLevel)).EndInit(); this.pRight.ResumeLayout(false); this.pRight.PerformLayout(); this.pLeft.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pSelected)).EndInit(); this.menu.ResumeLayout(false); this.menu.PerformLayout(); this.PTop.ResumeLayout(false); this.PTop.PerformLayout(); this.PRest.ResumeLayout(false); this.pButtom.ResumeLayout(false); this.pButtom.PerformLayout(); this.status.ResumeLayout(false); this.status.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureLevel; private System.Windows.Forms.Panel pRight; private System.Windows.Forms.Panel pLeft; private System.Windows.Forms.ImageList images; private System.Windows.Forms.ListView list; private System.Windows.Forms.MenuStrip menu; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mOpen; private System.Windows.Forms.ToolStripMenuItem mSave; private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem mExit; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem actiondToolStripMenuItem; private System.Windows.Forms.Panel PTop; private System.Windows.Forms.Panel PRest; private System.Windows.Forms.PictureBox pSelected; private System.Windows.Forms.ToolStripMenuItem offsetXSelectedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem offsetYSelectedToolStripMenuItem; private System.Windows.Forms.OpenFileDialog dOpen; private System.Windows.Forms.SaveFileDialog dSave; private System.Windows.Forms.ToolStripMenuItem mSaveAs; private System.Windows.Forms.Panel pButtom; private System.Windows.Forms.StatusStrip status; private System.Windows.Forms.ToolStripStatusLabel labelx; private System.Windows.Forms.ToolStripStatusLabel objectnamelabel; private System.Windows.Forms.ToolStripStatusLabel labely; private System.Windows.Forms.Timer timerobject; } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using System.IO; using System.Threading; using SR = System.Reflection; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using Mono.Collections.Generic; namespace Mono.Cecil { public enum ReadingMode { Immediate = 1, Deferred = 2, } public sealed class ReaderParameters { ReadingMode reading_mode; internal IAssemblyResolver assembly_resolver; internal IMetadataResolver metadata_resolver; #if !READ_ONLY internal IMetadataImporterProvider metadata_importer_provider; #if !CF internal IReflectionImporterProvider reflection_importer_provider; #endif #endif Stream symbol_stream; ISymbolReaderProvider symbol_reader_provider; bool read_symbols; public ReadingMode ReadingMode { get { return reading_mode; } set { reading_mode = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public IMetadataResolver MetadataResolver { get { return metadata_resolver; } set { metadata_resolver = value; } } #if !READ_ONLY public IMetadataImporterProvider MetadataImporterProvider { get { return metadata_importer_provider; } set { metadata_importer_provider = value; } } #if !CF public IReflectionImporterProvider ReflectionImporterProvider { get { return reflection_importer_provider; } set { reflection_importer_provider = value; } } #endif #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolReaderProvider SymbolReaderProvider { get { return symbol_reader_provider; } set { symbol_reader_provider = value; } } public bool ReadSymbols { get { return read_symbols; } set { read_symbols = value; } } public ReaderParameters () : this (ReadingMode.Deferred) { } public ReaderParameters (ReadingMode readingMode) { this.reading_mode = readingMode; } } #if !READ_ONLY public sealed class ModuleParameters { ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; IAssemblyResolver assembly_resolver; IMetadataResolver metadata_resolver; #if !READ_ONLY IMetadataImporterProvider metadata_importer_provider; #if !CF IReflectionImporterProvider reflection_importer_provider; #endif #endif public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public IAssemblyResolver AssemblyResolver { get { return assembly_resolver; } set { assembly_resolver = value; } } public IMetadataResolver MetadataResolver { get { return metadata_resolver; } set { metadata_resolver = value; } } #if !READ_ONLY public IMetadataImporterProvider MetadataImporterProvider { get { return metadata_importer_provider; } set { metadata_importer_provider = value; } } #if !CF public IReflectionImporterProvider ReflectionImporterProvider { get { return reflection_importer_provider; } set { reflection_importer_provider = value; } } #endif #endif public ModuleParameters () { this.kind = ModuleKind.Dll; this.Runtime = GetCurrentRuntime (); this.architecture = TargetArchitecture.I386; } static TargetRuntime GetCurrentRuntime () { #if !CF return typeof (object).Assembly.ImageRuntimeVersion.ParseRuntime (); #else var corlib_version = typeof (object).Assembly.GetName ().Version; switch (corlib_version.Major) { case 1: return corlib_version.Minor == 0 ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case 2: return TargetRuntime.Net_2_0; case 4: return TargetRuntime.Net_4_0; default: throw new NotSupportedException (); } #endif } } public sealed class WriterParameters { Stream symbol_stream; ISymbolWriterProvider symbol_writer_provider; bool write_symbols; #if !SILVERLIGHT && !CF SR.StrongNameKeyPair key_pair; #endif public Stream SymbolStream { get { return symbol_stream; } set { symbol_stream = value; } } public ISymbolWriterProvider SymbolWriterProvider { get { return symbol_writer_provider; } set { symbol_writer_provider = value; } } public bool WriteSymbols { get { return write_symbols; } set { write_symbols = value; } } #if !SILVERLIGHT && !CF public SR.StrongNameKeyPair StrongNameKeyPair { get { return key_pair; } set { key_pair = value; } } #endif } #endif public sealed class ModuleDefinition : ModuleReference, ICustomAttributeProvider { internal Image Image; internal MetadataSystem MetadataSystem; internal ReadingMode ReadingMode; internal ISymbolReaderProvider SymbolReaderProvider; internal ISymbolReader symbol_reader; internal IAssemblyResolver assembly_resolver; internal IMetadataResolver metadata_resolver; internal TypeSystem type_system; readonly MetadataReader reader; readonly string fq_name; internal string runtime_version; internal ModuleKind kind; TargetRuntime runtime; TargetArchitecture architecture; ModuleAttributes attributes; ModuleCharacteristics characteristics; Guid mvid; internal AssemblyDefinition assembly; MethodDefinition entry_point; #if !READ_ONLY #if !CF internal IReflectionImporter reflection_importer; #endif internal IMetadataImporter metadata_importer; #endif Collection<CustomAttribute> custom_attributes; Collection<AssemblyNameReference> references; Collection<ModuleReference> modules; Collection<Resource> resources; Collection<ExportedType> exported_types; TypeDefinitionCollection types; public bool IsMain { get { return kind != ModuleKind.NetModule; } } public ModuleKind Kind { get { return kind; } set { kind = value; } } public TargetRuntime Runtime { get { return runtime; } set { runtime = value; runtime_version = runtime.RuntimeVersionString (); } } public string RuntimeVersion { get { return runtime_version; } set { runtime_version = value; runtime = runtime_version.ParseRuntime (); } } public TargetArchitecture Architecture { get { return architecture; } set { architecture = value; } } public ModuleAttributes Attributes { get { return attributes; } set { attributes = value; } } public ModuleCharacteristics Characteristics { get { return characteristics; } set { characteristics = value; } } public string FullyQualifiedName { get { return fq_name; } } public Guid Mvid { get { return mvid; } set { mvid = value; } } internal bool HasImage { get { return Image != null; } } public bool HasSymbols { get { return symbol_reader != null; } } public ISymbolReader SymbolReader { get { return symbol_reader; } } public override MetadataScopeType MetadataScopeType { get { return MetadataScopeType.ModuleDefinition; } } public AssemblyDefinition Assembly { get { return assembly; } } #if !READ_ONLY #if !CF internal IReflectionImporter ReflectionImporter { get { if (reflection_importer == null) Interlocked.CompareExchange (ref reflection_importer, new ReflectionImporter (this), null); return reflection_importer; } } #endif internal IMetadataImporter MetadataImporter { get { if (metadata_importer == null) Interlocked.CompareExchange (ref metadata_importer, new MetadataImporter (this), null); return metadata_importer; } } #endif public IAssemblyResolver AssemblyResolver { get { if (assembly_resolver == null) Interlocked.CompareExchange (ref assembly_resolver, new DefaultAssemblyResolver (), null); return assembly_resolver; } } public IMetadataResolver MetadataResolver { get { if (metadata_resolver == null) Interlocked.CompareExchange (ref metadata_resolver, new MetadataResolver (this.AssemblyResolver), null); return metadata_resolver; } } public TypeSystem TypeSystem { get { if (type_system == null) Interlocked.CompareExchange (ref type_system, TypeSystem.CreateTypeSystem (this), null); return type_system; } } public bool HasAssemblyReferences { get { if (references != null) return references.Count > 0; return HasImage && Image.HasTable (Table.AssemblyRef); } } public Collection<AssemblyNameReference> AssemblyReferences { get { if (references != null) return references; if (HasImage) return Read (ref references, this, (_, reader) => reader.ReadAssemblyReferences ()); return references = new Collection<AssemblyNameReference> (); } } public bool HasModuleReferences { get { if (modules != null) return modules.Count > 0; return HasImage && Image.HasTable (Table.ModuleRef); } } public Collection<ModuleReference> ModuleReferences { get { if (modules != null) return modules; if (HasImage) return Read (ref modules, this, (_, reader) => reader.ReadModuleReferences ()); return modules = new Collection<ModuleReference> (); } } public bool HasResources { get { if (resources != null) return resources.Count > 0; if (HasImage) return Image.HasTable (Table.ManifestResource) || Read (this, (_, reader) => reader.HasFileResource ()); return false; } } public Collection<Resource> Resources { get { if (resources != null) return resources; if (HasImage) return Read (ref resources, this, (_, reader) => reader.ReadResources ()); return resources = new Collection<Resource> (); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (this); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, this)); } } public bool HasTypes { get { if (types != null) return types.Count > 0; return HasImage && Image.HasTable (Table.TypeDef); } } public Collection<TypeDefinition> Types { get { if (types != null) return types; if (HasImage) return Read (ref types, this, (_, reader) => reader.ReadTypes ()); return types = new TypeDefinitionCollection (this); } } public bool HasExportedTypes { get { if (exported_types != null) return exported_types.Count > 0; return HasImage && Image.HasTable (Table.ExportedType); } } public Collection<ExportedType> ExportedTypes { get { if (exported_types != null) return exported_types; if (HasImage) return Read (ref exported_types, this, (_, reader) => reader.ReadExportedTypes ()); return exported_types = new Collection<ExportedType> (); } } public MethodDefinition EntryPoint { get { if (entry_point != null) return entry_point; if (HasImage) return Read (ref entry_point, this, (_, reader) => reader.ReadEntryPoint ()); return entry_point = null; } set { entry_point = value; } } internal ModuleDefinition () { this.MetadataSystem = new MetadataSystem (); this.token = new MetadataToken (TokenType.Module, 1); } internal ModuleDefinition (Image image) : this () { this.Image = image; this.kind = image.Kind; this.RuntimeVersion = image.RuntimeVersion; this.architecture = image.Architecture; this.attributes = image.Attributes; this.characteristics = image.Characteristics; this.fq_name = image.FileName; this.reader = new MetadataReader (this); } public bool HasTypeReference (string fullName) { return HasTypeReference (string.Empty, fullName); } public bool HasTypeReference (string scope, string fullName) { CheckFullName (fullName); if (!HasImage) return false; return GetTypeReference (scope, fullName) != null; } public bool TryGetTypeReference (string fullName, out TypeReference type) { return TryGetTypeReference (string.Empty, fullName, out type); } public bool TryGetTypeReference (string scope, string fullName, out TypeReference type) { CheckFullName (fullName); if (!HasImage) { type = null; return false; } return (type = GetTypeReference (scope, fullName)) != null; } TypeReference GetTypeReference (string scope, string fullname) { return Read (new Row<string, string> (scope, fullname), (row, reader) => reader.GetTypeReference (row.Col1, row.Col2)); } public IEnumerable<TypeReference> GetTypeReferences () { if (!HasImage) return Empty<TypeReference>.Array; return Read (this, (_, reader) => reader.GetTypeReferences ()); } public IEnumerable<MemberReference> GetMemberReferences () { if (!HasImage) return Empty<MemberReference>.Array; return Read (this, (_, reader) => reader.GetMemberReferences ()); } public TypeReference GetType (string fullName, bool runtimeName) { return runtimeName ? TypeParser.ParseType (this, fullName) : GetType (fullName); } public TypeDefinition GetType (string fullName) { CheckFullName (fullName); var position = fullName.IndexOf ('/'); if (position > 0) return GetNestedType (fullName); return ((TypeDefinitionCollection) this.Types).GetType (fullName); } public TypeDefinition GetType (string @namespace, string name) { Mixin.CheckName (name); return ((TypeDefinitionCollection) this.Types).GetType (@namespace ?? string.Empty, name); } public IEnumerable<TypeDefinition> GetTypes () { return GetTypes (Types); } static IEnumerable<TypeDefinition> GetTypes (Collection<TypeDefinition> types) { for (int i = 0; i < types.Count; i++) { var type = types [i]; yield return type; if (!type.HasNestedTypes) continue; foreach (var nested in GetTypes (type.NestedTypes)) yield return nested; } } static void CheckFullName (string fullName) { if (fullName == null) throw new ArgumentNullException ("fullName"); if (fullName.Length == 0) throw new ArgumentException (); } TypeDefinition GetNestedType (string fullname) { var names = fullname.Split ('/'); var type = GetType (names [0]); if (type == null) return null; for (int i = 1; i < names.Length; i++) { var nested_type = type.GetNestedType (names [i]); if (nested_type == null) return null; type = nested_type; } return type; } internal FieldDefinition Resolve (FieldReference field) { return MetadataResolver.Resolve (field); } internal MethodDefinition Resolve (MethodReference method) { return MetadataResolver.Resolve (method); } internal TypeDefinition Resolve (TypeReference type) { return MetadataResolver.Resolve (type); } #if !READ_ONLY static void CheckContext (IGenericParameterProvider context, ModuleDefinition module) { if (context == null) return; if (context.Module != module) throw new ArgumentException (); } #if !CF [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (Type type) { return ImportReference (type, null); } public TypeReference ImportReference (Type type) { return ImportReference (type, null); } [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (Type type, IGenericParameterProvider context) { return ImportReference (type, context); } public TypeReference ImportReference (Type type, IGenericParameterProvider context) { Mixin.CheckType (type); CheckContext (context, this); return ReflectionImporter.ImportReference (type, context); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (SR.FieldInfo field) { return ImportReference (field, null); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (SR.FieldInfo field, IGenericParameterProvider context) { return ImportReference (field, context); } public FieldReference ImportReference (SR.FieldInfo field) { return ImportReference (field, null); } public FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context) { Mixin.CheckField (field); CheckContext (context, this); return ReflectionImporter.ImportReference (field, context); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (SR.MethodBase method) { return ImportReference (method, null); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (SR.MethodBase method, IGenericParameterProvider context) { return ImportReference (method, context); } public MethodReference ImportReference (SR.MethodBase method) { return ImportReference (method, null); } public MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context) { Mixin.CheckMethod (method); CheckContext (context, this); return ReflectionImporter.ImportReference (method, context); } #endif [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (TypeReference type) { return ImportReference (type, null); } [Obsolete ("Use ImportReference", error: false)] public TypeReference Import (TypeReference type, IGenericParameterProvider context) { return ImportReference (type, context); } public TypeReference ImportReference (TypeReference type) { return ImportReference (type, null); } public TypeReference ImportReference (TypeReference type, IGenericParameterProvider context) { Mixin.CheckType (type); if (type.Module == this) return type; CheckContext (context, this); return MetadataImporter.ImportReference (type, context); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (FieldReference field) { return ImportReference (field, null); } [Obsolete ("Use ImportReference", error: false)] public FieldReference Import (FieldReference field, IGenericParameterProvider context) { return ImportReference (field, context); } public FieldReference ImportReference (FieldReference field) { return ImportReference (field, null); } public FieldReference ImportReference (FieldReference field, IGenericParameterProvider context) { Mixin.CheckField (field); if (field.Module == this) return field; CheckContext (context, this); return MetadataImporter.ImportReference (field, context); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (MethodReference method) { return ImportReference (method, null); } [Obsolete ("Use ImportReference", error: false)] public MethodReference Import (MethodReference method, IGenericParameterProvider context) { return ImportReference (method, context); } public MethodReference ImportReference (MethodReference method) { return ImportReference (method, null); } public MethodReference ImportReference (MethodReference method, IGenericParameterProvider context) { Mixin.CheckMethod (method); if (method.Module == this) return method; CheckContext (context, this); return MetadataImporter.ImportReference (method, context); } #endif public IMetadataTokenProvider LookupToken (int token) { return LookupToken (new MetadataToken ((uint) token)); } public IMetadataTokenProvider LookupToken (MetadataToken token) { return Read (token, (t, reader) => reader.LookupToken (t)); } readonly object module_lock = new object(); internal object SyncRoot { get { return module_lock; } } internal TRet Read<TItem, TRet> (TItem item, Func<TItem, MetadataReader, TRet> read) { lock (module_lock) { var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return ret; } } internal TRet Read<TItem, TRet> (ref TRet variable, TItem item, Func<TItem, MetadataReader, TRet> read) where TRet : class { lock (module_lock) { if (variable != null) return variable; var position = reader.position; var context = reader.context; var ret = read (item, reader); reader.position = position; reader.context = context; return variable = ret; } } public bool HasDebugHeader { get { return Image != null && !Image.Debug.IsZero; } } public ImageDebugDirectory GetDebugHeader (out byte [] header) { if (!HasDebugHeader) throw new InvalidOperationException (); return Image.GetDebugHeader (out header); } void ProcessDebugHeader () { if (!HasDebugHeader) return; byte [] header; var directory = GetDebugHeader (out header); if (!symbol_reader.ProcessDebugHeader (directory, header)) throw new InvalidOperationException (); } #if !READ_ONLY public static ModuleDefinition CreateModule (string name, ModuleKind kind) { return CreateModule (name, new ModuleParameters { Kind = kind }); } public static ModuleDefinition CreateModule (string name, ModuleParameters parameters) { Mixin.CheckName (name); Mixin.CheckParameters (parameters); var module = new ModuleDefinition { Name = name, kind = parameters.Kind, Runtime = parameters.Runtime, architecture = parameters.Architecture, mvid = Guid.NewGuid (), Attributes = ModuleAttributes.ILOnly, Characteristics = (ModuleCharacteristics) 0x8540, }; if (parameters.AssemblyResolver != null) module.assembly_resolver = parameters.AssemblyResolver; if (parameters.MetadataResolver != null) module.metadata_resolver = parameters.MetadataResolver; #if !READ_ONLY if (parameters.MetadataImporterProvider != null) module.metadata_importer = parameters.MetadataImporterProvider.GetMetadataImporter (module); #if !CF if (parameters.ReflectionImporterProvider != null) module.reflection_importer = parameters.ReflectionImporterProvider.GetReflectionImporter (module); #endif #endif if (parameters.Kind != ModuleKind.NetModule) { var assembly = new AssemblyDefinition (); module.assembly = assembly; module.assembly.Name = CreateAssemblyName (name); assembly.main_module = module; } module.Types.Add (new TypeDefinition (string.Empty, "<Module>", TypeAttributes.NotPublic)); return module; } static AssemblyNameDefinition CreateAssemblyName (string name) { if (name.EndsWith (".dll") || name.EndsWith (".exe")) name = name.Substring (0, name.Length - 4); return new AssemblyNameDefinition (name, Mixin.ZeroVersion); } #endif public void ReadSymbols () { if (string.IsNullOrEmpty (fq_name)) throw new InvalidOperationException (); var provider = SymbolProvider.GetPlatformReaderProvider (); if (provider == null) throw new InvalidOperationException (); ReadSymbols (provider.GetSymbolReader (this, fq_name)); } public void ReadSymbols (ISymbolReader reader) { if (reader == null) throw new ArgumentNullException ("reader"); symbol_reader = reader; ProcessDebugHeader (); } public static ModuleDefinition ReadModule (string fileName) { return ReadModule (fileName, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (Stream stream) { return ReadModule (stream, new ReaderParameters (ReadingMode.Deferred)); } public static ModuleDefinition ReadModule (string fileName, ReaderParameters parameters) { using (var stream = GetFileStream (fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { return ReadModule (stream, parameters); } } public static ModuleDefinition ReadModule (Stream stream, ReaderParameters parameters) { Mixin.CheckStream (stream); if (!stream.CanRead || !stream.CanSeek) throw new ArgumentException (); Mixin.CheckParameters (parameters); return ModuleReader.CreateModuleFrom ( ImageReader.ReadImageFrom (stream), parameters); } static Stream GetFileStream (string fileName, FileMode mode, FileAccess access, FileShare share) { if (fileName == null) throw new ArgumentNullException ("fileName"); if (fileName.Length == 0) throw new ArgumentException (); return new FileStream (fileName, mode, access, share); } #if !READ_ONLY public void Write (string fileName) { Write (fileName, new WriterParameters ()); } public void Write (Stream stream) { Write (stream, new WriterParameters ()); } public void Write (string fileName, WriterParameters parameters) { using (var stream = GetFileStream (fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { Write (stream, parameters); } } public void Write (Stream stream, WriterParameters parameters) { Mixin.CheckStream (stream); if (!stream.CanWrite || !stream.CanSeek) throw new ArgumentException (); Mixin.CheckParameters (parameters); ModuleWriter.WriteModuleTo (this, stream, parameters); } #endif } static partial class Mixin { public static void CheckStream (object stream) { if (stream == null) throw new ArgumentNullException ("stream"); } #if !READ_ONLY public static void CheckType (object type) { if (type == null) throw new ArgumentNullException ("type"); } public static void CheckField (object field) { if (field == null) throw new ArgumentNullException ("field"); } public static void CheckMethod (object method) { if (method == null) throw new ArgumentNullException ("method"); } #endif public static void CheckParameters (object parameters) { if (parameters == null) throw new ArgumentNullException ("parameters"); } public static bool HasImage (this ModuleDefinition self) { return self != null && self.HasImage; } public static bool IsCoreLibrary (this ModuleDefinition module) { if (module.Assembly == null) return false; var assembly_name = module.Assembly.Name.Name; if (assembly_name != "mscorlib" && assembly_name != "System.Runtime") return false; if (module.HasImage && !module.MetadataSystem.HasSystemObject) return false; return true; } public static string GetFullyQualifiedName (this Stream self) { #if !SILVERLIGHT var file_stream = self as FileStream; if (file_stream == null) return string.Empty; return Path.GetFullPath (file_stream.Name); #else return string.Empty; #endif } public static TargetRuntime ParseRuntime (this string self) { switch (self [1]) { case '1': return self [3] == '0' ? TargetRuntime.Net_1_0 : TargetRuntime.Net_1_1; case '2': return TargetRuntime.Net_2_0; case '4': default: return TargetRuntime.Net_4_0; } } public static string RuntimeVersionString (this TargetRuntime runtime) { switch (runtime) { case TargetRuntime.Net_1_0: return "v1.0.3705"; case TargetRuntime.Net_1_1: return "v1.1.4322"; case TargetRuntime.Net_2_0: return "v2.0.50727"; case TargetRuntime.Net_4_0: default: return "v4.0.30319"; } } } }
/* '=============================================================================== ' Generated From - CSharp_dOOdads_BusinessEntity.vbgen ' ' ** IMPORTANT ** ' How to Generate your stored procedures: ' ' SQL = SQL_StoredProcs.vbgen ' ACCESS = Access_StoredProcs.vbgen ' ORACLE = Oracle_StoredProcs.vbgen ' FIREBIRD = FirebirdStoredProcs.vbgen ' POSTGRESQL = PostgreSQL_StoredProcs.vbgen ' ' The supporting base class SqlClientEntity is in the Architecture directory in "dOOdads". ' ' This object is 'abstract' which means you need to inherit from it to be able ' to instantiate it. This is very easilly done. You can override properties and ' methods in your derived class, this allows you to regenerate this class at any ' time and not worry about overwriting custom code. ' ' NEVER EDIT THIS FILE. ' ' public class YourObject : _YourObject ' { ' ' } ' '=============================================================================== */ // Generated by MyGeneration Version # (1.3.0.3) using System; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Collections.Specialized; using MyGeneration.dOOdads; namespace nTier.Entity { public abstract class _Suppliers : SqlClientEntity { public _Suppliers() { this.QuerySource = "Suppliers"; this.MappingName = "Suppliers"; } //================================================================= // public Overrides void AddNew() //================================================================= // //================================================================= public override void AddNew() { base.AddNew(); } public override void FlushData() { this._whereClause = null; this._aggregateClause = null; base.FlushData(); } //================================================================= // public Function LoadAll() As Boolean //================================================================= // Loads all of the records in the database, and sets the currentRow to the first row //================================================================= public bool LoadAll() { ListDictionary parameters = null; return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_SuppliersLoadAll]", parameters); } //================================================================= // public Overridable Function LoadByPrimaryKey() As Boolean //================================================================= // Loads a single row of via the primary key //================================================================= public virtual bool LoadByPrimaryKey(int SupplierID) { ListDictionary parameters = new ListDictionary(); parameters.Add(Parameters.SupplierID, SupplierID); return base.LoadFromSql("[" + this.SchemaStoredProcedure + "proc_SuppliersLoadByPrimaryKey]", parameters); } #region Parameters protected class Parameters { public static SqlParameter SupplierID { get { return new SqlParameter("@SupplierID", SqlDbType.Int, 0); } } public static SqlParameter CompanyName { get { return new SqlParameter("@CompanyName", SqlDbType.NVarChar, 40); } } public static SqlParameter ContactName { get { return new SqlParameter("@ContactName", SqlDbType.NVarChar, 30); } } public static SqlParameter ContactTitle { get { return new SqlParameter("@ContactTitle", SqlDbType.NVarChar, 30); } } public static SqlParameter Address { get { return new SqlParameter("@Address", SqlDbType.NVarChar, 60); } } public static SqlParameter City { get { return new SqlParameter("@City", SqlDbType.NVarChar, 15); } } public static SqlParameter Region { get { return new SqlParameter("@Region", SqlDbType.NVarChar, 15); } } public static SqlParameter PostalCode { get { return new SqlParameter("@PostalCode", SqlDbType.NVarChar, 10); } } public static SqlParameter Country { get { return new SqlParameter("@Country", SqlDbType.NVarChar, 15); } } public static SqlParameter Phone { get { return new SqlParameter("@Phone", SqlDbType.NVarChar, 24); } } public static SqlParameter Fax { get { return new SqlParameter("@Fax", SqlDbType.NVarChar, 24); } } public static SqlParameter HomePage { get { return new SqlParameter("@HomePage", SqlDbType.NText, 1073741823); } } } #endregion #region ColumnNames public class ColumnNames { public const string SupplierID = "SupplierID"; public const string CompanyName = "CompanyName"; public const string ContactName = "ContactName"; public const string ContactTitle = "ContactTitle"; public const string Address = "Address"; public const string City = "City"; public const string Region = "Region"; public const string PostalCode = "PostalCode"; public const string Country = "Country"; public const string Phone = "Phone"; public const string Fax = "Fax"; public const string HomePage = "HomePage"; static public string ToPropertyName(string columnName) { if(ht == null) { ht = new Hashtable(); ht[SupplierID] = _Suppliers.PropertyNames.SupplierID; ht[CompanyName] = _Suppliers.PropertyNames.CompanyName; ht[ContactName] = _Suppliers.PropertyNames.ContactName; ht[ContactTitle] = _Suppliers.PropertyNames.ContactTitle; ht[Address] = _Suppliers.PropertyNames.Address; ht[City] = _Suppliers.PropertyNames.City; ht[Region] = _Suppliers.PropertyNames.Region; ht[PostalCode] = _Suppliers.PropertyNames.PostalCode; ht[Country] = _Suppliers.PropertyNames.Country; ht[Phone] = _Suppliers.PropertyNames.Phone; ht[Fax] = _Suppliers.PropertyNames.Fax; ht[HomePage] = _Suppliers.PropertyNames.HomePage; } return (string)ht[columnName]; } static private Hashtable ht = null; } #endregion #region PropertyNames public class PropertyNames { public const string SupplierID = "SupplierID"; public const string CompanyName = "CompanyName"; public const string ContactName = "ContactName"; public const string ContactTitle = "ContactTitle"; public const string Address = "Address"; public const string City = "City"; public const string Region = "Region"; public const string PostalCode = "PostalCode"; public const string Country = "Country"; public const string Phone = "Phone"; public const string Fax = "Fax"; public const string HomePage = "HomePage"; static public string ToColumnName(string propertyName) { if(ht == null) { ht = new Hashtable(); ht[SupplierID] = _Suppliers.ColumnNames.SupplierID; ht[CompanyName] = _Suppliers.ColumnNames.CompanyName; ht[ContactName] = _Suppliers.ColumnNames.ContactName; ht[ContactTitle] = _Suppliers.ColumnNames.ContactTitle; ht[Address] = _Suppliers.ColumnNames.Address; ht[City] = _Suppliers.ColumnNames.City; ht[Region] = _Suppliers.ColumnNames.Region; ht[PostalCode] = _Suppliers.ColumnNames.PostalCode; ht[Country] = _Suppliers.ColumnNames.Country; ht[Phone] = _Suppliers.ColumnNames.Phone; ht[Fax] = _Suppliers.ColumnNames.Fax; ht[HomePage] = _Suppliers.ColumnNames.HomePage; } return (string)ht[propertyName]; } static private Hashtable ht = null; } #endregion #region StringPropertyNames public class StringPropertyNames { public const string SupplierID = "s_SupplierID"; public const string CompanyName = "s_CompanyName"; public const string ContactName = "s_ContactName"; public const string ContactTitle = "s_ContactTitle"; public const string Address = "s_Address"; public const string City = "s_City"; public const string Region = "s_Region"; public const string PostalCode = "s_PostalCode"; public const string Country = "s_Country"; public const string Phone = "s_Phone"; public const string Fax = "s_Fax"; public const string HomePage = "s_HomePage"; } #endregion #region Properties public virtual int? SupplierID { get { return base.Getint(ColumnNames.SupplierID); } set { base.Setint(ColumnNames.SupplierID, value); } } public virtual string CompanyName { get { return base.Getstring(ColumnNames.CompanyName); } set { base.Setstring(ColumnNames.CompanyName, value); } } public virtual string ContactName { get { return base.Getstring(ColumnNames.ContactName); } set { base.Setstring(ColumnNames.ContactName, value); } } public virtual string ContactTitle { get { return base.Getstring(ColumnNames.ContactTitle); } set { base.Setstring(ColumnNames.ContactTitle, value); } } public virtual string Address { get { return base.Getstring(ColumnNames.Address); } set { base.Setstring(ColumnNames.Address, value); } } public virtual string City { get { return base.Getstring(ColumnNames.City); } set { base.Setstring(ColumnNames.City, value); } } public virtual string Region { get { return base.Getstring(ColumnNames.Region); } set { base.Setstring(ColumnNames.Region, value); } } public virtual string PostalCode { get { return base.Getstring(ColumnNames.PostalCode); } set { base.Setstring(ColumnNames.PostalCode, value); } } public virtual string Country { get { return base.Getstring(ColumnNames.Country); } set { base.Setstring(ColumnNames.Country, value); } } public virtual string Phone { get { return base.Getstring(ColumnNames.Phone); } set { base.Setstring(ColumnNames.Phone, value); } } public virtual string Fax { get { return base.Getstring(ColumnNames.Fax); } set { base.Setstring(ColumnNames.Fax, value); } } public virtual string HomePage { get { return base.Getstring(ColumnNames.HomePage); } set { base.Setstring(ColumnNames.HomePage, value); } } #endregion #region String Properties public virtual string s_SupplierID { get { return this.IsColumnNull(ColumnNames.SupplierID) ? string.Empty : base.GetintAsString(ColumnNames.SupplierID); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.SupplierID); else this.SupplierID = base.SetintAsString(ColumnNames.SupplierID, value); } } public virtual string s_CompanyName { get { return this.IsColumnNull(ColumnNames.CompanyName) ? string.Empty : base.GetstringAsString(ColumnNames.CompanyName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.CompanyName); else this.CompanyName = base.SetstringAsString(ColumnNames.CompanyName, value); } } public virtual string s_ContactName { get { return this.IsColumnNull(ColumnNames.ContactName) ? string.Empty : base.GetstringAsString(ColumnNames.ContactName); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ContactName); else this.ContactName = base.SetstringAsString(ColumnNames.ContactName, value); } } public virtual string s_ContactTitle { get { return this.IsColumnNull(ColumnNames.ContactTitle) ? string.Empty : base.GetstringAsString(ColumnNames.ContactTitle); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.ContactTitle); else this.ContactTitle = base.SetstringAsString(ColumnNames.ContactTitle, value); } } public virtual string s_Address { get { return this.IsColumnNull(ColumnNames.Address) ? string.Empty : base.GetstringAsString(ColumnNames.Address); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Address); else this.Address = base.SetstringAsString(ColumnNames.Address, value); } } public virtual string s_City { get { return this.IsColumnNull(ColumnNames.City) ? string.Empty : base.GetstringAsString(ColumnNames.City); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.City); else this.City = base.SetstringAsString(ColumnNames.City, value); } } public virtual string s_Region { get { return this.IsColumnNull(ColumnNames.Region) ? string.Empty : base.GetstringAsString(ColumnNames.Region); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Region); else this.Region = base.SetstringAsString(ColumnNames.Region, value); } } public virtual string s_PostalCode { get { return this.IsColumnNull(ColumnNames.PostalCode) ? string.Empty : base.GetstringAsString(ColumnNames.PostalCode); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.PostalCode); else this.PostalCode = base.SetstringAsString(ColumnNames.PostalCode, value); } } public virtual string s_Country { get { return this.IsColumnNull(ColumnNames.Country) ? string.Empty : base.GetstringAsString(ColumnNames.Country); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Country); else this.Country = base.SetstringAsString(ColumnNames.Country, value); } } public virtual string s_Phone { get { return this.IsColumnNull(ColumnNames.Phone) ? string.Empty : base.GetstringAsString(ColumnNames.Phone); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Phone); else this.Phone = base.SetstringAsString(ColumnNames.Phone, value); } } public virtual string s_Fax { get { return this.IsColumnNull(ColumnNames.Fax) ? string.Empty : base.GetstringAsString(ColumnNames.Fax); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.Fax); else this.Fax = base.SetstringAsString(ColumnNames.Fax, value); } } public virtual string s_HomePage { get { return this.IsColumnNull(ColumnNames.HomePage) ? string.Empty : base.GetstringAsString(ColumnNames.HomePage); } set { if(string.Empty == value) this.SetColumnNull(ColumnNames.HomePage); else this.HomePage = base.SetstringAsString(ColumnNames.HomePage, value); } } #endregion #region Where Clause public class WhereClause { public WhereClause(BusinessEntity entity) { this._entity = entity; } public TearOffWhereParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffWhereParameter(this); } return _tearOff; } } #region WhereParameter TearOff's public class TearOffWhereParameter { public TearOffWhereParameter(WhereClause clause) { this._clause = clause; } public WhereParameter SupplierID { get { WhereParameter where = new WhereParameter(ColumnNames.SupplierID, Parameters.SupplierID); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter CompanyName { get { WhereParameter where = new WhereParameter(ColumnNames.CompanyName, Parameters.CompanyName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ContactName { get { WhereParameter where = new WhereParameter(ColumnNames.ContactName, Parameters.ContactName); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter ContactTitle { get { WhereParameter where = new WhereParameter(ColumnNames.ContactTitle, Parameters.ContactTitle); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Address { get { WhereParameter where = new WhereParameter(ColumnNames.Address, Parameters.Address); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter City { get { WhereParameter where = new WhereParameter(ColumnNames.City, Parameters.City); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Region { get { WhereParameter where = new WhereParameter(ColumnNames.Region, Parameters.Region); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter PostalCode { get { WhereParameter where = new WhereParameter(ColumnNames.PostalCode, Parameters.PostalCode); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Country { get { WhereParameter where = new WhereParameter(ColumnNames.Country, Parameters.Country); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Phone { get { WhereParameter where = new WhereParameter(ColumnNames.Phone, Parameters.Phone); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter Fax { get { WhereParameter where = new WhereParameter(ColumnNames.Fax, Parameters.Fax); this._clause._entity.Query.AddWhereParameter(where); return where; } } public WhereParameter HomePage { get { WhereParameter where = new WhereParameter(ColumnNames.HomePage, Parameters.HomePage); this._clause._entity.Query.AddWhereParameter(where); return where; } } private WhereClause _clause; } #endregion public WhereParameter SupplierID { get { if(_SupplierID_W == null) { _SupplierID_W = TearOff.SupplierID; } return _SupplierID_W; } } public WhereParameter CompanyName { get { if(_CompanyName_W == null) { _CompanyName_W = TearOff.CompanyName; } return _CompanyName_W; } } public WhereParameter ContactName { get { if(_ContactName_W == null) { _ContactName_W = TearOff.ContactName; } return _ContactName_W; } } public WhereParameter ContactTitle { get { if(_ContactTitle_W == null) { _ContactTitle_W = TearOff.ContactTitle; } return _ContactTitle_W; } } public WhereParameter Address { get { if(_Address_W == null) { _Address_W = TearOff.Address; } return _Address_W; } } public WhereParameter City { get { if(_City_W == null) { _City_W = TearOff.City; } return _City_W; } } public WhereParameter Region { get { if(_Region_W == null) { _Region_W = TearOff.Region; } return _Region_W; } } public WhereParameter PostalCode { get { if(_PostalCode_W == null) { _PostalCode_W = TearOff.PostalCode; } return _PostalCode_W; } } public WhereParameter Country { get { if(_Country_W == null) { _Country_W = TearOff.Country; } return _Country_W; } } public WhereParameter Phone { get { if(_Phone_W == null) { _Phone_W = TearOff.Phone; } return _Phone_W; } } public WhereParameter Fax { get { if(_Fax_W == null) { _Fax_W = TearOff.Fax; } return _Fax_W; } } public WhereParameter HomePage { get { if(_HomePage_W == null) { _HomePage_W = TearOff.HomePage; } return _HomePage_W; } } private WhereParameter _SupplierID_W = null; private WhereParameter _CompanyName_W = null; private WhereParameter _ContactName_W = null; private WhereParameter _ContactTitle_W = null; private WhereParameter _Address_W = null; private WhereParameter _City_W = null; private WhereParameter _Region_W = null; private WhereParameter _PostalCode_W = null; private WhereParameter _Country_W = null; private WhereParameter _Phone_W = null; private WhereParameter _Fax_W = null; private WhereParameter _HomePage_W = null; public void WhereClauseReset() { _SupplierID_W = null; _CompanyName_W = null; _ContactName_W = null; _ContactTitle_W = null; _Address_W = null; _City_W = null; _Region_W = null; _PostalCode_W = null; _Country_W = null; _Phone_W = null; _Fax_W = null; _HomePage_W = null; this._entity.Query.FlushWhereParameters(); } private BusinessEntity _entity; private TearOffWhereParameter _tearOff; } public WhereClause Where { get { if(_whereClause == null) { _whereClause = new WhereClause(this); } return _whereClause; } } private WhereClause _whereClause = null; #endregion #region Aggregate Clause public class AggregateClause { public AggregateClause(BusinessEntity entity) { this._entity = entity; } public TearOffAggregateParameter TearOff { get { if(_tearOff == null) { _tearOff = new TearOffAggregateParameter(this); } return _tearOff; } } #region AggregateParameter TearOff's public class TearOffAggregateParameter { public TearOffAggregateParameter(AggregateClause clause) { this._clause = clause; } public AggregateParameter SupplierID { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.SupplierID, Parameters.SupplierID); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter CompanyName { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.CompanyName, Parameters.CompanyName); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ContactName { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ContactName, Parameters.ContactName); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter ContactTitle { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.ContactTitle, Parameters.ContactTitle); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Address { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Address, Parameters.Address); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter City { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.City, Parameters.City); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Region { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Region, Parameters.Region); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter PostalCode { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.PostalCode, Parameters.PostalCode); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Country { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Country, Parameters.Country); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Phone { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Phone, Parameters.Phone); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter Fax { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.Fax, Parameters.Fax); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } public AggregateParameter HomePage { get { AggregateParameter aggregate = new AggregateParameter(ColumnNames.HomePage, Parameters.HomePage); this._clause._entity.Query.AddAggregateParameter(aggregate); return aggregate; } } private AggregateClause _clause; } #endregion public AggregateParameter SupplierID { get { if(_SupplierID_W == null) { _SupplierID_W = TearOff.SupplierID; } return _SupplierID_W; } } public AggregateParameter CompanyName { get { if(_CompanyName_W == null) { _CompanyName_W = TearOff.CompanyName; } return _CompanyName_W; } } public AggregateParameter ContactName { get { if(_ContactName_W == null) { _ContactName_W = TearOff.ContactName; } return _ContactName_W; } } public AggregateParameter ContactTitle { get { if(_ContactTitle_W == null) { _ContactTitle_W = TearOff.ContactTitle; } return _ContactTitle_W; } } public AggregateParameter Address { get { if(_Address_W == null) { _Address_W = TearOff.Address; } return _Address_W; } } public AggregateParameter City { get { if(_City_W == null) { _City_W = TearOff.City; } return _City_W; } } public AggregateParameter Region { get { if(_Region_W == null) { _Region_W = TearOff.Region; } return _Region_W; } } public AggregateParameter PostalCode { get { if(_PostalCode_W == null) { _PostalCode_W = TearOff.PostalCode; } return _PostalCode_W; } } public AggregateParameter Country { get { if(_Country_W == null) { _Country_W = TearOff.Country; } return _Country_W; } } public AggregateParameter Phone { get { if(_Phone_W == null) { _Phone_W = TearOff.Phone; } return _Phone_W; } } public AggregateParameter Fax { get { if(_Fax_W == null) { _Fax_W = TearOff.Fax; } return _Fax_W; } } public AggregateParameter HomePage { get { if(_HomePage_W == null) { _HomePage_W = TearOff.HomePage; } return _HomePage_W; } } private AggregateParameter _SupplierID_W = null; private AggregateParameter _CompanyName_W = null; private AggregateParameter _ContactName_W = null; private AggregateParameter _ContactTitle_W = null; private AggregateParameter _Address_W = null; private AggregateParameter _City_W = null; private AggregateParameter _Region_W = null; private AggregateParameter _PostalCode_W = null; private AggregateParameter _Country_W = null; private AggregateParameter _Phone_W = null; private AggregateParameter _Fax_W = null; private AggregateParameter _HomePage_W = null; public void AggregateClauseReset() { _SupplierID_W = null; _CompanyName_W = null; _ContactName_W = null; _ContactTitle_W = null; _Address_W = null; _City_W = null; _Region_W = null; _PostalCode_W = null; _Country_W = null; _Phone_W = null; _Fax_W = null; _HomePage_W = null; this._entity.Query.FlushAggregateParameters(); } private BusinessEntity _entity; private TearOffAggregateParameter _tearOff; } public AggregateClause Aggregate { get { if(_aggregateClause == null) { _aggregateClause = new AggregateClause(this); } return _aggregateClause; } } private AggregateClause _aggregateClause = null; #endregion protected override IDbCommand GetInsertCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_SuppliersInsert]"; CreateParameters(cmd); SqlParameter p; p = cmd.Parameters[Parameters.SupplierID.ParameterName]; p.Direction = ParameterDirection.Output; return cmd; } protected override IDbCommand GetUpdateCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_SuppliersUpdate]"; CreateParameters(cmd); return cmd; } protected override IDbCommand GetDeleteCommand() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "[" + this.SchemaStoredProcedure + "proc_SuppliersDelete]"; SqlParameter p; p = cmd.Parameters.Add(Parameters.SupplierID); p.SourceColumn = ColumnNames.SupplierID; p.SourceVersion = DataRowVersion.Current; return cmd; } private IDbCommand CreateParameters(SqlCommand cmd) { SqlParameter p; p = cmd.Parameters.Add(Parameters.SupplierID); p.SourceColumn = ColumnNames.SupplierID; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.CompanyName); p.SourceColumn = ColumnNames.CompanyName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ContactName); p.SourceColumn = ColumnNames.ContactName; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.ContactTitle); p.SourceColumn = ColumnNames.ContactTitle; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Address); p.SourceColumn = ColumnNames.Address; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.City); p.SourceColumn = ColumnNames.City; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Region); p.SourceColumn = ColumnNames.Region; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.PostalCode); p.SourceColumn = ColumnNames.PostalCode; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Country); p.SourceColumn = ColumnNames.Country; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Phone); p.SourceColumn = ColumnNames.Phone; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.Fax); p.SourceColumn = ColumnNames.Fax; p.SourceVersion = DataRowVersion.Current; p = cmd.Parameters.Add(Parameters.HomePage); p.SourceColumn = ColumnNames.HomePage; p.SourceVersion = DataRowVersion.Current; return cmd; } } }
using System; using Raksha.Crypto; namespace Raksha.Crypto.Digests { /** * Implementation of WhirlpoolDigest, based on Java source published by Barreto * and Rijmen. * */ public sealed class WhirlpoolDigest : IDigest { private const int BYTE_LENGTH = 64; private const int DIGEST_LENGTH_BYTES = 512 / 8; private const int ROUNDS = 10; private const int REDUCTION_POLYNOMIAL = 0x011d; // 2^8 + 2^4 + 2^3 + 2 + 1; private static readonly int[] SBOX = { 0x18, 0x23, 0xc6, 0xe8, 0x87, 0xb8, 0x01, 0x4f, 0x36, 0xa6, 0xd2, 0xf5, 0x79, 0x6f, 0x91, 0x52, 0x60, 0xbc, 0x9b, 0x8e, 0xa3, 0x0c, 0x7b, 0x35, 0x1d, 0xe0, 0xd7, 0xc2, 0x2e, 0x4b, 0xfe, 0x57, 0x15, 0x77, 0x37, 0xe5, 0x9f, 0xf0, 0x4a, 0xda, 0x58, 0xc9, 0x29, 0x0a, 0xb1, 0xa0, 0x6b, 0x85, 0xbd, 0x5d, 0x10, 0xf4, 0xcb, 0x3e, 0x05, 0x67, 0xe4, 0x27, 0x41, 0x8b, 0xa7, 0x7d, 0x95, 0xd8, 0xfb, 0xee, 0x7c, 0x66, 0xdd, 0x17, 0x47, 0x9e, 0xca, 0x2d, 0xbf, 0x07, 0xad, 0x5a, 0x83, 0x33, 0x63, 0x02, 0xaa, 0x71, 0xc8, 0x19, 0x49, 0xd9, 0xf2, 0xe3, 0x5b, 0x88, 0x9a, 0x26, 0x32, 0xb0, 0xe9, 0x0f, 0xd5, 0x80, 0xbe, 0xcd, 0x34, 0x48, 0xff, 0x7a, 0x90, 0x5f, 0x20, 0x68, 0x1a, 0xae, 0xb4, 0x54, 0x93, 0x22, 0x64, 0xf1, 0x73, 0x12, 0x40, 0x08, 0xc3, 0xec, 0xdb, 0xa1, 0x8d, 0x3d, 0x97, 0x00, 0xcf, 0x2b, 0x76, 0x82, 0xd6, 0x1b, 0xb5, 0xaf, 0x6a, 0x50, 0x45, 0xf3, 0x30, 0xef, 0x3f, 0x55, 0xa2, 0xea, 0x65, 0xba, 0x2f, 0xc0, 0xde, 0x1c, 0xfd, 0x4d, 0x92, 0x75, 0x06, 0x8a, 0xb2, 0xe6, 0x0e, 0x1f, 0x62, 0xd4, 0xa8, 0x96, 0xf9, 0xc5, 0x25, 0x59, 0x84, 0x72, 0x39, 0x4c, 0x5e, 0x78, 0x38, 0x8c, 0xd1, 0xa5, 0xe2, 0x61, 0xb3, 0x21, 0x9c, 0x1e, 0x43, 0xc7, 0xfc, 0x04, 0x51, 0x99, 0x6d, 0x0d, 0xfa, 0xdf, 0x7e, 0x24, 0x3b, 0xab, 0xce, 0x11, 0x8f, 0x4e, 0xb7, 0xeb, 0x3c, 0x81, 0x94, 0xf7, 0xb9, 0x13, 0x2c, 0xd3, 0xe7, 0x6e, 0xc4, 0x03, 0x56, 0x44, 0x7f, 0xa9, 0x2a, 0xbb, 0xc1, 0x53, 0xdc, 0x0b, 0x9d, 0x6c, 0x31, 0x74, 0xf6, 0x46, 0xac, 0x89, 0x14, 0xe1, 0x16, 0x3a, 0x69, 0x09, 0x70, 0xb6, 0xd0, 0xed, 0xcc, 0x42, 0x98, 0xa4, 0x28, 0x5c, 0xf8, 0x86 }; private static readonly long[] C0 = new long[256]; private static readonly long[] C1 = new long[256]; private static readonly long[] C2 = new long[256]; private static readonly long[] C3 = new long[256]; private static readonly long[] C4 = new long[256]; private static readonly long[] C5 = new long[256]; private static readonly long[] C6 = new long[256]; private static readonly long[] C7 = new long[256]; private readonly long[] _rc = new long[ROUNDS + 1]; /* * increment() can be implemented in this way using 2 arrays or * by having some temporary variables that are used to set the * value provided by EIGHT[i] and carry within the loop. * * not having done any timing, this seems likely to be faster * at the slight expense of 32*(sizeof short) bytes */ private static readonly short[] EIGHT = new short[BITCOUNT_ARRAY_SIZE]; static WhirlpoolDigest() { EIGHT[BITCOUNT_ARRAY_SIZE - 1] = 8; for (int i = 0; i < 256; i++) { int v1 = SBOX[i]; int v2 = maskWithReductionPolynomial(v1 << 1); int v4 = maskWithReductionPolynomial(v2 << 1); int v5 = v4 ^ v1; int v8 = maskWithReductionPolynomial(v4 << 1); int v9 = v8 ^ v1; C0[i] = packIntoLong(v1, v1, v4, v1, v8, v5, v2, v9); C1[i] = packIntoLong(v9, v1, v1, v4, v1, v8, v5, v2); C2[i] = packIntoLong(v2, v9, v1, v1, v4, v1, v8, v5); C3[i] = packIntoLong(v5, v2, v9, v1, v1, v4, v1, v8); C4[i] = packIntoLong(v8, v5, v2, v9, v1, v1, v4, v1); C5[i] = packIntoLong(v1, v8, v5, v2, v9, v1, v1, v4); C6[i] = packIntoLong(v4, v1, v8, v5, v2, v9, v1, v1); C7[i] = packIntoLong(v1, v4, v1, v8, v5, v2, v9, v1); } } public WhirlpoolDigest() { _rc[0] = 0L; for (int r = 1; r <= ROUNDS; r++) { int i = 8 * (r - 1); _rc[r] = (long)((ulong)C0[i] & 0xff00000000000000L) ^ (C1[i + 1] & (long) 0x00ff000000000000L) ^ (C2[i + 2] & (long) 0x0000ff0000000000L) ^ (C3[i + 3] & (long) 0x000000ff00000000L) ^ (C4[i + 4] & (long) 0x00000000ff000000L) ^ (C5[i + 5] & (long) 0x0000000000ff0000L) ^ (C6[i + 6] & (long) 0x000000000000ff00L) ^ (C7[i + 7] & (long) 0x00000000000000ffL); } } private static long packIntoLong(int b7, int b6, int b5, int b4, int b3, int b2, int b1, int b0) { return ((long)b7 << 56) ^ ((long)b6 << 48) ^ ((long)b5 << 40) ^ ((long)b4 << 32) ^ ((long)b3 << 24) ^ ((long)b2 << 16) ^ ((long)b1 << 8) ^ b0; } /* * int's are used to prevent sign extension. The values that are really being used are * actually just 0..255 */ private static int maskWithReductionPolynomial(int input) { int rv = input; if (rv >= 0x100L) // high bit set { rv ^= REDUCTION_POLYNOMIAL; // reduced by the polynomial } return rv; } // --------------------------------------------------------------------------------------// // -- buffer information -- private const int BITCOUNT_ARRAY_SIZE = 32; private byte[] _buffer = new byte[64]; private int _bufferPos; private short[] _bitCount = new short[BITCOUNT_ARRAY_SIZE]; // -- internal hash state -- private long[] _hash = new long[8]; private long[] _K = new long[8]; // the round key private long[] _L = new long[8]; private long[] _block = new long[8]; // mu (buffer) private long[] _state = new long[8]; // the current "cipher" state /** * Copy constructor. This will copy the state of the provided message * digest. */ public WhirlpoolDigest(WhirlpoolDigest originalDigest) { Array.Copy(originalDigest._rc, 0, _rc, 0, _rc.Length); Array.Copy(originalDigest._buffer, 0, _buffer, 0, _buffer.Length); this._bufferPos = originalDigest._bufferPos; Array.Copy(originalDigest._bitCount, 0, _bitCount, 0, _bitCount.Length); // -- internal hash state -- Array.Copy(originalDigest._hash, 0, _hash, 0, _hash.Length); Array.Copy(originalDigest._K, 0, _K, 0, _K.Length); Array.Copy(originalDigest._L, 0, _L, 0, _L.Length); Array.Copy(originalDigest._block, 0, _block, 0, _block.Length); Array.Copy(originalDigest._state, 0, _state, 0, _state.Length); } public string AlgorithmName { get { return "Whirlpool"; } } public int GetDigestSize() { return DIGEST_LENGTH_BYTES; } public int DoFinal(byte[] output, int outOff) { // sets output[outOff] .. output[outOff+DIGEST_LENGTH_BYTES] finish(); for (int i = 0; i < 8; i++) { convertLongToByteArray(_hash[i], output, outOff + (i * 8)); } Reset(); return GetDigestSize(); } /** * Reset the chaining variables */ public void Reset() { // set variables to null, blank, whatever _bufferPos = 0; Array.Clear(_bitCount, 0, _bitCount.Length); Array.Clear(_buffer, 0, _buffer.Length); Array.Clear(_hash, 0, _hash.Length); Array.Clear(_K, 0, _K.Length); Array.Clear(_L, 0, _L.Length); Array.Clear(_block, 0, _block.Length); Array.Clear(_state, 0, _state.Length); } // this takes a buffer of information and fills the block private void processFilledBuffer() { // copies into the block... for (int i = 0; i < _state.Length; i++) { _block[i] = bytesToLongFromBuffer(_buffer, i * 8); } processBlock(); _bufferPos = 0; Array.Clear(_buffer, 0, _buffer.Length); } private static long bytesToLongFromBuffer(byte[] buffer, int startPos) { long rv = (((buffer[startPos + 0] & 0xffL) << 56) | ((buffer[startPos + 1] & 0xffL) << 48) | ((buffer[startPos + 2] & 0xffL) << 40) | ((buffer[startPos + 3] & 0xffL) << 32) | ((buffer[startPos + 4] & 0xffL) << 24) | ((buffer[startPos + 5] & 0xffL) << 16) | ((buffer[startPos + 6] & 0xffL) << 8) | ((buffer[startPos + 7]) & 0xffL)); return rv; } private static void convertLongToByteArray(long inputLong, byte[] outputArray, int offSet) { for (int i = 0; i < 8; i++) { outputArray[offSet + i] = (byte)((inputLong >> (56 - (i * 8))) & 0xff); } } private void processBlock() { // buffer contents have been transferred to the _block[] array via // processFilledBuffer // compute and apply K^0 for (int i = 0; i < 8; i++) { _state[i] = _block[i] ^ (_K[i] = _hash[i]); } // iterate over the rounds for (int round = 1; round <= ROUNDS; round++) { for (int i = 0; i < 8; i++) { _L[i] = 0; _L[i] ^= C0[(int)(_K[(i - 0) & 7] >> 56) & 0xff]; _L[i] ^= C1[(int)(_K[(i - 1) & 7] >> 48) & 0xff]; _L[i] ^= C2[(int)(_K[(i - 2) & 7] >> 40) & 0xff]; _L[i] ^= C3[(int)(_K[(i - 3) & 7] >> 32) & 0xff]; _L[i] ^= C4[(int)(_K[(i - 4) & 7] >> 24) & 0xff]; _L[i] ^= C5[(int)(_K[(i - 5) & 7] >> 16) & 0xff]; _L[i] ^= C6[(int)(_K[(i - 6) & 7] >> 8) & 0xff]; _L[i] ^= C7[(int)(_K[(i - 7) & 7]) & 0xff]; } Array.Copy(_L, 0, _K, 0, _K.Length); _K[0] ^= _rc[round]; // apply the round transformation for (int i = 0; i < 8; i++) { _L[i] = _K[i]; _L[i] ^= C0[(int)(_state[(i - 0) & 7] >> 56) & 0xff]; _L[i] ^= C1[(int)(_state[(i - 1) & 7] >> 48) & 0xff]; _L[i] ^= C2[(int)(_state[(i - 2) & 7] >> 40) & 0xff]; _L[i] ^= C3[(int)(_state[(i - 3) & 7] >> 32) & 0xff]; _L[i] ^= C4[(int)(_state[(i - 4) & 7] >> 24) & 0xff]; _L[i] ^= C5[(int)(_state[(i - 5) & 7] >> 16) & 0xff]; _L[i] ^= C6[(int)(_state[(i - 6) & 7] >> 8) & 0xff]; _L[i] ^= C7[(int)(_state[(i - 7) & 7]) & 0xff]; } // save the current state Array.Copy(_L, 0, _state, 0, _state.Length); } // apply Miuaguchi-Preneel compression for (int i = 0; i < 8; i++) { _hash[i] ^= _state[i] ^ _block[i]; } } public void Update(byte input) { _buffer[_bufferPos] = input; //Console.WriteLine("adding to buffer = "+_buffer[_bufferPos]); ++_bufferPos; if (_bufferPos == _buffer.Length) { processFilledBuffer(); } increment(); } private void increment() { int carry = 0; for (int i = _bitCount.Length - 1; i >= 0; i--) { int sum = (_bitCount[i] & 0xff) + EIGHT[i] + carry; carry = sum >> 8; _bitCount[i] = (short)(sum & 0xff); } } public void BlockUpdate(byte[] input, int inOff, int length) { while (length > 0) { Update(input[inOff]); ++inOff; --length; } } private void finish() { /* * this makes a copy of the current bit length. at the expense of an * object creation of 32 bytes rather than providing a _stopCounting * boolean which was the alternative I could think of. */ byte[] bitLength = copyBitLength(); _buffer[_bufferPos++] |= 0x80; if (_bufferPos == _buffer.Length) { processFilledBuffer(); } /* * Final block contains * [ ... data .... ][0][0][0][ length ] * * if [ length ] cannot fit. Need to create a new block. */ if (_bufferPos > 32) { while (_bufferPos != 0) { Update((byte)0); } } while (_bufferPos <= 32) { Update((byte)0); } // copy the length information to the final 32 bytes of the // 64 byte block.... Array.Copy(bitLength, 0, _buffer, 32, bitLength.Length); processFilledBuffer(); } private byte[] copyBitLength() { byte[] rv = new byte[BITCOUNT_ARRAY_SIZE]; for (int i = 0; i < rv.Length; i++) { rv[i] = (byte)(_bitCount[i] & 0xff); } return rv; } public int GetByteLength() { return BYTE_LENGTH; } } }
namespace Microsoft.Protocols.TestSuites.MS_OXCFXICS { using System; /// <summary> /// The messageChangeFull element contains the complete content of /// a new or changed message: the message properties, the recipients, /// and the attachments. /// messageChangeFull = IncrSyncChg messageChangeHeader /// IncrSyncMessage propList /// MessageChildren /// </summary> public class MessageChangeFull : MessageChange { /// <summary> /// A messageChangeHeader value. /// </summary> private MessageChangeHeader messageChangeHeader; /// <summary> /// A propList value. /// </summary> private PropList propList; /// <summary> /// A MessageChildren value. /// </summary> private MessageChildren messageChildren; /// <summary> /// Initializes a new instance of the MessageChangeFull class. /// </summary> /// <param name="stream">A FastTransferStream.</param> public MessageChangeFull(FastTransferStream stream) : base(stream) { } /// <summary> /// Gets LastModificationTime. /// </summary> public override DateTime LastModificationTime { get { return this.MessageChangeHeader.LastModificationTime; } } /// <summary> /// Gets LastModificationTime. /// </summary> public DateTime MessageDeliveryTime { get { if (this.PropList != null) { ulong t = Convert.ToUInt64(this.PropList.GetPropValue(0x0E06, 0x0040)); return DateTime.FromBinary((long)t); } AdapterHelper.Site.Assert.Fail("The PropList should not be null."); return DateTime.Now; } } /// <summary> /// Gets a value indicating whether has a rtf body. /// </summary> public bool IsRTFFormat { get { if (this.PropList != null) { return this.PropList.HasPropertyTag(0x1009, 0x0102); } return false; } } /// <summary> /// Gets a value indicating whether all subObjects of this are in rtf format. /// </summary> public bool IsAllRTFFormat { get { if (this.PropList != null) { bool flag = this.PropList.HasPropertyTag(0x1009, 0x0102); if (flag) { if (this.messageChildren != null && this.messageChildren.Attachments != null && this.messageChildren.Attachments.Count > 0) { foreach (Attachment atta in this.messageChildren.Attachments) { flag = flag && atta.IsRTFFormat; if (!flag) { return false; } } } } return flag; } return false; } } /// <summary> /// Gets a value indicating whether has PidTagMid. /// </summary> public override bool HasPidTagMid { get { return this.MessageChangeHeader.HasPidTagMid; } } /// <summary> /// Gets a value indicating whether has PidTagMessageSize. /// </summary> public override bool HasPidTagMessageSize { get { return this.MessageChangeHeader.HasPidTagMessageSize; } } /// <summary> /// Gets a value indicating whether has PidTagChangeNumber. /// </summary> public override bool HasPidTagChangeNumber { get { return this.MessageChangeHeader.HasPidTagChangeNumber; } } /// <summary> /// Gets a value indicating the sourceKey property. /// </summary> public override byte[] SourceKey { get { return this.MessageChangeHeader.SourceKey; } } /// <summary> /// Gets a value indicating the PidTagChangeKey. /// </summary> public override byte[] PidTagChangeKey { get { return this.messageChangeHeader.PidTagChangeKey; } } /// <summary> /// Gets a value indicating the PidTagChangeNumber. /// </summary> public override long PidTagChangeNumber { get { return this.messageChangeHeader.PidTagChangeNumber; } } /// <summary> /// Gets a value indicating the PidTagMid. /// </summary> public override long PidTagMid { get { return this.messageChangeHeader.PidTagMid; } } /// <summary> /// Gets or sets messageChangeHeader. /// </summary> public MessageChangeHeader MessageChangeHeader { get { return this.messageChangeHeader; } set { this.messageChangeHeader = value; } } /// <summary> /// Gets or sets propList. /// </summary> public PropList PropList { get { return this.propList; } set { this.propList = value; } } /// <summary> /// Gets or sets MessageChildren. /// </summary> public MessageChildren MessageChildren { get { return this.messageChildren; } set { this.messageChildren = value; } } /// <summary> /// Verify that a stream's current position contains a serialized messageChangeFull. /// </summary> /// <param name="stream">A FastTransferStream.</param> /// <returns>If the stream's current position contains /// a serialized messageChangeFull, return true, else false.</returns> public static new bool Verify(FastTransferStream stream) { return stream.VerifyMarker(Markers.PidTagIncrSyncChg); } /// <summary> /// Deserialize fields from a FastTransferStream. /// </summary> /// <param name="stream">A FastTransferStream.</param> public override void Deserialize(FastTransferStream stream) { if (stream.ReadMarker(Markers.PidTagIncrSyncChg)) { this.messageChangeHeader = new MessageChangeHeader(stream); if (stream.ReadMarker(Markers.PidTagIncrSyncMessage)) { this.propList = new PropList(stream); this.messageChildren = new MessageChildren(stream); return; } } AdapterHelper.Site.Assert.Fail("The stream cannot be deserialized successfully."); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using log4net; using NetGore.IO; using SFML; using SFML.Audio; using SFML.Graphics; namespace NetGore.Content { /// <summary> /// An implementation of <see cref="IContentManager"/> for managing content in various levels of persistence. /// This way you can easily clear groups of content instead of clearing and having to re-load all content. /// </summary> public class ContentManager : IContentManager { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// When the length of a file name for a lazy asset exceeds this length, trim it down to only show the /// last characters, length of which is defined by <see cref="_lazyAssetTrimmedFileNameLength"/>. /// </summary> const int _lazyAssetTrimFileNameLength = 105; /// <summary> /// The length of a trimmed file name for lazy asset. /// </summary> const int _lazyAssetTrimmedFileNameLength = 100; /// <summary> /// Gets the minimum amount of time that an asset must go unused before being unloaded. /// </summary> const int _minElapsedTimeToUnload = 1000 * 60; // 1 minute static readonly object _instanceSync = new object(); static readonly StringComparer _stringComp = StringComparer.OrdinalIgnoreCase; static IContentManager _instance; readonly object _assetSync = new object(); readonly Dictionary<string, IMyLazyAsset>[] _loadedAssets; readonly Dictionary<string, IMyLazyAsset> _trackedLoads = new Dictionary<string, IMyLazyAsset>(_stringComp); bool _isDisposed = false; bool _isTrackingLoads = false; /// <summary> /// Initializes a new instance of the <see cref="ContentManager"/> class. /// </summary> ContentManager() { RootDirectory = ContentPaths.Build.Root; // Create the dictionaries for each level var maxLevel = EnumHelper<ContentLevel>.MaxValue; _loadedAssets = new Dictionary<string, IMyLazyAsset>[maxLevel + 1]; for (var i = 0; i < _loadedAssets.Length; i++) { _loadedAssets[i] = new Dictionary<string, IMyLazyAsset>(_stringComp); } } /// <summary> /// Changes the <see cref="ContentLevel"/> of an asset. This should only be called from a block /// locked by <see cref="_assetSync"/>. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="oldLevel">The old <see cref="ContentLevel"/>.</param> /// <param name="newLevel">The new <see cref="ContentLevel"/>.</param> /// <returns>True if the change was successful; false if the asset is not loaded or was not /// in the <paramref name="oldLevel"/>.</returns> bool ChangeAssetLevelNoLock(string assetName, ContentLevel oldLevel, ContentLevel newLevel) { if (oldLevel == newLevel) return false; // Grab from the old dictionary var oldDict = _loadedAssets[(int)oldLevel]; IMyLazyAsset asset; if (!oldDict.TryGetValue(assetName, out asset)) return false; // Remove if (!oldDict.Remove(assetName)) Debug.Fail("Uhm... how the hell...?"); // Add to the new dictionary var newDict = _loadedAssets[(int)newLevel]; newDict.Add(assetName, asset); return true; } /// <summary> /// Creates a <see cref="IContentManager"/>. /// </summary> /// <returns>The <see cref="IContentManager"/> instance.</returns> public static IContentManager Create() { lock (_instanceSync) { return _instance ?? (_instance = new ContentManager()); } } /// <summary> /// Disposes of the content manager. /// </summary> /// <param name="disposeManaged">If false, this was called from the destructor.</param> protected virtual void Dispose(bool disposeManaged) { Unload(); } /// <summary> /// Does the actual work of unloading assets. /// </summary> /// <param name="level">The <see cref="ContentLevel"/> of the content to unload.</param> /// <param name="ignoreTime">If true, the last-used time will be ignored.</param> void DoUnload(ContentLevel level, bool ignoreTime) { var currTime = TickCount.Now; lock (_assetSync) { // Loop through the given level and all levels below it for (var i = (int)level; i < _loadedAssets.Length; i++) { // Get the dictionary for the level var dic = _loadedAssets[i]; // Dispose all items that haven't been used for the needed amount of time foreach (var asset in dic.Values) { try { if (!ignoreTime && (currTime - asset.LastUsedTime < _minElapsedTimeToUnload)) continue; asset.Dispose(); } catch (Exception ex) { const string errmsg = "Failed to dispose asset `{0}`: {1}"; if (log.IsWarnEnabled) log.WarnFormat(errmsg, asset, ex); Debug.Fail(string.Format(errmsg, asset, ex)); } } } } } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="ContentManager"/> is reclaimed by garbage collection. /// </summary> ~ContentManager() { Dispose(false); } /// <summary> /// Gets the absolute file path for an asset. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <returns>The absolute file path for the <paramref name="assetName"/>.</returns> public static string GetAssetPath(string assetName) { var pipeIndex = assetName.LastIndexOf('|'); if (pipeIndex > 0) assetName = assetName.Substring(0, pipeIndex); return ContentPaths.Build.Root.Join(assetName + ContentPaths.ContentFileSuffix); } protected static LoadingFailedException InvalidTypeException(object obj, Type expected) { const string errmsg = "Invalid type `{0}` specified for asset `{1}`, which is of type `{2}`."; var err = string.Format(errmsg, expected, obj, obj.GetType()); if (log.IsErrorEnabled) log.Error(err); return new LoadingFailedException(err); } /// <summary> /// Checks if an asset is loaded. /// </summary> /// <param name="assetName">The name of the asset to look for.</param> /// <param name="asset">When this method returns true, contains the asset instance.</param> /// <param name="level">When this method returns true, contains the asset's <see cref="ContentLevel"/>.</param> /// <returns>True if the asset is loaded; otherwise false.</returns> bool IsAssetLoaded(string assetName, out IMyLazyAsset asset, out ContentLevel level) { for (var i = 0; i < _loadedAssets.Length; i++) { if (_loadedAssets[i].TryGetValue(assetName, out asset)) { level = (ContentLevel)i; return true; } } asset = null; level = 0; return false; } /// <summary> /// Gets the ToString() for a lazy asset. /// </summary> /// <param name="type">The name of the lazy asset type.</param> /// <param name="fileName">The file path.</param> /// <returns>The string to display.</returns> static string LazyAssetToString(string type, string fileName) { if (string.IsNullOrEmpty(fileName)) return "Lazy" + type + " []"; else if (fileName.Length > _lazyAssetTrimFileNameLength) { return "Lazy" + type + " [" + fileName.Substring(fileName.Length - _lazyAssetTrimmedFileNameLength, _lazyAssetTrimmedFileNameLength) + "]"; } else return "Lazy" + type + " [" + fileName + "]"; } /// <summary> /// Loads an asset. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="level">The <see cref="ContentLevel"/> to load the asset into.</param> /// <param name="loader">The loader.</param> /// <returns>The loaded asset.</returns> /// <exception cref="ObjectDisposedException"><c>ObjectDisposedException</c>.</exception> /// <exception cref="ArgumentNullException">Argument is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><c>level</c> is out of range.</exception> IMyLazyAsset Load(string assetName, ContentLevel level, Func<string, IMyLazyAsset> loader) { if (IsDisposed) throw new ObjectDisposedException(ToString()); if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); var levelInt = (int)level; if (levelInt >= _loadedAssets.Length || levelInt < 0) throw new ArgumentOutOfRangeException("level", string.Format("Invalid ContentLevel `{0}` value specified.", level)); lock (_assetSync) { // Check if the asset is already loaded IMyLazyAsset existingAsset; ContentLevel existingLevel; if (IsAssetLoaded(assetName, out existingAsset, out existingLevel)) { // If the specified level parameter is greater than the asset's current level, promote it if (level < existingLevel) { var success = ChangeAssetLevelNoLock(assetName, existingLevel, level); Debug.Assert(success); } return existingAsset; } // Load a new asset and add it into the appropriate level var asset = loader(assetName); _loadedAssets[levelInt].Add(assetName, asset); if (IsTrackingLoads && !_trackedLoads.ContainsKey(assetName)) _trackedLoads.Add(assetName, asset); return asset; } } /// <summary> /// Reads an asset from file. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="fontSize">The font size.</param> /// <returns>The loaded asset.</returns> /// <exception cref="ObjectDisposedException"><c>ObjectDisposedException</c>.</exception> /// <exception cref="ArgumentNullException">Argument is null.</exception> protected Font ReadAssetFont(string assetName, int fontSize) { if (IsDisposed) throw new ObjectDisposedException(ToString()); if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); var ret = new MyLazyFont(GetAssetPath(assetName), (uint)fontSize); return ret; } /// <summary> /// Reads an asset from file. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <returns>The asset instance.</returns> /// <exception cref="ObjectDisposedException"><c>ObjectDisposedException</c>.</exception> /// <exception cref="ArgumentNullException">Argument is null.</exception> protected Texture ReadAssetImage(string assetName) { if (IsDisposed) throw new ObjectDisposedException(ToString()); if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); var path = GetAssetPath(assetName); var ret = new MyLazyImage(path); return ret; } /// <summary> /// Reads an asset from file. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <returns>The loaded asset.</returns> /// <exception cref="ObjectDisposedException"><c>ObjectDisposedException</c>.</exception> /// <exception cref="ArgumentNullException">Argument is null.</exception> protected SoundBuffer ReadAssetSoundBuffer(string assetName) { if (IsDisposed) throw new ObjectDisposedException(ToString()); if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); var ret = new MyLazySoundBuffer(GetAssetPath(assetName)); return ret; } static string SanitizeAssetName(string assetName) { return assetName.Replace('\\', '/'); } #region IContentManager Members /// <summary> /// Gets if this object is disposed. /// </summary> /// <value></value> public bool IsDisposed { get { return _isDisposed; } } /// <summary> /// Gets if <see cref="IContentManager.BeginTrackingLoads"/> has been called and loaded items are being tracked. /// This will be set false when <see cref="IContentManager.EndTrackingLoads"/> is called. /// </summary> public bool IsTrackingLoads { get { return _isTrackingLoads; } } /// <summary> /// Gets or sets absolute path to the root content directory. The default value, which is /// <see cref="ContentPaths.Build"/>'s root, should be fine for most all cases. /// </summary> public PathString RootDirectory { get; set; } /// <summary> /// Starts tracking items that are loaded by this <see cref="IContentManager"/>. /// </summary> /// <exception cref="InvalidOperationException"><see cref="IContentManager.IsTrackingLoads"/> is true.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "IsTrackingLoads")] public void BeginTrackingLoads() { if (IsTrackingLoads) throw new InvalidOperationException("IsTrackingLoads must be false."); _isTrackingLoads = true; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_isDisposed) return; _isDisposed = true; Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Gets all of the assets that were loaded since <see cref="IContentManager.BeginTrackingLoads"/> was called. /// Content that was unloaded will still be included in the returned collection. /// </summary> /// <returns> /// All of the assets that were loaded since <see cref="IContentManager.BeginTrackingLoads"/> /// was called. /// </returns> /// <exception cref="InvalidOperationException"><see cref="IContentManager.IsTrackingLoads"/> is false.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "IsTrackingLoads")] public IEnumerable<KeyValuePair<string, object>> EndTrackingLoads() { if (!IsTrackingLoads) throw new InvalidOperationException("IsTrackingLoads must be true."); _isTrackingLoads = false; var ret = _trackedLoads.Select(x => new KeyValuePair<string, object>(x.Key, x.Value)).ToArray(); _trackedLoads.Clear(); return ret; } /// <summary> /// Loads a <see cref="Font"/> asset. /// </summary> /// <param name="assetName">The name of the asset to load.</param> /// <param name="fontSize">The size of the font.</param> /// <param name="level">The <see cref="ContentLevel"/> to load the asset into.</param> /// <returns>The loaded asset.</returns> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c>.</exception> public Font LoadFont(string assetName, int fontSize, ContentLevel level) { if (assetName == null) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); assetName += "|" + fontSize; var ret = Load(assetName, level, x => (IMyLazyAsset)ReadAssetFont(x, fontSize)); return (Font)ret; } /// <summary> /// Loads an <see cref="Texture"/> asset. /// </summary> /// <param name="assetName">The name of the asset to load.</param> /// <param name="level">The <see cref="ContentLevel"/> to load the asset into.</param> /// <returns>The loaded asset.</returns> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c>.</exception> public Texture LoadImage(string assetName, ContentLevel level) { if (assetName == null) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); var ret = Load(assetName, level, x => (IMyLazyAsset)ReadAssetImage(x)); return (Texture)ret; } /// <summary> /// Loads a <see cref="SoundBuffer"/> asset. /// </summary> /// <param name="assetName">The name of the asset to load.</param> /// <param name="level">The <see cref="ContentLevel"/> to load the asset into.</param> /// <returns>The loaded asset.</returns> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c> or empty.</exception> public SoundBuffer LoadSoundBuffer(string assetName, ContentLevel level) { if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); var ret = Load(assetName, level, x => (IMyLazyAsset)ReadAssetSoundBuffer(x)); return (SoundBuffer)ret; } /// <summary> /// Sets the level of an asset. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="level">The new <see cref="ContentLevel"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c> or empty.</exception> public void SetLevel(string assetName, ContentLevel level) { if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); lock (_assetSync) { IMyLazyAsset asset; ContentLevel currLevel; if (!IsAssetLoaded(assetName, out asset, out currLevel)) return; if (currLevel == level) return; ChangeAssetLevelNoLock(assetName, currLevel, level); } } /// <summary> /// Sets the level of an asset only if the specified level is greater than the current level. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="level">The new <see cref="ContentLevel"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c> or empty.</exception> public void SetLevelMax(string assetName, ContentLevel level) { if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); lock (_assetSync) { IMyLazyAsset asset; ContentLevel currLevel; if (!IsAssetLoaded(assetName, out asset, out currLevel)) return; if (currLevel <= level) return; ChangeAssetLevelNoLock(assetName, currLevel, level); } } /// <summary> /// Sets the level of an asset only if the specified level is lower than the current level. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="level">The new <see cref="ContentLevel"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c> or empty.</exception> public void SetLevelMin(string assetName, ContentLevel level) { if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); lock (_assetSync) { IMyLazyAsset asset; ContentLevel currLevel; if (!IsAssetLoaded(assetName, out asset, out currLevel)) return; if (currLevel >= level) return; ChangeAssetLevelNoLock(assetName, currLevel, level); } } /// <summary> /// Gets the content level of an asset. /// </summary> /// <param name="assetName">The name of the asset.</param> /// <param name="level">When this method returns true, contains the <see cref="ContentLevel"/> /// of the asset.</param> /// <returns>True if the asset was found; otherwise false.</returns> /// <exception cref="ArgumentNullException"><paramref name="assetName" /> is <c>null</c> or empty.</exception> public bool TryGetContentLevel(string assetName, out ContentLevel level) { if (string.IsNullOrEmpty(assetName)) throw new ArgumentNullException("assetName"); assetName = SanitizeAssetName(assetName); lock (_assetSync) { IMyLazyAsset o; return IsAssetLoaded(assetName, out o, out level); } } /// <summary> /// Unloads all content from the specified <see cref="ContentLevel"/>, and all levels /// below that level. /// </summary> /// <param name="level">The level of the content to unload. The content at this level, and all levels below it will be /// unloaded. The default is <see cref="ContentLevel.Global"/> to unload content from all levels.</param> /// <param name="ignoreTime">If true, the content in the <paramref name="level"/> will be forced to be unloaded even /// if it was recently used. By default, this is false to prevent excessive reloading. Usually you will only set this /// value to true if you are processing a lot of content at the same time just once, which usually only happens /// in the editors.</param> public void Unload(ContentLevel level = ContentLevel.Global, bool ignoreTime = false) { if (IsDisposed) return; DoUnload(level, ignoreTime); } #endregion /// <summary> /// Interface for the lazy assets of the <see cref="ContentManager"/>. /// </summary> interface IMyLazyAsset : IDisposable { /// <summary> /// Gets the <see cref="TickCount.Now"/> that this asset was last used. /// </summary> TickCount LastUsedTime { get; } } /// <summary> /// <see cref="LazyFont"/> implementation specifically for the <see cref="ContentManager"/>. /// </summary> sealed class MyLazyFont : LazyFont, IMyLazyAsset { TickCount _lastUsed; /// <summary> /// Initializes a new instance of the <see cref="T:SFML.Graphics.LazyFont"/> class. /// </summary> /// <param name="filename">Font file to load</param><param name="charSize">Character size</param><exception cref="T:SFML.LoadingFailedException"/> public MyLazyFont(string filename, uint charSize) : base(filename, charSize) { _lastUsed = TickCount.Now; } /// <summary> /// Access to the internal pointer of the object. /// For internal use only /// </summary> public override IntPtr CPointer { get { _lastUsed = TickCount.Now; return base.CPointer; } } /// <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() { return LazyAssetToString("Font", FileName); } #region IMyLazyAsset Members /// <summary> /// Gets the <see cref="TickCount.Now"/> that this asset was last used. /// </summary> public TickCount LastUsedTime { get { return _lastUsed; } } #endregion } /// <summary> /// <see cref="LazyTexture"/> implementation specifically for the <see cref="ContentManager"/>. /// </summary> sealed class MyLazyImage : LazyTexture, IMyLazyAsset { TickCount _lastUsed; /// <summary> /// Initializes a new instance of the <see cref="T:SFML.Graphics.LazyImage"/> class. /// </summary> /// <param name="filename">The file name.</param> public MyLazyImage(string filename) : base(filename) { _lastUsed = TickCount.Now; } /// <summary> /// Access to the internal pointer of the object. /// For internal use only /// </summary> public override IntPtr CPointer { get { _lastUsed = TickCount.Now; return base.CPointer; } } /// <summary> /// When overridden in the derived class, handles when the <see cref="T:SFML.Graphics.LazyImage"/> is reloaded. /// </summary> protected override void OnReload() { Smooth = false; using (var img = CopyToImage()) { img.CreateMaskFromColor(EngineSettings.TransparencyColor); Update(img); } } /// <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() { return LazyAssetToString("Image", FileName); } #region IMyLazyAsset Members /// <summary> /// Gets the <see cref="TickCount.Now"/> that this asset was last used. /// </summary> public TickCount LastUsedTime { get { return _lastUsed; } } #endregion } /// <summary> /// <see cref="LazySoundBuffer"/> implementation specifically for the <see cref="ContentManager"/>. /// </summary> sealed class MyLazySoundBuffer : LazySoundBuffer, IMyLazyAsset { TickCount _lastUsed; /// <summary> /// Initializes a new instance of the <see cref="MyLazySoundBuffer"/> class. /// </summary> /// <param name="filename">The file name.</param> public MyLazySoundBuffer(string filename) : base(filename) { _lastUsed = TickCount.Now; } /// <summary> /// Access to the internal pointer of the object. /// For internal use only /// </summary> public override IntPtr CPointer { get { _lastUsed = TickCount.Now; return base.CPointer; } } /// <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() { return LazyAssetToString("SoundBuffer", FileName); } #region IMyLazyAsset Members /// <summary> /// Gets the <see cref="TickCount.Now"/> that this asset was last used. /// </summary> public TickCount LastUsedTime { get { return _lastUsed; } } #endregion } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using Machine.Specifications; using RabbitBus.Configuration; using RabbitBus.Specs.Infrastructure; using RabbitBus.Specs.TestTypes; using RabbitMQ.Client; namespace RabbitBus.Specs.Integration { [Integration] [Subject("Headers Exchange")] public class when_configuring_a_message_with_a_headers_exchange { static IPublishConfigurationContext _publishConfigurationContext; Establish context = () => new BusBuilder().Configure( ctx => _publishConfigurationContext = ctx.Publish<TestMessage>().WithExchange("any", cfg => cfg.Headers())).Build(); It should_set_exchange_type_to_headers = () => ((IPublishInfoSource) _publishConfigurationContext).PublishInfo.ExchangeType.ShouldEqual(ExchangeType.Headers); } [Integration] [Subject("Headers Exchange")] public class when_subscribed_to_recieve_non_matching_messages_from_a_header_exchange { const string SpecId = "EE34BDA4-1175-49D3-9B65-B624F7D01715"; static RabbitExchange _exchange; static Bus _bus; static TestMessage _actualMessage; static readonly TestMessage _default = new TestMessage("error"); static IDictionary _headers; Establish context = () => { _headers = new Dictionary<string, object>(); _headers.Add("header-key", Encoding.UTF8.GetBytes("header key value")); _exchange = new RabbitExchange(SpecId, ExchangeType.Headers); _bus = new BusBuilder().Configure( ctx => ctx.Consume<TestMessage>().WithExchange(SpecId, cfg => cfg.Headers()).WithQueue(SpecId)).Build(); _bus.Connect(); _bus.Subscribe<TestMessage>(messageContext => { _actualMessage = messageContext.Message; }, _headers); }; Cleanup after = () => _bus.Close(); Because of = () => new Action(() => _exchange.Publish(new TestMessage("test"), new Dictionary<string, object>())).BlockUntil( () => _actualMessage != null)(); It should_not_receive_the_message = () => _actualMessage.ShouldBeNull(); } [Integration] [Subject("Headers Exchange")] public class when_subscribed_to_recieve_matching_messages_from_a_header_exchange { const string SpecId = "0B7720E6-CE0F-4BB3-9ED3-82562A203004"; static RabbitExchange _exchange; static Bus _bus; static TestMessage _actualMessage; static readonly TestMessage _default = new TestMessage("error"); static IDictionary _headers; Establish context = () => { _headers = new Dictionary<string, object>(); _headers.Add("header-key", Encoding.UTF8.GetBytes("header key value")); _exchange = new RabbitExchange(SpecId, ExchangeType.Headers); _bus = new BusBuilder().Configure( ctx => ctx.Consume<TestMessage>().WithExchange(SpecId, cfg => cfg.Headers()).WithQueue(SpecId)).Build(); _bus.Connect(); _bus.Subscribe<TestMessage>(messageContext => { _actualMessage = messageContext.Message; }, _headers); }; Cleanup after = () => _bus.Close(); Because of = () => new Action(() => _exchange.Publish(new TestMessage("test"), _headers)).BlockUntil(() => _actualMessage != null)(); It should_receive_the_message = () => _actualMessage.ProvideDefault(() => _default).Text.ShouldEqual("test"); } [Integration] [Subject("Headers exchanges")] public class when_publishing_messages_to_a_headers_exchange2 { const string SpecId = "DDAB5940-9366-41D3-A7C7-28AC6A84A383"; static RabbitQueue _queue; static IBasicProperties _messageProperties; static Bus _bus; Establish context = () => { var headers = new Dictionary<string, object>(); headers.Add("header-key", Encoding.UTF8.GetBytes("header key value")); _bus = new BusBuilder().Configure(ctx => ctx .Publish<TestMessage>() .WithExchange(SpecId, cfg => cfg.Headers())) .Build(); _bus.Connect(); _queue = new RabbitQueue("localhost", SpecId, ExchangeType.Headers, SpecId, false, true, false, true, "", headers); _bus.Publish(new TestMessage("test"), headers); }; Cleanup after = () => { _bus.Close(); _queue.Delete().Close(); }; Because of = () => new Action(() => _messageProperties = _queue.GetMessageProperties<TestMessage>()).ExecuteUntil( () => _messageProperties != null)(); It should_publish_the_message_with_headers = () => _messageProperties.Headers.Keys.ShouldContain("header-key"); } [Integration] [Subject("Headers exchanges")] public class when_publishing_messages_to_a_headers_exchange { const string SpecId = "DDAB5940-9366-41D3-A7C7-28AC6A84A383"; static RabbitQueue _queue; static IBasicProperties _messageProperties; static Bus _bus; Establish context = () => { var headers = new Dictionary<string, object>(); headers.Add("header-key", Encoding.UTF8.GetBytes("header key value")); _bus = new BusBuilder().Configure(ctx => ctx .Publish<TestMessage>() .WithExchange(SpecId, cfg => cfg.Headers())) .Build(); _bus.Connect(); _queue = new RabbitQueue("localhost", SpecId, ExchangeType.Headers, SpecId, false, true, false, true, "", headers); _bus.Publish(new TestMessage("test"), headers); }; Cleanup after = () => { _bus.Close(); _queue.Delete().Close(); }; Because of = () => new Action(() => _messageProperties = _queue.GetMessageProperties<TestMessage>()).ExecuteUntil( () => _messageProperties != null)(); It should_publish_the_message_with_headers = () => _messageProperties.Headers.Keys.ShouldContain("header-key"); } [Integration] [Subject("Headers exchanges")] public class when_publishing_messages_with_default_headers { const string SpecId = "12BA6C54-242E-4EF7-B61A-7BEA232993DC"; static RabbitQueue _queue; static IBasicProperties _messageProperties; static Bus _bus; Establish context = () => { var headers = new Dictionary<string, object>(); headers.Add("header-key", Encoding.UTF8.GetBytes("header key value")); _bus = new BusBuilder().Configure(ctx => ctx .Publish<TestMessage>() .WithExchange(SpecId) .WithDefaultHeaders(headers)) .Build(); _bus.Connect(); _queue = new RabbitQueue("localhost", SpecId, ExchangeType.Direct, SpecId, false, true, false, true, "", headers); _bus.Publish(new TestMessage("test")); }; Cleanup after = () => { _bus.Close(); _queue.Delete().Close(); }; Because of = () => new Action(() => _messageProperties = _queue.GetMessageProperties<TestMessage>()) .ExecuteUntil(() => _messageProperties != null)(); It should_publish_the_message_with_headers = () => _messageProperties.Headers.Keys.ShouldContain("header-key"); } [Integration] [Subject("Headers exchanges")] public class when_publishing_rpc_messages_with_default_headers { const string SpecId = "15192820-7236-444E-9EA8-5638F2CC3AC8"; static RabbitQueue _queue; static IBasicProperties _messageProperties; static Bus _bus; Establish context = () => { var headers = new Dictionary<string, object>(); headers.Add("header-key", Encoding.UTF8.GetBytes("header key value")); _bus = new BusBuilder().Configure(ctx => ctx .Publish<RequestMessage>() .WithExchange(SpecId) .WithDefaultHeaders(headers)) .Build(); _bus.Connect(); _queue = new RabbitQueue(SpecId, SpecId); _bus.Publish<RequestMessage, ReplyMessage>(new RequestMessage("test"), mc => { /* This will never get called because there's no server */ }); }; Cleanup after = () => { _bus.Close(); _queue.Delete().Close(); }; Because of = () => new Action(() => _messageProperties = _queue.GetMessageProperties<RequestMessage>()) .ExecuteUntil(() => _messageProperties != null)(); It should_publish_the_message_with_headers = () => _messageProperties.Headers.Keys.ShouldContain("header-key"); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Text; using System.Windows.Forms; using System.Collections; namespace DwarfFortressMapCompressor { public partial class MapViewer : Form { private MainMenuForm mainMenuForm; private string mapFilename; private string mapExtension; private ZLayerList zLayerList = null; private int zLayer = 0; private float mapZoom = 20.0f; private Bitmap mapBitmap = null; //private Bitmap backBuffer = null; private float mapCenterX = 0; private float mapCenterY = 0; private float mapSrcX = 0; private float mapSrcY = 0; private float mapSrcWidth = 0; private float mapSrcHeight = 0; private int accumulatedMousewheel = 0; private int startMousePosX; private int startMousePosY; private int lastMousePosX; private int lastMousePosY; private bool mouseDown; private float mapReverseZoomX; private float mapReverseZoomY; private Rectangle mapDestRect; private Rectangle backbufferDest; private float aspectRatio; //private byte[] dataBytes; //private byte[] blitDataBytes; //private int[, ,] blitBuffer; public MapViewer() { InitializeComponent(); mouseDown=false; #if MONO bool mvmd = true; #else bool mvmd = Properties.Settings.Default.mapViewerMouseDrags; #endif mouseDragsMapRadioButton.Checked=mvmd; mouseDraggingRepelsMapRadioButton.Checked=!mvmd; } public void ShowMap(MainMenuForm mainMenuForm, string filename, string extension) { this.mainMenuForm = mainMenuForm; this.mapFilename = filename; this.mapExtension = extension; zLayerList = mainMenuForm.GetZLayerList(filename, extension); zLayer = zLayerList.GetInitialZLayer(); zLevelChooser.Items.Clear(); zLevelChooser.Items.InsertRange(0, zLayerList.GetZLayers()); //zLevelChooser.Text = ""+zLayer; zLevelChooser.SelectedItem = zLayer; zLevelChooser.Visible = true; zLevelLabel.Visible = true; ShowMap(mainMenuForm.Run_DecodeFortressMap(filename, extension, zLayer, false), false); } public void ShowMap(Bitmap bitmap, bool noZLayers) { if (noZLayers) { this.mainMenuForm = null; this.mapFilename = ""; this.mapExtension = ""; zLevelChooser.Visible = false; zLevelLabel.Visible = false; zLayerList = null; zLayer = 0; zLevelChooser.Items.Clear(); ArrayList arrayList = new ArrayList(); arrayList.Add(0); zLevelChooser.Items.InsertRange(0, arrayList); zLevelChooser.Text = "0"; } Rectangle mapBoxRect = mapBox.GetWindowRect(); if (mapBoxRect.Height<10 || mapBoxRect.Width<10) { return; //Let's try not to crash. } this.aspectRatio = ((float) bitmap.Width / (float) bitmap.Height) / ((float) mapBox.Width / (float) mapBox.Height); //Console.WriteLine("Aspect ratio is "+aspectRatio); this.mapBitmap = bitmap; this.mapZoom = 1.0f; this.mapCenterX = 0.5f * bitmap.Width; this.mapCenterY = 0.5f * bitmap.Height; mapDestRect = new Rectangle(0, 0, mapBoxRect.Width, mapBoxRect.Height); backbufferDest = new Rectangle(0, 0, mapBoxRect.Width, mapBoxRect.Height); //backBuffer = new Bitmap((int) mapBoxRect.Width, (int) mapBoxRect.Height); //blitBuffer = new int[mapBoxRect.Width, mapBoxRect.Height, 4]; /*BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); IntPtr ptr = data.Scan0; dataBytes = new byte[data.Width*data.Height*3]; System.Runtime.InteropServices.Marshal.Copy(ptr, dataBytes, 0, dataBytes.Length); bitmap.UnlockBits(data); data = backBuffer.LockBits(new Rectangle(0, 0, backBuffer.Width, backBuffer.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat); ptr = data.Scan0; blitDataBytes = new byte[data.Width*data.Height*3]; System.Runtime.InteropServices.Marshal.Copy(blitDataBytes, 0, ptr, blitDataBytes.Length); backBuffer.UnlockBits(data);*/ //mapBox.Image = backBuffer; RecalculateZoom(); GC.Collect(); } private bool RecalculateZoom() { Rectangle mapBoxRect = mapBox.GetWindowRect(); this.mapSrcWidth = mapBitmap.Width / this.mapZoom; this.mapSrcHeight = (mapBitmap.Height * aspectRatio) / this.mapZoom; this.mapSrcX = this.mapCenterX - 0.5f * this.mapSrcWidth; this.mapSrcY = this.mapCenterY - 0.5f * this.mapSrcHeight; if (mapSrcX<0) { //Console.WriteLine("mapSrcX<0"); this.mapCenterX -= this.mapSrcX; this.mapSrcX = 0; } else if (mapSrcX + mapSrcWidth>=mapBitmap.Width) { //Console.WriteLine("mapSrcX>wv"); float oldMapSrcX = mapSrcX; mapSrcX = mapBitmap.Width-mapSrcWidth; mapCenterX += (mapSrcX - oldMapSrcX); } if (mapSrcY<0) { //Console.WriteLine("mapSrcY<0"); this.mapCenterY -= this.mapSrcY; this.mapSrcY = 0; } else if (mapSrcY + mapSrcHeight>=mapBitmap.Height) { //Console.WriteLine("mapSrcY>wy"); float oldMapSrcY = mapSrcY; mapSrcY = mapBitmap.Height-mapSrcHeight; mapCenterY += (mapSrcY - oldMapSrcY); } if (mapSrcWidth < mapBoxRect.Width) { mapSrcWidth = mapBoxRect.Width; return false; } if (mapSrcHeight < mapBoxRect.Height) { mapSrcHeight = mapBoxRect.Height; return false; } //At maximum zoom: //mapSrcWidth = mapBox.Width, and mapSrcHeight = mapBox.Height //using (Graphics g = Graphics.FromImage(backBuffer)) { //g.DrawImage(mapBitmap, backbufferDest, mapSrcX, mapSrcY, mapSrcWidth, mapSrcHeight, GraphicsUnit.Pixel); mapReverseZoomX = mapSrcWidth / mapBoxRect.Width; mapReverseZoomY = mapSrcHeight / mapBoxRect.Height; //Blit to: Bitmap backBuffer [0, 0] to [mapBox.Width, mapBox.Height] //From: mapBitmap [mapSrcX, mapSrcY] to [mapSrcX+mapSrcWidth, mapSrcY+mapSrcHeight] /* blitBuffer[0, 0, 0]=0; blitBuffer[0, 0, 1]=0; blitBuffer[0, 0, 2]=0; blitBuffer[0, 0, 3]=0; float numXPer = (float) mapSrcWidth/(float) mapBox.Width; float numYPer = (float) mapSrcHeight/(float) mapBox.Height; float ystep = 0.0f; int destY = 0; int initializedY = 0; int index = 0; for (int y=(int) mapSrcY, relY=0; relY<mapSrcHeight; y++, relY++, ystep+=1.0f) { if (ystep>numYPer) { ystep-=numYPer; destY+=1; } int destX = 0; float xstep = 0.0f; int initializedX = 0; for (int x=(int) mapSrcX, relX=0; relX<mapSrcWidth; x++, relX++, xstep+=1.0f, index+=3) { if (xstep>numXPer) { xstep-=numXPer; destX+=1; } if (initializedY<destY || initializedX<destX) { blitBuffer[destX, destY, 0]=dataBytes[index]; blitBuffer[destX, destY, 1]=dataBytes[index+1]; blitBuffer[destX, destY, 2]=dataBytes[index+2]; blitBuffer[destX, destY, 3]=1; initializedX = destX; initializedY = destY; } else { blitBuffer[destX, destY, 0]+=dataBytes[index]; blitBuffer[destX, destY, 1]+=dataBytes[index+1]; blitBuffer[destX, destY, 2]+=dataBytes[index+2]; blitBuffer[destX, destY, 3]+=1; } } } index=0; for (int y=0; y<backBuffer.Height; y++) { for (int x=0; x<backBuffer.Width; x++, index+=3) { if (blitBuffer[x, y, 0]!=0) { int rc = blitBuffer[x, y, 2]; int gc = blitBuffer[x, y, 1]; int bc = blitBuffer[x, y, 0]; } blitDataBytes[index]=(byte)(blitBuffer[x, y, 0]/blitBuffer[x, y, 3]); blitDataBytes[index+1]=(byte)(blitBuffer[x, y, 1]/blitBuffer[x, y, 3]); blitDataBytes[index+2]=(byte)(blitBuffer[x, y, 2]/blitBuffer[x, y, 3]); } } BitmapData data = backBuffer.LockBits(new Rectangle(0, 0, backBuffer.Width, backBuffer.Height), ImageLockMode.ReadWrite, backBuffer.PixelFormat); IntPtr ptr = data.Scan0; System.Runtime.InteropServices.Marshal.Copy(ptr, blitDataBytes, 0, blitDataBytes.Length); backBuffer.UnlockBits(data); */ Blit(); //} return true; } private void Blit() { //using (Graphics g = Graphics.FromImage(backBuffer)) { //g.DrawImage(mapBitmap, backbufferDest, mapSrcX, mapSrcY, mapSrcWidth, mapSrcHeight, GraphicsUnit.Pixel); //} //mapBox.Image=backBuffer; mapBox.SetValues(mapBitmap, backbufferDest, (int) mapSrcX, (int) mapSrcY, (int) mapSrcWidth, (int) mapSrcHeight); } private void mapBox_Click(object sender, EventArgs e) { //Console.WriteLine("Click."); } private void mapBox_MouseDown(object sender, MouseEventArgs e) { //Console.WriteLine("MouseDown "+e.Button+" "+e.Location); if (e.Button==MouseButtons.Left) { startMousePosX = e.X; startMousePosY = e.Y; lastMousePosX = startMousePosX; lastMousePosY = startMousePosY; mouseDown = true; actionTimer.Enabled=true; } } private void mapBox_MouseUp(object sender, MouseEventArgs e) { HandleMouseMove(e.X, e.Y, true); mouseDown = false; actionTimer.Enabled=false; } void mapBox_MouseMove(object sender, MouseEventArgs e) { HandleMouseMove(e.X, e.Y, false); } private void mapBox_MouseWheel(object sender, MouseEventArgs e) { //Console.WriteLine("MouseWheel "+e.Delta+" "+e.Button+" "+e.Location); GhrkOnMouseWheel(e); } public void zLevelChooser_MouseWheel(object sender, MouseEventArgs e) { //GhrkOnMouseWheel(e); } public void panel1_MouseWheel(object sender, MouseEventArgs e) { //Console.WriteLine("MouseWheel2 "+e.Delta+" "+e.Button+" "+e.Location); GhrkOnMouseWheel(e); } public void form_MouseWheel(object sender, MouseEventArgs e) { //Console.WriteLine("MouseWheel3 "+e.Delta+" "+e.Button+" "+e.Location); GhrkOnMouseWheel(e); } public void GhrkOnMouseWheel(MouseEventArgs e) { int wheelMovedAmount = e.Delta; accumulatedMousewheel += wheelMovedAmount; actionTimer.Enabled=false; actionTimer.Interval=200; actionTimer.Enabled=true; } /*private void mapBox_Paint(object sender, PaintEventArgs e) { }*/ internal void ReInit() { this.mapBitmap = null; } private void actionTimer_Tick(object sender, EventArgs e) { bool wheelUsed=false; if (accumulatedMousewheel!=0) { int absAmount = Math.Abs(accumulatedMousewheel); float zoomMultiplier = absAmount/2400.0f; if (accumulatedMousewheel>0) { zoomMultiplier = 1.0f+zoomMultiplier; } else { zoomMultiplier = 1.0f-zoomMultiplier; } mapZoom *= zoomMultiplier; if (mapZoom<1.0f) { mapZoom=1.0f; } float xChange = 0.0f; float yChange = 0.0f; if (zoomOnMouseRadioButton.Checked) { Point p = mapBox.PointToScreen(new Point((int) (mapBox.Left + mapBox.Width * 0.5f), (int) (mapBox.Top + mapBox.Height * 0.5f))); float mapBoxCenterX = p.X; float mapBoxCenterY = p.Y; xChange = (lastMousePosX-mapBoxCenterX) * mapReverseZoomX * zoomMultiplier; yChange = (lastMousePosY-mapBoxCenterY) * mapReverseZoomY * zoomMultiplier; this.mapCenterX += xChange; this.mapCenterY += yChange; } if (!RecalculateZoom()) { //Console.WriteLine("Map zoom now "+mapZoom); this.mapCenterX -= xChange; this.mapCenterY -= yChange; mapZoom /= zoomMultiplier; RecalculateZoom(); } accumulatedMousewheel=0; } if (mouseDown) { HandleMouseMove(lastMousePosX, lastMousePosY, true); } if (!mouseDown && !wheelUsed) { actionTimer.Enabled=false; } } private void HandleMouseMove(int x, int y, bool final) { lastMousePosX = x; lastMousePosY = y; if (!final) { actionTimer.Enabled=true; } else { DraggedFromTo(); } } private void DraggedFromTo() { float xChange = (lastMousePosX-startMousePosX) * mapReverseZoomX; float yChange = (lastMousePosY-startMousePosY) * mapReverseZoomY; if (mouseDragsMapRadioButton.Checked) { this.mapCenterX -= xChange; this.mapCenterY -= yChange; } else { this.mapCenterX += xChange; this.mapCenterY += yChange; } startMousePosX=lastMousePosX; startMousePosY=lastMousePosY; RecalculateZoom(); } private void mapViewer_Resize(object sender, EventArgs e) { //resize components: panel2.Top = this.Height - 85; panel3.Top = this.Height - 85; label1.Top = this.Height - 85; panel1.Top = 12; panel1.Left = 12; panel1.Height = this.Height - 110; panel1.Width = this.Width - 32; ShowMap(mapBitmap, false); } private void mouseDragsMapRadioButton_CheckedChanged(object sender, EventArgs e) { #if !MONO Properties.Settings.Default.mapViewerMouseDrags = true; Properties.Settings.Default.Save(); #endif } private void mouseDraggingRepelsMapRadioButton_CheckedChanged(object sender, EventArgs e) { #if !MONO Properties.Settings.Default.mapViewerMouseDrags = false; Properties.Settings.Default.Save(); #endif } private void MapViewer_FormClosed(object sender, FormClosedEventArgs e) { mapBitmap.Dispose(); mapBitmap = null; GC.Collect(); } private void zLevelChooser_ValueChanged(object sender, EventArgs e) { } private void zLevelChooser_SelectedItemChanged(object sender, EventArgs e) { if (zLayerList==null) { if (((int)zLevelChooser.SelectedItem)!=0) { zLevelChooser.SelectedItem = 0; } return; } int value = 0; try { value = Int32.Parse(zLevelChooser.Text); } catch(Exception) { } int newZLayer = zLayerList.ValidateZLayer(value); if (newZLayer!=zLayer) { zLayer = newZLayer; //zLevelChooser.Text = ""+zLayer; zLevelChooser.SelectedItem = zLayer; ShowMap(mainMenuForm.Run_DecodeFortressMap(mapFilename, mapExtension, zLayer, false), false); } else { //zLevelChooser.Text = ""+zLayer; } } } }
/* * REST API Documentation for Schoolbus * * API Sample * * OpenAPI spec version: v1 * * */ using System; using Xunit; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.XPath; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Serialization; using Npgsql; using Microsoft.EntityFrameworkCore; using Moq; using SchoolBusAPI; using SchoolBusAPI.Models; using SchoolBusAPI.Controllers; using SchoolBusAPI.Services.Impl; namespace SchoolBusAPI.Test { public class UserApiUnitTest { private readonly UserApiController _UserApi; /// <summary> /// Setup the test /// </summary> public UserApiUnitTest() { DbContextOptions<DbAppContext> options = new DbContextOptions<DbAppContext>(); Mock<DbAppContext> dbAppContext = new Mock<DbAppContext>(options); /* Here you will need to mock up the context. ItemType fakeItem = new ItemType(...); Mock<DbSet<ItemType>> mockList = MockDbSet.Create(fakeItem); dbAppContext.Setup(x => x.ModelEndpoint).Returns(mockItem.Object); */ UserApiService _service = new UserApiService(dbAppContext.Object); _UserApi = new UserApiController (_service); } [Fact] /// <summary> /// Unit test for UsersBulkPost /// </summary> public void TestUsersBulkPost() { // Add test code here // it may look like: // var result = _UserApiController.UsersBulkPost(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersCurrentGet /// </summary> public void TestUsersCurrentGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersCurrentGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersGet /// </summary> public void TestUsersGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdDelete /// </summary> public void TestUsersIdDelete() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdDelete(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdFavouritesGet /// </summary> public void TestUsersIdFavouritesGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdFavouritesGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdGet /// </summary> public void TestUsersIdGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdGroupsGet /// </summary> public void TestUsersIdGroupsGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdGroupsGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdGroupsPut /// </summary> public void TestUsersIdGroupsPut() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdGroupsPut(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdNotificationGet /// </summary> public void TestUsersIdNotificationGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdNotificationGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdPermissionsGet /// </summary> public void TestUsersIdPermissionsGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdPermissionsGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdPut /// </summary> public void TestUsersIdPut() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdPut(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdRolesGet /// </summary> public void TestUsersIdRolesGet() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdRolesGet(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdRolesPost /// </summary> public void TestUsersIdRolesPost() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdRolesPost(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersIdRolesPut /// </summary> public void TestUsersIdRolesPut() { // Add test code here // it may look like: // var result = _UserApiController.UsersIdRolesPut(); // Assert.True (result == expected-result); Assert.True(true); } [Fact] /// <summary> /// Unit test for UsersPost /// </summary> public void TestUsersPost() { // Add test code here // it may look like: // var result = _UserApiController.UsersPost(); // Assert.True (result == expected-result); Assert.True(true); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.StaticFiles; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OrchardCore.FileStorage; using OrchardCore.Media.Services; namespace OrchardCore.Media.Controllers { public class AdminController : Controller { private readonly HashSet<string> _allowedFileExtensions; private readonly IMediaFileStore _mediaFileStore; private readonly IAuthorizationService _authorizationService; private readonly IContentTypeProvider _contentTypeProvider; private readonly ILogger _logger; private readonly IStringLocalizer S; public AdminController( IMediaFileStore mediaFileStore, IAuthorizationService authorizationService, IContentTypeProvider contentTypeProvider, IOptions<MediaOptions> options, ILogger<AdminController> logger, IStringLocalizer<AdminController> stringLocalizer ) { _mediaFileStore = mediaFileStore; _authorizationService = authorizationService; _contentTypeProvider = contentTypeProvider; _allowedFileExtensions = options.Value.AllowedFileExtensions; _logger = logger; S = stringLocalizer; } public async Task<IActionResult> Index() { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } return View(); } public async Task<ActionResult<IEnumerable<IFileStoreEntry>>> GetFolders(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { path = ""; } if (await _mediaFileStore.GetDirectoryInfoAsync(path) == null) { return NotFound(); } var content = (await _mediaFileStore.GetDirectoryContentAsync(path)).Where(x => x.IsDirectory); var allowed = new List<IFileStoreEntry>(); foreach (var entry in content) { if ((await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)entry.Path))) { allowed.Add(entry); } } return allowed.ToArray(); } public async Task<ActionResult<IEnumerable<object>>> GetMediaItems(string path) { if (string.IsNullOrEmpty(path)) { path = ""; } if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)path)) { return Forbid(); } if (await _mediaFileStore.GetDirectoryInfoAsync(path) == null) { return NotFound(); } var files = (await _mediaFileStore.GetDirectoryContentAsync(path)).Where(x => !x.IsDirectory); var allowed = new List<IFileStoreEntry>(); foreach (var entry in files) { if ((await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)entry.Path))) { allowed.Add(entry); } } return allowed.Select(CreateFileResult).ToArray(); } public async Task<ActionResult<object>> GetMediaItem(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { return NotFound(); } var f = await _mediaFileStore.GetFileInfoAsync(path); if (f == null) { return NotFound(); } return CreateFileResult(f); } [HttpPost] [MediaSizeLimit] public async Task<ActionResult<object>> Upload( string path, string contentType, ICollection<IFormFile> files) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { path = ""; } var result = new List<object>(); // Loop through each file in the request foreach (var file in files) { // TODO: support clipboard if (!_allowedFileExtensions.Contains(Path.GetExtension(file.FileName), StringComparer.OrdinalIgnoreCase)) { result.Add(new { name = file.FileName, size = file.Length, folder = path, error = S["This file extension is not allowed: {0}", Path.GetExtension(file.FileName)].ToString() }); _logger.LogInformation("File extension not allowed: '{0}'", file.FileName); continue; } Stream stream = null; try { var mediaFilePath = _mediaFileStore.Combine(path, file.FileName); stream = file.OpenReadStream(); mediaFilePath = await _mediaFileStore.CreateFileFromStreamAsync(mediaFilePath, stream); var mediaFile = await _mediaFileStore.GetFileInfoAsync(mediaFilePath); result.Add(CreateFileResult(mediaFile)); } catch (Exception ex) { _logger.LogError(ex, "An error occurred while uploading a media"); result.Add(new { name = file.FileName, size = file.Length, folder = path, error = ex.Message }); } finally { stream?.Dispose(); } } return new { files = result.ToArray() }; } [HttpPost] public async Task<IActionResult> DeleteFolder(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)path)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot delete root media folder"]); } var mediaFolder = await _mediaFileStore.GetDirectoryInfoAsync(path); if (mediaFolder != null && !mediaFolder.IsDirectory) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot delete path because it is not a directory"]); } if (await _mediaFileStore.TryDeleteDirectoryAsync(path) == false) { return NotFound(); } return Ok(); } [HttpPost] public async Task<IActionResult> DeleteMedia(string path) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)path)) { return Forbid(); } if (string.IsNullOrEmpty(path)) { return NotFound(); } if (await _mediaFileStore.TryDeleteFileAsync(path) == false) return NotFound(); return Ok(); } [HttpPost] public async Task<IActionResult> MoveMedia(string oldPath, string newPath) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)oldPath)) { return Forbid(); } if (string.IsNullOrEmpty(oldPath) || string.IsNullOrEmpty(newPath)) { return NotFound(); } if (await _mediaFileStore.GetFileInfoAsync(oldPath) == null) { return NotFound(); } if (!_allowedFileExtensions.Contains(Path.GetExtension(newPath), StringComparer.OrdinalIgnoreCase)) { return StatusCode(StatusCodes.Status403Forbidden, S["This file extension is not allowed: {0}", Path.GetExtension(newPath)]); } if (await _mediaFileStore.GetFileInfoAsync(newPath) != null) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot move media because a file already exists with the same name"]); } await _mediaFileStore.MoveFileAsync(oldPath, newPath); return Ok(); } [HttpPost] public async Task<IActionResult> DeleteMediaList(string[] paths) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia)) { return Forbid(); } foreach (var path in paths) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)path)) { return Forbid(); } } if (paths == null) { return NotFound(); } foreach (var p in paths) { if (await _mediaFileStore.TryDeleteFileAsync(p) == false) return NotFound(); } return Ok(); } [HttpPost] public async Task<IActionResult> MoveMediaList(string[] mediaNames, string sourceFolder, string targetFolder) { if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)sourceFolder) || !await _authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)targetFolder)) { return Forbid(); } if ((mediaNames == null) || (mediaNames.Length < 1) || string.IsNullOrEmpty(sourceFolder) || string.IsNullOrEmpty(targetFolder)) { return NotFound(); } sourceFolder = sourceFolder == "root" ? string.Empty : sourceFolder; targetFolder = targetFolder == "root" ? string.Empty : targetFolder; var filesOnError = new List<string>(); foreach (var name in mediaNames) { var sourcePath = _mediaFileStore.Combine(sourceFolder, name); var targetPath = _mediaFileStore.Combine(targetFolder, name); try { await _mediaFileStore.MoveFileAsync(sourcePath, targetPath); } catch (FileStoreException) { filesOnError.Add(sourcePath); } } if (filesOnError.Count > 0) { return BadRequest(S["Error when moving files. Maybe they already exist on the target folder? Files on error: {0}", string.Join(",", filesOnError)].ToString()); } else { return Ok(); } } [HttpPost] public async Task<ActionResult<IFileStoreEntry>> CreateFolder( string path, string name, [FromServices] IAuthorizationService authorizationService) { if (string.IsNullOrEmpty(path)) { path = ""; } var newPath = _mediaFileStore.Combine(path, name); if (!await authorizationService.AuthorizeAsync(User, Permissions.ManageMedia) || !await authorizationService.AuthorizeAsync(User, Permissions.ManageAttachedMediaFieldsFolder, (object)newPath)) { return Forbid(); } var mediaFolder = await _mediaFileStore.GetDirectoryInfoAsync(newPath); if (mediaFolder != null) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot create folder because a folder already exists with the same name"]); } var existingFile = await _mediaFileStore.GetFileInfoAsync(newPath); if (existingFile != null) { return StatusCode(StatusCodes.Status403Forbidden, S["Cannot create folder because a file already exists with the same name"]); } await _mediaFileStore.TryCreateDirectoryAsync(newPath); mediaFolder = await _mediaFileStore.GetDirectoryInfoAsync(newPath); return new ObjectResult(mediaFolder); } public IActionResult MediaApplication() { return View(); } public object CreateFileResult(IFileStoreEntry mediaFile) { _contentTypeProvider.TryGetContentType(mediaFile.Name, out var contentType); return new { name = mediaFile.Name, size = mediaFile.Length, lastModify = mediaFile.LastModifiedUtc.Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc)).TotalMilliseconds, folder = mediaFile.DirectoryPath, url = _mediaFileStore.MapPathToPublicUrl(mediaFile.Path), mediaPath = mediaFile.Path, mime = contentType ?? "application/octet-stream" }; } } }
// // Pop3Engine.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2014 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Threading; using System.Collections.Generic; #if NETFX_CORE using Encoding = Portable.Text.Encoding; #endif namespace MailKit.Net.Pop3 { /// <summary> /// The state of the <see cref="Pop3Engine"/>. /// </summary> enum Pop3EngineState { /// <summary> /// The Pop3Engine is in the disconnected state. /// </summary> Disconnected, /// <summary> /// The Pop3Engine is in the connected state. /// </summary> Connected, /// <summary> /// The Pop3Engine is in the transaction state, indicating that it is /// authenticated and may retrieve messages from the server. /// </summary> Transaction } /// <summary> /// A POP3 command engine. /// </summary> class Pop3Engine { static readonly Encoding Latin1 = Encoding.GetEncoding (28591); readonly List<Pop3Command> queue; Pop3Stream stream; int nextId; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Net.Pop3.Pop3Engine"/> class. /// </summary> public Pop3Engine () { AuthenticationMechanisms = new HashSet<string> (); Capabilities = Pop3Capabilities.User; queue = new List<Pop3Command> (); nextId = 1; } /// <summary> /// Gets the authentication mechanisms supported by the POP3 server. /// </summary> /// <remarks> /// The authentication mechanisms are queried durring the /// <see cref="Connect"/> method. /// </remarks> /// <value>The authentication mechanisms.</value> public HashSet<string> AuthenticationMechanisms { get; private set; } /// <summary> /// Gets the capabilities supported by the POP3 server. /// </summary> /// <remarks> /// The capabilities will not be known until a successful connection /// has been made via the <see cref="Connect"/> method. /// </remarks> /// <value>The capabilities.</value> public Pop3Capabilities Capabilities { get; set; } /// <summary> /// Gets the underlying POP3 stream. /// </summary> /// <remarks> /// Gets the underlying POP3 stream. /// </remarks> /// <value>The pop3 stream.</value> public Pop3Stream Stream { get { return stream; } } /// <summary> /// Gets or sets the state of the engine. /// </summary> /// <remarks> /// Gets or sets the state of the engine. /// </remarks> /// <value>The engine state.</value> public Pop3EngineState State { get; internal set; } /// <summary> /// Gets whether or not the engine is currently connected to a POP3 server. /// </summary> /// <remarks> /// Gets whether or not the engine is currently connected to a POP3 server. /// </remarks> /// <value><c>true</c> if the engine is connected; otherwise, <c>false</c>.</value> public bool IsConnected { get { return stream != null && stream.IsConnected; } } /// <summary> /// Gets the APOP authentication token. /// </summary> /// <remarks> /// Gets the APOP authentication token. /// </remarks> /// <value>The APOP authentication token.</value> public string ApopToken { get; private set; } /// <summary> /// Gets the EXPIRE extension policy value. /// </summary> /// <remarks> /// Gets the EXPIRE extension policy value. /// </remarks> /// <value>The EXPIRE policy.</value> public int ExpirePolicy { get; private set; } /// <summary> /// Gets the implementation details of the server. /// </summary> /// <remarks> /// Gets the implementation details of the server. /// </remarks> /// <value>The implementation details.</value> public string Implementation { get; private set; } /// <summary> /// Gets the login delay. /// </summary> /// <remarks> /// Gets the login delay. /// </remarks> /// <value>The login delay.</value> public int LoginDelay { get; private set; } /// <summary> /// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting. /// </summary> /// <remarks> /// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting. /// </remarks> /// <param name="pop3">The pop3 stream.</param> /// <param name="cancellationToken">The cancellation token</param> public void Connect (Pop3Stream pop3, CancellationToken cancellationToken) { if (stream != null) stream.Dispose (); Capabilities = Pop3Capabilities.User; AuthenticationMechanisms.Clear (); State = Pop3EngineState.Disconnected; ApopToken = null; stream = pop3; // read the pop3 server greeting var greeting = ReadLine (cancellationToken).TrimEnd (); int index = greeting.IndexOf (' '); string token, text; if (index != -1) { token = greeting.Substring (0, index); while (index < greeting.Length && char.IsWhiteSpace (greeting[index])) index++; if (index < greeting.Length) text = greeting.Substring (index); else text = string.Empty; } else { text = string.Empty; token = greeting; } if (token != "+OK") { stream.Dispose (); stream = null; throw new Pop3ProtocolException (string.Format ("Unexpected greeting from server: {0}", greeting)); } index = text.IndexOf ('>'); if (text.Length > 0 && text[0] == '<' && index != -1) { ApopToken = text.Substring (0, index + 1); Capabilities |= Pop3Capabilities.Apop; } State = Pop3EngineState.Connected; } public event EventHandler<EventArgs> Disconnected; void OnDisconnected () { var handler = Disconnected; if (handler != null) handler (this, EventArgs.Empty); } /// <summary> /// Disconnects the <see cref="Pop3Engine"/>. /// </summary> /// <remarks> /// Disconnects the <see cref="Pop3Engine"/>. /// </remarks> public void Disconnect () { if (stream != null) { stream.Dispose (); stream = null; } if (State != Pop3EngineState.Disconnected) { State = Pop3EngineState.Disconnected; OnDisconnected (); } } /// <summary> /// Reads a single line from the <see cref="Pop3Stream"/>. /// </summary> /// <returns>The line.</returns> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.InvalidOperationException"> /// The engine is not connected. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public string ReadLine (CancellationToken cancellationToken) { if (stream == null) throw new InvalidOperationException (); using (var memory = new MemoryStream ()) { int offset, count; byte[] buf; while (!stream.ReadLine (out buf, out offset, out count, cancellationToken)) memory.Write (buf, offset, count); memory.Write (buf, offset, count); count = (int) memory.Length; #if !NETFX_CORE buf = memory.GetBuffer (); #else buf = memory.ToArray (); #endif try { return Encoding.UTF8.GetString (buf, 0, count); } catch { return Latin1.GetString (buf, 0, count); } } } public static Pop3CommandStatus GetCommandStatus (string response, out string text) { int index = response.IndexOf (' '); string token; if (index != -1) { token = response.Substring (0, index); while (index < response.Length && char.IsWhiteSpace (response[index])) index++; if (index < response.Length) text = response.Substring (index); else text = string.Empty; } else { text = string.Empty; token = response; } if (token == "+OK") return Pop3CommandStatus.Ok; if (token == "-ERR") return Pop3CommandStatus.Error; if (token == "+") return Pop3CommandStatus.Continue; return Pop3CommandStatus.ProtocolError; } void SendCommand (Pop3Command pc) { var buf = Encoding.UTF8.GetBytes (pc.Command + "\r\n"); stream.Write (buf, 0, buf.Length); } void ReadResponse (Pop3Command pc) { string response, text; try { response = ReadLine (pc.CancellationToken).TrimEnd (); } catch { pc.Status = Pop3CommandStatus.ProtocolError; Disconnect (); throw; } pc.Status = GetCommandStatus (response, out text); pc.StatusText = text; switch (pc.Status) { case Pop3CommandStatus.ProtocolError: Disconnect (); throw new Pop3ProtocolException (string.Format ("Unexpected response from server: {0}", response)); case Pop3CommandStatus.Continue: case Pop3CommandStatus.Ok: if (pc.Handler != null) { try { pc.Handler (this, pc, text); } catch { pc.Status = Pop3CommandStatus.ProtocolError; Disconnect (); throw; } } break; } } public int Iterate () { if (stream == null) throw new InvalidOperationException (); if (queue.Count == 0) return 0; int count = (Capabilities & Pop3Capabilities.Pipelining) != 0 ? queue.Count : 1; var cancellationToken = queue[0].CancellationToken; var active = new List<Pop3Command> (); if (cancellationToken.IsCancellationRequested) { queue.RemoveAll (x => x.CancellationToken.IsCancellationRequested); cancellationToken.ThrowIfCancellationRequested (); } for (int i = 0; i < count; i++) { var pc = queue[0]; if (i > 0 && !pc.CancellationToken.Equals (cancellationToken)) break; queue.RemoveAt (0); pc.Status = Pop3CommandStatus.Active; active.Add (pc); SendCommand (pc); } stream.Flush (cancellationToken); for (int i = 0; i < active.Count; i++) ReadResponse (active[i]); return active[active.Count - 1].Id; } public Pop3Command QueueCommand (CancellationToken cancellationToken, Pop3CommandHandler handler, string format, params object[] args) { var pc = new Pop3Command (cancellationToken, handler, format, args); pc.Id = nextId++; queue.Add (pc); return pc; } static void CapaHandler (Pop3Engine engine, Pop3Command pc, string text) { // clear all CAPA response capabilities (except the APOP capability) engine.Capabilities &= Pop3Capabilities.Apop; engine.AuthenticationMechanisms.Clear (); engine.Implementation = null; engine.ExpirePolicy = 0; engine.LoginDelay = 0; if (pc.Status != Pop3CommandStatus.Ok) return; string response; do { if ((response = engine.ReadLine (pc.CancellationToken).TrimEnd ()) == ".") break; int index = response.IndexOf (' '); string token, data; int value; if (index != -1) { token = response.Substring (0, index); while (index < response.Length && char.IsWhiteSpace (response[index])) index++; if (index < response.Length) data = response.Substring (index); else data = string.Empty; } else { data = string.Empty; token = response; } switch (token) { case "EXPIRE": engine.Capabilities |= Pop3Capabilities.Expire; var tokens = data.Split (' '); if (int.TryParse (tokens[0], out value)) engine.ExpirePolicy = value; else if (tokens[0] == "NEVER") engine.ExpirePolicy = -1; break; case "IMPLEMENTATION": engine.Implementation = data; break; case "LOGIN-DELAY": if (int.TryParse (data, out value)) { engine.Capabilities |= Pop3Capabilities.LoginDelay; engine.LoginDelay = value; } break; case "PIPELINING": engine.Capabilities |= Pop3Capabilities.Pipelining; break; case "RESP-CODES": engine.Capabilities |= Pop3Capabilities.ResponseCodes; break; case "SASL": engine.Capabilities |= Pop3Capabilities.Sasl; foreach (var authmech in data.Split (new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) engine.AuthenticationMechanisms.Add (authmech); break; case "STLS": engine.Capabilities |= Pop3Capabilities.StartTLS; break; case "TOP": engine.Capabilities |= Pop3Capabilities.Top; break; case "UIDL": engine.Capabilities |= Pop3Capabilities.UIDL; break; case "USER": engine.Capabilities |= Pop3Capabilities.User; break; case "UTF8": engine.Capabilities |= Pop3Capabilities.UTF8; foreach (var item in data.Split (' ')) { if (item == "USER") engine.Capabilities |= Pop3Capabilities.UTF8User; } break; case "LANG": engine.Capabilities |= Pop3Capabilities.Lang; break; } } while (true); } public Pop3CommandStatus QueryCapabilities (CancellationToken cancellationToken) { if (stream == null) throw new InvalidOperationException (); var pc = QueueCommand (cancellationToken, CapaHandler, "CAPA"); while (Iterate () < pc.Id) { // continue processing commands... } return pc.Status; } } }
// 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 System.Runtime.ExceptionServices; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudio.Debugger.Interop.UnixPortSupplier; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using MICore; using System.Globalization; using Microsoft.DebugEngineHost; using Logger = MICore.Logger; namespace Microsoft.MIDebugEngine { // AD7Engine is the primary entrypoint object for the sample engine. // // It implements: // // IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session, // from creating breakpoints to setting and clearing exceptions. // // IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs. // // IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each // process only contains one program, it is implemented on the engine. // // IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee. [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.InteropServices.Guid("0fc2f352-2fc1-4f80-8736-51cd1ab28f16")] sealed public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugEngine3, IDebugProgram3, IDebugEngineProgram2, IDebugMemoryBytes2, IDebugEngine110 { // used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load. private EngineCallback _engineCallback; // The sample debug engine is split into two parts: a managed front-end and a mixed-mode back end. DebuggedProcess is the primary // object in the back-end. AD7Engine holds a reference to it. private DebuggedProcess _debuggedProcess; // This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging // api requires thread affinity to several operations. private WorkerThread _pollThread; // This object manages breakpoints in the sample engine. private BreakpointManager _breakpointManager; private Guid _engineGuid = EngineConstants.EngineId; // A unique identifier for the program being debugged. private Guid _ad7ProgramId; private HostConfigurationStore _configStore; public Logger Logger { private set; get; } private IDebugSettingsCallback110 _settingsCallback; private static List<int> s_childProcessLaunch; static AD7Engine() { s_childProcessLaunch = new List<int>(); } public AD7Engine() { Host.EnsureMainThreadInitialized(); _breakpointManager = new BreakpointManager(this); } ~AD7Engine() { if (_pollThread != null) { _pollThread.Close(); } } internal static void AddChildProcess(int processId) { lock (s_childProcessLaunch) { s_childProcessLaunch.Add(processId); } } internal static bool RemoveChildProcess(int processId) { lock (s_childProcessLaunch) { return s_childProcessLaunch.Remove(processId); } } internal EngineCallback Callback { get { return _engineCallback; } } internal DebuggedProcess DebuggedProcess { get { return _debuggedProcess; } } internal uint CurrentRadix() { uint radix; if (_settingsCallback != null && _settingsCallback.GetDisplayRadix(out radix) == Constants.S_OK) { if (radix != _debuggedProcess.MICommandFactory.Radix) { _debuggedProcess.WorkerThread.RunOperation(async () => { await _debuggedProcess.MICommandFactory.SetRadix(radix); }); } } return _debuggedProcess.MICommandFactory.Radix; } internal bool ProgramCreateEventSent { get; private set; } public string GetAddressDescription(ulong ip) { return EngineUtils.GetAddressDescription(_debuggedProcess, ip); } public object GetMetric(string metric) { return _configStore.GetEngineMetric(metric); } #region IDebugEngine2 Members // Attach the debug engine to a program. public int Attach(IDebugProgram2[] portProgramArray, IDebugProgramNode2[] programNodeArray, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason) { Debug.Assert(_ad7ProgramId == Guid.Empty); if (celtPrograms != 1) { Debug.Fail("SampleEngine only expects to see one program in a process"); throw new ArgumentException(); } IDebugProgram2 portProgram = portProgramArray[0]; Exception exception = null; try { IDebugProcess2 process; EngineUtils.RequireOk(portProgram.GetProcess(out process)); AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); EngineUtils.RequireOk(portProgram.GetProgramId(out _ad7ProgramId)); // Attach can either be called to attach to a new process, or to complete an attach // to a launched process if (_pollThread == null) { if (processId.ProcessIdType != (uint)enum_AD_PROCESS_ID.AD_PROCESS_ID_SYSTEM) { Debug.Fail("Invalid process to attach to"); throw new ArgumentException(); } IDebugPort2 port; EngineUtils.RequireOk(process.GetPort(out port)); Debug.Assert(_engineCallback == null); Debug.Assert(_debuggedProcess == null); _engineCallback = new EngineCallback(this, ad7Callback); LaunchOptions launchOptions = CreateAttachLaunchOptions(processId.dwProcessId, port); StartDebugging(launchOptions); } else { if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { Debug.Fail("Asked to attach to a process while we are debugging"); return Constants.E_FAIL; } } AD7EngineCreateEvent.Send(this); AD7ProgramCreateEvent.Send(this); this.ProgramCreateEventSent = true; return Constants.S_OK; } catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true)) { exception = e; } // If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and // return that the attach was canceled OnStartDebuggingFailed(exception); return AD7_HRESULT.E_ATTACH_USER_CANCELED; } private LaunchOptions CreateAttachLaunchOptions(uint processId, IDebugPort2 port) { LaunchOptions launchOptions; var unixPort = port as IDebugUnixShellPort; if (unixPort != null) { MIMode miMode; if (_engineGuid == EngineConstants.ClrdbgEngine) { miMode = MIMode.Clrdbg; } else if (_engineGuid == EngineConstants.GdbEngine) { miMode = MIMode.Gdb; } else { // TODO: LLDB support throw new NotImplementedException(); } if (processId > int.MaxValue) { throw new ArgumentOutOfRangeException("processId"); } string getClrDbgUrl = GetMetric("GetClrDbgUrl") as string; string remoteDebuggerInstallationDirectory = GetMetric("RemoteInstallationDirectory") as string; string remoteDebuggerInstallationSubDirectory = GetMetric("RemoteInstallationSubDirectory") as string; string clrDbgVersion = GetMetric("ClrDbgVersion") as string; launchOptions = UnixShellPortLaunchOptions.CreateForAttachRequest(unixPort, (int)processId, miMode, getClrDbgUrl, remoteDebuggerInstallationDirectory, remoteDebuggerInstallationSubDirectory, clrDbgVersion); // TODO: Add a tools option page for: // AdditionalSOLibSearchPath // VisualizerFile? } else { // TODO: when we have a tools options page, we can add support for the attach dialog here pretty easily: //var defaultPort = port as IDebugDefaultPort2; //if (defaultPort != null && defaultPort.QueryIsLocal() == Constants.S_OK) //{ // launchOptions = new LocalLaunchOptions(...); //} //else //{ // // Invalid port // throw new ArgumentException(); //} throw new NotSupportedException(); } return launchOptions; } // Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM, // was received and processed. The only event the sample engine sends in this fashion is Program Destroy. // It responds to that event by shutting down the engine. public int ContinueFromSynchronousEvent(IDebugEvent2 eventObject) { try { if (eventObject is AD7ProgramCreateEvent) { Exception exception = null; try { // At this point breakpoints and exception settings have been sent down, so we can resume the target _pollThread.RunOperation(() => { return _debuggedProcess.ResumeFromLaunch(); }); } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } if (exception != null) { // If something goes wrong, report the error and then stop debugging. The SDM will drop errors // from ContinueFromSynchronousEvent, so we want to deal with them ourself. SendStartDebuggingError(exception); _debuggedProcess.Terminate(); } return Constants.S_OK; } else if (eventObject is AD7ProgramDestroyEvent) { Dispose(); } else { Debug.Fail("Unknown syncronious event"); } } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } private void Dispose() { WorkerThread pollThread = _pollThread; DebuggedProcess debuggedProcess = _debuggedProcess; _engineCallback = null; _debuggedProcess = null; _pollThread = null; _ad7ProgramId = Guid.Empty; debuggedProcess?.Close(); pollThread?.Close(); } // Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to // a location in the debuggee. public int CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP) { Debug.Assert(_breakpointManager != null); ppPendingBP = null; try { _breakpointManager.CreatePendingBreakpoint(pBPRequest, out ppPendingBP); } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } // Informs a DE that the program specified has been atypically terminated and that the DE should // clean up all references to the program and send a program destroy event. public int DestroyProgram(IDebugProgram2 pProgram) { // Tell the SDM that the engine knows that the program is exiting, and that the // engine will send a program destroy. We do this because the Win32 debug api will always // tell us that the process exited, and otherwise we have a race condition. return (AD7_HRESULT.E_PROGRAM_DESTROY_PENDING); } // Gets the GUID of the DE. public int GetEngineId(out Guid guidEngine) { guidEngine = _engineGuid; return Constants.S_OK; } // Removes the list of exceptions the IDE has set for a particular run-time architecture or language. public int RemoveAllSetExceptions(ref Guid guidType) { _debuggedProcess?.ExceptionManager.RemoveAllSetExceptions(guidType); return Constants.S_OK; } // Removes the specified exception so it is no longer handled by the debug engine. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. public int RemoveSetException(EXCEPTION_INFO[] pException) { _debuggedProcess?.ExceptionManager.RemoveSetException(ref pException[0]); return Constants.S_OK; } // Specifies how the DE should handle a given exception. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. public int SetException(EXCEPTION_INFO[] pException) { _debuggedProcess?.ExceptionManager.SetException(ref pException[0]); return Constants.S_OK; } // Sets the locale of the DE. // This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that // strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented. public int SetLocale(ushort wLangID) { return Constants.S_OK; } // A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality. // This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric. public int SetMetric(string pszMetric, object varValue) { if (string.CompareOrdinal(pszMetric, "JustMyCodeStepping") == 0) { string strJustMyCode = varValue.ToString(); bool optJustMyCode; if (string.CompareOrdinal(strJustMyCode, "0") == 0) { optJustMyCode = false; } else if (string.CompareOrdinal(strJustMyCode, "1") == 0) { optJustMyCode = true; } else { return Constants.E_FAIL; } _pollThread.RunOperation(new Operation(() => { _debuggedProcess.MICommandFactory.SetJustMyCode(optJustMyCode); })); return Constants.S_OK; } else if (string.CompareOrdinal(pszMetric, "EnableStepFiltering") == 0) { string enableStepFiltering = varValue.ToString(); bool optStepFiltering; if (string.CompareOrdinal(enableStepFiltering, "0") == 0) { optStepFiltering = false; } else if (string.CompareOrdinal(enableStepFiltering, "1") == 0) { optStepFiltering = true; } else { return Constants.E_FAIL; } _pollThread.RunOperation(new Operation(() => { _debuggedProcess.MICommandFactory.SetStepFiltering(optStepFiltering); })); return Constants.S_OK; } return Constants.E_NOTIMPL; } // Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored // This allows the debugger to tell the engine where that location is. public int SetRegistryRoot(string registryRoot) { _configStore = new HostConfigurationStore(registryRoot); Logger = Logger.EnsureInitialized(_configStore); return Constants.S_OK; } #endregion #region IDebugEngineLaunch2 Members // Determines if a process can be terminated. int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_OK; } else { return Constants.S_FALSE; } } // Launches a process by means of the debug engine. // Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger // to the suspended program. However, there are circumstances in which the debug engine may need to launch a program // (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language), // in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method // The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state. int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process) { Debug.Assert(_pollThread == null); Debug.Assert(_engineCallback == null); Debug.Assert(_debuggedProcess == null); Debug.Assert(_ad7ProgramId == Guid.Empty); // Check if the logger was enabled late. Logger.LoadMIDebugLogger(_configStore); process = null; _engineCallback = new EngineCallback(this, ad7Callback); Exception exception; try { bool noDebug = launchFlags.HasFlag(enum_LAUNCH_FLAGS.LAUNCH_NODEBUG); // Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop LaunchOptions launchOptions = LaunchOptions.GetInstance(_configStore, exe, args, dir, options, noDebug, _engineCallback, TargetEngine.Native, Logger); StartDebugging(launchOptions); EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process)); return Constants.S_OK; } catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true)) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } // If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and then // return E_ABORT. OnStartDebuggingFailed(exception); return Constants.E_ABORT; } private void StartDebugging(LaunchOptions launchOptions) { Debug.Assert(_engineCallback != null); Debug.Assert(_pollThread == null); Debug.Assert(_debuggedProcess == null); // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(Logger); var cancellationTokenSource = new CancellationTokenSource(); using (cancellationTokenSource) { _pollThread.RunOperation(ResourceStrings.InitializingDebugger, cancellationTokenSource, (HostWaitLoop waitLoop) => { try { _debuggedProcess = new DebuggedProcess(true, launchOptions, _engineCallback, _pollThread, _breakpointManager, this, _configStore, waitLoop); } finally { // If there is an exception from the DebuggeedProcess constructor, it is our responsibility to dispose the DeviceAppLauncher, // otherwise the DebuggedProcess object takes ownership. if (_debuggedProcess == null && launchOptions.DeviceAppLauncher != null) { launchOptions.DeviceAppLauncher.Dispose(); } } _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; return _debuggedProcess.Initialize(waitLoop, cancellationTokenSource.Token); }); } } private void OnStartDebuggingFailed(Exception exception) { Logger.Flush(); SendStartDebuggingError(exception); Dispose(); } private void SendStartDebuggingError(Exception exception) { if (exception is OperationCanceledException) { return; // don't show a message in this case } string description = EngineUtils.GetExceptionDescription(exception); string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnableToStartDebugging, description); var initializationException = exception as MIDebuggerInitializeFailedException; if (initializationException != null) { string outputMessage = string.Join("\r\n", initializationException.OutputLines) + "\r\n"; // NOTE: We can't write to the output window by sending an AD7 event because this may be called before the session create event HostOutputWindow.WriteLaunchError(outputMessage); } _engineCallback.OnErrorImmediate(message); } // Resume a process launched by IDebugEngineLaunch2.LaunchSuspended int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); Debug.Assert(_ad7ProgramId == Guid.Empty); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } // Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach // which will complete the hookup with AD7 IDebugPort2 port; EngineUtils.RequireOk(process.GetPort(out port)); IDebugDefaultPort2 defaultPort = (IDebugDefaultPort2)port; IDebugPortNotify2 portNotify; EngineUtils.RequireOk(defaultPort.GetPortNotify(out portNotify)); EngineUtils.RequireOk(portNotify.AddProgramNode(new AD7ProgramNode(_debuggedProcess.Id, _engineGuid))); if (_ad7ProgramId == Guid.Empty) { Debug.Fail("Unexpected problem -- IDebugEngine2.Attach wasn't called"); return Constants.E_FAIL; } // NOTE: We wait for the program create event to be continued before we really resume the process return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) when (ExceptionHelper.BeforeCatch(e, Logger, reportOnlyCorrupting: true)) { return EngineUtils.UnexpectedException(e); } } // This function is used to terminate a process that the SampleEngine launched // The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method. int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } try { _pollThread.RunOperation(() => _debuggedProcess.CmdTerminate()); if (_debuggedProcess.MICommandFactory.Mode != MIMode.Clrdbg) { _debuggedProcess.Terminate(); } else { // Clrdbg issues a proper exit event on CmdTerminate call, don't call _debuggedProcess.Terminate() which // simply sends a fake exit event that overrides the exit code of the real one } } catch (ObjectDisposedException) { // Ignore failures caused by the connection already being dead. } return Constants.S_OK; } #endregion #region IDebugEngine3 Members public int SetSymbolPath(string szSymbolSearchPath, string szSymbolCachePath, uint Flags) { return Constants.S_OK; } public int LoadSymbols() { return Constants.S_FALSE; // indicate that we didn't load symbols for anything } public int SetJustMyCodeState(int fUpdate, uint dwModules, JMC_CODE_SPEC[] rgJMCSpec) { return Constants.S_OK; } public int SetEngineGuid(ref Guid guidEngine) { _engineGuid = guidEngine; _configStore.SetEngineGuid(_engineGuid); return Constants.S_OK; } public int SetAllExceptions(enum_EXCEPTION_STATE dwState) { _debuggedProcess?.ExceptionManager.SetAllExceptions(dwState); return Constants.S_OK; } #endregion #region IDebugProgram2 Members // Determines if a debug engine (DE) can detach from the program. public int CanDetach() { bool canDetach = _debuggedProcess != null && _debuggedProcess.MICommandFactory.CanDetach(); return canDetach ? Constants.S_OK : Constants.S_FALSE; } // The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering // breakmode. public int CauseBreak() { _pollThread.RunOperation(() => _debuggedProcess.CmdBreak(MICore.Debugger.BreakRequest.Async)); return Constants.S_OK; } // Continue is called from the SDM when it wants execution to continue in the debugee // but have stepping state remain. An example is when a tracepoint is executed, // and the debugger does not want to actually enter break mode. public int Continue(IDebugThread2 pThread) { // VS Code currently isn't providing a thread Id in certain cases. Work around this by handling null values. AD7Thread thread = pThread as AD7Thread; try { if (_pollThread.IsPollThread()) { _debuggedProcess.Continue(thread?.GetDebuggedThread()); } else { _pollThread.RunOperation(() => _debuggedProcess.Continue(thread?.GetDebuggedThread())); } } catch (InvalidCoreDumpOperationException) { return AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED; } return Constants.S_OK; } // Detach is called when debugging is stopped and the process was attached to (as opposed to launched) // or when one of the Detach commands are executed in the UI. public int Detach() { _breakpointManager.ClearBoundBreakpoints(); try { _pollThread.RunOperation(() => _debuggedProcess.CmdDetach()); } catch (DebuggerDisposedException e) when (e.AbortedCommand == "-target-detach") { // Detach command could cause DebuggerDisposedException and we ignore that. } _debuggedProcess.Detach(); return Constants.S_OK; } // Enumerates the code contexts for a given position in a source file. public int EnumCodeContexts(IDebugDocumentPosition2 docPosition, out IEnumDebugCodeContexts2 ppEnum) { string documentName; EngineUtils.CheckOk(docPosition.GetFileName(out documentName)); // Get the location in the document TEXT_POSITION[] startPosition = new TEXT_POSITION[1]; TEXT_POSITION[] endPosition = new TEXT_POSITION[1]; EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition)); List<IDebugCodeContext2> codeContexts = new List<IDebugCodeContext2>(); List<ulong> addresses = null; uint line = startPosition[0].dwLine + 1; _debuggedProcess.WorkerThread.RunOperation(async () => { addresses = await DebuggedProcess.StartAddressesForLine(documentName, line); }); if (addresses != null && addresses.Count > 0) { foreach (var a in addresses) { var codeCxt = new AD7MemoryAddress(this, a, null); TEXT_POSITION pos; pos.dwLine = line; pos.dwColumn = 0; MITextPosition textPosition = new MITextPosition(documentName, pos, pos); codeCxt.SetDocumentContext(new AD7DocumentContext(textPosition, codeCxt, this.DebuggedProcess)); codeContexts.Add(codeCxt); } if (codeContexts.Count > 0) { ppEnum = new AD7CodeContextEnum(codeContexts.ToArray()); return Constants.S_OK; } } ppEnum = null; return Constants.E_FAIL; } // EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which // function to step into. This is not something that the SampleEngine supports. public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext) { pathEnum = null; safetyContext = null; return Constants.E_NOTIMPL; } // EnumModules is called by the debugger when it needs to enumerate the modules in the program. public int EnumModules(out IEnumDebugModules2 ppEnum) { DebuggedModule[] modules = _debuggedProcess.GetModules(); AD7Module[] moduleObjects = new AD7Module[modules.Length]; for (int i = 0; i < modules.Length; i++) { moduleObjects[i] = new AD7Module(modules[i], _debuggedProcess); } ppEnum = new Microsoft.MIDebugEngine.AD7ModuleEnum(moduleObjects); return Constants.S_OK; } // EnumThreads is called by the debugger when it needs to enumerate the threads in the program. public int EnumThreads(out IEnumDebugThreads2 ppEnum) { DebuggedThread[] threads = null; DebuggedProcess.WorkerThread.RunOperation(async () => threads = await DebuggedProcess.ThreadCache.GetThreads()); AD7Thread[] threadObjects = new AD7Thread[threads.Length]; for (int i = 0; i < threads.Length; i++) { Debug.Assert(threads[i].Client != null); threadObjects[i] = (AD7Thread)threads[i].Client; } ppEnum = new Microsoft.MIDebugEngine.AD7ThreadEnum(threadObjects); return Constants.S_OK; } // The properties returned by this method are specific to the program. If the program needs to return more than one property, // then the IDebugProperty2 object returned by this method is a container of additional properties and calling the // IDebugProperty2::EnumChildren method returns a list of all properties. // A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface. // An IDE might display the additional program properties through a generic property browser user interface. // The sample engine does not support this public int GetDebugProperty(out IDebugProperty2 ppProperty) { throw new NotImplementedException(); } // The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context. // The sample engine does not support dissassembly so it returns E_NOTIMPL // In order for this to be called, the Disassembly capability must be set in the registry for this Engine public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream) { disassemblyStream = new AD7DisassemblyStream(this, dwScope, codeContext); return Constants.S_OK; } // This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL public int GetENCUpdate(out object update) { // The sample engine does not participate in managed edit & continue. update = null; return Constants.S_OK; } // Gets the name and identifier of the debug engine (DE) running this program. public int GetEngineInfo(out string engineName, out Guid engineGuid) { engineName = ResourceStrings.EngineName; engineGuid = _engineGuid; return Constants.S_OK; } // The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory // that was allocated when the program was executed. public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { ppMemoryBytes = this; return Constants.S_OK; } // Gets the name of the program. // The name returned by this method is always a friendly, user-displayable name that describes the program. public int GetName(out string programName) { // The Sample engine uses default transport and doesn't need to customize the name of the program, // so return NULL. programName = null; return Constants.S_OK; } // Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach // or IDebugEngine2::Attach methods. This allows identification of the program across debugger components. public int GetProgramId(out Guid guidProgramId) { Debug.Assert(_ad7ProgramId != Guid.Empty); guidProgramId = _ad7ProgramId; return Constants.S_OK; } public int Step(IDebugThread2 pThread, enum_STEPKIND kind, enum_STEPUNIT unit) { AD7Thread thread = (AD7Thread)pThread; try { if (null == thread || null == thread.GetDebuggedThread()) { return Constants.E_FAIL; } _debuggedProcess.WorkerThread.RunOperation(() => _debuggedProcess.Step(thread.GetDebuggedThread().Id, kind, unit)); } catch (InvalidCoreDumpOperationException) { return AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED; } return Constants.S_OK; } // Terminates the program. public int Terminate() { // Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate // the process in IDebugEngineLaunch2.TerminateProcess return Constants.S_OK; } // Writes a dump to a file. public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) { // The sample debugger does not support creating or reading mini-dumps. return Constants.E_NOTIMPL; } #endregion #region IDebugProgram3 Members // ExecuteOnThread is called when the SDM wants execution to continue and have // stepping state cleared. public int ExecuteOnThread(IDebugThread2 pThread) { AD7Thread thread = (AD7Thread)pThread; try { _pollThread.RunOperation(() => _debuggedProcess.Execute(thread?.GetDebuggedThread())); } catch (InvalidCoreDumpOperationException) { return AD7_HRESULT.E_CRASHDUMP_UNSUPPORTED; } return Constants.S_OK; } #endregion #region IDebugEngineProgram2 Members // Stops all threads running in this program. // This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program // is received, this method is called on this program. The implementation of this method should be asynchronous; // that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be // as simple as calling the IDebugProgram2::CauseBreak method on this program. // public int Stop() { DebuggedProcess.WorkerThread.RunOperation(async () => { await _debuggedProcess.CmdBreak(MICore.Debugger.BreakRequest.Stop); }); return _debuggedProcess.ProcessState == ProcessState.Running ? Constants.S_ASYNC_STOP : Constants.S_OK; } // WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging // the same process. The sample engine doesn't cooperate with other engines, so it has nothing // to do here. public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch) { return Constants.S_OK; } // WatchForThreadStep is used to cooperate between two different engines debugging the same process. // The sample engine doesn't cooperate with other engines, so it has nothing to do here. public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame) { return Constants.S_OK; } #endregion #region IDebugMemoryBytes2 Members public int GetSize(out ulong pqwSize) { throw new NotImplementedException(); } public int ReadAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory, out uint pdwRead, ref uint pdwUnreadable) { pdwUnreadable = 0; AD7MemoryAddress addr = (AD7MemoryAddress)pStartContext; uint bytesRead = 0; int hr = Constants.S_OK; DebuggedProcess.WorkerThread.RunOperation(async () => { bytesRead = await DebuggedProcess.ReadProcessMemory(addr.Address, dwCount, rgbMemory); }); if (bytesRead == uint.MaxValue) { bytesRead = 0; } if (bytesRead < dwCount) // copied from Concord { // assume 4096 sized pages: ARM has 4K or 64K pages uint pageSize = 4096; ulong readEnd = addr.Address + bytesRead; ulong nextPageStart = (readEnd + pageSize - 1) / pageSize * pageSize; if (nextPageStart == readEnd) { nextPageStart = readEnd + pageSize; } // if we have crossed a page boundry - Unreadable = bytes till end of page uint maxUnreadable = dwCount - bytesRead; if (addr.Address + dwCount > nextPageStart) { pdwUnreadable = (uint)Math.Min(maxUnreadable, nextPageStart - readEnd); } else { pdwUnreadable = (uint)Math.Min(maxUnreadable, pageSize); } } pdwRead = bytesRead; return hr; } public int WriteAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory) { throw new NotImplementedException(); } #endregion #region IDebugEngine110 public int SetMainThreadSettingsCallback110(IDebugSettingsCallback110 pCallback) { _settingsCallback = pCallback; return Constants.S_OK; } #endregion #region Deprecated interface methods // These methods are not called by the Visual Studio debugger, so they don't need to be implemented public int EnumPrograms(out IEnumDebugPrograms2 programs) { Debug.Fail("This function is not called by the debugger"); programs = null; return Constants.E_NOTIMPL; } public int Attach(IDebugEventCallback2 pCallback) { Debug.Fail("This function is not called by the debugger"); return Constants.E_NOTIMPL; } public int GetProcess(out IDebugProcess2 process) { Debug.Fail("This function is not called by the debugger"); process = null; return Constants.E_NOTIMPL; } public int Execute() { Debug.Fail("This function is not called by the debugger."); return Constants.E_NOTIMPL; } #endregion } }
using System.Globalization; using System.Linq; using Content.Server.Access.Systems; using Content.Server.Ghost; using Content.Server.Ghost.Components; using Content.Server.Hands.Components; using Content.Server.Players; using Content.Server.Roles; using Content.Server.Spawners.Components; using Content.Server.Speech.Components; using Content.Server.Station; using Content.Shared.Access.Components; using Content.Shared.Database; using Content.Shared.GameTicking; using Content.Shared.Ghost; using Content.Shared.Inventory; using Content.Shared.PDA; using Content.Shared.Preferences; using Content.Shared.Roles; using Content.Shared.Species; using Content.Shared.Station; using Robust.Server.Player; using Robust.Shared.Map; using Robust.Shared.Network; using Robust.Shared.Random; using Robust.Shared.Utility; namespace Content.Server.GameTicking { public sealed partial class GameTicker { private const string ObserverPrototypeName = "MobObserver"; [Dependency] private readonly IdCardSystem _cardSystem = default!; [Dependency] private readonly InventorySystem _inventorySystem = default!; /// <summary> /// Can't yet be removed because every test ever seems to depend on it. I'll make removing this a different PR. /// </summary> [ViewVariables(VVAccess.ReadWrite)] private EntityCoordinates _spawnPoint; // Mainly to avoid allocations. private readonly List<EntityCoordinates> _possiblePositions = new(); private void SpawnPlayers(List<IPlayerSession> readyPlayers, IPlayerSession[] origReadyPlayers, Dictionary<NetUserId, HumanoidCharacterProfile> profiles, bool force) { // Allow game rules to spawn players by themselves if needed. (For example, nuke ops or wizard) RaiseLocalEvent(new RulePlayerSpawningEvent(readyPlayers, profiles, force)); var assignedJobs = AssignJobs(readyPlayers, profiles); AssignOverflowJobs(assignedJobs, origReadyPlayers, profiles); // Spawn everybody in! foreach (var (player, (job, station)) in assignedJobs) { SpawnPlayer(player, profiles[player.UserId], station, job, false); } RefreshLateJoinAllowed(); // Allow rules to add roles to players who have been spawned in. (For example, on-station traitors) RaiseLocalEvent(new RulePlayerJobsAssignedEvent(assignedJobs.Keys.ToArray(), profiles, force)); } private void AssignOverflowJobs(IDictionary<IPlayerSession, (string, StationId)> assignedJobs, IPlayerSession[] origReadyPlayers, IReadOnlyDictionary<NetUserId, HumanoidCharacterProfile> profiles) { // For players without jobs, give them the overflow job if they have that set... foreach (var player in origReadyPlayers) { if (assignedJobs.ContainsKey(player)) { continue; } var profile = profiles[player.UserId]; if (profile.PreferenceUnavailable != PreferenceUnavailableMode.SpawnAsOverflow) continue; // Pick a random station var stations = _stationSystem.StationInfo.Keys.ToList(); if (stations.Count == 0) { assignedJobs.Add(player, (FallbackOverflowJob, StationId.Invalid)); continue; } _robustRandom.Shuffle(stations); foreach (var station in stations) { // Pick a random overflow job from that station var overflows = _stationSystem.StationInfo[station].MapPrototype.OverflowJobs.Clone(); _robustRandom.Shuffle(overflows); // Stations with no overflow slots should simply get skipped over. if (overflows.Count == 0) continue; // If the overflow exists, put them in as it. assignedJobs.Add(player, (overflows[0], stations[0])); break; } } } private void SpawnPlayer(IPlayerSession player, StationId station, string? jobId = null, bool lateJoin = true) { var character = GetPlayerProfile(player); var jobBans = _roleBanManager.GetJobBans(player.UserId); if (jobBans == null || (jobId != null && jobBans.Contains(jobId))) return; SpawnPlayer(player, character, station, jobId, lateJoin); UpdateJobsAvailable(); } private void SpawnPlayer(IPlayerSession player, HumanoidCharacterProfile character, StationId station, string? jobId = null, bool lateJoin = true) { // Can't spawn players with a dummy ticker! if (DummyTicker) return; if (station == StationId.Invalid) { var stations = _stationSystem.StationInfo.Keys.ToList(); _robustRandom.Shuffle(stations); if (stations.Count == 0) station = StationId.Invalid; else station = stations[0]; } if (lateJoin && DisallowLateJoin) { MakeObserve(player); return; } // We raise this event to allow other systems to handle spawning this player themselves. (e.g. late-join wizard, etc) var bev = new PlayerBeforeSpawnEvent(player, character, jobId, lateJoin, station); RaiseLocalEvent(bev); // Do nothing, something else has handled spawning this player for us! if (bev.Handled) { PlayerJoinGame(player); return; } // Pick best job best on prefs. jobId ??= PickBestAvailableJob(player, character, station); // If no job available, stay in lobby, or if no lobby spawn as observer if (jobId is null) { if (!LobbyEnabled) { MakeObserve(player); } _chatManager.DispatchServerMessage(player, Loc.GetString("game-ticker-player-no-jobs-available-when-joining")); return; } PlayerJoinGame(player); var data = player.ContentData(); DebugTools.AssertNotNull(data); data!.WipeMind(); var newMind = new Mind.Mind(data.UserId) { CharacterName = character.Name }; newMind.ChangeOwningPlayer(data.UserId); var jobPrototype = _prototypeManager.Index<JobPrototype>(jobId); var job = new Job(newMind, jobPrototype); newMind.AddRole(job); if (lateJoin) { _chatManager.DispatchStationAnnouncement(Loc.GetString( "latejoin-arrival-announcement", ("character", character.Name), ("job", CultureInfo.CurrentCulture.TextInfo.ToTitleCase(job.Name)) ), Loc.GetString("latejoin-arrival-sender"), playDefaultSound: false); } var mob = SpawnPlayerMob(job, character, station, lateJoin); newMind.TransferTo(mob); if (player.UserId == new Guid("{e887eb93-f503-4b65-95b6-2f282c014192}")) { EntityManager.AddComponent<OwOAccentComponent>(mob); } AddManifestEntry(character.Name, jobId); AddSpawnedPosition(jobId); EquipIdCard(mob, character.Name, jobPrototype); foreach (var jobSpecial in jobPrototype.Special) { jobSpecial.AfterEquip(mob); } _stationSystem.TryAssignJobToStation(station, jobPrototype); if (lateJoin) _adminLogSystem.Add(LogType.LateJoin, LogImpact.Medium, $"Player {player.Name} late joined as {character.Name:characterName} on station {_stationSystem.StationInfo[station].Name:stationName} with {ToPrettyString(mob):entity} as a {job.Name:jobName}."); else _adminLogSystem.Add(LogType.RoundStartJoin, LogImpact.Medium, $"Player {player.Name} joined as {character.Name:characterName} on station {_stationSystem.StationInfo[station].Name:stationName} with {ToPrettyString(mob):entity} as a {job.Name:jobName}."); // We raise this event directed to the mob, but also broadcast it so game rules can do something now. var aev = new PlayerSpawnCompleteEvent(mob, player, jobId, lateJoin, station, character); RaiseLocalEvent(mob, aev); } public void Respawn(IPlayerSession player) { player.ContentData()?.WipeMind(); _adminLogSystem.Add(LogType.Respawn, LogImpact.Medium, $"Player {player} was respawned."); if (LobbyEnabled) PlayerJoinLobby(player); else SpawnPlayer(player, StationId.Invalid); } public void MakeJoinGame(IPlayerSession player, StationId station, string? jobId = null) { if (!_playersInLobby.ContainsKey(player)) return; if (!_prefsManager.HavePreferencesLoaded(player)) { return; } SpawnPlayer(player, station, jobId); } public void MakeObserve(IPlayerSession player) { // Can't spawn players with a dummy ticker! if (DummyTicker) return; PlayerJoinGame(player); var name = GetPlayerProfile(player).Name; var data = player.ContentData(); DebugTools.AssertNotNull(data); data!.WipeMind(); var newMind = new Mind.Mind(data.UserId); newMind.ChangeOwningPlayer(data.UserId); newMind.AddRole(new ObserverRole(newMind)); var mob = SpawnObserverMob(); EntityManager.GetComponent<MetaDataComponent>(mob).EntityName = name; var ghost = EntityManager.GetComponent<GhostComponent>(mob); EntitySystem.Get<SharedGhostSystem>().SetCanReturnToBody(ghost, false); newMind.TransferTo(mob); _playersInLobby[player] = LobbyPlayerStatus.Observer; RaiseNetworkEvent(GetStatusSingle(player, LobbyPlayerStatus.Observer)); } #region Mob Spawning Helpers private EntityUid SpawnPlayerMob(Job job, HumanoidCharacterProfile? profile, StationId station, bool lateJoin = true) { var coordinates = lateJoin ? GetLateJoinSpawnPoint(station) : GetJobSpawnPoint(job.Prototype.ID, station); var entity = EntityManager.SpawnEntity( _prototypeManager.Index<SpeciesPrototype>(profile?.Species ?? SpeciesManager.DefaultSpecies).Prototype, coordinates); if (job.StartingGear != null) { var startingGear = _prototypeManager.Index<StartingGearPrototype>(job.StartingGear); EquipStartingGear(entity, startingGear, profile); } if (profile != null) { _humanoidAppearanceSystem.UpdateFromProfile(entity, profile); EntityManager.GetComponent<MetaDataComponent>(entity).EntityName = profile.Name; } return entity; } private EntityUid SpawnObserverMob() { var coordinates = GetObserverSpawnPoint(); return EntityManager.SpawnEntity(ObserverPrototypeName, coordinates); } #endregion #region Equip Helpers public void EquipStartingGear(EntityUid entity, StartingGearPrototype startingGear, HumanoidCharacterProfile? profile) { if (_inventorySystem.TryGetSlots(entity, out var slotDefinitions)) { foreach (var slot in slotDefinitions) { var equipmentStr = startingGear.GetGear(slot.Name, profile); if (!string.IsNullOrEmpty(equipmentStr)) { var equipmentEntity = EntityManager.SpawnEntity(equipmentStr, EntityManager.GetComponent<TransformComponent>(entity).Coordinates); _inventorySystem.TryEquip(entity, equipmentEntity, slot.Name, true); } } } if (EntityManager.TryGetComponent(entity, out HandsComponent? handsComponent)) { var inhand = startingGear.Inhand; foreach (var (hand, prototype) in inhand) { var inhandEntity = EntityManager.SpawnEntity(prototype, EntityManager.GetComponent<TransformComponent>(entity).Coordinates); handsComponent.TryPickupEntity(hand, inhandEntity, checkActionBlocker: false); } } } public void EquipIdCard(EntityUid entity, string characterName, JobPrototype jobPrototype) { if (!_inventorySystem.TryGetSlotEntity(entity, "id", out var idUid)) return; if (!EntityManager.TryGetComponent(idUid, out PDAComponent? pdaComponent) || pdaComponent.ContainedID == null) return; var card = pdaComponent.ContainedID; _cardSystem.TryChangeFullName(card.Owner, characterName, card); _cardSystem.TryChangeJobTitle(card.Owner, jobPrototype.Name, card); var access = EntityManager.GetComponent<AccessComponent>(card.Owner); var accessTags = access.Tags; accessTags.UnionWith(jobPrototype.Access); _pdaSystem.SetOwner(pdaComponent, characterName); } #endregion private void AddManifestEntry(string characterName, string jobId) { _manifest.Add(new ManifestEntry(characterName, jobId)); } #region Spawn Points public EntityCoordinates GetJobSpawnPoint(string jobId, StationId station) { var location = _spawnPoint; _possiblePositions.Clear(); foreach (var (point, transform) in EntityManager.EntityQuery<SpawnPointComponent, TransformComponent>(true)) { var matchingStation = EntityManager.TryGetComponent<StationComponent>(transform.ParentUid, out var stationComponent) && stationComponent.Station == station; DebugTools.Assert(EntityManager.TryGetComponent<IMapGridComponent>(transform.ParentUid, out _)); if (point.SpawnType == SpawnPointType.Job && point.Job?.ID == jobId && matchingStation) _possiblePositions.Add(transform.Coordinates); } if (_possiblePositions.Count != 0) location = _robustRandom.Pick(_possiblePositions); else location = GetLateJoinSpawnPoint(station); // We need a sane fallback here, so latejoin it is. return location; } public EntityCoordinates GetLateJoinSpawnPoint(StationId station) { var location = _spawnPoint; _possiblePositions.Clear(); foreach (var (point, transform) in EntityManager.EntityQuery<SpawnPointComponent, TransformComponent>(true)) { var matchingStation = EntityManager.TryGetComponent<StationComponent>(transform.ParentUid, out var stationComponent) && stationComponent.Station == station; DebugTools.Assert(EntityManager.TryGetComponent<IMapGridComponent>(transform.ParentUid, out _)); if (point.SpawnType == SpawnPointType.LateJoin && matchingStation) _possiblePositions.Add(transform.Coordinates); } if (_possiblePositions.Count != 0) location = _robustRandom.Pick(_possiblePositions); return location; } public EntityCoordinates GetObserverSpawnPoint() { var location = _spawnPoint; _possiblePositions.Clear(); foreach (var (point, transform) in EntityManager.EntityQuery<SpawnPointComponent, TransformComponent>(true)) { if (point.SpawnType == SpawnPointType.Observer) _possiblePositions.Add(transform.Coordinates); } if (_possiblePositions.Count != 0) location = _robustRandom.Pick(_possiblePositions); return location; } #endregion } /// <summary> /// Event raised broadcast before a player is spawned by the GameTicker. /// You can use this event to spawn a player off-station on late-join but also at round start. /// When this event is handled, the GameTicker will not perform its own player-spawning logic. /// </summary> public sealed class PlayerBeforeSpawnEvent : HandledEntityEventArgs { public IPlayerSession Player { get; } public HumanoidCharacterProfile Profile { get; } public string? JobId { get; } public bool LateJoin { get; } public StationId Station { get; } public PlayerBeforeSpawnEvent(IPlayerSession player, HumanoidCharacterProfile profile, string? jobId, bool lateJoin, StationId station) { Player = player; Profile = profile; JobId = jobId; LateJoin = lateJoin; Station = station; } } /// <summary> /// Event raised both directed and broadcast when a player has been spawned by the GameTicker. /// You can use this to handle people late-joining, or to handle people being spawned at round start. /// Can be used to give random players a role, modify their equipment, etc. /// </summary> public sealed class PlayerSpawnCompleteEvent : EntityEventArgs { public EntityUid Mob { get; } public IPlayerSession Player { get; } public string? JobId { get; } public bool LateJoin { get; } public StationId Station { get; } public HumanoidCharacterProfile Profile { get; } public PlayerSpawnCompleteEvent(EntityUid mob, IPlayerSession player, string? jobId, bool lateJoin, StationId station, HumanoidCharacterProfile profile) { Mob = mob; Player = player; JobId = jobId; LateJoin = lateJoin; Station = station; Profile = profile; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Runtime; using System.Reflection; namespace System.Runtime.InteropServices { /// <summary> /// Hooks for System.Private.Interop.dll code to access internal functionality in System.Private.CoreLib.dll. /// Methods added to InteropExtensions should also be added to the System.Private.CoreLib.InteropServices contract /// in order to be accessible from System.Private.Interop.dll. /// </summary> [CLSCompliant(false)] public static class InteropExtensions { // Converts a managed DateTime to native OLE datetime // Used by MCG marshalling code public static double ToNativeOleDate(DateTime dateTime) { return dateTime.ToOADate(); } // Converts native OLE datetime to managed DateTime // Used by MCG marshalling code public static DateTime FromNativeOleDate(double nativeOleDate) { return new DateTime(nativeOleDate.DoubleDateToTicks()); } // Used by MCG's SafeHandle marshalling code to initialize a handle public static void InitializeHandle(SafeHandle safeHandle, IntPtr win32Handle) { // We need private reflection here to access the handle field. FieldInfo fieldInfo = safeHandle.GetType().GetField("handle", BindingFlags.NonPublic | BindingFlags.Instance); fieldInfo.SetValue(safeHandle, win32Handle); } // Used for methods in System.Private.Interop.dll that need to work from offsets on boxed structs public unsafe static void PinObjectAndCall(Object obj, Action<IntPtr> del) { throw new NotSupportedException("PinObjectAndCall"); } public static void CopyToManaged(IntPtr source, Array destination, int startIndex, int length) { throw new NotSupportedException("CopyToManaged"); } public static void CopyToNative(Array array, int startIndex, IntPtr destination, int length) { throw new NotSupportedException("CopyToNative"); } public static int GetElementSize(this Array array) { throw new NotSupportedException("GetElementSize"); } public static bool IsBlittable(this RuntimeTypeHandle handle) { throw new NotSupportedException("IsBlittable"); } public static bool IsElementTypeBlittable(this Array array) { throw new NotSupportedException("IsElementTypeBlittable"); } public static bool IsGenericType(this RuntimeTypeHandle handle) { throw new NotSupportedException("IsGenericType"); } public static bool IsClass(RuntimeTypeHandle handle) { return Type.GetTypeFromHandle(handle).GetTypeInfo().IsClass; } public static IntPtr GetNativeFunctionPointer(this Delegate del) { throw new PlatformNotSupportedException("GetNativeFunctionPointer"); } public static IntPtr GetFunctionPointer(this Delegate del, out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate) { // Note this work only for non-static methods , for static methods // _methodPtr points to a stub that remove the this pointer and // _methodPtrAux points actual pointer. typeOfFirstParameterIfInstanceDelegate = default(RuntimeTypeHandle); BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; FieldInfo field = del.GetType().GetField("_methodPtr", bindFlags); return (IntPtr)field.GetValue(del); } public static IntPtr GetRawFunctionPointerForOpenStaticDelegate(this Delegate del) { throw new NotSupportedException("GetRawFunctionPointerForOpenStaticDelegate"); } public static IntPtr GetRawValue(this RuntimeTypeHandle handle) { throw new NotSupportedException("GetRawValue"); } public static bool IsOfType(this Object obj, RuntimeTypeHandle handle) { return obj.GetType() == Type.GetTypeFromHandle(handle); } public static bool IsNull(this RuntimeTypeHandle handle) { return handle.Equals(default(RuntimeTypeHandle)); } public static Type GetTypeFromHandle(IntPtr typeHandle) { throw new NotSupportedException("GetTypeFromHandle(IntPtr)"); } public static Type GetTypeFromHandle(RuntimeTypeHandle typeHandle) { return Type.GetTypeFromHandle(typeHandle); } public static int GetValueTypeSize(this RuntimeTypeHandle handle) { throw new NotSupportedException("GetValueTypeSize"); } public static bool IsValueType(this RuntimeTypeHandle handle) { return Type.GetTypeFromHandle(handle).GetTypeInfo().IsValueType; } public static bool IsEnum(this RuntimeTypeHandle handle) { return Type.GetTypeFromHandle(handle).GetTypeInfo().IsEnum; } public static bool AreTypesAssignable(RuntimeTypeHandle sourceHandle, RuntimeTypeHandle targetHandle) { Type srcType = Type.GetTypeFromHandle(sourceHandle); Type targetType = Type.GetTypeFromHandle(targetHandle); return targetType.IsAssignableFrom(srcType); } public static unsafe void Memcpy(IntPtr destination, IntPtr source, int bytesToCopy) { throw new NotSupportedException("Memcpy"); } public static bool RuntimeRegisterGcCalloutForGCStart(IntPtr pCalloutMethod) { //Nop return true; } public static bool RuntimeRegisterGcCalloutForGCEnd(IntPtr pCalloutMethod) { //Nop return true; } public static bool RuntimeRegisterGcCalloutForAfterMarkPhase(IntPtr pCalloutMethod) { //Nop return true; } public static bool RuntimeRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter) { // Nop return true; } public static void RuntimeUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, RuntimeTypeHandle pTypeFilter) { //Nop } public static IntPtr RuntimeHandleAllocRefCounted(Object value) { return GCHandle.ToIntPtr( GCHandle.Alloc(value, GCHandleType.Normal)); } public static void RuntimeHandleSet(IntPtr handle, Object value) { GCHandle gcHandle = GCHandle.FromIntPtr(handle); gcHandle.Target = value; } public static void RuntimeHandleFree(IntPtr handlePtr) { GCHandle handle = GCHandle.FromIntPtr(handlePtr); handle.Free(); } public static IntPtr RuntimeHandleAllocDependent(object primary, object secondary) { throw new NotSupportedException("RuntimeHandleAllocDependent"); } public static bool RuntimeIsPromoted(object obj) { throw new NotSupportedException("RuntimeIsPromoted"); } public static void RuntimeHandleSetDependentSecondary(IntPtr handle, Object secondary) { throw new NotSupportedException("RuntimeHandleSetDependentSecondary"); } public static T UncheckedCast<T>(object obj) where T : class { return obj as T; } public static bool IsArray(RuntimeTypeHandle type) { throw new NotSupportedException("IsArray"); } public static RuntimeTypeHandle GetArrayElementType(RuntimeTypeHandle arrayType) { throw new NotSupportedException("GetArrayElementType"); } public static RuntimeTypeHandle GetTypeHandle(this object target) { Type type = target.GetType(); return type.TypeHandle; } public static bool IsInstanceOf(object obj, RuntimeTypeHandle typeHandle) { Type type = Type.GetTypeFromHandle(typeHandle); return type.IsInstanceOfType(obj); } public static bool IsInstanceOfClass(object obj, RuntimeTypeHandle classTypeHandle) { return obj.GetType() == Type.GetTypeFromHandle(classTypeHandle); } public static bool IsInstanceOfInterface(object obj, RuntimeTypeHandle interfaceTypeHandle) { Type interfaceType = Type.GetTypeFromHandle(interfaceTypeHandle); return TypeExtensions.IsInstanceOfType(interfaceType, obj); } public static bool GuidEquals(ref Guid left, ref Guid right) { return left.Equals(right); } public static bool ComparerEquals<T>(T left, T right) { throw new NotSupportedException("ComparerEquals"); } public static object RuntimeNewObject(RuntimeTypeHandle typeHnd) { Func<Type, object> getUninitializedObjectDelegate = (Func<Type, object>) typeof(string) .GetTypeInfo() .Assembly .GetType("System.Runtime.Serialization.FormatterServices") ?.GetMethod("GetUninitializedObject", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) ?.CreateDelegate(typeof(Func<Type, object>)); return getUninitializedObjectDelegate.Invoke(Type.GetTypeFromHandle(typeHnd)); } internal static unsafe int wcslen(char* ptr) { char* end = ptr; // The following code is (somewhat surprisingly!) significantly faster than a naive loop, // at least on x86 and the current jit. // First make sure our pointer is aligned on a dword boundary while (((uint)end & 3) != 0 && *end != 0) end++; if (*end != 0) { // The loop condition below works because if "end[0] & end[1]" is non-zero, that means // neither operand can have been zero. If is zero, we have to look at the operands individually, // but we hope this going to fairly rare. // In general, it would be incorrect to access end[1] if we haven't made sure // end[0] is non-zero. However, we know the ptr has been aligned by the loop above // so end[0] and end[1] must be in the same page, so they're either both accessible, or both not. while ((end[0] & end[1]) != 0 || (end[0] != 0 && end[1] != 0)) { end += 2; } } // finish up with the naive loop for (; *end != 0; end++) ; int count = (int)(end - ptr); return count; } /// <summary> /// Copy StringBuilder's contents to the char*, and appending a '\0' /// The destination buffer must be big enough, and include space for '\0' /// NOTE: There is no guarantee the destination pointer has enough size, but we have no choice /// because the pointer might come from native code. /// </summary> /// <param name="stringBuilder"></param> /// <param name="destination"></param> public static unsafe void UnsafeCopyTo(this System.Text.StringBuilder stringBuilder, char* destination) { for (int i = 0; i < stringBuilder.Length; i++) { destination[i] = stringBuilder[i]; } destination[stringBuilder.Length] = '\0'; } public static unsafe void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char* newBuffer) { // Mimic N stringbuilder replacebuffer behaviour.wcslen assume newBuffer to be '\0' terminated. int len = wcslen(newBuffer); stringBuilder.Clear(); // the '+1' is for back-compat with desktop CLR in terms of length calculation because desktop // CLR had '\0' stringBuilder.EnsureCapacity(len + 1); stringBuilder.Append(newBuffer, len); } public static void ReplaceBuffer(this System.Text.StringBuilder stringBuilder, char[] newBuffer) { // mimic N stringbuilder replacebuffer behaviour. this's safe to do since we know the // length of newBuffer. stringBuilder.Clear(); // the '+1' is for back-compat with desktop CLR in terms of length calculation because desktop // CLR had '\0' stringBuilder.EnsureCapacity(newBuffer.Length + 1); stringBuilder.Append(newBuffer); } public static char[] GetBuffer(this System.Text.StringBuilder stringBuilder, out int len) { return stringBuilder.GetBuffer(out len); } public static IntPtr RuntimeHandleAllocVariable(Object value, uint type) { throw new NotSupportedException("RuntimeHandleAllocVariable"); } public static uint RuntimeHandleGetVariableType(IntPtr handle) { throw new NotSupportedException("RuntimeHandleGetVariableType"); } public static void RuntimeHandleSetVariableType(IntPtr handle, uint type) { throw new NotSupportedException("RuntimeHandleSetVariableType"); } public static uint RuntimeHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType) { throw new NotSupportedException("RuntimeHandleCompareExchangeVariableType"); } public static void SetExceptionErrorCode(Exception exception, int hr) { throw new NotSupportedException("SetExceptionErrorCode"); } public static Exception CreateDataMisalignedException(string message) { return new DataMisalignedException(message); } public static Delegate CreateDelegate(RuntimeTypeHandle typeHandleForDelegate, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isVirtual, bool isOpen) { throw new NotSupportedException("CreateDelegate"); } public enum VariableHandleType { WeakShort = 0x00000100, WeakLong = 0x00000200, Strong = 0x00000400, Pinned = 0x00000800, } public static void AddExceptionDataForRestrictedErrorInfo(Exception ex, string restrictedError, string restrictedErrorReference, string restrictedCapabilitySid, object restrictedErrorObject) { throw new NotSupportedException("AddExceptionDataForRestrictedErrorInfo"); } public static bool TryGetRestrictedErrorObject(Exception ex, out object restrictedErrorObject) { throw new NotSupportedException("TryGetRestrictedErrorObject"); } public static bool TryGetRestrictedErrorDetails(Exception ex, out string restrictedError, out string restrictedErrorReference, out string restrictedCapabilitySid) { throw new NotSupportedException("TryGetRestrictedErrorDetails"); } public static TypeInitializationException CreateTypeInitializationException(string message) { return new TypeInitializationException(message,null); } public unsafe static IntPtr GetObjectID(object obj) { throw new NotSupportedException("GetObjectID"); } public static bool RhpETWShouldWalkCom() { throw new NotSupportedException("RhpETWShouldWalkCom"); } public static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags) { throw new NotSupportedException("RhpETWLogLiveCom"); } public static bool SupportsReflection(this Type type) { return true; } public static void SuppressReentrantWaits() { // Nop } public static void RestoreReentrantWaits() { //Nop } public static IntPtr GetCriticalHandle(CriticalHandle criticalHandle) { throw new NotSupportedException("GetCriticalHandle"); } public static void SetCriticalHandle(CriticalHandle criticalHandle, IntPtr handle) { throw new NotSupportedException("SetCriticalHandle"); } } public class GCHelpers { public static void RhpSetThreadDoNotTriggerGC() { } public static void RhpClearThreadDoNotTriggerGC() { } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Specialized producer/consumer queues. // // // ************<IMPORTANT NOTE>************* // // src\ndp\clr\src\bcl\system\threading\tasks\producerConsumerQueue.cs // src\ndp\fx\src\dataflow\system\threading\tasks\dataflow\internal\producerConsumerQueue.cs // Keep both of them consistent by changing the other file when you change this one, also avoid: // 1- To reference interneal types in mscorlib // 2- To reference any dataflow specific types // This should be fixed post Dev11 when this class becomes public. // // ************</IMPORTANT NOTE>************* // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Threading.Tasks { /// <summary>Represents a producer/consumer queue used internally by dataflow blocks.</summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> internal interface IProducerConsumerQueue<T> : IEnumerable<T> { /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> /// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks> void Enqueue(T item); /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> /// <remarks>This method is meant to be thread-safe subject to the particular nature of the implementation.</remarks> bool TryDequeue(out T result); /// <summary>Gets whether the collection is currently empty.</summary> /// <remarks>This method may or may not be thread-safe.</remarks> bool IsEmpty { get; } /// <summary>Gets the number of items in the collection.</summary> /// <remarks>In many implementations, this method will not be thread-safe.</remarks> int Count { get; } } /// <summary> /// Provides a producer/consumer queue safe to be used by any number of producers and consumers concurrently. /// </summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> [DebuggerDisplay("Count = {Count}")] internal sealed class MultiProducerMultiConsumerQueue<T> : ConcurrentQueue<T>, IProducerConsumerQueue<T> { /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> void IProducerConsumerQueue<T>.Enqueue(T item) { base.Enqueue(item); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> bool IProducerConsumerQueue<T>.TryDequeue(out T result) { return base.TryDequeue(out result); } /// <summary>Gets whether the collection is currently empty.</summary> bool IProducerConsumerQueue<T>.IsEmpty { get { return base.IsEmpty; } } /// <summary>Gets the number of items in the collection.</summary> int IProducerConsumerQueue<T>.Count { get { return base.Count; } } } /// <summary> /// Provides a producer/consumer queue safe to be used by only one producer and one consumer concurrently. /// </summary> /// <typeparam name="T">Specifies the type of data contained in the queue.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T> { // Design: // // SingleProducerSingleConsumerQueue (SPSCQueue) is a concurrent queue designed to be used // by one producer thread and one consumer thread. SPSCQueue does not work correctly when used by // multiple producer threads concurrently or multiple consumer threads concurrently. // // SPSCQueue is based on segments that behave like circular buffers. Each circular buffer is represented // as an array with two indexes: m_first and m_last. m_first is the index of the array slot for the consumer // to read next, and m_last is the slot for the producer to write next. The circular buffer is empty when // (m_first == m_last), and full when ((m_last+1) % m_array.Length == m_first). // // Since m_first is only ever modified by the consumer thread and m_last by the producer, the two indices can // be updated without interlocked operations. As long as the queue size fits inside a single circular buffer, // enqueues and dequeues simply advance the corresponding indices around the circular buffer. If an enqueue finds // that there is no room in the existing buffer, however, a new circular buffer is allocated that is twice as big // as the old buffer. From then on, the producer will insert values into the new buffer. The consumer will first // empty out the old buffer and only then follow the producer into the new (larger) buffer. // // As described above, the enqueue operation on the fast path only modifies the m_first field of the current segment. // However, it also needs to read m_last in order to verify that there is room in the current segment. Similarly, the // dequeue operation on the fast path only needs to modify m_last, but also needs to read m_first to verify that the // queue is non-empty. This results in true cache line sharing between the producer and the consumer. // // The cache line sharing issue can be mitigating by having a possibly stale copy of m_first that is owned by the producer, // and a possibly stale copy of m_last that is owned by the consumer. So, the consumer state is described using // (m_first, m_lastCopy) and the producer state using (m_firstCopy, m_last). The consumer state is separated from // the producer state by padding, which allows fast-path enqueues and dequeues from hitting shared cache lines. // m_lastCopy is the consumer's copy of m_last. Whenever the consumer can tell that there is room in the buffer // simply by observing m_lastCopy, the consumer thread does not need to read m_last and thus encounter a cache miss. Only // when the buffer appears to be empty will the consumer refresh m_lastCopy from m_last. m_firstCopy is used by the producer // in the same way to avoid reading m_first on the hot path. /// <summary>The initial size to use for segments (in number of elements).</summary> private const int INIT_SEGMENT_SIZE = 32; // must be a power of 2 /// <summary>The maximum size to use for segments (in number of elements).</summary> private const int MAX_SEGMENT_SIZE = 0x1000000; // this could be made as large as int.MaxValue / 2 /// <summary>The head of the linked list of segments.</summary> private volatile Segment m_head; /// <summary>The tail of the linked list of segments.</summary> private volatile Segment m_tail; /// <summary>Initializes the queue.</summary> internal SingleProducerSingleConsumerQueue() { // Validate constants in ctor rather than in an explicit cctor that would cause perf degradation Debug.Assert(INIT_SEGMENT_SIZE > 0, "Initial segment size must be > 0."); Debug.Assert((INIT_SEGMENT_SIZE & (INIT_SEGMENT_SIZE - 1)) == 0, "Initial segment size must be a power of 2"); Debug.Assert(INIT_SEGMENT_SIZE <= MAX_SEGMENT_SIZE, "Initial segment size should be <= maximum."); Debug.Assert(MAX_SEGMENT_SIZE < int.MaxValue / 2, "Max segment size * 2 must be < int.MaxValue, or else overflow could occur."); // Initialize the queue m_head = m_tail = new Segment(INIT_SEGMENT_SIZE); } /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> public void Enqueue(T item) { Segment segment = m_tail; var array = segment.m_array; int last = segment.m_state.m_last; // local copy to avoid multiple volatile reads // Fast path: there's obviously room in the current segment int tail2 = (last + 1) & (array.Length - 1); if (tail2 != segment.m_state.m_firstCopy) { array[last] = item; segment.m_state.m_last = tail2; } // Slow path: there may not be room in the current segment. else EnqueueSlow(item, ref segment); } /// <summary>Enqueues an item into the queue.</summary> /// <param name="item">The item to enqueue.</param> /// <param name="segment">The segment in which to first attempt to store the item.</param> private void EnqueueSlow(T item, ref Segment segment) { Debug.Assert(segment != null, "Expected a non-null segment."); if (segment.m_state.m_firstCopy != segment.m_state.m_first) { segment.m_state.m_firstCopy = segment.m_state.m_first; Enqueue(item); // will only recur once for this enqueue operation return; } int newSegmentSize = m_tail.m_array.Length << 1; // double size Debug.Assert(newSegmentSize > 0, "The max size should always be small enough that we don't overflow."); if (newSegmentSize > MAX_SEGMENT_SIZE) newSegmentSize = MAX_SEGMENT_SIZE; var newSegment = new Segment(newSegmentSize); newSegment.m_array[0] = item; newSegment.m_state.m_last = 1; newSegment.m_state.m_lastCopy = 1; try { } finally { // Finally block to protect against corruption due to a thread abort // between setting m_next and setting m_tail. Volatile.Write(ref m_tail.m_next, newSegment); // ensure segment not published until item is fully stored m_tail = newSegment; } } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> public bool TryDequeue(out T result) { Segment segment = m_head; var array = segment.m_array; int first = segment.m_state.m_first; // local copy to avoid multiple volatile reads // Fast path: there's obviously data available in the current segment if (first != segment.m_state.m_lastCopy) { result = array[first]; array[first] = default; // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (array.Length - 1); return true; } // Slow path: there may not be data available in the current segment else return TryDequeueSlow(ref segment, ref array, out result); } /// <summary>Attempts to dequeue an item from the queue.</summary> /// <param name="array">The array from which the item was dequeued.</param> /// <param name="segment">The segment from which the item was dequeued.</param> /// <param name="result">The dequeued item.</param> /// <returns>true if an item could be dequeued; otherwise, false.</returns> private bool TryDequeueSlow(ref Segment segment, ref T[] array, out T result) { Debug.Assert(segment != null, "Expected a non-null segment."); Debug.Assert(array != null, "Expected a non-null item array."); if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryDequeue(out result); // will only recur once for this dequeue operation } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } var first = segment.m_state.m_first; // local copy to avoid extraneous volatile reads if (first == segment.m_state.m_last) { result = default; return false; } result = array[first]; array[first] = default; // Clear the slot to release the element segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1); segment.m_state.m_lastCopy = segment.m_state.m_last; // Refresh m_lastCopy to ensure that m_first has not passed m_lastCopy return true; } /// <summary>Gets whether the collection is currently empty.</summary> /// <remarks>WARNING: This should not be used concurrently without further vetting.</remarks> public bool IsEmpty { // This implementation is optimized for calls from the consumer. get { var head = m_head; if (head.m_state.m_first != head.m_state.m_lastCopy) return false; // m_first is volatile, so the read of m_lastCopy cannot get reordered if (head.m_state.m_first != head.m_state.m_last) return false; return head.m_next == null; } } /// <summary>Gets an enumerable for the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks> public IEnumerator<T> GetEnumerator() { for (Segment segment = m_head; segment != null; segment = segment.m_next) { for (int pt = segment.m_state.m_first; pt != segment.m_state.m_last; pt = (pt + 1) & (segment.m_array.Length - 1)) { yield return segment.m_array[pt]; } } } /// <summary>Gets an enumerable for the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not safe to be used concurrently.</remarks> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary>Gets the number of items in the collection.</summary> /// <remarks>WARNING: This should only be used for debugging purposes. It is not meant to be used concurrently.</remarks> public int Count { get { int count = 0; for (Segment segment = m_head; segment != null; segment = segment.m_next) { int arraySize = segment.m_array.Length; int first, last; while (true) // Count is not meant to be used concurrently, but this helps to avoid issues if it is { first = segment.m_state.m_first; last = segment.m_state.m_last; if (first == segment.m_state.m_first) break; } count += (last - first) & (arraySize - 1); } return count; } } /// <summary>A segment in the queue containing one or more items.</summary> [StructLayout(LayoutKind.Sequential)] private sealed class Segment { /// <summary>The next segment in the linked list of segments.</summary> internal Segment m_next; /// <summary>The data stored in this segment.</summary> internal readonly T[] m_array; /// <summary>Details about the segment.</summary> internal SegmentState m_state; // separated out to enable StructLayout attribute to take effect /// <summary>Initializes the segment.</summary> /// <param name="size">The size to use for this segment.</param> internal Segment(int size) { Debug.Assert((size & (size - 1)) == 0, "Size must be a power of 2"); m_array = new T[size]; } } /// <summary>Stores information about a segment.</summary> [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing private struct SegmentState { /// <summary>Padding to reduce false sharing between the segment's array and m_first.</summary> internal Internal.PaddingFor32 m_pad0; /// <summary>The index of the current head in the segment.</summary> internal volatile int m_first; /// <summary>A copy of the current tail index.</summary> internal int m_lastCopy; // not volatile as read and written by the producer, except for IsEmpty, and there m_lastCopy is only read after reading the volatile m_first /// <summary>Padding to reduce false sharing between the first and last.</summary> internal Internal.PaddingFor32 m_pad1; /// <summary>A copy of the current head index.</summary> internal int m_firstCopy; // not voliatle as only read and written by the consumer thread /// <summary>The index of the current tail in the segment.</summary> internal volatile int m_last; /// <summary>Padding to reduce false sharing with the last and what's after the segment.</summary> internal Internal.PaddingFor32 m_pad2; } /// <summary>Debugger type proxy for a SingleProducerSingleConsumerQueue of T.</summary> private sealed class SingleProducerSingleConsumerQueue_DebugView { /// <summary>The queue being visualized.</summary> private readonly SingleProducerSingleConsumerQueue<T> m_queue; /// <summary>Initializes the debug view.</summary> /// <param name="queue">The queue being debugged.</param> public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue) { Debug.Assert(queue != null, "Expected a non-null queue."); m_queue = queue; } } } }
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.ModelConfiguration.Conventions; using Abp.Application.Editions; using Abp.Application.Features; using Abp.Auditing; using Abp.Authorization.Roles; using Abp.Authorization.Users; using Abp.BackgroundJobs; using Abp.Domain.Entities; using Abp.EntityFramework.Extensions; using Abp.MultiTenancy; using Abp.Notifications; namespace Abp.Zero.EntityFramework { /// <summary> /// Base DbContext for ABP zero. /// Derive your DbContext from this class to have base entities. /// </summary> public abstract class AbpZeroDbContext<TTenant, TRole, TUser> : AbpZeroCommonDbContext<TRole, TUser> where TTenant : AbpTenant<TUser> where TRole : AbpRole<TUser> where TUser : AbpUser<TUser> { /// <summary> /// Tenants /// </summary> public virtual IDbSet<TTenant> Tenants { get; set; } /// <summary> /// Editions. /// </summary> public virtual IDbSet<Edition> Editions { get; set; } /// <summary> /// FeatureSettings. /// </summary> public virtual IDbSet<FeatureSetting> FeatureSettings { get; set; } /// <summary> /// TenantFeatureSetting. /// </summary> public virtual IDbSet<TenantFeatureSetting> TenantFeatureSettings { get; set; } /// <summary> /// EditionFeatureSettings. /// </summary> public virtual IDbSet<EditionFeatureSetting> EditionFeatureSettings { get; set; } /// <summary> /// Background jobs. /// </summary> public virtual IDbSet<BackgroundJobInfo> BackgroundJobs { get; set; } /// <summary> /// User accounts /// </summary> public virtual IDbSet<UserAccount> UserAccounts { get; set; } protected AbpZeroDbContext() { } protected AbpZeroDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } protected AbpZeroDbContext(DbCompiledModel model) : base(model) { } protected AbpZeroDbContext(DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection) { } protected AbpZeroDbContext(string nameOrConnectionString, DbCompiledModel model) : base(nameOrConnectionString, model) { } protected AbpZeroDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext) { } protected AbpZeroDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); #region BackgroundJobInfo.IX_IsAbandoned_NextTryTime modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.IsAbandoned) .CreateIndex("IX_IsAbandoned_NextTryTime", 1); modelBuilder.Entity<BackgroundJobInfo>() .Property(j => j.NextTryTime) .CreateIndex("IX_IsAbandoned_NextTryTime", 2); #endregion #region NotificationSubscriptionInfo.IX_NotificationName_EntityTypeName_EntityId_UserId modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.NotificationName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 1); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.EntityTypeName) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 2); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.EntityId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 3); modelBuilder.Entity<NotificationSubscriptionInfo>() .Property(ns => ns.UserId) .CreateIndex("IX_NotificationName_EntityTypeName_EntityId_UserId", 4); #endregion #region UserNotificationInfo.IX_UserId_State_CreationTime modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.UserId) .CreateIndex("IX_UserId_State_CreationTime", 1); modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.State) .CreateIndex("IX_UserId_State_CreationTime", 2); modelBuilder.Entity<UserNotificationInfo>() .Property(un => un.CreationTime) .CreateIndex("IX_UserId_State_CreationTime", 3); #endregion #region UserLoginAttempt.IX_TenancyName_UserNameOrEmailAddress_Result modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.TenancyName) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.UserNameOrEmailAddress) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 2); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.Result) .CreateIndex("IX_TenancyName_UserNameOrEmailAddress_Result", 3); #endregion #region UserLoginAttempt.IX_UserId_TenantId modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.UserId) .CreateIndex("IX_UserId_TenantId", 1); modelBuilder.Entity<UserLoginAttempt>() .Property(ula => ula.TenantId) .CreateIndex("IX_UserId_TenantId", 2); #endregion #region AuditLog.Set_MaxLengths modelBuilder.Entity<AuditLog>() .Property(e => e.ServiceName) .HasMaxLength(AuditLog.MaxServiceNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.MethodName) .HasMaxLength(AuditLog.MaxMethodNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.Parameters) .HasMaxLength(AuditLog.MaxParametersLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ClientIpAddress) .HasMaxLength(AuditLog.MaxClientIpAddressLength); modelBuilder.Entity<AuditLog>() .Property(e => e.ClientName) .HasMaxLength(AuditLog.MaxClientNameLength); modelBuilder.Entity<AuditLog>() .Property(e => e.BrowserInfo) .HasMaxLength(AuditLog.MaxBrowserInfoLength); modelBuilder.Entity<AuditLog>() .Property(e => e.Exception) .HasMaxLength(AuditLog.MaxExceptionLength); modelBuilder.Entity<AuditLog>() .Property(e => e.CustomData) .HasMaxLength(AuditLog.MaxCustomDataLength); #endregion #region Common Indexes modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<ISoftDelete, bool>(m => m.IsDeleted)); modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<IMayHaveTenant, int?>(m => m.TenantId)); modelBuilder.Conventions.AddAfter<IndexAttributeConvention>(new IndexingPropertyConvention<IMustHaveTenant, int>(m => m.TenantId)); #endregion } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Management.Automation.Host; using System.Collections.Concurrent; using System.Management.Automation.Internal; namespace System.Management.Automation.Runspaces { internal class PSSnapInTypeAndFormatErrors { public string psSnapinName; // only one of fullPath or formatTable or typeData or typeDefinition should be specified.. // typeData and isRemove should be used together internal PSSnapInTypeAndFormatErrors(string psSnapinName, string fullPath) { this.psSnapinName = psSnapinName; FullPath = fullPath; Errors = new ConcurrentBag<string>(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, FormatTable formatTable) { this.psSnapinName = psSnapinName; FormatTable = formatTable; Errors = new ConcurrentBag<string>(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, TypeData typeData, bool isRemove) { this.psSnapinName = psSnapinName; TypeData = typeData; IsRemove = isRemove; Errors = new ConcurrentBag<string>(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, ExtendedTypeDefinition typeDefinition) { this.psSnapinName = psSnapinName; FormatData = typeDefinition; Errors = new ConcurrentBag<string>(); } internal ExtendedTypeDefinition FormatData { get; } internal TypeData TypeData { get; } internal bool IsRemove { get; } internal string FullPath { get; } internal FormatTable FormatTable { get; } internal ConcurrentBag<string> Errors { get; set; } internal string PSSnapinName { get { return psSnapinName; } } internal bool FailToLoadFile; } internal static class FormatAndTypeDataHelper { private const string FileNotFound = "FileNotFound"; private const string CannotFindRegistryKey = "CannotFindRegistryKey"; private const string CannotFindRegistryKeyPath = "CannotFindRegistryKeyPath"; private const string EntryShouldBeMshXml = "EntryShouldBeMshXml"; private const string DuplicateFile = "DuplicateFile"; internal const string ValidationException = "ValidationException"; private static string GetBaseFolder( RunspaceConfiguration runspaceConfiguration, Collection<string> independentErrors) { string returnValue = CommandDiscovery.GetShellPathFromRegistry(runspaceConfiguration.ShellId); if (returnValue == null) { returnValue = Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); } else { returnValue = Path.GetDirectoryName(returnValue); if (!Directory.Exists(returnValue)) { string newReturnValue = Path.GetDirectoryName(typeof(FormatAndTypeDataHelper).GetTypeInfo().Assembly.Location); string error = StringUtil.Format(TypesXmlStrings.CannotFindRegistryKeyPath, returnValue, Utils.GetRegistryConfigurationPath(runspaceConfiguration.ShellId), "\\Path", newReturnValue); independentErrors.Add(error); returnValue = newReturnValue; } } return returnValue; } internal static Collection<PSSnapInTypeAndFormatErrors> GetFormatAndTypesErrors( RunspaceConfiguration runspaceConfiguration, PSHost host, IEnumerable<RunspaceConfigurationEntry> configurationEntryCollection, Collection<string> independentErrors, Collection<int> entryIndicesToRemove) { Collection<PSSnapInTypeAndFormatErrors> returnValue = new Collection<PSSnapInTypeAndFormatErrors>(); string baseFolder = GetBaseFolder(runspaceConfiguration, independentErrors); var psHome = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); // this hashtable will be used to check whether this is duplicated file for types or formats. HashSet<string> fullFileNameSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); int index = -1; foreach (var configurationEntry in configurationEntryCollection) { string fileName; string psSnapinName = configurationEntry.PSSnapIn == null ? runspaceConfiguration.ShellId : configurationEntry.PSSnapIn.Name; index++; var typeEntry = configurationEntry as TypeConfigurationEntry; if (typeEntry != null) { fileName = typeEntry.FileName; if (fileName == null) { returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, typeEntry.TypeData, typeEntry.IsRemove)); continue; } } else { FormatConfigurationEntry formatEntry = (FormatConfigurationEntry)configurationEntry; fileName = formatEntry.FileName; if (fileName == null) { returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, formatEntry.FormatData)); continue; } } bool checkFileExists = configurationEntry.PSSnapIn == null || string.Equals(psHome, configurationEntry.PSSnapIn.AbsoluteModulePath, StringComparison.OrdinalIgnoreCase); bool needToRemoveEntry = false; string fullFileName = GetAndCheckFullFileName(psSnapinName, fullFileNameSet, baseFolder, fileName, independentErrors, ref needToRemoveEntry, checkFileExists); if (fullFileName == null) { if (needToRemoveEntry) { entryIndicesToRemove.Add(index); } continue; } returnValue.Add(new PSSnapInTypeAndFormatErrors(psSnapinName, fullFileName)); } return returnValue; } private static string GetAndCheckFullFileName( string psSnapinName, HashSet<string> fullFileNameSet, string baseFolder, string baseFileName, Collection<string> independentErrors, ref bool needToRemoveEntry, bool checkFileExists) { string retValue = Path.IsPathRooted(baseFileName) ? baseFileName : Path.Combine(baseFolder, baseFileName); if (checkFileExists && !File.Exists(retValue)) { string error = StringUtil.Format(TypesXmlStrings.FileNotFound, psSnapinName, retValue); independentErrors.Add(error); return null; } if (fullFileNameSet.Contains(retValue)) { // Do not add Errors as we want loading of type/format files to be idempotent. // Just mark as Duplicate so the duplicate entry gets removed needToRemoveEntry = true; return null; } if (!retValue.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase)) { string error = StringUtil.Format(TypesXmlStrings.EntryShouldBeMshXml, psSnapinName, retValue); independentErrors.Add(error); return null; } fullFileNameSet.Add(retValue); return retValue; } internal static void ThrowExceptionOnError( string errorId, Collection<string> independentErrors, Collection<PSSnapInTypeAndFormatErrors> PSSnapinFilesCollection, RunspaceConfigurationCategory category) { Collection<string> errors = new Collection<string>(); if (independentErrors != null) { foreach (string error in independentErrors) { errors.Add(error); } } foreach (PSSnapInTypeAndFormatErrors PSSnapinFiles in PSSnapinFilesCollection) { foreach (string error in PSSnapinFiles.Errors) { errors.Add(error); } } if (errors.Count == 0) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = ""; if (category == RunspaceConfigurationCategory.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == RunspaceConfigurationCategory.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; } internal static void ThrowExceptionOnError( string errorId, ConcurrentBag<string> errors, RunspaceConfigurationCategory category) { if (errors.Count == 0) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = ""; if (category == RunspaceConfigurationCategory.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == RunspaceConfigurationCategory.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading; using DotNetty.Buffers; using DotNetty.Common; using DotNetty.Common.Concurrency; using DotNetty.Common.Internal.Logging; using DotNetty.Common.Utilities; public sealed class ChannelOutboundBuffer { #pragma warning disable 420 // all volatile fields are used with referenced in Interlocked methods only static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance<ChannelOutboundBuffer>(); static readonly ThreadLocalByteBufferList NioBuffers = new ThreadLocalByteBufferList(); readonly IChannel channel; // Entry(flushedEntry) --> ... Entry(unflushedEntry) --> ... Entry(tailEntry) // // The Entry that is the first in the linked-list structure that was flushed Entry flushedEntry; // The Entry which is the first unflushed in the linked-list structure Entry unflushedEntry; // The Entry which represents the tail of the buffer Entry tailEntry; // The number of flushed entries that are not written yet int flushed; //int nioBufferCount; bool inFail; long totalPendingSize; volatile int unwritable; internal ChannelOutboundBuffer(IChannel channel) { this.channel = channel; } /// <summary> /// Add given message to this {@link ChannelOutboundBuffer}. The given {@link ChannelPromise} will be notified once /// the message was written. /// </summary> public void AddMessage(object msg, int size, TaskCompletionSource promise) { Entry entry = Entry.NewInstance(msg, size, promise); if (this.tailEntry == null) { this.flushedEntry = null; this.tailEntry = entry; } else { Entry tail = this.tailEntry; tail.Next = entry; this.tailEntry = entry; } if (this.unflushedEntry == null) { this.unflushedEntry = entry; } // increment pending bytes after adding message to the unflushed arrays. // See https://github.com/netty/netty/issues/1619 this.IncrementPendingOutboundBytes(size, false); } /// <summary> /// Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed /// and so you will be able to handle them. /// </summary> public void AddFlush() { // There is no need to process all entries if there was already a flush before and no new messages // where added in the meantime. // // See https://github.com/netty/netty/issues/2577 Entry entry = this.unflushedEntry; if (entry != null) { if (this.flushedEntry == null) { // there is no flushedEntry yet, so start with the entry this.flushedEntry = entry; } do { this.flushed++; if (!entry.Promise.SetUncancellable()) { // Was cancelled so make sure we free up memory and notify about the freed bytes int pending = entry.Cancel(); this.DecrementPendingOutboundBytes(pending, false, true); } entry = entry.Next; } while (entry != null); // All flushed so reset unflushedEntry this.unflushedEntry = null; } } /// <summary> /// Increment the pending bytes which will be written at some point. /// This method is thread-safe! /// </summary> internal void IncrementPendingOutboundBytes(long size) => this.IncrementPendingOutboundBytes(size, true); void IncrementPendingOutboundBytes(long size, bool invokeLater) { if (size == 0) { return; } long newWriteBufferSize = Interlocked.Add(ref this.totalPendingSize, size); if (newWriteBufferSize >= this.channel.Configuration.WriteBufferHighWaterMark) { this.SetUnwritable(invokeLater); } } /// <summary> /// Decrement the pending bytes which will be written at some point. /// This method is thread-safe! /// </summary> internal void DecrementPendingOutboundBytes(long size) => this.DecrementPendingOutboundBytes(size, true, true); void DecrementPendingOutboundBytes(long size, bool invokeLater, bool notifyWritability) { if (size == 0) { return; } long newWriteBufferSize = Interlocked.Add(ref this.totalPendingSize, -size); if (notifyWritability && (newWriteBufferSize == 0 || newWriteBufferSize <= this.channel.Configuration.WriteBufferLowWaterMark)) { this.SetWritable(invokeLater); } } /// <summary> /// Return the current message to write or {@code null} if nothing was flushed before and so is ready to be written. /// </summary> public object Current => this.flushedEntry?.Message; /// <summary> /// Notify the {@link ChannelPromise} of the current message about writing progress. /// </summary> public void Progress(long amount) { // todo: support progress report? //Entry e = this.flushedEntry; //Contract.Assert(e != null); //var p = e.promise; //if (p is ChannelProgressivePromise) //{ // long progress = e.progress + amount; // e.progress = progress; // ((ChannelProgressivePromise)p).tryProgress(progress, e.Total); //} } /// <summary> /// Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no /// flushed message exists at the time this method is called it will return {@code false} to signal that no more /// messages are ready to be handled. /// </summary> public bool Remove() { Entry e = this.flushedEntry; if (e == null) { this.ClearNioBuffers(); return false; } object msg = e.Message; TaskCompletionSource promise = e.Promise; int size = e.PendingSize; this.RemoveEntry(e); if (!e.Cancelled) { // only release message, notify and decrement if it was not canceled before. ReferenceCountUtil.SafeRelease(msg); Util.SafeSetSuccess(promise, Logger); this.DecrementPendingOutboundBytes(size, false, true); } // recycle the entry e.Recycle(); return true; } /// <summary> /// Will remove the current message, mark its {@link ChannelPromise} as failure using the given {@link Exception} /// and return {@code true}. If no flushed message exists at the time this method is called it will return /// {@code false} to signal that no more messages are ready to be handled. /// </summary> public bool Remove(Exception cause) => this.Remove0(cause, true); bool Remove0(Exception cause, bool notifyWritability) { Entry e = this.flushedEntry; if (e == null) { this.ClearNioBuffers(); return false; } object msg = e.Message; TaskCompletionSource promise = e.Promise; int size = e.PendingSize; this.RemoveEntry(e); if (!e.Cancelled) { // only release message, fail and decrement if it was not canceled before. ReferenceCountUtil.SafeRelease(msg); Util.SafeSetFailure(promise, cause, Logger); this.DecrementPendingOutboundBytes(size, false, notifyWritability); } // recycle the entry e.Recycle(); return true; } void RemoveEntry(Entry e) { if (--this.flushed == 0) { // processed everything this.flushedEntry = null; if (e == this.tailEntry) { this.tailEntry = null; this.unflushedEntry = null; } } else { this.flushedEntry = e.Next; } } /// <summary> /// Removes the fully written entries and update the reader index of the partially written entry. /// This operation assumes all messages in this buffer is {@link ByteBuf}. /// </summary> public void RemoveBytes(long writtenBytes) { while (true) { object msg = this.Current; if (!(msg is IByteBuffer)) { Contract.Assert(writtenBytes == 0); break; } var buf = (IByteBuffer)msg; int readerIndex = buf.ReaderIndex; int readableBytes = buf.WriterIndex - readerIndex; if (readableBytes <= writtenBytes) { if (writtenBytes != 0) { this.Progress(readableBytes); writtenBytes -= readableBytes; } this.Remove(); } else { // readableBytes > writtenBytes if (writtenBytes != 0) { buf.SetReaderIndex(readerIndex + (int)writtenBytes); this.Progress(writtenBytes); } break; } } this.ClearNioBuffers(); } // Clear all ByteBuffer from the array so these can be GC'ed. // See https://github.com/netty/netty/issues/3837 void ClearNioBuffers() => NioBuffers.Value.Clear(); /// ///Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only. ///{@link #nioBufferCount()} and {@link #nioBufferSize()} will return the number of NIO buffers in the returned ///array and the total number of readable bytes of the NIO buffers respectively. ///<p> ///Note that the returned array is reused and thus should not escape ///{@link AbstractChannel#doWrite(ChannelOutboundBuffer)}. ///Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example. ///</p> /// @param maxCount The maximum amount of buffers that will be added to the return value. /// @param maxBytes A hint toward the maximum number of bytes to include as part of the return value. Note that this /// value maybe exceeded because we make a best effort to include at least 1 {@link ByteBuffer} /// in the return value to ensure write progress is made. /// public List<ArraySegment<byte>> GetSharedBufferList(int maxCount, long maxBytes = int.MaxValue) { long nioBufferSize = 0; InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.Get(); List<ArraySegment<byte>> nioBuffers = NioBuffers.Get(threadLocalMap); Entry entry = this.flushedEntry; int nioBufferCount = 0; while (this.IsFlushedEntry(entry) && entry.Message is IByteBuffer) { if (!entry.Cancelled) { var buf = (IByteBuffer)entry.Message; int readerIndex = buf.ReaderIndex; int readableBytes = buf.WriterIndex - readerIndex; if (readableBytes > 0) { if (maxBytes - readableBytes < nioBufferSize && nioBufferCount != 0) { // If the nioBufferSize + readableBytes will overflow an Integer we stop populate the // ByteBuffer array. This is done as bsd/osx don't allow to write more bytes then // Integer.MAX_VALUE with one writev(...) call and so will return 'EINVAL', which will // raise an IOException. On Linux it may work depending on the // architecture and kernel but to be safe we also enforce the limit here. // This said writing more the Integer.MAX_VALUE is not a good idea anyway. // // See also: // - https://www.freebsd.org/cgi/man.cgi?query=write&sektion=2 // - http://linux.die.net/man/2/writev break; } nioBufferSize += readableBytes; int count = entry.Count; if (count == -1) { //noinspection ConstantValueVariableUse entry.Count = count = buf.IoBufferCount; } if (count == 1) { ArraySegment<byte> nioBuf = entry.Buffer; if (nioBuf.Array == null) { // cache ByteBuffer as it may need to create a new ByteBuffer instance if its a // derived buffer entry.Buffer = nioBuf = buf.GetIoBuffer(readerIndex, readableBytes); } nioBuffers.Add(nioBuf); nioBufferCount++; } else { ArraySegment<byte>[] nioBufs = entry.Buffers; if (nioBufs == null) { // cached ByteBuffers as they may be expensive to create in terms // of Object allocation entry.Buffers = nioBufs = buf.GetIoBuffers(); } for (int i = 0; i < nioBufs.Length && nioBufferCount < maxCount; i++) { ArraySegment<byte> nioBuf = nioBufs[i]; if (nioBuf.Array == null) { break; } else if (nioBuf.Count == 0) { continue; } nioBuffers.Add(nioBuf); nioBufferCount++; } } if (nioBufferCount == maxCount) { break; } } } entry = entry.Next; } this.NioBufferSize = nioBufferSize; return nioBuffers; } /// ///Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only. ///{@link #nioBufferCount()} and {@link #nioBufferSize()} will return the number of NIO buffers in the returned ///array and the total number of readable bytes of the NIO buffers respectively. ///<p> ///Note that the returned array is reused and thus should not escape ///{@link AbstractChannel#doWrite(ChannelOutboundBuffer)}. ///Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example. ///</p> /// public List<ArraySegment<byte>> GetSharedBufferList() { return this.GetSharedBufferList(int.MaxValue, int.MaxValue); } /** * Returns the number of bytes that can be written out of the {@link ByteBuffer} array that was * obtained via {@link #nioBuffers()}. This method <strong>MUST</strong> be called after {@link #nioBuffers()} * was called. */ public long NioBufferSize { get; private set; } /// <summary> /// Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only. /// {@link #IoBufferCount} and {@link #NioBufferSize} will return the number of NIO buffers in the returned /// array and the total number of readable bytes of the NIO buffers respectively. /// <p> /// Note that the returned array is reused and thus should not escape /// {@link AbstractChannel#doWrite(ChannelOutboundBuffer)}. /// Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example. /// </p> /// </summary> /// <summary> /// Returns {@code true} if and only if {@linkplain #totalPendingWriteBytes() the total number of pending bytes} did /// not exceed the write watermark of the {@link Channel} and /// no {@linkplain #SetUserDefinedWritability(int, bool) user-defined writability flag} has been set to /// {@code false}. /// </summary> public bool IsWritable => this.unwritable == 0; /// <summary> /// Returns {@code true} if and only if the user-defined writability flag at the specified index is set to /// {@code true}. /// </summary> public bool GetUserDefinedWritability(int index) => (this.unwritable & WritabilityMask(index)) == 0; /// <summary> /// Sets a user-defined writability flag at the specified index. /// </summary> public void SetUserDefinedWritability(int index, bool writable) { if (writable) { this.SetUserDefinedWritability(index); } else { this.ClearUserDefinedWritability(index); } } void SetUserDefinedWritability(int index) { int mask = ~WritabilityMask(index); while (true) { int oldValue = this.unwritable; int newValue = oldValue & mask; if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue) { if (oldValue != 0 && newValue == 0) { this.FireChannelWritabilityChanged(true); } break; } } } void ClearUserDefinedWritability(int index) { int mask = WritabilityMask(index); while (true) { int oldValue = this.unwritable; int newValue = oldValue | mask; if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue) { if (oldValue == 0 && newValue != 0) { this.FireChannelWritabilityChanged(true); } break; } } } static int WritabilityMask(int index) { if (index < 1 || index > 31) { throw new InvalidOperationException("index: " + index + " (expected: 1~31)"); } return 1 << index; } void SetWritable(bool invokeLater) { while (true) { int oldValue = this.unwritable; int newValue = oldValue & ~1; if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue) { if (oldValue != 0 && newValue == 0) { this.FireChannelWritabilityChanged(invokeLater); } break; } } } void SetUnwritable(bool invokeLater) { while (true) { int oldValue = this.unwritable; int newValue = oldValue | 1; if (Interlocked.CompareExchange(ref this.unwritable, newValue, oldValue) == oldValue) { if (oldValue == 0 && newValue != 0) { this.FireChannelWritabilityChanged(invokeLater); } break; } } } void FireChannelWritabilityChanged(bool invokeLater) { IChannelPipeline pipeline = this.channel.Pipeline; if (invokeLater) { // todo: allocation check this.channel.EventLoop.Execute(p => ((IChannelPipeline)p).FireChannelWritabilityChanged(), pipeline); } else { pipeline.FireChannelWritabilityChanged(); } } /// <summary> /// Returns the number of flushed messages in this {@link ChannelOutboundBuffer}. /// </summary> public int Count => this.flushed; /// <summary> /// Returns {@code true} if there are flushed messages in this {@link ChannelOutboundBuffer} or {@code false} /// otherwise. /// </summary> public bool IsEmpty => this.flushed == 0; public void FailFlushed(Exception cause, bool notify) { // Make sure that this method does not reenter. A listener added to the current promise can be notified by the // current thread in the tryFailure() call of the loop below, and the listener can trigger another fail() call // indirectly (usually by closing the channel.) // // See https://github.com/netty/netty/issues/1501 if (this.inFail) { return; } try { this.inFail = true; for (; ; ) { if (!this.Remove0(cause, notify)) { break; } } } finally { this.inFail = false; } } internal void Close(ClosedChannelException cause) { if (this.inFail) { this.channel.EventLoop.Execute((buf, ex) => ((ChannelOutboundBuffer)buf).Close((ClosedChannelException)ex), this, cause); return; } this.inFail = true; if (this.channel.Open) { throw new InvalidOperationException("close() must be invoked after the channel is closed."); } if (!this.IsEmpty) { throw new InvalidOperationException("close() must be invoked after all flushed writes are handled."); } // Release all unflushed messages. try { Entry e = this.unflushedEntry; while (e != null) { // Just decrease; do not trigger any events via DecrementPendingOutboundBytes() int size = e.PendingSize; Interlocked.Add(ref this.totalPendingSize, -size); if (!e.Cancelled) { ReferenceCountUtil.SafeRelease(e.Message); Util.SafeSetFailure(e.Promise, cause, Logger); } e = e.RecycleAndGetNext(); } } finally { this.inFail = false; } this.ClearNioBuffers(); } public long TotalPendingWriteBytes() => Volatile.Read(ref this.totalPendingSize); /// <summary> /// Call {@link IMessageProcessor#processMessage(Object)} for each flushed message /// in this {@link ChannelOutboundBuffer} until {@link IMessageProcessor#processMessage(Object)} /// returns {@code false} or there are no more flushed messages to process. /// </summary> bool IsFlushedEntry(Entry e) => e != null && e != this.unflushedEntry; sealed class Entry { static readonly ThreadLocalPool<Entry> Pool = new ThreadLocalPool<Entry>(h => new Entry(h)); readonly ThreadLocalPool.Handle handle; public Entry Next; public object Message; public ArraySegment<byte>[] Buffers; public ArraySegment<byte> Buffer; public TaskCompletionSource Promise; public int PendingSize; public int Count = -1; public bool Cancelled; Entry(ThreadLocalPool.Handle handle) { this.handle = handle; } public static Entry NewInstance(object msg, int size, TaskCompletionSource promise) { Entry entry = Pool.Take(); entry.Message = msg; entry.PendingSize = size; entry.Promise = promise; return entry; } public int Cancel() { if (!this.Cancelled) { this.Cancelled = true; int pSize = this.PendingSize; // release message and replace with an empty buffer ReferenceCountUtil.SafeRelease(this.Message); this.Message = Unpooled.Empty; this.PendingSize = 0; this.Buffers = null; this.Buffer = new ArraySegment<byte>(); return pSize; } return 0; } public void Recycle() { this.Next = null; this.Buffers = null; this.Buffer = new ArraySegment<byte>(); this.Message = null; this.Promise = null; this.PendingSize = 0; this.Count = -1; this.Cancelled = false; this.handle.Release(this); } public Entry RecycleAndGetNext() { Entry next = this.Next; this.Recycle(); return next; } } sealed class ThreadLocalByteBufferList : FastThreadLocal<List<ArraySegment<byte>>> { protected override List<ArraySegment<byte>> GetInitialValue() => new List<ArraySegment<byte>>(1024); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Drawing; using System.IO; using ConsoleExamples.Examples; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.ML.Data.Image; using Encog.ML.Train.Strategy; using Encog.Neural.Networks; using Encog.Neural.Networks.Training.Propagation.Resilient; using Encog.Util.DownSample; using Encog.Util.Simple; namespace Encog.Examples.Image { /// <summary> /// Should have an input file similar to: /// /// CreateTraining: width:16,height:16,type:RGB /// Input: image:./coins/dime.png, identity:dime /// Input: image:./coins/dollar.png, identity:dollar /// Input: image:./coins/half.png, identity:half dollar /// Input: image:./coins/nickle.png, identity:nickle /// Input: image:./coins/penny.png, identity:penny /// Input: image:./coins/quarter.png, identity:quarter /// Network: hidden1:100, hidden2:0 /// Train: Mode:console, Minutes:1, StrategyError:0.25, StrategyCycles:50 /// Whatis: image:./coins/dime.png /// Whatis: image:./coins/half.png /// Whatis: image:./coins/testcoin.png /// </summary> public class ImageNeuralNetwork : IExample { private readonly IDictionary<String, String> args = new Dictionary<String, String>(); private readonly IDictionary<String, int> identity2neuron = new Dictionary<String, int>(); private readonly IList<ImagePair> imageList = new List<ImagePair>(); private readonly IDictionary<int, String> neuron2identity = new Dictionary<int, String>(); private IExampleInterface app; private IDownSample downsample; private int downsampleHeight; private int downsampleWidth; private String line; private BasicNetwork network; private int outputCount; private ImageMLDataSet training; public static ExampleInfo Info { get { var info = new ExampleInfo( typeof (ImageNeuralNetwork), "image", "Image Neural Networks", "Simple ADALINE neural network that recognizes the digits."); return info; } } #region IExample Members public void Execute(IExampleInterface app) { this.app = app; if (this.app.Args.Length < 1) { this.app.WriteLine("Must specify command file. See source for format."); } else { // Read the file and display it line by line. var file = new StreamReader(this.app.Args[0]); while ((line = file.ReadLine()) != null) { ExecuteLine(); } file.Close(); } } #endregion private int AssignIdentity(String identity) { if (identity2neuron.ContainsKey(identity.ToLower())) { return identity2neuron[identity.ToLower()]; } int result = outputCount; identity2neuron[identity.ToLower()] = result; neuron2identity[result] = identity.ToLower(); outputCount++; return result; } private void ExecuteCommand(String command, IDictionary<String, String> args) { if (command.Equals("input")) { ProcessInput(); } else if (command.Equals("createtraining")) { ProcessCreateTraining(); } else if (command.Equals("train")) { ProcessTrain(); } else if (command.Equals("network")) { ProcessNetwork(); } else if (command.Equals("whatis")) { ProcessWhatIs(); } } public void ExecuteLine() { int index = line.IndexOf(':'); if (index == -1) { throw new EncogError("Invalid command: " + line); } String command = line.Substring(0, index).ToLower() .Trim(); String argsStr = line.Substring(index + 1).Trim(); String[] tok = argsStr.Split(','); args.Clear(); foreach (String arg in tok) { int index2 = arg.IndexOf(':'); if (index2 == -1) { throw new EncogError("Invalid command: " + line); } String key = arg.Substring(0, index2).ToLower().Trim(); String value = arg.Substring(index2 + 1).Trim(); args[key] = value; } ExecuteCommand(command, args); } private String GetArg(String name) { String result = args[name]; if (result == null) { throw new EncogError("Missing argument " + name + " on line: " + line); } return result; } private void ProcessCreateTraining() { String strWidth = GetArg("width"); String strHeight = GetArg("height"); String strType = GetArg("type"); downsampleHeight = int.Parse(strWidth); downsampleWidth = int.Parse(strHeight); if (strType.Equals("RGB")) { downsample = new RGBDownsample(); } else { downsample = new SimpleIntensityDownsample(); } training = new ImageMLDataSet(downsample, false, 1, -1); app.WriteLine("Training set created"); } private void ProcessInput() { String image = GetArg("image"); String identity = GetArg("identity"); int idx = AssignIdentity(identity); imageList.Add(new ImagePair(image, idx)); app.WriteLine("Added input image:" + image); } private void ProcessNetwork() { app.WriteLine("Downsampling images..."); foreach (ImagePair pair in imageList) { var ideal = new BasicMLData(outputCount); int idx = pair.Identity; for (int i = 0; i < outputCount; i++) { if (i == idx) { ideal[i] = 1; } else { ideal[i] = -1; } } try { var img = new Bitmap(pair.File); var data = new ImageMLData(img); training.Add(data, ideal); } catch (Exception e) { app.WriteLine("Error loading: " + pair.File + ": " + e.Message); } } String strHidden1 = GetArg("hidden1"); String strHidden2 = GetArg("hidden2"); if (training.Count == 0) { app.WriteLine("No images to create network for."); return; } training.Downsample(downsampleHeight, downsampleWidth); int hidden1 = int.Parse(strHidden1); int hidden2 = int.Parse(strHidden2); network = EncogUtility.SimpleFeedForward(training .InputSize, hidden1, hidden2, training.IdealSize, true); app.WriteLine("Created network: " + network); } private void ProcessTrain() { if (network == null) return; String strMode = GetArg("mode"); String strMinutes = GetArg("minutes"); String strStrategyError = GetArg("strategyerror"); String strStrategyCycles = GetArg("strategycycles"); app.WriteLine("Training Beginning... Output patterns=" + outputCount); double strategyError = double.Parse(strStrategyError); int strategyCycles = int.Parse(strStrategyCycles); var train = new ResilientPropagation(network, training); train.AddStrategy(new ResetStrategy(strategyError, strategyCycles)); if (String.Compare(strMode, "gui", true) == 0) { EncogUtility.TrainDialog(train, network, training); } else { int minutes = int.Parse(strMinutes); EncogUtility.TrainConsole(train, network, training, minutes); } app.WriteLine("Training Stopped..."); } public void ProcessWhatIs() { String filename = GetArg("image"); try { var img = new Bitmap(filename); var input = new ImageMLData(img); input.Downsample(downsample, false, downsampleHeight, downsampleWidth, 1, -1); int winner = network.Winner(input); app.WriteLine("What is: " + filename + ", it seems to be: " + neuron2identity[winner]); } catch (Exception e) { app.WriteLine("Error loading: " + filename + ", " + e.Message); } } } }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // 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 Yaapii.Atoms.Enumerable; namespace Yaapii.Atoms.Map { /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <typeparam name="Key">Key Type of the Map</typeparam> /// <typeparam name="Value">Value Type of the Map</typeparam> public sealed class Sorted<Key, Value> : MapEnvelope<Key, Value> { /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="dict">Map to be sorted</param> public Sorted(IDictionary<Key, Value> dict) : this(dict, Comparer<Key>.Default) { } /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="compare">Function to compare two keys</param> public Sorted(IDictionary<Key, Value> dict, Func<Key, Key, int> compare) : this(dict, new SimpleComparer<Key>(compare)) { } /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="pairs">Map elements to be sorted</param> public Sorted(IEnumerable<KeyValuePair<Key, Value>> pairs) : this(pairs, Comparer<Key>.Default) { } /// <summary> /// Sorts the given map with the given key compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two keys</param> public Sorted(IEnumerable<KeyValuePair<Key, Value>> pairs, Func<Key, Key, int> compare) : this(pairs, new SimpleComparer<Key>(compare)) { } /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two elements</param> public Sorted(IEnumerable<KeyValuePair<Key, Value>> pairs, Func<KeyValuePair<Key, Value>, KeyValuePair<Key, Value>, int> compare) : this(pairs, new SimpleComparer<KeyValuePair<Key, Value>>(compare)) { } /// <summary> /// Sorts the given map with the given key comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public Sorted(IEnumerable<KeyValuePair<Key, Value>> pairs, IComparer<Key> cmp) : this(pairs, new KeyComparer<Key, Value>(cmp)) { } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing elements</param> public Sorted(IEnumerable<KeyValuePair<Key, Value>> pairs, IComparer<KeyValuePair<Key, Value>> cmp) : base( () => { var items = new List<KeyValuePair<Key, Value>>(pairs); items.Sort(cmp); return new MapOf<Key, Value>(items); }, false ) { } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public Sorted(IDictionary<Key, Value> dict, IComparer<Key> cmp) : base( () => { var keys = new List<Key>(dict.Keys); keys.Sort(cmp); var result = new LazyDict<Key, Value>( new Mapped<Key, IKvp<Key, Value>>( key => new KvpOf<Key, Value>(key, () => dict[key]), keys ) ); return result; }, false ) { } } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <typeparam name="Value">Value Type of the Map</typeparam> public sealed class Sorted<Value> : MapEnvelope<Value> { /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="dict">Map to be sorted</param> public Sorted(IDictionary<string, Value> dict) : this(dict, Comparer<string>.Default) { } /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="compare">Function to compare two keys</param> public Sorted(IDictionary<string, Value> dict, Func<string, string, int> compare) : this(dict, new SimpleComparer<string>(compare)) { } /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="pairs">Map elements to be sorted</param> public Sorted(IEnumerable<KeyValuePair<string, Value>> pairs) : this(pairs, Comparer<string>.Default) { } /// <summary> /// Sorts the given map with the given key compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two keys</param> public Sorted(IEnumerable<KeyValuePair<string, Value>> pairs, Func<string, string, int> compare) : this(pairs, new SimpleComparer<string>(compare)) { } /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two elements</param> public Sorted(IEnumerable<KeyValuePair<string, Value>> pairs, Func<KeyValuePair<string, Value>, KeyValuePair<string, Value>, int> compare) : this(pairs, new SimpleComparer<KeyValuePair<string, Value>>(compare)) { } /// <summary> /// Sorts the given map with the given key comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public Sorted(IEnumerable<KeyValuePair<string, Value>> pairs, IComparer<string> cmp) : this(pairs, new KeyComparer<string, Value>(cmp)) { } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing elements</param> public Sorted(IEnumerable<KeyValuePair<string, Value>> pairs, IComparer<KeyValuePair<string, Value>> cmp) : base( () => { var items = new List<KeyValuePair<string, Value>>(pairs); items.Sort(cmp); return new MapOf<string, Value>(items); }, false ) { } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public Sorted(IDictionary<string, Value> dict, IComparer<string> cmp) : base( () => { var keys = new List<string>(dict.Keys); keys.Sort(cmp); var result = new LazyDict<string, Value>( new Mapped<string, IKvp<string, Value>>( key => new KvpOf<string, Value>(key, () => dict[key]), keys ) ); return result; }, false ) { } } /// <summary> /// Sorts the given map with the given comparer /// </summary> public sealed class Sorted : MapEnvelope { /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="dict">Map to be sorted</param> public Sorted(IDictionary<string, string> dict) : this(dict, Comparer<string>.Default) { } /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="compare">Function to compare two keys</param> public Sorted(IDictionary<string, string> dict, Func<string, string, int> compare) : this(dict, new SimpleComparer<string>(compare)) { } /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="pairs">Map elements to be sorted</param> public Sorted(IEnumerable<KeyValuePair<string, string>> pairs) : this(pairs, Comparer<string>.Default) { } /// <summary> /// Sorts the given map with the given key compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two keys</param> public Sorted(IEnumerable<KeyValuePair<string, string>> pairs, Func<string, string, int> compare) : this(pairs, new SimpleComparer<string>(compare)) { } /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two elements</param> public Sorted(IEnumerable<KeyValuePair<string, string>> pairs, Func<KeyValuePair<string, string>, KeyValuePair<string, string>, int> compare) : this(pairs, new SimpleComparer<KeyValuePair<string, string>>(compare)) { } /// <summary> /// Sorts the given map with the given key comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public Sorted(IEnumerable<KeyValuePair<string, string>> pairs, IComparer<string> cmp) : this(pairs, new KeyComparer<string, string>(cmp)) { } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing elements</param> public Sorted(IEnumerable<KeyValuePair<string, string>> pairs, IComparer<KeyValuePair<string, string>> cmp) : base( () => { var items = new List<KeyValuePair<string, string>>(pairs); items.Sort(cmp); return new MapOf<string, string>(items); }, false ) { } /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public Sorted(IDictionary<string, string> dict, IComparer<string> cmp) : base( () => { var keys = new List<string>(dict.Keys); keys.Sort(cmp); var result = new LazyDict<string, string>( new Mapped<string, IKvp<string, string>>( key => new KvpOf<string, string>(key, () => dict[key]), keys ) ); return result; }, false ) { } /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="dict">Map to be sorted</param> public static IDictionary<Key, Value> New<Key, Value>(IDictionary<Key, Value> dict) => new Sorted<Key, Value>(dict); /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="compare">Function to compare two keys</param> public static IDictionary<Key, Value> New<Key, Value>(IDictionary<Key, Value> dict, Func<Key, Key, int> compare) => new Sorted<Key, Value>(dict, compare); /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="pairs">Map elements to be sorted</param> public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<KeyValuePair<Key, Value>> pairs) => new Sorted<Key, Value>(pairs); /// <summary> /// Sorts the given map with the given key compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two keys</param> public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<KeyValuePair<Key, Value>> pairs, Func<Key, Key, int> compare) => new Sorted<Key, Value>(pairs, compare); /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two elements</param> public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<KeyValuePair<Key, Value>> pairs, Func<KeyValuePair<Key, Value>, KeyValuePair<Key, Value>, int> compare) => new Sorted<Key, Value>(pairs, compare); /// <summary> /// Sorts the given map with the given key comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<KeyValuePair<Key, Value>> pairs, IComparer<Key> cmp) => new Sorted<Key, Value>(pairs, cmp); /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing elements</param> public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<KeyValuePair<Key, Value>> pairs, IComparer<KeyValuePair<Key, Value>> cmp) => new Sorted<Key, Value>(pairs, cmp); /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public static IDictionary<Key, Value> New<Key, Value>(IDictionary<Key, Value> dict, IComparer<Key> cmp) => new Sorted<Key, Value>(dict, cmp); /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="dict">Map to be sorted</param> public static IDictionary<string, Value> New<Value>(IDictionary<string, Value> dict) => new Sorted<Value>(dict); /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="compare">Function to compare two keys</param> public static IDictionary<string, Value> New<Value>(IDictionary<string, Value> dict, Func<string, string, int> compare) => new Sorted<Value>(dict, compare); /// <summary> /// Sorts the given map with the default comperator of the key /// </summary> /// <param name="pairs">Map elements to be sorted</param> public static IDictionary<string, Value> New<Value>(IEnumerable<KeyValuePair<string, Value>> pairs) => new Sorted<Value>(pairs); /// <summary> /// Sorts the given map with the given key compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two keys</param> public static IDictionary<string, Value> New<Value>(IEnumerable<KeyValuePair<string, Value>> pairs, Func<string, string, int> compare) => new Sorted<Value>(pairs, compare); /// <summary> /// Sorts the given map with the given compare function /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="compare">Function to compare two elements</param> public static IDictionary<string, Value> New<Value>(IEnumerable<KeyValuePair<string, Value>> pairs, Func<KeyValuePair<string, Value>, KeyValuePair<string, Value>, int> compare) => new Sorted<Value>(pairs, compare); /// <summary> /// Sorts the given map with the given key comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public static IDictionary<string, Value> New<Value>(IEnumerable<KeyValuePair<string, Value>> pairs, IComparer<string> cmp) => new Sorted<Value>(pairs, cmp); /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="pairs">Map elements to be sorted</param> /// <param name="cmp">Comparer comparing elements</param> public static IDictionary<string, Value> New<Value>(IEnumerable<KeyValuePair<string, Value>> pairs, IComparer<KeyValuePair<string, Value>> cmp) => new Sorted<Value>(pairs, cmp); /// <summary> /// Sorts the given map with the given comparer /// </summary> /// <param name="dict">Map to be sorted</param> /// <param name="cmp">Comparer comparing keys</param> public static IDictionary<string, Value> New<Value>(IDictionary<string, Value> dict, IComparer<string> cmp) => new Sorted<Value>(dict, cmp); } /// <summary> /// Simple Comparer comparing two elements /// </summary> /// <typeparam name="T">Type of the elements</typeparam> internal sealed class SimpleComparer<T> : IComparer<T> { private readonly Func<T, T, int> compare; /// <summary> /// Comparer from a function comparing two elements /// </summary> /// <param name="compare">Function comparing two elements</param> public SimpleComparer(Func<T, T, int> compare) { this.compare = compare; } public int Compare(T x, T y) { return this.compare(x, y); } } /// <summary> /// Comparer comparing two KeyValuePairs by key /// </summary> /// <typeparam name="Key">Key Type</typeparam> /// <typeparam name="Value">Value Type</typeparam> internal sealed class KeyComparer<Key, Value> : IComparer<KeyValuePair<Key, Value>> { private readonly IComparer<Key> cmp; /// <summary> /// Comparer comparing two KeyValuePairs by key /// </summary> /// <param name="cmp">Comparer compairing the key type</param> public KeyComparer(IComparer<Key> cmp) { this.cmp = cmp; } public int Compare(KeyValuePair<Key, Value> x, KeyValuePair<Key, Value> y) { return this.cmp.Compare(x.Key, y.Key); } } }
using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.Authorization; using Signum.Services; using Signum.Utilities; using System; using System.DirectoryServices.AccountManagement; using System.Linq; using System.Security.Claims; #pragma warning disable CA1416 // Validate platform compatibility namespace Signum.Engine.Authorization { public interface IAutoCreateUserContext { public string UserName { get; } public string? EmailAddress { get; } public string FirstName { get; } public string LastName { get; } public Guid? OID { get; } } public class DirectoryServiceAutoCreateUserContext : IAutoCreateUserContext { public readonly PrincipalContext PrincipalContext; public string UserName { get; private set; } public string DomainName { get; private set; } public string? EmailAddress => this.GetUserPrincipal().EmailAddress; public string FirstName => this.GetUserPrincipal().GivenName; public string LastName => this.GetUserPrincipal().Surname; public Guid? OID => null; UserPrincipal? userPrincipal; public DirectoryServiceAutoCreateUserContext(PrincipalContext principalContext, string localName, string domainName) { PrincipalContext = principalContext; UserName = localName; DomainName = domainName; } public UserPrincipal GetUserPrincipal() //https://stackoverflow.com/questions/14278274/how-i-get-active-directory-user-properties-with-system-directoryservices-account { return userPrincipal ?? (userPrincipal = UserPrincipal.FindByIdentity(PrincipalContext, DomainName + @"\" + UserName)); } } public class AzureClaimsAutoCreateUserContext : IAutoCreateUserContext { public ClaimsPrincipal ClaimsPrincipal { get; private set; } string GetClaim(string type) => ClaimsPrincipal.Claims.SingleEx(a => a.Type == type).Value; string? TryGetClain(string type) => ClaimsPrincipal.Claims.SingleOrDefaultEx(a => a.Type == type)?.Value; public Guid? OID => Guid.Parse(GetClaim("http://schemas.microsoft.com/identity/claims/objectidentifier")); public string UserName => GetClaim("preferred_username"); public string? EmailAddress => GetClaim("preferred_username"); public string? FullName => TryGetClain("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name"); public string FirstName { get { var name = FullName; return name == null ? "Unknown" : name.Contains(",") ? name.After(",").Trim() : name.TryBefore(" ")?.Trim() ?? name.DefaultToNull() ?? "Unknown"; } } public string LastName { get { var name = FullName; return name == null ? "Unknown" : name.Contains(",") ? name.Before(",").Trim() : name.TryAfter(" ")?.Trim() ?? "Unknown"; } } public AzureClaimsAutoCreateUserContext(ClaimsPrincipal claimsPrincipal) { this.ClaimsPrincipal = claimsPrincipal; } } public class ActiveDirectoryAuthorizer : ICustomAuthorizer { public Func<ActiveDirectoryConfigurationEmbedded> GetConfig; public ActiveDirectoryAuthorizer(Func<ActiveDirectoryConfigurationEmbedded> getConfig) { this.GetConfig = getConfig; } public virtual UserEntity Login(string userName, string password, out string authenticationType) { var passwordHash = Security.EncodePassword(password); if (AuthLogic.TryRetrieveUser(userName, passwordHash) != null) return AuthLogic.Login(userName, passwordHash, out authenticationType); //Database is faster than Active Directory UserEntity? user = LoginWithActiveDirectoryRegistry(userName, password); if (user != null) { authenticationType = "adRegistry"; return user; } return AuthLogic.Login(userName, Security.EncodePassword(password), out authenticationType); } public virtual UserEntity? LoginWithActiveDirectoryRegistry(string userName, string password) { using (AuthLogic.Disable()) { var config = this.GetConfig(); var domainName = userName.TryAfterLast('@') ?? userName.TryBefore('\\') ?? config.DomainName; var localName = userName.TryBeforeLast('@') ?? userName.TryAfter('\\') ?? userName; if (domainName != null && config.LoginWithActiveDirectoryRegistry) { try { using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainName, localName + "@" + domainName, password)) { if (pc.ValidateCredentials(localName + "@" + domainName, password, ContextOptions.Negotiate)) { UserEntity? user = AuthLogic.RetrieveUser(userName); if (user == null) { user = OnAutoCreateUser(new DirectoryServiceAutoCreateUserContext(pc, localName, domainName!)); } if (user != null) { AuthLogic.OnUserLogingIn(user); return user; } else { throw new InvalidOperationException(ActiveDirectoryAuthorizerMessage.ActiveDirectoryUser0IsNotAssociatedWithAUserInThisApplication.NiceToString(localName)); } } } } catch (PrincipalServerDownException) { // Do nothing for this kind of Active Directory exception } } return null; } } public virtual UserEntity? OnAutoCreateUser(IAutoCreateUserContext ctx) { if (!GetConfig().AutoCreateUsers) return null; var user = this.AutoCreateUserInternal(ctx); if (user != null && user.IsNew) { using (ExecutionMode.Global()) using (OperationLogic.AllowSave<UserEntity>()) { user.Save(); } } return user; } public virtual UserEntity? AutoCreateUserInternal(IAutoCreateUserContext ctx) { var result = new UserEntity { UserName = ctx.UserName, PasswordHash = null, Email = ctx.EmailAddress, Role = GetRole(ctx, throwIfNull: true)!, State = UserState.Saved, }; var mixin = result.TryMixin<UserOIDMixin>(); if (mixin != null) mixin.OID = ctx.OID; return result; } public virtual Lite<RoleEntity>? GetRole(IAutoCreateUserContext ctx, bool throwIfNull) { var config = GetConfig(); if (ctx is DirectoryServiceAutoCreateUserContext ds) { var groups = ds.GetUserPrincipal().GetGroups(); var role = config.RoleMapping.FirstOrDefault(m => { Guid.TryParse(m.ADNameOrGuid, out var guid); return groups.Any(g => g.Name == m.ADNameOrGuid || g.Guid == guid); })?.Role ?? config.DefaultRole; if (role != null) return role; if (throwIfNull) throw new InvalidOperationException("No Default Role set and no matching RoleMapping found for any role: \r\n" + groups.ToString(a => a.Name, "\r\n")); else return null; } else { if (config.DefaultRole != null) return config.DefaultRole; if (throwIfNull) throw new InvalidOperationException("No default role set"); else return null; } } } }
using System; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using GitHub.Unity; using NSubstitute; using NUnit.Framework; using System.IO; using System.Linq; namespace IntegrationTests { [TestFixture] class GitInstallerTests : BaseIntegrationTest { const int Timeout = 30000; public override void OnSetup() { base.OnSetup(); InitializeEnvironment(TestBasePath, false, false); InitializePlatform(TestBasePath); } private TestWebServer.HttpServer server; public override void TestFixtureSetUp() { base.TestFixtureSetUp(); server = new TestWebServer.HttpServer(SolutionDirectory.Combine("files"), 50000); Task.Factory.StartNew(server.Start); ApplicationConfiguration.WebTimeout = 10000; } public override void TestFixtureTearDown() { base.TestFixtureTearDown(); server.Stop(); ApplicationConfiguration.WebTimeout = ApplicationConfiguration.DefaultWebTimeout; ZipHelper.Instance = null; } [Test] public void GitInstallWindows() { var gitInstallationPath = TestBasePath.Combine("GitInstall").CreateDirectory(); var installDetails = new GitInstaller.GitInstallDetails(gitInstallationPath, DefaultEnvironment.OnWindows) { GitPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitPackageName}", GitLfsPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitLfsPackageName}", }; TestBasePath.Combine("git").CreateDirectory(); var zipHelper = Substitute.For<IZipHelper>(); zipHelper.Extract(Arg.Any<string>(), Arg.Do<string>(x => { var n = x.ToNPath(); n.EnsureDirectoryExists(); if (n.FileName == "git-lfs") { n.Combine("git-lfs" + Environment.ExecutableExtension).WriteAllText(""); } }), Arg.Any<CancellationToken>(), Arg.Any<Func<long, long, bool>>()).Returns(true); ZipHelper.Instance = zipHelper; var gitInstaller = new GitInstaller(Environment, ProcessManager, TaskManager.Token, installDetails: installDetails); var state = gitInstaller.SetupGitIfNeeded(); state.Should().NotBeNull(); Assert.AreEqual(gitInstallationPath.Combine(GitInstaller.GitInstallDetails.GitDirectory), state.GitInstallationPath); state.GitExecutablePath.Should().Be(gitInstallationPath.Combine(GitInstaller.GitInstallDetails.GitDirectory, "cmd", "git" + Environment.ExecutableExtension)); state.GitLfsExecutablePath.Should().Be(gitInstallationPath.Combine(GitInstaller.GitInstallDetails.GitLfsDirectory, "git-lfs" + Environment.ExecutableExtension)); Environment.GitInstallationState = state; var procTask = new SimpleProcessTask(TaskManager.Token, "something") .Configure(ProcessManager); procTask.Process.StartInfo.EnvironmentVariables["PATH"].Should().StartWith(gitInstallationPath.ToString()); } //[Test] public void MacSkipsInstallWhenSettingsGitExists() { DefaultEnvironment.OnMac = true; DefaultEnvironment.OnWindows = false; var filesystem = Substitute.For<IFileSystem>(); filesystem.FileExists(Arg.Any<string>()).Returns(true); filesystem.DirectoryExists(Arg.Any<string>()).Returns(true); filesystem.DirectorySeparatorChar.Returns('/'); Environment.FileSystem = filesystem; var gitInstallationPath = "/usr/local".ToNPath(); var gitExecutablePath = gitInstallationPath.Combine("bin/git"); var gitLfsInstallationPath = gitInstallationPath; var gitLfsExecutablePath = gitLfsInstallationPath.Combine("bin/git-lfs"); var installDetails = new GitInstaller.GitInstallDetails(gitInstallationPath, Environment.IsWindows) { GitPackageFeed = $"http://localhost:{server.Port}/unity/git/mac/{GitInstaller.GitInstallDetails.GitPackageName}", GitLfsPackageFeed = $"http://localhost:{server.Port}/unity/git/mac/{GitInstaller.GitInstallDetails.GitLfsPackageName}", }; var ret = new string[] { gitLfsExecutablePath }; filesystem.GetFiles(Arg.Any<string>(), Arg.Is<string>(installDetails.GitLfsExecutablePath.FileName), Arg.Any<SearchOption>()) .Returns(ret); var settings = Substitute.For<ISettings>(); var settingsRet = gitExecutablePath.ToString(); settings.Get(Arg.Is<string>(Constants.GitInstallPathKey), Arg.Any<string>()).Returns(settingsRet); var installer = new GitInstaller(Environment, ProcessManager, TaskManager.Token, installDetails); var result = installer.SetupGitIfNeeded(); Assert.AreEqual(gitInstallationPath, result.GitInstallationPath); Assert.AreEqual(gitLfsInstallationPath, result.GitLfsInstallationPath); Assert.AreEqual(gitExecutablePath, result.GitExecutablePath); Assert.AreEqual(gitLfsExecutablePath, result.GitLfsExecutablePath); } //[Test] public void WindowsSkipsInstallWhenSettingsGitExists() { DefaultEnvironment.OnMac = false; DefaultEnvironment.OnWindows = true; var filesystem = Substitute.For<IFileSystem>(); filesystem.FileExists(Arg.Any<string>()).Returns(true); filesystem.DirectoryExists(Arg.Any<string>()).Returns(true); filesystem.DirectorySeparatorChar.Returns('\\'); Environment.FileSystem = filesystem; var gitInstallationPath = "c:/Program Files/Git".ToNPath(); var gitExecutablePath = gitInstallationPath.Combine("cmd/git.exe"); var gitLfsInstallationPath = gitInstallationPath; var gitLfsExecutablePath = gitLfsInstallationPath.Combine("mingw32/libexec/git-core/git-lfs.exe"); var installDetails = new GitInstaller.GitInstallDetails(gitInstallationPath, Environment.IsWindows) { GitPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitPackageName}", GitLfsPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitLfsPackageName}", }; var ret = new string[] { gitLfsExecutablePath }; filesystem.GetFiles(Arg.Any<string>(), Arg.Is<string>(installDetails.GitLfsExecutablePath.FileName), Arg.Any<SearchOption>()) .Returns(ret); var settings = Substitute.For<ISettings>(); var settingsRet = gitExecutablePath.ToString(); settings.Get(Arg.Is<string>(Constants.GitInstallPathKey), Arg.Any<string>()).Returns(settingsRet); var installer = new GitInstaller(Environment, ProcessManager, TaskManager.Token, installDetails); var result = installer.SetupGitIfNeeded(); Assert.AreEqual(gitInstallationPath, result.GitInstallationPath); Assert.AreEqual(gitLfsInstallationPath, result.GitLfsInstallationPath); Assert.AreEqual(gitExecutablePath, result.GitExecutablePath); Assert.AreEqual(gitLfsExecutablePath, result.GitLfsExecutablePath); } } [TestFixture] class GitInstallerTestsWithHttp : BaseTestWithHttpServer { public override void OnSetup() { base.OnSetup(); InitializeEnvironment(TestBasePath, false, false); InitializePlatform(TestBasePath); } [Test] public void GitLfsIsInstalledIfMissing() { var tempZipExtractPath = TestBasePath.Combine("Temp", "git_zip_extract_zip_paths"); var gitInstallationPath = TestBasePath.Combine("GitInstall").Combine(GitInstaller.GitInstallDetails.GitDirectory); var gitLfsInstallationPath = TestBasePath.Combine("GitInstall").Combine(GitInstaller.GitInstallDetails.GitLfsDirectory); var gitZipUri = new UriString($"http://localhost:{server.Port}/unity/git/windows/git-slim.zip"); var downloader = new Downloader(Environment.FileSystem); downloader.QueueDownload(gitZipUri, tempZipExtractPath); downloader.RunSynchronously(); var gitExtractPath = tempZipExtractPath.Combine("git").CreateDirectory(); ZipHelper.Instance.Extract(tempZipExtractPath.Combine(gitZipUri.Filename), gitExtractPath, TaskManager.Token, null); var source = gitExtractPath; var target = gitInstallationPath; target.DeleteIfExists(); target.EnsureParentDirectoryExists(); source.Move(target); var installDetails = new GitInstaller.GitInstallDetails(gitInstallationPath.Parent, DefaultEnvironment.OnWindows) { GitPackageFeed = "http://nope", GitLfsPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitLfsPackageName}", }; var gitInstaller = new GitInstaller(Environment, ProcessManager, TaskManager.Token, installDetails: installDetails); var result = gitInstaller.SetupGitIfNeeded(); result.Should().NotBeNull(); Assert.AreEqual(gitInstallationPath, result.GitInstallationPath); result.GitExecutablePath.Should().Be(gitInstallationPath.Combine("cmd", "git" + Environment.ExecutableExtension)); result.GitLfsExecutablePath.Should().Be(gitLfsInstallationPath.Combine("git-lfs" + Environment.ExecutableExtension)); } [Test] public void GitLfsIsInstalledIfMissingWithCustomGitPath() { var tempZipExtractPath = TestBasePath.Combine("Temp", "git_zip_extract_zip_paths"); var customGitInstall = TestBasePath.Combine("CustomGitInstall").Combine(GitInstaller.GitInstallDetails.GitDirectory); var gitZipUri = new UriString($"http://localhost:{server.Port}/unity/git/windows/git-slim.zip"); var downloader = new Downloader(Environment.FileSystem); downloader.QueueDownload(gitZipUri, tempZipExtractPath); downloader.RunSynchronously(); var gitExtractPath = tempZipExtractPath.Combine("git").CreateDirectory(); ZipHelper.Instance.Extract(tempZipExtractPath.Combine(gitZipUri.Filename), gitExtractPath, TaskManager.Token, null); var source = gitExtractPath; var target = customGitInstall; target.DeleteIfExists(); target.EnsureParentDirectoryExists(); source.Move(target); var gitExec = customGitInstall.Combine("cmd/git.exe"); var state = new GitInstaller.GitInstallationState(); state.GitExecutablePath = gitExec; Environment.GitInstallationState = state; var defaultGitInstall = TestBasePath.Combine("DefaultInstall"); var installDetails = new GitInstaller.GitInstallDetails(defaultGitInstall, DefaultEnvironment.OnWindows) { GitPackageFeed = "http://nope", GitLfsPackageFeed = $"http://localhost:{server.Port}/unity/git/windows/{GitInstaller.GitInstallDetails.GitLfsPackageName}", }; var gitInstaller = new GitInstaller(Environment, ProcessManager, TaskManager.Token, installDetails: installDetails); state = gitInstaller.SetupGitIfNeeded(); state.Should().NotBeNull(); var gitLfsBasePath = defaultGitInstall.Combine(GitInstaller.GitInstallDetails.GitLfsDirectory); var gitLfsExec = gitLfsBasePath.Combine("git-lfs.exe"); state.GitInstallationPath.Should().Be(customGitInstall); state.GitExecutablePath.Should().Be(gitExec); state.GitLfsInstallationPath.Should().Be(gitLfsExec.Parent); state.GitLfsExecutablePath.Should().Be(gitLfsExec); gitLfsExec.FileExists().Should().BeTrue(); Environment.GitInstallationState = state; var procTask = new SimpleProcessTask(TaskManager.Token, "something") .Configure(ProcessManager); var pathList = procTask.Process.StartInfo.EnvironmentVariables["PATH"].ToNPathList(Environment).TakeWhile(x => x != "END"); pathList.First().Should().Be(gitLfsExec.Parent); pathList.Skip(1).First().Should().Be(gitExec.Parent); } } }
using System; using System.Collections; using System.Collections.Generic; namespace XSharpx { /// <summary> /// An immutable in-memory single-linked list. /// </summary> /// <typeparam name="A">The element type held by this homogenous list.</typeparam> /// <remarks>Also known as a cons-list.</remarks> public sealed class List<A> : IEnumerable<A> { private readonly bool e; private readonly A h; private List<A> t; private List(bool e, A h, List<A> t) { this.e = e; this.h = h; this.t = t; } // To be used by ListBuffer only internal void UnsafeTailUpdate(List<A> t) { this.t = t; } // To be used by ListBuffer only internal A UnsafeHead { get { if(e) throw new Exception("Head on empty List"); else return h; } } // To be used by ListBuffer only internal List<A> UnsafeTail { get { if(e) throw new Exception("Tail on empty List"); else return t; } } public bool IsEmpty { get { return e; } } public bool IsNotEmpty { get { return !e; } } public List<List<A>> Duplicate { get { return Extend(q => q); } } public List<B> Extend<B>(Func<List<A>, B> f) { var b = ListBuffer<B>.Empty(); var a = this; while(!a.IsEmpty) { b.Snoc(f(a)); a = a.UnsafeTail; } return b.ToList; } public List<C> ProductWith<B, C>(List<B> o, Func<A, Func<B, C>> f) { return this.SelectMany(a => o.Select(b => f(a)(b))); } public List<Pair<A, B>> Product<B>(List<B> o) { return ProductWith<B, Pair<A, B>>(o, Pair<A, B>.pairF()); } public List<A> Append(List<A> x) { var b = ListBuffer<A>.Empty(); foreach(var a in this) b.Snoc(a); foreach(var a in x) b.Snoc(a); return b.ToList; } public DiffList<A> ToDiffList { get { return DiffList<A>.diffList(r => this * r); } } public NonEmptyList<A> Append(NonEmptyList<A> x) { return IsEmpty ? x : new NonEmptyList<A>(UnsafeHead, UnsafeTail).Append(x); } public static List<A> operator +(A h, List<A> t) { return Cons(h, t); } public static NonEmptyList<A> operator &(A h, List<A> t) { return new NonEmptyList<A>(h, t); } public static List<A> operator *(List<A> a1, List<A> a2) { return a1.Append(a2); } public static List<A> Empty { get { return new List<A>(true, default(A), default(List<A>)); } } public static List<A> Cons(A h, List<A> t) { return new List<A>(false, h, t); } public static List<A> list(params A[] a) { var k = List<A>.Empty; for(int i = a.Length - 1; i >= 0; i--) { k = a[i] + k; } return k; } private class ListEnumerator : IEnumerator<A> { private bool z = true; private readonly List<A> o; private List<A> a; public ListEnumerator(List<A> o) { this.o = o; } public void Dispose() {} public void Reset() { z = true; } public bool MoveNext() { if(z) { a = o; z = false; } else a = a.UnsafeTail; return !a.IsEmpty; } A IEnumerator<A>.Current { get { return a.UnsafeHead; } } public object Current { get { return a.UnsafeHead; } } } private ListEnumerator Enumerate() { return new ListEnumerator(this); } IEnumerator<A> IEnumerable<A>.GetEnumerator() { return Enumerate(); } IEnumerator IEnumerable.GetEnumerator() { return Enumerate(); } public ListBuffer<A> Buffer { get { var b = ListBuffer<A>.Empty(); foreach(var a in this) b.Snoc(a); return b; } } public Option<A> Head { get { return IsEmpty ? Option.Empty : Option.Some(UnsafeHead); } } public Option<List<A>> Tail { get { return IsEmpty ? Option.Empty : Option.Some(UnsafeTail); } } public A HeadOr(Func<A> a) { return IsEmpty ? a() : UnsafeHead; } public List<A> TailOr(Func<List<A>> a) { return IsEmpty ? a() : UnsafeTail; } public X Uncons<X>(Func<X> nil, Func<A, List<A>, X> headTail) { return IsEmpty ? nil() : headTail(UnsafeHead, UnsafeTail); } public Option<Pair<A, List<A>>> HeadTail { get { return IsEmpty ? Option.Empty : Pair<A, List<A>>.pair(UnsafeHead, UnsafeTail).Some(); } } public B FoldRight<B>(Func<A, B, B> f, B b) { return e ? b : f(UnsafeHead, UnsafeTail.FoldRight(f, b)); } public B FoldLeft<B>(Func<B, A, B> f, B b) { var x = b; foreach(A z in this) { x = f(x, z); } return x; } public A SumRight(Monoid<A> m) { return FoldRight<A>(m.Op, m.Id); } public A SumLeft(Monoid<A> m) { return FoldLeft<A>(m.Op, m.Id); } public B SumMapRight<B>(Func<A, B> f, Monoid<B> m) { return FoldRight<B>((a, b) => m.Op(f(a), b), m.Id); } public B SumMapLeft<B>(Func<A, B> f, Monoid<B> m) { return FoldLeft<B>((a, b) => m.Op(a, f(b)), m.Id); } public void ForEach(Action<A> a) { foreach(A x in this) { a(x); } } public List<A> Where(Func<A, bool> f) { var b = ListBuffer<A>.Empty(); foreach(var a in this) if(f(a)) b.Snoc(a); return b.ToList; } public List<A> Take(int n) { return n <= 0 || e ? List<A>.Empty : UnsafeHead + UnsafeTail.Take(n - 1); } public List<A> Drop(int n) { return n <= 0 ? this : e ? List<A>.Empty : UnsafeTail.Drop(n - 1); } public List<A> TakeWhile(Func<A, bool> p) { return e ? this : p(UnsafeHead) ? UnsafeHead + UnsafeTail.TakeWhile(p) : List<A>.Empty; } public List<A> DropWhile(Func<A, bool> p) { var a = this; while(!a.IsEmpty && p(a.UnsafeHead)) { a = a.UnsafeTail; } return a; } public int Length { get { return FoldLeft((b, _) => b + 1, 0); } } public List<A> Reverse { get { return FoldLeft<List<A>>((b, a) => a + b, List<A>.Empty); } } public Option<A> this [int n] { get { return n < 0 || IsEmpty ? Option.Empty : n == 0 ? Option.Some(UnsafeHead) : UnsafeTail[n - 1]; } } public List<C> ZipWith<B, C>(List<B> bs, Func<A, Func<B, C>> f) { return IsEmpty && bs.IsEmpty ? List<C>.Empty : f(UnsafeHead)(bs.UnsafeHead) + UnsafeTail.ZipWith(bs.UnsafeTail, f); } public List<Pair<A, B>> Zip<B>(List<B> bs) { return ZipWith<B, Pair<A, B>>(bs, a => b => Pair<A, B>.pair(a, b)); } public bool All(Func<A, bool> f) { var x = true; foreach(var t in this) { if(!f(t)) return false; } return x; } public bool Any(Func<A, bool> f) { var x = false; foreach(var t in this) { if(f(t)) return true; } return x; } public List<List<B>> TraverseList<B>(Func<A, List<B>> f) { return FoldRight<List<List<B>>>( (a, b) => f(a).ProductWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.ListValue() ); } public Option<List<B>> TraverseOption<B>(Func<A, Option<B>> f) { return FoldRight<Option<List<B>>>( (a, b) => f(a).ZipWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.Some() ); } public Terminal<List<B>> TraverseTerminal<B>(Func<A, Terminal<B>> f) { return FoldRight<Terminal<List<B>>>( (a, b) => f(a).ZipWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.TerminalValue() ); } public Input<List<B>> TraverseInput<B>(Func<A, Input<B>> f) { return FoldRight<Input<List<B>>>( (a, b) => f(a).ZipWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.InputElement() ); } public Either<X, List<B>> TraverseEither<X, B>(Func<A, Either<X, B>> f) { return FoldRight<Either<X, List<B>>>( (a, b) => f(a).ZipWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.Right<X, List<B>>() ); } public NonEmptyList<List<B>> TraverseNonEmptyList<B>(Func<A, NonEmptyList<B>> f) { return FoldRight<NonEmptyList<List<B>>>( (a, b) => f(a).ProductWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.NonEmptyListValue() ); } public Pair<X, List<B>> TraversePair<X, B>(Func<A, Pair<X, B>> f, Monoid<X> m) { return FoldRight<Pair<X, List<B>>>( (a, b) => f(a).Constrain(m).ZipWith<List<B>, List<B>>(b.Constrain(m), aa => bb => aa + bb).Pair , m.Id.And(List<B>.Empty) ); } public Func<X, List<B>> TraverseFunc<X, B>(Func<A, Func<X, B>> f) { return x => this.Select(a => f(a)(x)); } public Tree<List<B>> TraverseTree<B>(Func<A, Tree<B>> f) { return FoldRight<Tree<List<B>>>( (a, b) => f(a).ZipWith<List<B>, List<B>>(b, aa => bb => aa + bb) , List<B>.Empty.TreeValue() ); } public Option<ListZipper<A>> Zipper { get { return IsEmpty ? Option<ListZipper<A>>.Empty : (new ListZipper<A>(List<A>.Empty, UnsafeHead, UnsafeTail)).Some(); } } } public static class ListExtension { public static List<B> Select<A, B>(this List<A> ps, Func<A, B> f) { var b = ListBuffer<B>.Empty(); foreach(var a in ps) b.Snoc(f(a)); return b.ToList; } public static List<B> SelectMany<A, B>(this List<A> ps, Func<A, List<B>> f) { var b = ListBuffer<B>.Empty(); foreach(var a in ps) b.Append(f(a)); return b.ToList; } public static List<C> SelectMany<A, B, C>(this List<A> ps, Func<A, List<B>> p, Func<A, B, C> f) { return SelectMany(ps, a => Select(p(a), b => f(a, b))); } public static List<B> Apply<A, B>(this List<Func<A, B>> f, List<A> o) { return f.ProductWith<A, B>(o, a => b => a(b)); } public static List<B> ApplyZip<A, B>(this List<Func<A, B>> f, List<A> o) { return f.ZipWith<A, B>(o, a => b => a(b)); } public static List<A> Flatten<A>(this List<List<A>> o) { return o.SelectMany(z => z); } public static Pair<List<A>, List<B>> Unzip<A, B>(this List<Pair<A, B>> p) { return p.FoldRight<Pair<List<A>, List<B>>>( (x, y) => (x._1.Get + y._1.Get).And(x._2.Get + y._2.Get) , List<A>.Empty.And(List<B>.Empty) ); } public static List<A> ListValue<A>(this A a) { return List<A>.Cons(a, List<A>.Empty); } public static List<B> UnfoldList<A, B>(this A a, Func<A, Option<Pair<B, A>>> f) { return f(a).Fold<List<B>>(p => p._1.Get + p._2.Get.UnfoldList(f), () => List<B>.Empty); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.UI.Notifications; using EDEngineer.Localization; using EDEngineer.Models; using EDEngineer.Utils.System; using EDEngineer.Views.Popups; using Application = System.Windows.Application; namespace EDEngineer.Views { public class CommanderToasts : IDisposable { private readonly State state; private readonly string commanderName; private readonly BlockingCollection<ToastNotification> toasts = new BlockingCollection<ToastNotification>(); private readonly CancellationTokenSource tokenSource = new CancellationTokenSource(); public CommanderToasts(State state, string commanderName) { this.state = state; this.commanderName = commanderName; Task.Factory.StartNew(ConsumeToasts); } private void ConsumeToasts() { var toDisplay = new HashSet<ToastNotification>(); var fiveSeconds = TimeSpan.FromSeconds(5); while (!tokenSource.Token.IsCancellationRequested) { ToastNotification item; while (toasts.TryTake(out item, fiveSeconds) && toDisplay.Add(item)); if (toDisplay.Count <= 2) { foreach (var toast in toDisplay) { ToastNotificationManager.CreateToastNotifier("EDEngineer").Show(toast); } } else { var translator = Languages.Instance; var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01); var stringElements = toastXml.GetElementsByTagName("text"); stringElements[0].AppendChild(toastXml.CreateTextNode(translator.Translate("Multiple Blueprints Ready"))); var imagePath = "file:///" + Path.GetFullPath("Resources/Images/elite-dangerous-clean.png"); var imageElements = toastXml.GetElementsByTagName("image"); imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath; var toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier("EDEngineer").Show(toast); } toDisplay.Clear(); } } private void ThresholdToastCheck(string item) { if (!SettingsManager.ThresholdWarningEnabled) { return; } var translator = Languages.Instance; if (!state.Cargo.ContainsKey(item)) { return; } var entry = state.Cargo[item]; if (entry.Threshold.HasValue && entry.Threshold <= entry.Count) { try { var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02); var stringElements = toastXml.GetElementsByTagName("text"); var content = string.Format( translator.Translate( "Reached {0} {1} - threshold set at {2} (click this to configure your thresholds)"), entry.Count, translator.Translate(entry.Data.Name), entry.Threshold); stringElements[0].AppendChild(toastXml.CreateTextNode(translator.Translate("Threshold Reached!"))); stringElements[1].AppendChild(toastXml.CreateTextNode(content)); var imagePath = "file:///" + Path.GetFullPath("Resources/Images/elite-dangerous-clean.png"); var imageElements = toastXml.GetElementsByTagName("image"); imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath; var toast = new ToastNotification(toastXml); toast.Activated += (o, e) => Application.Current.Dispatcher.Invoke(() => ThresholdsManagerWindow.ShowThresholds(translator, state.Cargo, commanderName)); ToastNotificationManager.CreateToastNotifier("EDEngineer").Show(toast); } catch (Exception) { // silently fail for platforms not supporting toasts } } } private void LimitToastCheck(string property) { if (!SettingsManager.CargoAlmostFullWarningEnabled) { return; } var translator = Languages.Instance; var ratio = state.MaxMaterials - state.MaterialsCount; string headerText, contentText; if (ratio <= 5 && property == "MaterialsCount") { headerText = translator.Translate("Materials Almost Full!"); contentText = string.Format(translator.Translate("You have only {0} slots left for your materials."), ratio); } else if ((ratio = state.MaxData - state.DataCount) <= 5 && property == "DataCount") { headerText = translator.Translate("Data Almost Full!"); contentText = string.Format(translator.Translate("You have only {0} slots left for your data."), ratio); } else { return; } try { var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02); var stringElements = toastXml.GetElementsByTagName("text"); stringElements[0].AppendChild(toastXml.CreateTextNode(headerText)); stringElements[1].AppendChild(toastXml.CreateTextNode(contentText)); var imagePath = "file:///" + Path.GetFullPath("Resources/Images/elite-dangerous-clean.png"); var imageElements = toastXml.GetElementsByTagName("image"); imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath; var toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier("EDEngineer").Show(toast); } catch (Exception) { // silently fail for platforms not supporting toasts } } private void BlueprintOnFavoriteAvailable(object sender, EventArgs e) { if (!SettingsManager.BlueprintReadyToastEnabled) { return; } var blueprint = (Blueprint)sender; try { var translator = Languages.Instance; var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04); var stringElements = toastXml.GetElementsByTagName("text"); stringElements[0].AppendChild(toastXml.CreateTextNode(translator.Translate("Blueprint Ready"))); stringElements[1].AppendChild(toastXml.CreateTextNode($"{translator.Translate(blueprint.BlueprintName)} (G{blueprint.Grade})")); stringElements[2].AppendChild(toastXml.CreateTextNode($"{string.Join(", ", blueprint.Engineers)}")); var imagePath = "file:///" + Path.GetFullPath("Resources/Images/elite-dangerous-clean.png"); var imageElements = toastXml.GetElementsByTagName("image"); imageElements[0].Attributes.GetNamedItem("src").NodeValue = imagePath; var toast = new ToastNotification(toastXml); toasts.Add(toast); } catch (Exception) { // silently fail for platforms not supporting toasts } } public void UnsubscribeToasts() { foreach (var blueprint in state.Blueprints) { blueprint.FavoriteAvailable -= BlueprintOnFavoriteAvailable; } state.PropertyChanged -= StateCargoCountChanged; } public void SubscribeToasts() { foreach (var blueprint in state.Blueprints) { blueprint.FavoriteAvailable += BlueprintOnFavoriteAvailable; } state.PropertyChanged += StateCargoCountChanged; } private void StateCargoCountChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "MaterialsCount" || e.PropertyName == "DataCount") { LimitToastCheck(e.PropertyName); } ThresholdToastCheck(e.PropertyName); } public void Dispose() { tokenSource.Cancel(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Tests { public class TypeTestsNetcore { private static readonly IList<Type> NonArrayBaseTypes; static TypeTestsNetcore() { NonArrayBaseTypes = new List<Type>() { typeof(int), typeof(void), typeof(int*), typeof(Outside), typeof(Outside<int>), typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0], new object().GetType().GetType() }; if (PlatformDetection.IsWindows) { NonArrayBaseTypes.Add(Type.GetTypeFromCLSID(default(Guid))); } } [Fact] public void IsSZArray_FalseForNonArrayTypes() { foreach (Type type in NonArrayBaseTypes) { Assert.False(type.IsSZArray); } } [Fact] public void IsSZArray_TrueForSZArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType())) { Assert.True(type.IsSZArray); } } [Fact] public void IsSZArray_FalseForVariableBoundArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1))) { Assert.False(type.IsSZArray); } foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2))) { Assert.False(type.IsSZArray); } } [Fact] public void IsSZArray_FalseForNonArrayByRefType() { Assert.False(typeof(int).MakeByRefType().IsSZArray); } [Fact] public void IsSZArray_FalseForByRefSZArrayType() { Assert.False(typeof(int[]).MakeByRefType().IsSZArray); } [Fact] public void IsSZArray_FalseForByRefVariableArrayType() { Assert.False(typeof(int[,]).MakeByRefType().IsSZArray); } [Fact] public void IsVariableBoundArray_FalseForNonArrayTypes() { foreach (Type type in NonArrayBaseTypes) { Assert.False(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_FalseForSZArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType())) { Assert.False(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_TrueForVariableBoundArrayTypes() { foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(1))) { Assert.True(type.IsVariableBoundArray); } foreach (Type type in NonArrayBaseTypes.Select(nonArrayBaseType => nonArrayBaseType.MakeArrayType(2))) { Assert.True(type.IsVariableBoundArray); } } [Fact] public void IsVariableBoundArray_FalseForNonArrayByRefType() { Assert.False(typeof(int).MakeByRefType().IsVariableBoundArray); } [Fact] public void IsVariableBoundArray_FalseForByRefSZArrayType() { Assert.False(typeof(int[]).MakeByRefType().IsVariableBoundArray); } [Fact] public void IsVariableBoundArray_FalseForByRefVariableArrayType() { Assert.False(typeof(int[,]).MakeByRefType().IsVariableBoundArray); } [Theory] [MemberData(nameof(DefinedTypes))] public void IsTypeDefinition_True(Type type) { Assert.True(type.IsTypeDefinition); } [Theory] [MemberData(nameof(NotDefinedTypes))] public void IsTypeDefinition_False(Type type) { Assert.False(type.IsTypeDefinition); } // In the unlikely event we ever add new values to the CorElementType enumeration, CoreCLR will probably miss it because of the way IsTypeDefinition // works. It's likely that such a type will live in the core assembly so to improve our chances of catching this situation, test IsTypeDefinition // on every type exposed out of that assembly. // // Skipping this on .NET Native because: // - We really don't want to opt in all the metadata in System.Private.CoreLib // - The .NET Native implementation of IsTypeDefinition is not the one that works by enumerating selected values off CorElementType. // It has much less need of a test like this. [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot)] public void IsTypeDefinition_AllDefinedTypesInCoreAssembly() { foreach (Type type in typeof(object).Assembly.DefinedTypes) { Assert.True(type.IsTypeDefinition, "IsTypeDefinition expected to be true for type " + type); } } public static IEnumerable<object[]> DefinedTypes { get { yield return new object[] { typeof(void) }; yield return new object[] { typeof(int) }; yield return new object[] { typeof(Outside) }; yield return new object[] { typeof(Outside.Inside) }; yield return new object[] { typeof(Outside<>) }; yield return new object[] { typeof(IEnumerable<>) }; yield return new object[] { 3.GetType().GetType() }; // This yields a reflection-blocked type on .NET Native - which is implemented separately if (PlatformDetection.IsWindows) yield return new object[] { Type.GetTypeFromCLSID(default(Guid)) }; } } public static IEnumerable<object[]> NotDefinedTypes { get { Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { typeof(int[]) }; yield return new object[] { theT.MakeArrayType(1) }; // Using an open type as element type gets around .NET Native nonsupport of rank-1 multidim arrays yield return new object[] { typeof(int[,]) }; yield return new object[] { typeof(int).MakeByRefType() }; yield return new object[] { typeof(int).MakePointerType() }; yield return new object[] { typeof(Outside<int>) }; yield return new object[] { typeof(Outside<int>.Inside<int>) }; yield return new object[] { theT }; } } [Theory] [MemberData(nameof(IsByRefLikeTestData))] public static void TestIsByRefLike(Type type, bool expected) { Assert.Equal(expected, type.IsByRefLike); } public static IEnumerable<object[]> IsByRefLikeTestData { get { Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { typeof(ArgIterator), true }; yield return new object[] { typeof(ByRefLikeStruct), true }; yield return new object[] { typeof(RegularStruct), false }; yield return new object[] { typeof(RuntimeArgumentHandle), true }; yield return new object[] { typeof(Span<>), true }; yield return new object[] { typeof(Span<>).MakeGenericType(theT), true }; yield return new object[] { typeof(Span<int>), true }; yield return new object[] { typeof(Span<int>).MakeByRefType(), false }; yield return new object[] { typeof(Span<int>).MakePointerType(), false }; yield return new object[] { typeof(TypedReference), true }; yield return new object[] { theT, false }; yield return new object[] { typeof(int[]), false }; yield return new object[] { typeof(int[,]), false }; yield return new object[] { typeof(object), false }; if (PlatformDetection.IsWindows) // GetTypeFromCLSID is Windows only { yield return new object[] { Type.GetTypeFromCLSID(default(Guid)), false }; } } } private ref struct ByRefLikeStruct { public ByRefLikeStruct(int dummy) { S = default(Span<int>); } public Span<int> S; } private struct RegularStruct { } [Theory] [MemberData(nameof(IsGenericParameterTestData))] public static void TestIsGenericParameter(Type type, bool isGenericParameter, bool isGenericTypeParameter, bool isGenericMethodParameter) { Assert.Equal(isGenericParameter, type.IsGenericParameter); Assert.Equal(isGenericTypeParameter, type.IsGenericTypeParameter); Assert.Equal(isGenericMethodParameter, type.IsGenericMethodParameter); } public static IEnumerable<object[]> IsGenericParameterTestData { get { yield return new object[] { typeof(void), false, false, false }; yield return new object[] { typeof(int), false, false, false }; yield return new object[] { typeof(int[]), false, false, false }; yield return new object[] { typeof(int).MakeArrayType(1), false, false, false }; yield return new object[] { typeof(int[,]), false, false, false }; yield return new object[] { typeof(int).MakeByRefType(), false, false, false }; yield return new object[] { typeof(int).MakePointerType(), false, false, false }; yield return new object[] { typeof(DummyGenericClassForTypeTestsNetcore<>), false, false, false }; yield return new object[] { typeof(DummyGenericClassForTypeTestsNetcore<int>), false, false, false }; if (PlatformDetection.IsWindows) // GetTypeFromCLSID is Windows only { yield return new object[] { Type.GetTypeFromCLSID(default(Guid)), false, false, false }; } Type theT = typeof(Outside<>).GetTypeInfo().GenericTypeParameters[0]; yield return new object[] { theT, true, true, false }; Type theM = typeof(TypeTestsNetcore).GetMethod(nameof(GenericMethod), BindingFlags.NonPublic | BindingFlags.Static).GetGenericArguments()[0]; yield return new object[] { theM, true, false, true }; } } private static void GenericMethod<M>() { } } } internal class DummyGenericClassForTypeTestsNetcore<T> { }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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 UnityEngine; using System.Collections.Generic; /// <summary> /// Controls the player's movement in virtual reality. /// </summary> [RequireComponent(typeof(CharacterController))] public class OVRPlayerController : MonoBehaviour { /// <summary> /// The rate acceleration during movement. /// </summary> public float Acceleration = 0.1f; /// <summary> /// The rate of damping on movement. /// </summary> public float Damping = 0.3f; /// <summary> /// The rate of additional damping when moving sideways or backwards. /// </summary> public float BackAndSideDampen = 0.5f; /// <summary> /// The force applied to the character when jumping. /// </summary> public float JumpForce = 0.3f; /// <summary> /// The rate of rotation when using a gamepad. /// </summary> public float RotationAmount = 1.5f; /// <summary> /// The rate of rotation when using the keyboard. /// </summary> public float RotationRatchet = 0.0f; /// <summary> /// If true, reset the initial yaw of the player controller when the Hmd pose is recentered. /// </summary> public bool HmdResetsY = true; /// <summary> /// If true, tracking data from a child OVRCameraRig will update the direction of movement. /// </summary> public bool HmdRotatesY = true; /// <summary> /// Modifies the strength of gravity. /// </summary> public float GravityModifier = 0.015f;//0.379f; /// <summary> /// If true, each OVRPlayerController will use the player's physical height. /// </summary> public bool useProfileData = true; protected CharacterController Controller = null; protected OVRCameraRig CameraRig = null; private float MoveScale = 1.0f; private Vector3 MoveThrottle = Vector3.zero; private float FallSpeed = 0.0f; private OVRPose? InitialPose; private float InitialYRotation = 0.0f; private float MoveScaleMultiplier = 1.0f; private float RotationScaleMultiplier = 1.0f; private bool SkipMouseRotation = false; private bool HaltUpdateMovement = false; private bool prevHatLeft = false; private bool prevHatRight = false; private float SimulationRate = 60f; public List<Vector3> OculusMovements = new List<Vector3>(); public List<float> OculusTime = new List<float>(); public Vector3 OculusPrevRot = Vector3.zero; void Start() { // Add eye-depth as a camera offset from the player controller var p = CameraRig.transform.localPosition; p.z = OVRManager.profile.eyeDepth; CameraRig.transform.localPosition = p; } void Awake() { Controller = gameObject.GetComponent<CharacterController>(); if (Controller == null) Debug.LogWarning("OVRPlayerController: No CharacterController attached."); // We use OVRCameraRig to set rotations to cameras, // and to be influenced by rotation OVRCameraRig[] CameraRigs = gameObject.GetComponentsInChildren<OVRCameraRig>(); if (CameraRigs.Length == 0) Debug.LogWarning("OVRPlayerController: No OVRCameraRig attached."); else if (CameraRigs.Length > 1) Debug.LogWarning("OVRPlayerController: More then 1 OVRCameraRig attached."); else CameraRig = CameraRigs[0]; InitialYRotation = transform.rotation.eulerAngles.y; } void OnEnable() { OVRManager.display.RecenteredPose += ResetOrientation; if (CameraRig != null) { CameraRig.UpdatedAnchors += UpdateTransform; } } void OnDisable() { OVRManager.display.RecenteredPose -= ResetOrientation; if (CameraRig != null) { CameraRig.UpdatedAnchors -= UpdateTransform; } } public Vector3 GetOculusRotation() { if (transform != null && OVRManager.instance.GetRotation() != null) return OVRManager.instance.GetRotation() - transform.eulerAngles; Debug.Log("error"); return Vector3.zero; } public bool CheckShakingHead() { int cnt = 0; int nbPatern = 0; bool direction = true; float angle = .0f; List<Vector3> tmp = OculusMovements; //Debug.Log("Start Debug"); tmp.Reverse(); direction = (tmp[0].y < 0); foreach (Vector3 move in tmp) { angle += move.y; if (Mathf.Abs(angle) > 60 && cnt < 20) { nbPatern += 1; cnt++; angle = .0f; direction = !direction; if (nbPatern == 2) { OculusMovements.Clear(); OculusTime.Clear(); return true; } } else if (((direction && move.y > 0) || (!direction && move.y < 0)) && Mathf.Abs(move.y) < 15) { return false; } } return false; } private float getAxis(int axisSelect, Vector3 move) { if (axisSelect == 0) return move.x; else if (axisSelect == 1) return move.y; else if (axisSelect == 2) return move.z; return .0f; } public bool ShakingHeadChecker(int axis, float minAngle, float maxAngle, float minTime, float maxTime, float stopTime, int repeat) { int nbPatern = 0; bool direction = (axis < 3); float angle = .0f; float time = .0f; axis = axis % 3; for (int cnt = OculusMovements.Count - 1; cnt >= 0; cnt--) { float tmp = getAxis(axis, OculusMovements[cnt]); if ((((direction && tmp < -5) || (!direction && tmp > 5)) && nbPatern != repeat) || nbPatern > repeat) { //Debug.Log("Wrong Way / " + tmp + " / " + direction); return false; } angle += getAxis(axis, OculusMovements[cnt]); time += OculusTime[cnt]; if (minAngle <= Mathf.Abs(angle) && Mathf.Abs(angle) <= maxAngle && minTime <= time && time <= maxTime && ((direction && tmp < 0) || (!direction && tmp > 0))) { nbPatern += 1; //Debug.Log("Patern Get " + nbPatern + " / " + angle + " / " + direction + " lol " + time); angle = .0f; time = .0f; direction = !direction; } else if (nbPatern == repeat) { //Debug.Log("Ok Mais pas"); if (angle > 30 && stopTime != 0.0f) { //Debug.Log("Caca3 / " + angle); return false; } if (time > stopTime) { OculusMovements.Clear(); OculusTime.Clear(); return true; } } else if (Mathf.Abs(angle) > maxAngle || time > maxTime) { //Debug.Log("Caca4 / " + Mathf.Abs(angle) + " / " + maxAngle + " | " + time + " / " + maxTime); return false; } } //Debug.Log("LoL ? " + OculusMovements.Count + " / " + Mathf.Abs(angle) + " / " + maxAngle + " | " + time + " / " + maxTime); return false; } private float RepairAxis(float axis) { if (axis > 340) return (axis - 360.0f) * -1.0f; if (axis < -340) return (axis + 360.0f) * -1.0f; return axis; } protected virtual void Update() { Vector3 TmpMovement = GetOculusRotation() - OculusPrevRot; TmpMovement.x = RepairAxis(TmpMovement.x); TmpMovement.y = RepairAxis(TmpMovement.y); TmpMovement.z = RepairAxis(TmpMovement.z); OculusMovements.Add(TmpMovement); OculusTime.Add(Time.deltaTime); OculusPrevRot = GetOculusRotation(); if (OculusMovements.Count > 150) { OculusMovements.RemoveAt(0); OculusTime.RemoveAt(0); } //if (ShakingHeadChecker(1, 60.0f, 300.0f, 0.0f, 1.0f, 1.0f, 2)) // Debug.Log("WEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); if (useProfileData) { if (InitialPose == null) { // Save the initial pose so it can be recovered if useProfileData // is turned off later. InitialPose = new OVRPose() { position = CameraRig.transform.localPosition, orientation = CameraRig.transform.localRotation }; } var p = CameraRig.transform.localPosition; p.y = OVRManager.profile.eyeHeight - 0.5f * Controller.height + Controller.center.y; CameraRig.transform.localPosition = p; } else if (InitialPose != null) { // Return to the initial pose if useProfileData was turned off at runtime CameraRig.transform.localPosition = InitialPose.Value.position; CameraRig.transform.localRotation = InitialPose.Value.orientation; InitialPose = null; } UpdateMovement(); Vector3 moveDirection = Vector3.zero; float motorDamp = (1.0f + (Damping * SimulationRate * Time.deltaTime)); MoveThrottle.x /= motorDamp; MoveThrottle.y = (MoveThrottle.y > 0.0f) ? (MoveThrottle.y / motorDamp) : MoveThrottle.y; MoveThrottle.z /= motorDamp; moveDirection += MoveThrottle * SimulationRate * Time.deltaTime; // Gravity if (Controller.isGrounded && FallSpeed <= 0) FallSpeed = ((Physics.gravity.y * (GravityModifier * 0.002f))); else FallSpeed += ((Physics.gravity.y * (GravityModifier * 0.002f)) * SimulationRate * Time.deltaTime); moveDirection.y += FallSpeed * SimulationRate * Time.deltaTime; // Offset correction for uneven ground float bumpUpOffset = 0.0f; if (Controller.isGrounded && MoveThrottle.y <= transform.lossyScale.y * 0.001f) { bumpUpOffset = Mathf.Max(Controller.stepOffset, new Vector3(moveDirection.x, 0, moveDirection.z).magnitude); moveDirection -= bumpUpOffset * Vector3.up; } Vector3 predictedXZ = Vector3.Scale((Controller.transform.localPosition + moveDirection), new Vector3(1, 0, 1)); // Move contoller Controller.Move(moveDirection); Vector3 actualXZ = Vector3.Scale(Controller.transform.localPosition, new Vector3(1, 0, 1)); if (predictedXZ != actualXZ) MoveThrottle += (actualXZ - predictedXZ) / (SimulationRate * Time.deltaTime); } public virtual void UpdateMovement() { if (HaltUpdateMovement) return; bool moveForward = Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow); bool moveLeft = Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow); bool moveRight = Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow); bool moveBack = Input.GetKey(KeyCode.S) || Input.GetKey(KeyCode.DownArrow); bool dpad_move = false; if (OVRInput.Get(OVRInput.Button.DpadUp)) { moveForward = true; dpad_move = true; } if (OVRInput.Get(OVRInput.Button.DpadDown)) { moveBack = true; dpad_move = true; } MoveScale = 1.0f; if (Input.GetButton("Jump")) Jump(); if ( (moveForward && moveLeft) || (moveForward && moveRight) || (moveBack && moveLeft) || (moveBack && moveRight) ) MoveScale = 0.70710678f; // No positional movement if we are in the air //if (!Controller.isGrounded) // MoveScale = 0.0f; MoveScale *= SimulationRate * Time.deltaTime; // Compute this for key movement float moveInfluence = Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; // Run! if (dpad_move || Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) moveInfluence *= 2.0f; Quaternion ort = transform.rotation; Vector3 ortEuler = ort.eulerAngles; ortEuler.z = ortEuler.x = 0f; ort = Quaternion.Euler(ortEuler); if (moveForward) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * Vector3.forward); if (moveBack) MoveThrottle += ort * (transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if (moveLeft) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if (moveRight) MoveThrottle += ort * (transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); Vector3 euler = transform.rotation.eulerAngles; //Use keys to ratchet rotation if (Input.GetKeyDown(KeyCode.Q)) euler.y -= RotationRatchet; if (Input.GetKeyDown(KeyCode.E)) euler.y += RotationRatchet; float rotateInfluence = SimulationRate * Time.deltaTime * RotationAmount * RotationScaleMultiplier; #if !UNITY_ANDROID || UNITY_EDITOR if (!SkipMouseRotation) euler.y += Input.GetAxis("Mouse X") * rotateInfluence * 3.25f; #endif moveInfluence = SimulationRate * Time.deltaTime * Acceleration * 0.1f * MoveScale * MoveScaleMultiplier; #if !UNITY_ANDROID // LeftTrigger not avail on Android game pad moveInfluence *= 1.0f + OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger); #endif Vector2 primaryAxis = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick); if(primaryAxis.y > 0.0f) MoveThrottle += ort * (primaryAxis.y * transform.lossyScale.z * moveInfluence * Vector3.forward); if(primaryAxis.y < 0.0f) MoveThrottle += ort * (Mathf.Abs(primaryAxis.y) * transform.lossyScale.z * moveInfluence * BackAndSideDampen * Vector3.back); if(primaryAxis.x < 0.0f) MoveThrottle += ort * (Mathf.Abs(primaryAxis.x) * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.left); if(primaryAxis.x > 0.0f) MoveThrottle += ort * (primaryAxis.x * transform.lossyScale.x * moveInfluence * BackAndSideDampen * Vector3.right); Vector2 secondaryAxis = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick); euler.y += secondaryAxis.x * rotateInfluence; transform.rotation = Quaternion.Euler(euler); } /// <summary> /// Invoked by OVRCameraRig's UpdatedAnchors callback. Allows the Hmd rotation to update the facing direction of the player. /// </summary> public void UpdateTransform(OVRCameraRig rig) { Transform root = CameraRig.trackingSpace; Transform centerEye = CameraRig.centerEyeAnchor; if (HmdRotatesY) { Vector3 prevPos = root.position; Quaternion prevRot = root.rotation; transform.rotation = Quaternion.Euler(0.0f, centerEye.rotation.eulerAngles.y, 0.0f); root.position = prevPos; root.rotation = prevRot; } } /// <summary> /// Jump! Must be enabled manually. /// </summary> public bool Jump() { if (!Controller.isGrounded) return false; MoveThrottle += new Vector3(0, transform.lossyScale.y * JumpForce, 0); return true; } /// <summary> /// Stop this instance. /// </summary> public void Stop() { Controller.Move(Vector3.zero); MoveThrottle = Vector3.zero; FallSpeed = 0.0f; } /// <summary> /// Gets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void GetMoveScaleMultiplier(ref float moveScaleMultiplier) { moveScaleMultiplier = MoveScaleMultiplier; } /// <summary> /// Sets the move scale multiplier. /// </summary> /// <param name="moveScaleMultiplier">Move scale multiplier.</param> public void SetMoveScaleMultiplier(float moveScaleMultiplier) { MoveScaleMultiplier = moveScaleMultiplier; } /// <summary> /// Gets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void GetRotationScaleMultiplier(ref float rotationScaleMultiplier) { rotationScaleMultiplier = RotationScaleMultiplier; } /// <summary> /// Sets the rotation scale multiplier. /// </summary> /// <param name="rotationScaleMultiplier">Rotation scale multiplier.</param> public void SetRotationScaleMultiplier(float rotationScaleMultiplier) { RotationScaleMultiplier = rotationScaleMultiplier; } /// <summary> /// Gets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">Allow mouse rotation.</param> public void GetSkipMouseRotation(ref bool skipMouseRotation) { skipMouseRotation = SkipMouseRotation; } /// <summary> /// Sets the allow mouse rotation. /// </summary> /// <param name="skipMouseRotation">If set to <c>true</c> allow mouse rotation.</param> public void SetSkipMouseRotation(bool skipMouseRotation) { SkipMouseRotation = skipMouseRotation; } /// <summary> /// Gets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">Halt update movement.</param> public void GetHaltUpdateMovement(ref bool haltUpdateMovement) { haltUpdateMovement = HaltUpdateMovement; } /// <summary> /// Sets the halt update movement. /// </summary> /// <param name="haltUpdateMovement">If set to <c>true</c> halt update movement.</param> public void SetHaltUpdateMovement(bool haltUpdateMovement) { HaltUpdateMovement = haltUpdateMovement; } /// <summary> /// Resets the player look rotation when the device orientation is reset. /// </summary> public void ResetOrientation() { if (HmdResetsY) { Vector3 euler = transform.rotation.eulerAngles; euler.y = InitialYRotation; transform.rotation = Quaternion.Euler(euler); } } }
/* * * (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.SIP.Proxy { #region usings using System; using System.Collections.Generic; using System.Net; using AUTH; using Message; using Stack; #endregion #region Delegates /// <summary> /// Represents the method that will handle the SIP_ProxyCore.IsLocalUri event. /// </summary> /// <param name="uri">Request URI.</param> /// <returns>Returns true if server local URI, otherwise false.</returns> public delegate bool SIP_IsLocalUriEventHandler(string uri); /// <summary> /// Represents the method that will handle the SIP_ProxyCore.Authenticate event. /// </summary> public delegate void SIP_AuthenticateEventHandler(SIP_AuthenticateEventArgs e); /// <summary> /// Represents the method that will handle the SIP_ProxyCore.AddressExists event. /// </summary> /// <param name="address">SIP address to check.</param> /// <returns>Returns true if specified address exists, otherwise false.</returns> public delegate bool SIP_AddressExistsEventHandler(string address); /// <summary> /// Represents the method that will handle the SIP_ProxyCore.GetGateways event. /// </summary> /// <param name="e">Event data.</param> public delegate void SIP_GetGatewaysEventHandler(SIP_GatewayEventArgs e); #endregion /// <summary> /// Implements SIP registrar,statefull and stateless proxy. /// </summary> public class SIP_ProxyCore : IDisposable { #region Events /// <summary> /// This event is raised when SIP proxy needs to know if specified local server address exists. /// </summary> public event SIP_AddressExistsEventHandler AddressExists = null; /// <summary> /// This event is raised when SIP proxy or registrar server needs to authenticate user. /// </summary> public event SIP_AuthenticateEventHandler Authenticate = null; /// <summary> /// This event is raised when SIP proxy needs to get gateways for non-SIP URI. /// </summary> public event SIP_GetGatewaysEventHandler GetGateways = null; /// <summary> /// This event is raised when SIP proxy needs to know if specified request URI is local URI or remote URI. /// </summary> public event SIP_IsLocalUriEventHandler IsLocalUri = null; #endregion #region Members private readonly string m_Opaque = ""; private SIP_ForkingMode m_ForkingMode = SIP_ForkingMode.Parallel; private bool m_IsDisposed; private SIP_B2BUA m_pB2BUA; internal List<SIP_ProxyContext> m_pProxyContexts; private SIP_Registrar m_pRegistrar; private SIP_ProxyMode m_ProxyMode = SIP_ProxyMode.Registrar | SIP_ProxyMode.Statefull; private SIP_Stack m_pStack; #endregion #region Properties /// <summary> /// Gets if this object is disposed. /// </summary> public bool IsDisposed { get { return m_IsDisposed; } } /// <summary> /// Gets owner SIP stack. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Stack Stack { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pStack; } } /// <summary> /// Gets or sets proxy mode. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> /// <exception cref="ArgumentException">Is raised when invalid combination modes passed.</exception> public SIP_ProxyMode ProxyMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_ProxyMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } // Check for invalid mode () if ((value & SIP_ProxyMode.Statefull) != 0 && (value & SIP_ProxyMode.Stateless) != 0) { throw new ArgumentException("Proxy can't be at Statefull and Stateless at same time !"); } m_ProxyMode = value; } } /// <summary> /// Gets or sets how proxy handle forking. This property applies for statefull proxy only. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_ForkingMode ForkingMode { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_ForkingMode; } set { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } m_ForkingMode = value; } } /// <summary> /// Gets SIP registrar server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_Registrar Registrar { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pRegistrar; } } /// <summary> /// Gets SIP B2BUA server. /// </summary> /// <exception cref="ObjectDisposedException">Is raised when this object is disposed and and this property is accessed.</exception> public SIP_B2BUA B2BUA { get { if (m_IsDisposed) { throw new ObjectDisposedException(GetType().Name); } return m_pB2BUA; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="stack">Reference to SIP stack.</param> /// <exception cref="ArgumentNullException">Is raised when <b>sipStack</b> is null.</exception> public SIP_ProxyCore(SIP_Stack stack) { if (stack == null) { throw new ArgumentNullException("stack"); } m_pStack = stack; m_pStack.RequestReceived += m_pStack_RequestReceived; m_pStack.ResponseReceived += m_pStack_ResponseReceived; m_pRegistrar = new SIP_Registrar(this); m_pB2BUA = new SIP_B2BUA(this); m_Opaque = Auth_HttpDigest.CreateOpaque(); m_pProxyContexts = new List<SIP_ProxyContext>(); } #endregion #region Methods /// <summary> /// Cleans up any resources being used. /// </summary> public void Dispose() { if (m_IsDisposed) { return; } m_IsDisposed = true; if (m_pStack != null) { m_pStack.Dispose(); m_pStack = null; } m_pRegistrar = null; m_pB2BUA = null; m_pProxyContexts = null; } #endregion #region Event handlers /// <summary> /// This method is called when SIP stack receives new request. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pStack_RequestReceived(object sender, SIP_RequestReceivedEventArgs e) { OnRequestReceived(e); } /// <summary> /// This method is called when SIP stack receives new response. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event data.</param> private void m_pStack_ResponseReceived(object sender, SIP_ResponseReceivedEventArgs e) { OnResponseReceived(e); } #endregion #region Utility methods /// <summary> /// This method is called when new request is received. /// </summary> /// <param name="e">Request event arguments.</param> private void OnRequestReceived(SIP_RequestReceivedEventArgs e) { /* RFC 3261 16.12. ????????? Forward does all thse steps. 1. The proxy will inspect the Request-URI. If it indicates a resource owned by this proxy, the proxy will replace it with the results of running a location service. Otherwise, the proxy will not change the Request-URI. 2. The proxy will inspect the URI in the topmost Route header field value. If it indicates this proxy, the proxy removes it from the Route header field (this route node has been reached). 3. The proxy will forward the request to the resource indicated by the URI in the topmost Route header field value or in the Request-URI if no Route header field is present. The proxy determines the address, port and transport to use when forwarding the request by applying the procedures in [4] to that URI. */ SIP_Request request = e.Request; try { #region Registrar // Registrar if ((m_ProxyMode & SIP_ProxyMode.Registrar) != 0 && request.RequestLine.Method == SIP_Methods.REGISTER) { m_pRegistrar.Register(e); } #endregion #region Presence /* // Presence else if((m_ProxyMode & SIP_ProxyMode.Presence) != 0 && (request.Method == "SUBSCRIBE" || request.Method == "NOTIFY")){ } */ #endregion #region Statefull // Statefull else if ((m_ProxyMode & SIP_ProxyMode.Statefull) != 0) { // Statefull proxy is transaction statefull proxy only, // what don't create dialogs and keep dialog state. /* RFC 3261 16.10. StateFull proxy: If a matching response context is found, the element MUST immediately return a 200 (OK) response to the CANCEL request. If a response context is not found, the element does not have any knowledge of the request to apply the CANCEL to. It MUST statelessly forward the CANCEL request (it may have statelessly forwarded the associated request previously). */ if (e.Request.RequestLine.Method == SIP_Methods.CANCEL) { // Don't do server transaction before we get CANCEL matching transaction. SIP_ServerTransaction trToCancel = m_pStack.TransactionLayer.MatchCancelToTransaction(e.Request); if (trToCancel != null) { trToCancel.Cancel(); e.ServerTransaction.SendResponse(m_pStack.CreateResponse( SIP_ResponseCodes.x200_Ok, request)); } else { ForwardRequest(false, e); } } // ACK never creates transaction, it's always passed directly to transport layer. else if (e.Request.RequestLine.Method == SIP_Methods.ACK) { ForwardRequest(false, e); } else { ForwardRequest(true, e); } } #endregion #region B2BUA // B2BUA else if ((m_ProxyMode & SIP_ProxyMode.B2BUA) != 0) { m_pB2BUA.OnRequestReceived(e); } #endregion #region Stateless // Stateless else if ((m_ProxyMode & SIP_ProxyMode.Stateless) != 0) { // Stateless proxy don't do transaction, just forwards all. ForwardRequest(false, e); } #endregion #region Proxy won't accept command else { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x501_Not_Implemented, request)); } #endregion } catch (Exception x) { try { m_pStack.TransportLayer.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x500_Server_Internal_Error + ": " + x.Message, e.Request)); } catch { // Skip transport layer exception if send fails. } // Don't raise OnError for transport errors. if (!(x is SIP_TransportException)) { m_pStack.OnError(x); } } } /// <summary> /// This method is called when new response is received. /// </summary> /// <param name="e">Response event arguments.</param> private void OnResponseReceived(SIP_ResponseReceivedEventArgs e) { if ((m_ProxyMode & SIP_ProxyMode.B2BUA) != 0) { m_pB2BUA.OnResponseReceived(e); } else { /* This method is called when stateless proxy gets response or statefull proxy has no matching server transaction. */ /* RFC 3261 16.11. When a response arrives at a stateless proxy, the proxy MUST inspect the sent-by value in the first (topmost) Via header field value. If that address matches the proxy, (it equals a value this proxy has inserted into previous requests) the proxy MUST remove that header field value from the response and forward the result to the location indicated in the next Via header field value. */ // Just remove topmost Via:, sent-by check is done in transport layer. e.Response.Via.RemoveTopMostValue(); if ((m_ProxyMode & SIP_ProxyMode.Statefull) != 0) { // We should not reach here. This happens when no matching client transaction found. // RFC 3161 18.1.2 orders to forward them statelessly. m_pStack.TransportLayer.SendResponse(e.Response); } else if ((m_ProxyMode & SIP_ProxyMode.Stateless) != 0) { m_pStack.TransportLayer.SendResponse(e.Response); } } } /// <summary> /// Forwards specified request to destination recipient. /// </summary> /// <param name="statefull">Specifies if request is sent statefully or statelessly.</param> /// <param name="e">Request event arguments.</param> private void ForwardRequest(bool statefull, SIP_RequestReceivedEventArgs e) { ForwardRequest(statefull, e, e.Request, true); } #endregion #region Internal methods /// <summary> /// Forwards specified request to target recipient. /// </summary> /// <param name="statefull">Specifies if request is sent statefully or statelessly.</param> /// <param name="e">Request event arguments.</param> /// <param name="request">SIP request to forward.</param> /// <param name="addRecordRoute">Specifies if Record-Route header filed is added.</param> internal void ForwardRequest(bool statefull, SIP_RequestReceivedEventArgs e, SIP_Request request, bool addRecordRoute) { List<SIP_ProxyTarget> targetSet = new List<SIP_ProxyTarget>(); List<NetworkCredential> credentials = new List<NetworkCredential>(); SIP_Uri route = null; /* RFC 3261 16. 1. Validate the request (Section 16.3) 1. Reasonable Syntax 2. URI scheme 3. Max-Forwards 4. (Optional) Loop Detection 5. Proxy-Require 6. Proxy-Authorization 2. Preprocess routing information (Section 16.4) 3. Determine target(s) for the request (Section 16.5) 4. Forward the request (Section 16.6) */ #region 1. Validate the request (Section 16.3) // 1.1 Reasonable Syntax. // SIP_Message will do it. // 1.2 URI scheme check. if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString())) { // TODO: SIP_GatewayEventArgs eArgs = OnGetGateways("uriScheme", "userName"); // No suitable gateway or authenticated user has no access. if (eArgs.Gateways.Count == 0) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x416_Unsupported_URI_Scheme, e.Request)); return; } } // 1.3 Max-Forwards. if (request.MaxForwards <= 0) { e.ServerTransaction.SendResponse(m_pStack.CreateResponse( SIP_ResponseCodes.x483_Too_Many_Hops, request)); return; } // 1.4 (Optional) Loop Detection. // Skip. // 1.5 Proxy-Require. // TODO: // 1.6 Proxy-Authorization. // We need to auth all foreign calls. if (!SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) || !OnIsLocalUri(((SIP_Uri) request.RequestLine.Uri).Host)) { // We need to pass-through ACK. if (request.RequestLine.Method == SIP_Methods.ACK) {} else if (!AuthenticateRequest(e)) { return; } } #endregion #region 2. Preprocess routing information (Section 16.4). /* The proxy MUST inspect the Request-URI of the request. If the Request-URI of the request contains a value this proxy previously placed into a Record-Route header field (see Section 16.6 item 4), the proxy MUST replace the Request-URI in the request with the last value from the Route header field, and remove that value from the Route header field. The proxy MUST then proceed as if it received this modified request. If the first value in the Route header field indicates this proxy, the proxy MUST remove that value from the request. */ // Strict route. if (SIP_Utils.IsSipOrSipsUri(request.RequestLine.Uri.ToString()) && IsLocalRoute(((SIP_Uri) request.RequestLine.Uri))) { request.RequestLine.Uri = request.Route.GetAllValues()[request.Route.GetAllValues().Length - 1].Address.Uri; SIP_t_AddressParam[] routes = request.Route.GetAllValues(); route = (SIP_Uri) routes[routes.Length - 1].Address.Uri; request.Route.RemoveLastValue(); } // Loose route. else if (request.Route.GetAllValues().Length > 0 && IsLocalRoute(SIP_Uri.Parse(request.Route.GetTopMostValue().Address.Uri.ToString()))) { route = (SIP_Uri) request.Route.GetTopMostValue().Address.Uri; request.Route.RemoveTopMostValue(); } #endregion #region 3. Determine target(s) for the request (Section 16.5) /* 3. Determine target(s) for the request (Section 16.5) Next, the proxy calculates the target(s) of the request. The set of targets will either be predetermined by the contents of the request or will be obtained from an abstract location service. Each target in the set is represented as a URI. If the domain of the Request-URI indicates a domain this element is not responsible for, the Request-URI MUST be placed into the target set as the only target, and the element MUST proceed to the task of Request Forwarding (Section 16.6). If the target set for the request has not been predetermined as described above, this implies that the element is responsible for the domain in the Request-URI, and the element MAY use whatever mechanism it desires to determine where to send the request. Any of these mechanisms can be modeled as accessing an abstract Location Service. This may consist of obtaining information from a location service created by a SIP Registrar, reading a database, consulting a presence server, utilizing other protocols, or simply performing an algorithmic substitution on the Request-URI. When accessing the location service constructed by a registrar, the Request-URI MUST first be canonicalized as described in Section 10.3 before being used as an index. The output of these mechanisms is used to construct the target set. */ // Non-SIP // Foreign SIP // Local SIP // FIX ME: we may have tel: here SIP_Uri requestUri = (SIP_Uri) e.Request.RequestLine.Uri; // Proxy is not responsible for the domain in the Request-URI. if (!OnIsLocalUri(requestUri.Host)) { /* NAT traversal. When we do record routing, store request sender flow info and request target flow info. Now the tricky part, how proxy later which flow is target (because both sides can send requests). Sender-flow will store from-tag to flow and target-flow will store flowID only (Because we don't know to-tag). Later if request to-tag matches(incoming request), use that flow, otherwise(outgoing request) other flow. flowInfo: sender-flow "/" target-flow sender-flow = from-tag ":" flowID target-flow = flowID */ SIP_Flow targetFlow = null; string flowInfo = (route != null && route.Parameters["flowInfo"] != null) ? route.Parameters["flowInfo"].Value : null; if (flowInfo != null && request.To.Tag != null) { string flow1Tag = flowInfo.Substring(0, flowInfo.IndexOf(':')); string flow1ID = flowInfo.Substring(flowInfo.IndexOf(':') + 1, flowInfo.IndexOf('/') - flowInfo.IndexOf(':') - 1); string flow2ID = flowInfo.Substring(flowInfo.IndexOf('/') + 1); if (flow1Tag == request.To.Tag) { targetFlow = m_pStack.TransportLayer.GetFlow(flow1ID); } else { ; targetFlow = m_pStack.TransportLayer.GetFlow(flow2ID); } } targetSet.Add(new SIP_ProxyTarget(requestUri, targetFlow)); } // Proxy is responsible for the domain in the Request-URI. else { // TODO: tel: //SIP_Uri requestUri = SIP_Uri.Parse(e.Request.Uri); // Try to get AOR from registrar. SIP_Registration registration = m_pRegistrar.GetRegistration(requestUri.Address); // We have AOR specified in request-URI in registrar server. if (registration != null) { // Add all AOR SIP contacts to target set. foreach (SIP_RegistrationBinding binding in registration.Bindings) { if (binding.ContactURI is SIP_Uri && binding.TTL > 0) { targetSet.Add(new SIP_ProxyTarget((SIP_Uri) binding.ContactURI, binding.Flow)); } } } // We don't have AOR specified in request-URI in registrar server. else { // If the Request-URI indicates a resource at this proxy that does not // exist, the proxy MUST return a 404 (Not Found) response. if (!OnAddressExists(requestUri.Address)) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x404_Not_Found, e.Request)); return; } } } // If the target set remains empty after applying all of the above, the proxy MUST return an error response, // which SHOULD be the 480 (Temporarily Unavailable) response. if (targetSet.Count == 0) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse(SIP_ResponseCodes.x480_Temporarily_Unavailable, e.Request)); return; } #endregion #region 4. Forward the request (Section 16.6) #region Statefull if (statefull) { // Create proxy context that will be responsible for forwarding request. SIP_ProxyContext proxyContext = new SIP_ProxyContext(this, e.ServerTransaction, request, addRecordRoute, m_ForkingMode, (ProxyMode & SIP_ProxyMode.B2BUA) != 0, false, false, targetSet.ToArray(), credentials.ToArray()); m_pProxyContexts.Add(proxyContext); proxyContext.Start(); } #endregion #region Stateless else { /* RFC 3261 16.6 Request Forwarding. For each target, the proxy forwards the request following these steps: 1. Make a copy of the received request 2. Update the Request-URI 3. Update the Max-Forwards header field 4. Optionally add a Record-route header field value 5. Optionally add additional header fields 6. Postprocess routing information 7. Determine the next-hop address, port, and transport 8. Add a Via header field value 9. Add a Content-Length header field if necessary 10. Forward the new request */ /* RFC 3261 16.11 Stateless Proxy. o A stateless proxy MUST choose one and only one target from the target set. This choice MUST only rely on fields in the message and time-invariant properties of the server. In particular, a retransmitted request MUST be forwarded to the same destination each time it is processed. Furthermore, CANCEL and non-Routed ACK requests MUST generate the same choice as their associated INVITE. However, a stateless proxy cannot simply use a random number generator to compute the first component of the branch ID, as described in Section 16.6 bullet 8. This is because retransmissions of a request need to have the same value, and a stateless proxy cannot tell a retransmission from the original request. We just use: "z9hG4bK-" + md5(topmost branch) */ bool isStrictRoute = false; SIP_Hop[] hops = null; #region 1. Make a copy of the received request SIP_Request forwardRequest = request.Copy(); #endregion #region 2. Update the Request-URI forwardRequest.RequestLine.Uri = targetSet[0].TargetUri; #endregion #region 3. Update the Max-Forwards header field forwardRequest.MaxForwards--; #endregion #region 4. Optionally add a Record-route header field value #endregion #region 5. Optionally add additional header fields #endregion #region 6. Postprocess routing information /* 6. Postprocess routing information. If the copy contains a Route header field, the proxy MUST inspect the URI in its first value. If that URI does not contain an lr parameter, the proxy MUST modify the copy as follows: - The proxy MUST place the Request-URI into the Route header field as the last value. - The proxy MUST then place the first Route header field value into the Request-URI and remove that value from the Route header field. */ if (forwardRequest.Route.GetAllValues().Length > 0 && !forwardRequest.Route.GetTopMostValue().Parameters.Contains("lr")) { forwardRequest.Route.Add(forwardRequest.RequestLine.Uri.ToString()); forwardRequest.RequestLine.Uri = SIP_Utils.UriToRequestUri(forwardRequest.Route.GetTopMostValue().Address.Uri); forwardRequest.Route.RemoveTopMostValue(); isStrictRoute = true; } #endregion #region 7. Determine the next-hop address, port, and transport /* 7. Determine the next-hop address, port, and transport. The proxy MAY have a local policy to send the request to a specific IP address, port, and transport, independent of the values of the Route and Request-URI. Such a policy MUST NOT be used if the proxy is not certain that the IP address, port, and transport correspond to a server that is a loose router. However, this mechanism for sending the request through a specific next hop is NOT RECOMMENDED; instead a Route header field should be used for that purpose as described above. In the absence of such an overriding mechanism, the proxy applies the procedures listed in [4] as follows to determine where to send the request. If the proxy has reformatted the request to send to a strict-routing element as described in step 6 above, the proxy MUST apply those procedures to the Request-URI of the request. Otherwise, the proxy MUST apply the procedures to the first value in the Route header field, if present, else the Request-URI. The procedures will produce an ordered set of (address, port, transport) tuples. Independently of which URI is being used as input to the procedures of [4], if the Request-URI specifies a SIPS resource, the proxy MUST follow the procedures of [4] as if the input URI were a SIPS URI. As described in [4], the proxy MUST attempt to deliver the message to the first tuple in that set, and proceed through the set in order until the delivery attempt succeeds. For each tuple attempted, the proxy MUST format the message as appropriate for the tuple and send the request using a new client transaction as detailed in steps 8 through 10. Since each attempt uses a new client transaction, it represents a new branch. Thus, the branch parameter provided with the Via header field inserted in step 8 MUST be different for each attempt. If the client transaction reports failure to send the request or a timeout from its state machine, the proxy continues to the next address in that ordered set. If the ordered set is exhausted, the request cannot be forwarded to this element in the target set. The proxy does not need to place anything in the response context, but otherwise acts as if this element of the target set returned a 408 (Request Timeout) final response. */ SIP_Uri uri = null; if (isStrictRoute) { uri = (SIP_Uri) forwardRequest.RequestLine.Uri; } else if (forwardRequest.Route.GetTopMostValue() != null) { uri = (SIP_Uri) forwardRequest.Route.GetTopMostValue().Address.Uri; } else { uri = (SIP_Uri) forwardRequest.RequestLine.Uri; } hops = m_pStack.GetHops(uri, forwardRequest.ToByteData().Length, ((SIP_Uri) forwardRequest.RequestLine.Uri).IsSecure); if (hops.Length == 0) { if (forwardRequest.RequestLine.Method != SIP_Methods.ACK) { e.ServerTransaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x503_Service_Unavailable + ": No hop(s) for target.", forwardRequest)); } return; } #endregion #region 8. Add a Via header field value forwardRequest.Via.AddToTop( "SIP/2.0/transport-tl-addign sentBy-tl-assign-it;branch=z9hG4bK-" + Core.ComputeMd5(request.Via.GetTopMostValue().Branch, true)); // Add 'flowID' what received request, you should use the same flow to send response back. // For more info see RFC 3261 18.2.2. forwardRequest.Via.GetTopMostValue().Parameters.Add("flowID", request.Flow.ID); #endregion #region 9. Add a Content-Length header field if necessary // Skip, our SIP_Message class is smart and do it when ever it's needed. #endregion #region 10. Forward the new request try { try { if (targetSet[0].Flow != null) { m_pStack.TransportLayer.SendRequest(targetSet[0].Flow, request); return; } } catch { m_pStack.TransportLayer.SendRequest(request, null, hops[0]); } } catch (SIP_TransportException x) { string dummy = x.Message; if (forwardRequest.RequestLine.Method != SIP_Methods.ACK) { /* RFC 3261 16.9 Handling Transport Errors If the transport layer notifies a proxy of an error when it tries to forward a request (see Section 18.4), the proxy MUST behave as if the forwarded request received a 503 (Service Unavailable) response. */ e.ServerTransaction.SendResponse( m_pStack.CreateResponse( SIP_ResponseCodes.x503_Service_Unavailable + ": Transport error.", forwardRequest)); } } #endregion } #endregion #endregion } /// <summary> /// Authenticates SIP request. This method also sends all needed replys to request sender. /// </summary> /// <param name="e">Request event arguments.</param> /// <returns>Returns true if request was authenticated.</returns> internal bool AuthenticateRequest(SIP_RequestReceivedEventArgs e) { string userName = null; return AuthenticateRequest(e, out userName); } /// <summary> /// Authenticates SIP request. This method also sends all needed replys to request sender. /// </summary> /// <param name="e">Request event arguments.</param> /// <param name="userName">If authentication sucessful, then authenticated user name is stored to this variable.</param> /// <returns>Returns true if request was authenticated.</returns> internal bool AuthenticateRequest(SIP_RequestReceivedEventArgs e, out string userName) { userName = null; SIP_t_Credentials credentials = SIP_Utils.GetCredentials(e.Request, m_pStack.Realm); // No credentials for our realm. if (credentials == null) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse(SIP_ResponseCodes.x407_Proxy_Authentication_Required, e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } Auth_HttpDigest auth = new Auth_HttpDigest(credentials.AuthData, e.Request.RequestLine.Method); // Check opaque validity. if (auth.Opaque != m_Opaque) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse( SIP_ResponseCodes.x407_Proxy_Authentication_Required + ": Opaque value won't match !", e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); // Send response e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } // Check nonce validity. if (!m_pStack.DigestNonceManager.NonceExists(auth.Nonce)) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse( SIP_ResponseCodes.x407_Proxy_Authentication_Required + ": Invalid nonce value !", e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); // Send response e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } // Valid nonce, consume it so that nonce can't be used any more. else { m_pStack.DigestNonceManager.RemoveNonce(auth.Nonce); } SIP_AuthenticateEventArgs eArgs = OnAuthenticate(auth); // Authenticate failed. if (!eArgs.Authenticated) { SIP_Response notAuthenticatedResponse = m_pStack.CreateResponse( SIP_ResponseCodes.x407_Proxy_Authentication_Required + ": Authentication failed.", e.Request); notAuthenticatedResponse.ProxyAuthenticate.Add( new Auth_HttpDigest(m_pStack.Realm, m_pStack.DigestNonceManager.CreateNonce(), m_Opaque). ToChallange()); // Send response e.ServerTransaction.SendResponse(notAuthenticatedResponse); return false; } userName = auth.UserName; return true; } /// <summary> /// Gets if this proxy server is responsible for specified route. /// </summary> /// <param name="uri">Route value to check.</param> /// <returns>Returns trues if server route, otherwise false.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>uri</b> is null reference.</exception> internal bool IsLocalRoute(SIP_Uri uri) { if (uri == null) { throw new ArgumentNullException("uri"); } // Not a route. if (uri.User != null) { return false; } // Consider any IP address as local route, because if server behind NAT we can't do IP check. if (Net_Utils.IsIPAddress(uri.Host)) { return true; } else { foreach (IPBindInfo bind in m_pStack.BindInfo) { if (uri.Host.ToLower() == bind.HostName.ToLower()) { return true; } } } return false; } // REMOVE ME: /* /// <summary> /// Creates new Contact header field for b2bua forward request. /// </summary> /// <param name="address">Address.</param> /// <returns>Returns new Contact value.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>address</b> is null.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> internal SIP_t_NameAddress CreateContactX(SIP_t_NameAddress address) { if(address == null){ throw new ArgumentNullException("address"); } if(address.IsSipOrSipsUri){ SIP_Uri uri = SIP_Uri.Parse(address.Uri.ToString()); uri.Host = m_pStack.TransportLayer.GetEndPoint(address.Uri); uri.Port = -1; SIP_t_NameAddress contact = new SIP_t_NameAddress(); contact.Uri = uri; return contact; } else{ throw new ArgumentException("Not SIP URI !"); } }*/ /// <summary> /// Raises 'IsLocalUri' event. /// </summary> /// <param name="uri">Request URI.</param> /// <returns>Returns true if server local URI, otherwise false.</returns> internal bool OnIsLocalUri(string uri) { if (IsLocalUri != null) { return IsLocalUri(uri); } return true; } /// <summary> /// Is called by SIP proxy or registrar server when it needs to authenticate user. /// </summary> /// <param name="auth">Authentication context.</param> /// <returns></returns> internal SIP_AuthenticateEventArgs OnAuthenticate(Auth_HttpDigest auth) { SIP_AuthenticateEventArgs eArgs = new SIP_AuthenticateEventArgs(auth); if (Authenticate != null) { Authenticate(eArgs); } return eArgs; } /// <summary> /// Is called by SIP proxy if it needs to check if specified address exists. /// </summary> /// <param name="address">SIP address to check.</param> /// <returns>Returns true if specified address exists, otherwise false.</returns> internal bool OnAddressExists(string address) { if (AddressExists != null) { return AddressExists(address); } return false; } #endregion /// <summary> /// Is called by SIP proxy when SIP proxy needs to get gateways for non-SIP URI. /// </summary> /// <param name="uriScheme">Non-SIP URI scheme which gateways to get.</param> /// <param name="userName">Authenticated user name.</param> /// <returns>Returns event data.</returns> protected SIP_GatewayEventArgs OnGetGateways(string uriScheme, string userName) { SIP_GatewayEventArgs e = new SIP_GatewayEventArgs(uriScheme, userName); if (GetGateways != null) { GetGateways(e); } return e; } } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Permissive License. // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. // All other rights reserved. using System; using System.CodeDom; using System.Collections; using System.Drawing; using System.Globalization; using System.Threading; using System.Windows.Automation; using System.Windows; namespace InternalHelper.Tests.Patterns { using InternalHelper; using InternalHelper.Tests; using InternalHelper.Enumerations; using Microsoft.Test.UIAutomation; using Microsoft.Test.UIAutomation.Core; using Microsoft.Test.UIAutomation.TestManager; using Microsoft.Test.UIAutomation.Interfaces; enum EventHappened { Yes, No, Undetermined } /// ----------------------------------------------------------------------- /// <summary></summary> /// ----------------------------------------------------------------------- public class WindowPatternWrapper : PatternObject { #region Variables WindowPattern m_pattern = null; #endregion #region constructor /// <summary></summary> protected WindowPatternWrapper(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands) : base(element, testSuite, priority, typeOfControl, typeOfPattern, dirResults, testEvents, commands) { m_pattern = (WindowPattern)GetPattern(m_le, m_useCurrent, WindowPattern.Pattern); } #endregion Constructor #region Properties internal WindowInteractionState pattern_getWindowInteractionState { get { if (m_useCurrent == true) return m_pattern.Current.WindowInteractionState; else return m_pattern.Cached.WindowInteractionState; } } internal WindowVisualState pattern_getVisualState { get { if (m_useCurrent == true) return m_pattern.Current.WindowVisualState; else return m_pattern.Cached.WindowVisualState; } } internal bool pattern_getCanMaximize { get { if (m_useCurrent == true) return m_pattern.Current.CanMaximize; else return m_pattern.Cached.CanMaximize; } } internal bool pattern_getCanMinimize { get { if (m_useCurrent) return m_pattern.Current.CanMinimize; else return m_pattern.Cached.CanMinimize; } } internal bool pattern_getIsModal { get { if (m_useCurrent) return m_pattern.Current.IsModal; else return m_pattern.Cached.IsModal; } } #endregion Properties #region Methods internal void pattern_SetWindowVisualState(WindowVisualState state, Type expectedException, CheckType checkType) { string call = "SetWindowVisualState(" + state + ")"; try { m_pattern.SetWindowVisualState(state); } catch (Exception actualException) { TestException(expectedException, actualException, call, checkType); return; } TestNoException(expectedException, call, checkType); } #endregion Methods } } namespace Microsoft.Test.UIAutomation.Tests.Patterns { using InternalHelper; using InternalHelper.Tests; using InternalHelper.Tests.Patterns; using InternalHelper.Enumerations; using Microsoft.Test.UIAutomation; using Microsoft.Test.UIAutomation.Core; using Microsoft.Test.UIAutomation.TestManager; using Microsoft.Test.UIAutomation.Interfaces; /// ----------------------------------------------------------------------- /// <summary></summary> /// ----------------------------------------------------------------------- public sealed class WindowTests : WindowPatternWrapper { #region Member variables const string THIS = "WindowTests"; /// <summary></summary> public const string TestSuite = NAMESPACE + "." + THIS; /// <summary>Defines which UIAutomation Pattern this tests</summary> public static readonly string TestWhichPattern = Automation.PatternName(WindowPattern.Pattern); #endregion /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- public WindowTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands) : base(element, TestSuite, priority, typeOfControl, TypeOfPattern.Window, dirResults, testEvents, commands) { } #region WindowPattern.SetWindowState // /// ------------------------------------------------------------------- // /// <summary> // /// Verifies that the interaction state is correct // /// </summary> // /// <param name="state"></param> // /// <param name="checkType"></param> // /// ------------------------------------------------------------------- // void TS_VerifyInteractionState (int state, CheckType checkType) // { // int good = (int)pattern_getWindowInteractionState & state; // if (!good.Equals(0)) // { // m_TestStep++; // } // else // { // ThrowMe ("InteractioState == " + pattern_getWindowInteractionState, checkType); // } // } #endregion WindowPattern.SetWindowState #region WindowPattern.MaximizableProperty ///<summary>TestCase: Window.MaximizableProperty.S.6.1</summary> [TestCaseAttribute("Window.MaximizableProperty.S.6.1", Priority = TestPriorities.Pri1, TestCaseType = TestCaseType.Generic | TestCaseType.Events, EventTested = "PropertyChangeEvents", Status = TestStatus.Works, Author = "Microsoft Corp.", Description = new string[]{ "Verify that Current.CanMaximize is true", "Verify that Current.CanMinimize is true", "Step: Setup WindowPattern.WindowVisualStateProperty property change event listener", "Step: Set WindowVisualState = WindowVisualState.Minimized", "Wait for WindowVisualState(Minimized) event", "Verify that Current.CanMaximize is true", "Set the WindowVisualState = WindowVisualState.Maximized", "Wait for WindowVisualState(Maximized) to fire", "Verify: WindowPattern.WindowVisualStateProperty property change event was fired", "Verify that the WindowVisualState = WindowVisualState.Maximized after setting the property" })] public void TestMaximizeS61(TestCaseAttribute testCase) { HeaderComment(testCase); AutomationProperty[] properties = new AutomationProperty [] { WindowPattern.WindowVisualStateProperty }; // "Verify that Current.CanMaximize is true", TSC_VerifyPropertyEqual(pattern_getCanMaximize, true, WindowPattern.CanMaximizeProperty, CheckType.IncorrectElementConfiguration); // "Verify that Current.CanMinimize is true", TSC_VerifyPropertyEqual(pattern_getCanMinimize, true, WindowPattern.CanMinimizeProperty, CheckType.IncorrectElementConfiguration); // "Step: Setup WindowPattern.WindowVisualStateProperty property change event listener", TSC_AddPropertyChangedListener(m_le, TreeScope.Element, properties, CheckType.Verification); // "Step: Set WindowVisualState = WindowVisualState.Minimized", TS_VerifySetVisualState(WindowVisualState.Minimized, null, CheckType.Verification); // "Wait for WindowVisualState(Minimized) event", TSC_WaitForEvents(1); RemoveAllEventsFired(); // "Verify that Current.CanMaximize is true", TSC_VerifyPropertyEqual(pattern_getCanMaximize, true, WindowPattern.CanMaximizeProperty, CheckType.IncorrectElementConfiguration); // "Set the WindowVisualState = WindowVisualState.Maximized", TS_VerifySetVisualState(WindowVisualState.Maximized, null, CheckType.Verification); // "Wait for WindowVisualState(Maximized) to fire", TSC_WaitForEvents(1); // "Verify: WindowPattern.WindowVisualStateProperty property change event was fired", TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { EventFired.True }, properties, CheckType.Verification); // "Verify that the WindowVisualState = WindowVisualState.Maximized after setting the property" TS_VerifyVisualState(WindowVisualState.Maximized, true, CheckType.Verification); } ///<summary>TestCase: Window.MaximizableProperty.S.6.2</summary> [TestCaseAttribute("Window.MaximizableProperty.S.6.2", Priority = TestPriorities.Pri1, TestCaseType = TestCaseType.Generic, Status = TestStatus.Works, Author = "Microsoft Corp.", Description = new string[]{ "Precondition: Maximizable property is false", "Verify that setting the VisualState property to WindowVisualState.Maximizable returns false", "Verify that the WindowVisualState is not WindowVisualState.Maximizable after setting the property" } )] public void TestMaximizeS62(TestCaseAttribute testCase) { HeaderComment(testCase); // "Precondition: Maximizable property is false", TSC_VerifyPropertyEqual(pattern_getCanMaximize, false, WindowPattern.CanMaximizeProperty, CheckType.IncorrectElementConfiguration); // "Verify that you can set the VisualState property to WindowVisualState.Maximizable", TS_VerifySetVisualState(WindowVisualState.Maximized, typeof(InvalidOperationException), CheckType.Verification); // "Verify that the WindowVisualState is WindowVisualState.Maximizable after setting the property" TS_VerifyVisualState(WindowVisualState.Maximized, false, CheckType.Verification); } #endregion WindowPattern.MaximizableProperty #region WindowPattern.MinimizableProperty ///<summary>TestCase: Window.MinimizableProperty.S.7.2</summary> [TestCaseAttribute("Window.MinimizableProperty.S.7.2", Priority = TestPriorities.Pri1, TestCaseType = TestCaseType.Generic, Status = TestStatus.Works, Author = "Microsoft Corp.", Description = new string[]{ "Precondition: Minimizable property is false", "Verify that you cannot set the VisualState property to WindowVisualState.Minimized and that SetVisualStats returns false", "Verify that the WindowVisualState is not WindowVisualState.MinimizableProperty after setting the VisualState property" } )] public void TestMinimizePropertyS72(TestCaseAttribute testCase) { HeaderComment(testCase); // "Precondition: Minimizable property is false",, TSC_VerifyPropertyEqual(pattern_getCanMinimize, false, WindowPattern.CanMinimizeProperty, CheckType.IncorrectElementConfiguration); // "Verify that you cannot set the VisualState property to WindowVisualState.Minimizable", TS_VerifySetVisualState(WindowVisualState.Minimized, typeof(InvalidOperationException), CheckType.Verification); // "Verify that the WindowVisualState is not WindowVisualState.Minimizable after setting the property" TS_VerifyVisualState(WindowVisualState.Minimized, false, CheckType.Verification); } #endregion WindowPattern.MinimizableProperty #region WindowPattern.ResizableProperty #endregion WindowPattern.ResizableProperty #region WindowPattern.ModalProperty ///<summary>TestCase: Window.ModalProperty.S.10.1</summary> [TestCaseAttribute("Window.ModalProperty.S.10.1", Priority = TestPriorities.Pri1, TestCaseType = TestCaseType.Generic, Status = TestStatus.Works, Author = "Microsoft Corp.", Description = new string[] { "Precondition: Modal property is true", })] public void TestWindowModalS101(TestCaseAttribute testCase) { HeaderComment(testCase); // Precondition: Resizable = false TSC_VerifyPropertyEqual(pattern_getIsModal, true, WindowPattern.IsModalProperty, CheckType.IncorrectElementConfiguration); } #endregion WindowPattern.ModalProperty #region Verification // /// ------------------------------------------------------------------- // void TS_Minimizable(bool ShouldBeMinimized, CheckType checkType) // { // if (!pattern_getCanMinimize.Equals(ShouldBeMinimized)) // ThrowMe("CanMinimize == " + pattern_getCanMinimize, checkType); // // m_TestStep++; // } /// ------------------------------------------------------------------- void TS_VerifyVisualState(WindowVisualState WindowVisualState, bool shouldBe, CheckType checkType) { if (!pattern_getVisualState.Equals(WindowVisualState).Equals(shouldBe)) ThrowMe(checkType, TestCaseCurrentStep + ": WindowVisualState = " + pattern_getVisualState); Comment("WindowVisualState = " + pattern_getWindowInteractionState); m_TestStep++; } /// ------------------------------------------------------------------- void TS_VerifySetVisualState(WindowVisualState WindowVisualState, Type expectedException, CheckType checkType) { pattern_SetWindowVisualState(WindowVisualState, expectedException, checkType); m_TestStep++; } #endregion Verification } }
using System; using System.Diagnostics; using System.Threading; using Raven.Abstractions.Data; using Raven.Abstractions.Exceptions; using Raven.Client; namespace Fluidity.Raven.Lock { /// <summary> /// The locker /// </summary> public sealed class Locker : ILocker { private const int TickMilliseconds = 50; private readonly IDocumentStore _documentStore; private readonly string _lockName; private Lock _lock; private Etag _lockEtag; private IDocumentSession _session; /// <summary> /// Initializes a new instance of the <see cref="Locker" /> class. /// </summary> /// <param name="documentStore">The documentStore.</param> /// <param name="lockName">Name of the lock.</param> /// <param name="timeout">The timeout.</param> /// <param name="lifetime">The lifetime.</param> public Locker(IDocumentStore documentStore, string lockName, TimeSpan timeout, TimeSpan lifetime) { _documentStore = documentStore; _lockName = lockName; _session = CreateSession(); WaitToLock(timeout, lifetime); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Estende o tempo de vido do lock, para garantir que a tarefa seja executada. /// </summary> /// <param name="lifetime">The lifetime.</param> /// <exception cref="System.NotImplementedException"></exception> public void Renew(TimeSpan lifetime) { _lock.Expiration = DateTime.UtcNow + lifetime; _session.Store(_lock, _lockEtag, _lock.Id); _session.SaveChanges(); _lockEtag = _session.Advanced.GetEtagFor(_lock); } /// <summary> /// Finalizes an instance of the <see cref="Locker" /> class. /// </summary> ~Locker() { Dispose(false); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only /// unmanaged resources. /// </param> private void Dispose(bool disposing) { if (_session != null && _lock != null) { try { _session.Delete(_lock); _session.SaveChanges(); } finally { _lock = null; } } if (_session != null) _session.Dispose(); if (disposing) _session = null; } /// <summary> /// Creates an isolated session. /// </summary> /// <returns></returns> private IDocumentSession CreateSession() { IDocumentSession session = _documentStore.OpenSession(); session.Advanced.UseOptimisticConcurrency = true; session.Advanced.MaxNumberOfRequestsPerSession = int.MaxValue; return session; } /// <summary> /// Waits to lock to be acquired. /// </summary> /// <param name="timeout">The timeout.</param> /// <param name="lifetime">The lifetime.</param> /// <exception cref="System.TimeoutException"></exception> private void WaitToLock(TimeSpan timeout, TimeSpan lifetime) { var stopWatch = new Stopwatch(); stopWatch.Start(); int attempt = 0; do { bool expired = stopWatch.Elapsed > timeout; if (expired) throw new TimeoutException(); if (TryAcquireLock(_lockName, lifetime, ++attempt)) break; Wait(); } while (true); } /// <summary> /// Try to acquire the lock. /// </summary> /// <remarks> /// If after to many attempts the lock is not acquired, it also checks if that lock is expired, so it could remove it. /// </remarks> /// <param name="lockName">Name of the lock.</param> /// <param name="lifetime">The lifetime.</param> /// <param name="attempt">The attempt.</param> /// <returns></returns> private bool TryAcquireLock(string lockName, TimeSpan lifetime, int attempt) { bool acquired = false; _lock = new Lock { Id = string.Format("Locks/{0}", lockName), Expiration = DateTime.UtcNow.Add(lifetime) }; try { _session.Store(_lock, Etag.Empty, _lock.Id); _session.SaveChanges(); _lockEtag = _session.Advanced.GetEtagFor(_lock); acquired = true; } catch (ConcurrencyException) { Trace.WriteLine("Session already locked for " + lockName); if (attempt%3 == 0) RemoveExpiredLock(_lock.Id); _lock = null; _session.Advanced.Clear(); } return acquired; } /// <summary> /// Removes the expired lock. /// </summary> /// <param name="lockId">The lock identifier.</param> private void RemoveExpiredLock(string lockId) { using (IDocumentSession session = _documentStore.OpenSession()) { var lockInstance = session.Load<Lock>(lockId); if (lockInstance != null && lockInstance.Expired) { session.Delete(lockInstance); session.SaveChanges(); } } } /// <summary> /// Waits for some time. /// </summary> private void Wait() { Thread.Sleep(TickMilliseconds); } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Security.Cryptography.X509Certificates; using log4net; using Novell.Directory.Ldap; using MindTouch.Dream; using MindTouch.Xml; namespace MindTouch.Deki.Services { public class LdapClient { //--- Fields --- private string _username; private string _password; private ILog _log; private int _timeLimit = 5000; private const int LDAP_PORT = 389; private const int LDAPS_PORT = 636; private LdapAuthenticationService.LdapConfig _config; //--- Constructors --- public LdapClient(LdapAuthenticationService.LdapConfig config, string username, string password, ILog logger) { _config = config; _log = logger; _username = username; _password = password; } //--- Methods --- private LdapConnection GetLdapConnectionFromBindingDN(string server, string bindingdn, string password) { LdapConnection conn = null; try { conn = new LdapConnection(); conn.SecureSocketLayer = _config.SSL; int port = _config.SSL ? LDAPS_PORT : LDAP_PORT; conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidateCert); string[] temp = server.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries); server = temp[0]; if(temp.Length > 1) { int.TryParse(temp[1], out port); } //if server has a port number specified, it's used instead. conn.Connect(server, port); if (!string.IsNullOrEmpty(bindingdn)) { conn.Bind(bindingdn, password); } } catch (Exception x) { UnBind(conn); _log.WarnExceptionMethodCall(x, "GetLdapConnection", string.Format("Failed to bind to LDAP server: '{0}' with bindingdn: '{1}'. Password provided? {2}. Exception: {3}", server, bindingdn, string.IsNullOrEmpty(password), x)); throw; } return conn; } /// <summary> /// Authenticates by creating a bind. /// Connection exceptions will be thrown but invalid credential will return false /// </summary> /// <returns></returns> public bool Authenticate() { bool ret = false; LdapConnection conn = null; LdapConnection queryConn = null; try { //When using the proxy bind, authentications requires a user lookup and another bind. if (!string.IsNullOrEmpty(_config.BindingPw)) { LdapSearchResults authUser = LookupLdapUser(false, _username, out queryConn); if (authUser.hasMore()) { LdapEntry entry = authUser.next(); conn = Bind(_config.LdapHostname, entry.DN, _password); } else { _log.WarnFormat("No users matched search creteria for username '{0}'", _username); ret = false; } } else { conn = Bind(); } if (conn != null) { ret = conn.Bound; } } catch (LdapException x) { ret = false; if (x.ResultCode != LdapException.INVALID_CREDENTIALS) { throw; } } finally { UnBind(queryConn); UnBind(conn); } return ret; } private LdapConnection Bind() { string hostname = _config.LdapHostname; string bindDN = string.Empty; string bindPW = string.Empty; //Determine if a query account is configured or not with BindingDN and BindingPW if (!string.IsNullOrEmpty(_config.BindingPw)) { bindDN = _config.BindingDn; bindPW = _config.BindingPw; } else { //No preconfigured account exists: need to establish a bind with provided credentials. bindDN = BuildBindDn(_username); bindPW = _password; } return Bind(hostname, bindDN, bindPW); } private LdapConnection Bind(string hostname, string bindDN, string bindPW) { LdapConnection conn = null; try { //Establish ldap bind conn = GetLdapConnectionFromBindingDN(hostname, bindDN, bindPW); if (!conn.Bound) { UnBind(conn); conn = null; //Sometimes it doesn't throw an exception but ramains unbound. throw new DreamAbortException(DreamMessage.AccessDenied("MindTouch Core LDAP Service", string.Format("An LDAP bind was not established. Server: '{0}'. BindingDN: '{1}'. Password provided? '{2}'", hostname, bindDN, string.IsNullOrEmpty(bindPW) ? "No." : "Yes."))); } } catch (LdapException x) { UnBind(conn); if (x.ResultCode == LdapException.INVALID_CREDENTIALS) { throw new DreamAbortException(DreamMessage.AccessDenied("MindTouch Core LDAP Service", string.Format("Invalid LDAP credentials. Server: '{0}'. BindingDN: '{1}'. Password provided? '{2}'", hostname, bindDN, string.IsNullOrEmpty(bindPW) ? "No." : "Yes."))); } else { throw; } } return conn; } private void UnBind(LdapConnection conn) { if (conn != null && conn.Connected) { try { conn.Disconnect(); } catch { } } } private LdapSearchResults LookupLdapUser(bool retrieveGroupMembership, string username, out LdapConnection conn) { conn = Bind(); username = EscapeLdapString(username); //search filter is built based on passed userQuery with username substitution string searchFilter = this.BuildUserSearchQuery(username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "sAMAccountName", "uid", "cn", "userAccountControl", "whenCreated", "name", "givenname", "sn", "telephonenumber", "mail", "description" }); if (retrieveGroupMembership) { attrs.Add(_config.GroupMembersAttribute); } if (!string.IsNullOrEmpty(_config.UserNameAttribute) && !attrs.Contains(_config.UserNameAttribute)) { attrs.Add(_config.UserNameAttribute); } //add more attributes to lookup if using a displayname-pattern string[] patternAttributes = RetrieveAttributesFromPattern(_config.DisplayNamePattern); if (patternAttributes != null) { foreach (string patternAttribute in patternAttributes) { if (!attrs.Contains(patternAttribute)) attrs.Add(patternAttribute); } } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); return results; } /// <summary> /// Authenticates by creating a bind and returning info about the user. /// This either returns a /users/user xml block or an exception xml if unable to connect or authenticate. /// In case of exception, invalid credentials is noted as /exception/message = "invalid credentials" /// </summary> /// <returns></returns> public XDoc AuthenticateXml() { return GetUserInfo(false, _username); } #region overloads for retrial handling public XDoc GetUserInfo(bool retrieveGroupMembership, uint retries, string username) { do { try { return GetUserInfo(retrieveGroupMembership, username); } catch (TimeoutException) { } } while (retries-- > 0); throw new TimeoutException(); } public XDoc GetGroupInfo(bool retrieveGroupMembers, uint retries, string optionalGroupName) { do { try { return GetGroupInfo(retrieveGroupMembers, optionalGroupName); } catch (TimeoutException) { } } while (retries-- > 0); throw new TimeoutException(); } #endregion /// <summary> /// Retrieve information about one or more users /// </summary> /// <param name="retrieveGroupMembership">retrieving list of groups for each user will take longer</param> /// <param name="username">Username to lookup</param> /// <returns></returns> public XDoc GetUserInfo(bool retrieveGroupMembership, string username) { XDoc resultXml = null; LdapConnection conn = null; try { LdapSearchResults results = LookupLdapUser(retrieveGroupMembership, username, out conn); if (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) throw new ArgumentNullException("nextEntry"); //Create xml from search entry resultXml = new XDoc("user"); string name = string.Empty; //If a usernameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.UserNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.UserNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } string displayName = BuildDisplayNameFromPattern(_config.DisplayNamePattern, nextEntry); resultXml.Attr("name", name); if (!string.IsNullOrEmpty(displayName)) resultXml.Attr("displayname", displayName); resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); resultXml.Start("firstname").Value(GetAttributeSafe(nextEntry, "givenname")).End(); resultXml.Start("lastname").Value(GetAttributeSafe(nextEntry, "sn")).End(); resultXml.Start("phonenumber").Value(GetAttributeSafe(nextEntry, "telephonenumber")).End(); resultXml.Start("email").Value(GetAttributeSafe(nextEntry, "mail")).End(); resultXml.Start("description").Value(GetAttributeSafe(nextEntry, "description")).End(); //Retrieve group memberships if (string.IsNullOrEmpty(_config.GroupMembershipQuery)) { LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = null; if (memberAttrSet != null) memberAttr = memberAttrSet.getAttribute(_config.GroupMembersAttribute); if (memberAttr != null) { resultXml.Start("groups"); foreach (string member in memberAttr.StringValueArray) { resultXml.Start("group"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } resultXml.End(); } } else { //Perform custom query to determine groups of a user PopulateGroupsForUserWithQuery(resultXml, username, conn); } } } finally { UnBind(conn); } return resultXml; } private void PopulateGroupsForUserWithQuery(XDoc doc, string username, LdapConnection conn) { doc.Start("groups"); string searchFilter = string.Format(Dream.PhpUtil.ConvertToFormatString(_config.GroupMembershipQuery), username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) throw new ArgumentNullException("nextEntry"); //Create xml from search entry doc.Start("group").Attr("name", GetNameFromDn(nextEntry.DN)).Start("ldap-dn").Value(nextEntry.DN).End().End(); } doc.End(); //groups } /// <summary> /// Retrieves group information from ldap /// </summary> /// <param name="retrieveGroupMembers">true to return users in each group. This may hurt performance</param> /// <param name="optionalGroupName">Group to lookup by name. Null for all groups</param> /// <returns></returns> public XDoc GetGroupInfo(bool retrieveGroupMembers, string optionalGroupName) { LdapConnection conn = null; XDoc resultXml = null; try { //Confirm a query bind has been established conn = Bind(); string searchFilter; //Build the searchfilter based on if a group name is given. if (!string.IsNullOrEmpty(optionalGroupName)) { optionalGroupName = EscapeLdapString(optionalGroupName); //Looking up group by name searchFilter = string.Format(PhpUtil.ConvertToFormatString(_config.GroupQuery), optionalGroupName); } else { //Looking up all groups searchFilter = _config.GroupQueryAll; } //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); if (retrieveGroupMembers) { attrs.Add("member"); } if (!string.IsNullOrEmpty(_config.GroupNameAttribute) && !attrs.Contains(_config.GroupNameAttribute)) { attrs.Add(_config.GroupNameAttribute); } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); //Create outer groups collection if multiple groups are being looked up or none provided if (string.IsNullOrEmpty(optionalGroupName)) resultXml = new XDoc("groups"); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); continue; } //Create xml from search entry if (resultXml == null) resultXml = new XDoc("group"); else resultXml.Start("group"); string name = string.Empty; //If a groupnameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.GroupNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.GroupNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } resultXml.Attr("name", name); resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); //Retrieve and write group membership to xml LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = memberAttrSet.getAttribute("member"); // TODO MaxM: This currently does not differentiate between user and group // members. if (memberAttr != null) { foreach (string member in memberAttr.StringValueArray) { resultXml.Start("member"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } } if (string.IsNullOrEmpty(optionalGroupName)) resultXml.End(); } } finally { UnBind(conn); } return resultXml; } #region Properties /// <summary> /// In milliseconds. Default = 5000 /// </summary> public int TimeLimit { get { return _timeLimit; } set { _timeLimit = value; } } public string UserName { get { return _username; } } #endregion public string BuildUserSearchQuery(string username) { return string.Format(Dream.PhpUtil.ConvertToFormatString(_config.UserQuery), username); } public string BuildBindDn(string username) { if (string.IsNullOrEmpty(username)) return null; return string.Format(PhpUtil.ConvertToFormatString(_config.BindingDn), username); } #region Helper methods private string GetNameFromDn(string dn) { string name; name = dn.Split(',')[0].Split('=')[1]; name = UnEscapeLdapString(name); return name; } private DateTime ldapStringToDate(string ldapDate) { if (string.IsNullOrEmpty(ldapDate)) return DateTime.MinValue; else { DateTime result; return DateTime.TryParseExact(ldapDate, "yyyyMMddHHmmss.0Z", System.Globalization.DateTimeFormatInfo.CurrentInfo, System.Globalization.DateTimeStyles.AssumeUniversal, out result) ? result : DateTime.MinValue; } } private string GetAttributeSafe(LdapEntry entry, string attributeName) { string ret = string.Empty; if (entry != null && !String.IsNullOrEmpty(attributeName)) { LdapAttribute attr = entry.getAttribute(attributeName); if (attr != null) ret = attr.StringValue; } return ret; } private static readonly Regex _displayNamePatternRegex = new Regex("{(?<attribute>[^}]*)}", RegexOptions.Compiled | RegexOptions.CultureInvariant); private string BuildDisplayNameFromPattern(string displayNamePattern, LdapEntry entry) { if (string.IsNullOrEmpty(displayNamePattern)) return string.Empty; string displayName = displayNamePattern; string[] attributes = RetrieveAttributesFromPattern(displayNamePattern); if (attributes != null) { foreach (string attribute in attributes) { displayName = displayName.Replace("{" + attribute + "}", GetAttributeSafe(entry, attribute)); } } return displayName; } private string[] RetrieveAttributesFromPattern(string displayNamePattern) { if (string.IsNullOrEmpty(displayNamePattern)) return null; List<string> attributes = null; try { MatchCollection mc = _displayNamePatternRegex.Matches(displayNamePattern); attributes = new List<string>(); foreach (Match m in mc) { attributes.Add(m.Groups["attribute"].Value); } } catch (Exception x) { _log.Warn(string.Format("Could not parse the displayname-pattern '{0}'", displayNamePattern), x); attributes = null; } if (attributes == null) return null; else return attributes.ToArray(); } private void HandleLdapException(LdapException x) { switch (x.ResultCode) { case LdapException.Ldap_TIMEOUT: throw new TimeoutException("Ldap lookup timed out", x); case LdapException.OPERATIONS_ERROR: case LdapException.INVALID_DN_SYNTAX: if (x.ResultCode == 1 && x.LdapErrorMessage.Contains("DSID-0C090627")) throw new DreamAbortException(DreamMessage.Forbidden(string.Format("Account '{0}' is disabled", this._username))); throw new ArgumentException(string.Format("The search base '{0}' may have invalid format (Example: 'DC=sales,DC=acme,DC=com') or the account used for binding may be disabled. Error returned from LDAP: {1}", _config.LdapSearchBase, x.LdapErrorMessage), x); default: throw x; } } private string UnEscapeLdapString(string original) { if (string.IsNullOrEmpty(original)) return original; return original.Replace("\\", ""); } private string EscapeLdapString(string original) { //Per http://www.ietf.org/rfc/rfc2253.txt section 2.4 if (string.IsNullOrEmpty(original)) return original; StringBuilder sb = new StringBuilder(); foreach (char c in original) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == ' ')) { sb.Append(c); } else { sb.Append(@"\" + Convert.ToString((int) c, 16)); } } return sb.ToString(); } #endregion private bool ValidateCert(X509Certificate certificate, int[] certificateErrors) { if (certificateErrors.Length == 0) { return true; } string errors = string.Join(",", Array.ConvertAll<int, string>(certificateErrors, new Converter<int, string>(delegate(int value) { return value.ToString(); }))); _log.WarnFormat("Got error# {0} from LDAPS certificate: {1}", errors, certificate.ToString(true)); return _config.SSLIgnoreCertErrors; } } public class AccountDisabledException : Exception { public AccountDisabledException() { } } }
using System.IO; using System.Net; using System.Text; using System.Web; using Newtonsoft.Json.Linq; namespace LoveSeat.Support { /// <summary> /// Repersent a web request for CouchDB database. /// </summary> public class CouchRequest { private const string INVALID_USERNAME_OR_PASSWORD = "reason=Name or password is incorrect"; private const string NOT_AUTHORIZED = "reason=You are not authorized to access this db."; private const int STREAM_BUFFER_SIZE = 4096; private readonly HttpWebRequest request; public CouchRequest(string uri) : this(uri, new Cookie(), null) { } /// <summary> /// Request with Cookie authentication /// </summary> /// <param name="uri"></param> /// <param name="authCookie"></param> /// <param name="eTag"></param> public CouchRequest(string uri, Cookie authCookie, string eTag) { request = (HttpWebRequest)WebRequest.Create(uri); request.Headers.Clear(); //important if (!string.IsNullOrEmpty(eTag)) request.Headers.Add("If-None-Match", eTag); request.Headers.Add("Accept-Charset", "utf-8"); request.Headers.Add("Accept-Language", "en-us"); request.Accept = "application/json"; request.Referer = uri; request.ContentType = "application/json"; request.KeepAlive = true; if (authCookie != null) request.Headers.Add("Cookie", "AuthSession=" + authCookie.Value); request.Timeout = 10000; } /// <summary> /// Basic Authorization Header /// </summary> /// <param name="uri"></param> /// <param name="username"></param> /// <param name="password"></param> public CouchRequest(string uri, string username, string password) { request = (HttpWebRequest)WebRequest.Create(uri); request.Headers.Clear(); //important // Deal with Authorization Header if (username != null) { string authValue = "Basic "; string userNAndPassword = username + ":" + password; // Base64 encode string b64 = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(userNAndPassword)); authValue = authValue + b64; request.Headers.Add("Authorization", authValue); } request.Headers.Add("Accept-Charset", "utf-8"); request.Headers.Add("Accept-Language", "en-us"); request.ContentType = "application/json"; request.KeepAlive = true; request.Timeout = 10000; } public CouchRequest Put() { request.Method = "PUT"; return this; } public CouchRequest Get() { request.Method = "GET"; return this; } public CouchRequest Post() { request.Method = "POST"; return this; } public CouchRequest Delete() { request.Method = "DELETE"; return this; } public CouchRequest Data(Stream data) { using (var body = request.GetRequestStream()) { var buffer = new byte[STREAM_BUFFER_SIZE]; var bytesRead = 0; while (0 != (bytesRead = data.Read(buffer, 0, buffer.Length))) { body.Write(buffer, 0, bytesRead); } } return this; } public CouchRequest Data(string data) { using (var body = request.GetRequestStream()) { var encodedData = Encoding.UTF8.GetBytes(data); body.Write(encodedData, 0, encodedData.Length); } return this; } public CouchRequest Data(byte[] attachment) { using (var body = request.GetRequestStream()) { body.Write(attachment, 0, attachment.Length); } return this; } public CouchRequest Data(JObject obj) { return Data(obj.ToString()); } public CouchRequest ContentType(string contentType) { request.ContentType = contentType; return this; } public CouchRequest Form() { request.ContentType = "application/x-www-form-urlencoded"; return this; } public CouchRequest Json() { request.ContentType = "application/json"; return this; } public CouchRequest Timeout(int timeoutMs) { request.Timeout = timeoutMs; return this; } public HttpWebRequest GetRequest() { return request; } /// <summary> /// Get the response from CouchDB. /// </summary> /// <returns></returns> public CouchResponse GetCouchResponse() { bool failedAuth = false; try { using (var response = (HttpWebResponse)request.GetResponse()) { string msg = ""; if (isAuthenticateOrAuthorized(response, ref msg) == false) { failedAuth = true; throw new WebException(msg); } if (response.StatusCode == HttpStatusCode.BadRequest) { throw new CouchException(request, response, response.GetResponseString() + "\n" + request.RequestUri); } return new CouchResponse(response); } } catch (WebException webEx) { if (failedAuth == true) { throw; } var response = (HttpWebResponse)webEx.Response; if (response == null) throw new HttpException("Request failed to receive a response", webEx); return new CouchResponse(response); } throw new HttpException("Request failed to receive a response"); } public HttpWebResponse GetHttpResponse() { bool failedAuth = false; try { var response = (HttpWebResponse)request.GetResponse(); string msg = ""; if (isAuthenticateOrAuthorized(response, ref msg) == false) { failedAuth = true; throw new WebException(msg, new System.Exception(msg)); } return response; } catch (WebException webEx) { if (failedAuth == true) { throw; } var response = (HttpWebResponse)webEx.Response; if (response == null) throw new HttpException("Request failed to receive a response", webEx); return response; } throw new HttpException("Request failed to receive a response"); } /// <summary> /// Checks response if username and password was valid /// </summary> /// <param name="response"></param> private bool isAuthenticateOrAuthorized(HttpWebResponse response, ref string message) { //"reason=Name or password is incorrect" // Check if query string is okay string[] split = response.ResponseUri.Query.Split('&'); if (split.Length > 0) { for (int i = 0; i < split.Length; i++) { string temp = System.Web.HttpUtility.UrlDecode(split[i]); if (temp.Contains(INVALID_USERNAME_OR_PASSWORD) == true) { message = "Invalid username or password"; return false; } else if (temp.Contains(NOT_AUTHORIZED) == true) { message = "Not Authorized to access database"; return false; } } } return true; }// end private void checkResponse(... } }
namespace Pathfinding { using UnityEngine; public struct AstarWorkItem { /** Init function. * May be null if no initialization is needed. * Will be called once, right before the first call to #update. */ public System.Action init; /** Init function. * May be null if no initialization is needed. * Will be called once, right before the first call to #update. * * A context object is sent as a parameter. This can be used * to for example queue a flood fill that will be executed either * when a work item calls EnsureValidFloodFill or all work items have * been completed. If multiple work items are updating nodes * so that they need a flood fill afterwards, using the QueueFloodFill * method is preferred since then only a single flood fill needs * to be performed for all of the work items instead of one * per work item. */ public System.Action<IWorkItemContext> initWithContext; /** Update function, called once per frame when the work item executes. * Takes a param \a force. If that is true, the work item should try to complete the whole item in one go instead * of spreading it out over multiple frames. * \returns True when the work item is completed. */ public System.Func<bool, bool> update; /** Update function, called once per frame when the work item executes. * Takes a param \a force. If that is true, the work item should try to complete the whole item in one go instead * of spreading it out over multiple frames. * \returns True when the work item is completed. * * A context object is sent as a parameter. This can be used * to for example queue a flood fill that will be executed either * when a work item calls EnsureValidFloodFill or all work items have * been completed. If multiple work items are updating nodes * so that they need a flood fill afterwards, using the QueueFloodFill * method is preferred since then only a single flood fill needs * to be performed for all of the work items instead of one * per work item. */ public System.Func<IWorkItemContext, bool, bool> updateWithContext; public AstarWorkItem (System.Func<bool, bool> update) { this.init = null; this.initWithContext = null; this.updateWithContext = null; this.update = update; } public AstarWorkItem (System.Func<IWorkItemContext, bool, bool> update) { this.init = null; this.initWithContext = null; this.updateWithContext = update; this.update = null; } public AstarWorkItem (System.Action init, System.Func<bool, bool> update = null) { this.init = init; this.initWithContext = null; this.update = update; this.updateWithContext = null; } public AstarWorkItem (System.Action<IWorkItemContext> init, System.Func<IWorkItemContext, bool, bool> update = null) { this.init = null; this.initWithContext = init; this.update = null; this.updateWithContext = update; } } /** Interface to expose a subset of the WorkItemProcessor functionality */ public interface IWorkItemContext { /** Call during work items to queue a flood fill. * An instant flood fill can be done via FloodFill() * but this method can be used to batch several updates into one * to increase performance. * WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill * to ensure that a flood fill is done if any earlier work items queued one. * * Once a flood fill is queued it will be done after all WorkItems have been executed. */ void QueueFloodFill (); /** If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills */ void EnsureValidFloodFill (); } class WorkItemProcessor : IWorkItemContext { /** Used to prevent waiting for work items to complete inside other work items as that will cause the program to hang */ bool workItemsInProgressRightNow = false; readonly AstarPath astar; readonly IndexedQueue<AstarWorkItem> workItems = new IndexedQueue<AstarWorkItem>(); /** True if any work items have queued a flood fill. * \see QueueWorkItemFloodFill */ bool queuedWorkItemFloodFill = false; /** * True while a batch of work items are being processed. * Set to true when a work item is started to be processed, reset to false when all work items are complete. * * Work item updates are often spread out over several frames, this flag will be true during the whole time the * updates are in progress. */ public bool workItemsInProgress { get; private set; } /** Similar to Queue<T> but allows random access */ class IndexedQueue<T> { T[] buffer = new T[4]; int start; int length; public T this[int index] { get { if (index < 0 || index >= length) throw new System.IndexOutOfRangeException(); return buffer[(start + index) % buffer.Length]; } set { if (index < 0 || index >= length) throw new System.IndexOutOfRangeException(); buffer[(start + index) % buffer.Length] = value; } } public int Count { get { return length; } } public void Enqueue (T item) { if (length == buffer.Length) { var newBuffer = new T[buffer.Length*2]; for (int i = 0; i < length; i++) { newBuffer[i] = this[i]; } buffer = newBuffer; start = 0; } buffer[(start + length) % buffer.Length] = item; length++; } public T Dequeue () { if (length == 0) throw new System.InvalidOperationException(); var item = buffer[start]; start = (start + 1) % buffer.Length; length--; return item; } } /** Call during work items to queue a flood fill. * An instant flood fill can be done via FloodFill() * but this method can be used to batch several updates into one * to increase performance. * WorkItems which require a valid Flood Fill in their execution can call EnsureValidFloodFill * to ensure that a flood fill is done if any earlier work items queued one. * * Once a flood fill is queued it will be done after all WorkItems have been executed. */ void IWorkItemContext.QueueFloodFill () { queuedWorkItemFloodFill = true; } /** If a WorkItem needs to have a valid flood fill during execution, call this method to ensure there are no pending flood fills */ public void EnsureValidFloodFill () { if (queuedWorkItemFloodFill) { astar.FloodFill(); } } public WorkItemProcessor (AstarPath astar) { this.astar = astar; } public void OnFloodFill () { queuedWorkItemFloodFill = false; } /** Add a work item to be processed when pathfinding is paused. * * \see ProcessWorkItems */ public void AddWorkItem (AstarWorkItem itm) { workItems.Enqueue(itm); } /** Process graph updating work items. * Process all queued work items, e.g graph updates and the likes. * * \returns * - false if there are still items to be processed. * - true if the last work items was processed and pathfinding threads are ready to be resumed. * * \see AddWorkItem * \see threadSafeUpdateState * \see Update */ public bool ProcessWorkItems (bool force) { if (workItemsInProgressRightNow) throw new System.Exception("Processing work items recursively. Please do not wait for other work items to be completed inside work items. " + "If you think this is not caused by any of your scripts, this might be a bug."); workItemsInProgressRightNow = true; while (workItems.Count > 0) { // Working on a new batch if (!workItemsInProgress) { workItemsInProgress = true; queuedWorkItemFloodFill = false; } // Peek at first item in the queue AstarWorkItem itm = workItems[0]; // Call init the first time the item is seen if (itm.init != null) { itm.init(); itm.init = null; } if (itm.initWithContext != null) { itm.initWithContext(this); itm.initWithContext = null; } // Make sure the item in the queue is up to date workItems[0] = itm; bool status; try { if (itm.update != null) { status = itm.update(force); } else if (itm.updateWithContext != null) { status = itm.updateWithContext(this, force); } else { status = true; } } catch { workItems.Dequeue(); workItemsInProgressRightNow = false; throw; } if (!status) { if (force) { Debug.LogError("Misbehaving WorkItem. 'force'=true but the work item did not complete.\nIf force=true is passed to a WorkItem it should always return true."); } // Still work items to process workItemsInProgressRightNow = false; return false; } else { workItems.Dequeue(); } } EnsureValidFloodFill(); workItemsInProgressRightNow = false; workItemsInProgress = false; return true; } } }
//----------------------------------------------------------------------- // <copyright file="ArgumentProcessorTests.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using Microsoft.VisualStudio.TestTools.UnitTesting; using SonarQube.Plugins.Roslyn.CommandLine; using System.IO; using SonarQube.Plugins.Test.Common; namespace SonarQube.Plugins.Roslyn.PluginGeneratorTests { [TestClass] public class ArgumentProcessorTests { public TestContext TestContext { get; set; } #region Tests [TestMethod] public void ArgProc_EmptyArgs() { // Arrange TestLogger logger = new TestLogger(); string[] rawArgs = { }; // Act ProcessedArgs actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); // Assert AssertArgumentsNotProcessed(actualArgs, logger); } [TestMethod] public void ArgProc_AnalyzerRef_Invalid() { // 0. Setup TestLogger logger; string[] rawArgs; ProcessedArgs actualArgs; // 1. No value logger = new TestLogger(); rawArgs = new string [] { "/analyzer:" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); // 2. Id and missing version logger = new TestLogger(); rawArgs = new string[] { "/analyzer:testing.id.missing.version:" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); // 3. Id and invalid version logger = new TestLogger(); rawArgs = new string[] { "/analyzer:testing.id.invalid.version:1.0.-invalid.version.1" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); // 4. Missing id logger = new TestLogger(); rawArgs = new string[] { "/analyzer::2.1.0" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); } [TestMethod] public void ArgProc_AnalyzerRef_Valid() { // 0. Setup TestLogger logger; string[] rawArgs; ProcessedArgs actualArgs; // 1. Id but no version logger = new TestLogger(); rawArgs = new string[] { "/a:testing.id.no.version" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsProcessed(actualArgs, logger, "testing.id.no.version", null, null, false); // 2. Id and version logger = new TestLogger(); rawArgs = new string[] { "/analyzer:testing.id.with.version:1.0.0-rc1" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsProcessed(actualArgs, logger, "testing.id.with.version", "1.0.0-rc1", null, false); // 3. Id containing a colon, with version logger = new TestLogger(); rawArgs = new string[] { "/analyzer:id.with:colon:2.1.0" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsProcessed(actualArgs, logger, "id.with:colon", "2.1.0", null, false); } [TestMethod] public void ArgProc_SqaleFile() { // 0. Setup TestLogger logger; string[] rawArgs; ProcessedArgs actualArgs; // 1. No sqale file value -> valid logger = new TestLogger(); rawArgs = new string[] { "/a:validId" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsProcessed(actualArgs, logger, "validId", null, null, false); // 2. Missing sqale file logger = new TestLogger(); rawArgs = new string[] { "/sqale:missingFile.txt", "/a:validId" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); logger.AssertSingleErrorExists("missingFile.txt"); // should be an error containing the missing file name // 3. Existing sqale file string testDir = TestUtils.CreateTestDirectory(this.TestContext); string filePath = TestUtils.CreateTextFile("valid.sqale.txt", testDir, "sqale file contents"); logger = new TestLogger(); rawArgs = new string[] { "/sqale:" + filePath, "/a:valid:1.0" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsProcessed(actualArgs, logger, "valid", "1.0", filePath, false); } [TestMethod] public void ArgProc_AcceptLicenses_Valid() { // 0. Setup TestLogger logger; string[] rawArgs; ProcessedArgs actualArgs; // 1. Correct argument -> valid and accept is true logger = new TestLogger(); rawArgs = new string[] { "/a:validId", "/acceptLicenses" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsProcessed(actualArgs, logger, "validId", null, null, true); } [TestMethod] public void ArgProc_AcceptLicensesInvalid() { // 0. Setup TestLogger logger; string[] rawArgs; ProcessedArgs actualArgs; // 1. Correct text, wrong case -> invalid logger = new TestLogger(); rawArgs = new string[] { "/a:validId", "/ACCEPTLICENSES" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); // 2. Unrecognised argument -> invalid logger = new TestLogger(); rawArgs = new string[] { "/a:validId", "/acceptLicenses=true" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); // 3. Unrecognised argument -> invalid logger = new TestLogger(); rawArgs = new string[] { "/a:validId", "/acceptLicensesXXX" }; actualArgs = ArgumentProcessor.TryProcessArguments(rawArgs, logger); AssertArgumentsNotProcessed(actualArgs, logger); } #endregion #region Checks private static void AssertArgumentsNotProcessed(ProcessedArgs actualArgs, TestLogger logger) { Assert.IsNull(actualArgs, "Not expecting the arguments to have been processed successfully"); logger.AssertErrorsLogged(); } private static void AssertArgumentsProcessed(ProcessedArgs actualArgs, TestLogger logger, string expectedId, string expectedVersion, string expectedSqale, bool expectedAcceptLicenses) { Assert.IsNotNull(actualArgs, "Expecting the arguments to have been processed successfully"); Assert.AreEqual(actualArgs.PackageId, expectedId, "Unexpected package id returned"); if (expectedVersion == null) { Assert.IsNull(actualArgs.PackageVersion, "Expecting the version to be null"); } else { Assert.IsNotNull(actualArgs.PackageVersion, "Not expecting the version to be null"); Assert.AreEqual(expectedVersion, actualArgs.PackageVersion.ToString()); } Assert.AreEqual(expectedSqale, actualArgs.SqaleFilePath, "Unexpected sqale file path"); if (expectedSqale != null) { Assert.IsTrue(File.Exists(expectedSqale), "Specified sqale file should exist: {0}", expectedSqale); } Assert.AreEqual(expectedAcceptLicenses, actualArgs.AcceptLicenses, "Unexpected value for AcceptLicenses"); logger.AssertErrorsLogged(0); } #endregion } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections.Generic; using System.Threading; using Sce.Atf.Adaptation; using Sce.Atf.Dom; using Sce.Sled.Lua.Dom; using Sce.Sled.Lua.Resources; using Sce.Sled.Shared.Document; using Sce.Sled.Shared.Utilities; using Sce.Sled.SyntaxEditor; namespace Sce.Sled.Lua { public static class SledLuaUtil { static SledLuaUtil() { // Generate hashes for SyntaxEditor tokens foreach (var token in s_syntaxEditorTokenStrings) s_syntaxEditorTokenHashes.Add(token.GetHashCode(), token); } /// <summary> /// Path in the assembly to the Lua specific icons /// </summary> public const string LuaIconPath = "Sce.Sled.Lua.Resources.Icons"; /// <summary> /// Path in the assembly to the Lua XML schema /// </summary> public const string LuaSchemaPath = "Sce.Sled.Lua.Schemas.SledLuaProjectFiles.xsd"; public static ISledLuaVarBaseType GetRootLevelVar(ISledLuaVarBaseType luaVar) { // Lineage starts with the current node and heads // toward the root (instead of starting with root // and heading toward current node) var lineage = new List<DomNode>(luaVar.DomNode.Lineage); // Return the 2nd to last item (if any) return lineage.Count <= 1 ? luaVar : lineage[lineage.Count - 2].As<ISledLuaVarBaseType>(); } /// <summary> /// Convert a Lua type string (like LUA_TNIL) to /// its corresponding Lua type integer value /// </summary> /// <param name="szLuaType"></param> /// <returns></returns> public static int LuaTypeStringToInt(string szLuaType) { int iRetval; switch (szLuaType) { case "LUA_TNIL": iRetval = (int)LuaType.LUA_TNIL; break; case "LUA_TBOOLEAN": iRetval = (int)LuaType.LUA_TBOOLEAN; break; case "LUA_TLIGHTUSERDATA": iRetval = (int)LuaType.LUA_TLIGHTUSERDATA; break; case "LUA_TNUMBER": iRetval = (int)LuaType.LUA_TNUMBER; break; case "LUA_TSTRING": iRetval = (int)LuaType.LUA_TSTRING; break; case "LUA_TTABLE": iRetval = (int)LuaType.LUA_TTABLE; break; case "LUA_TFUNCTION": iRetval = (int)LuaType.LUA_TFUNCTION; break; case "LUA_TUSERDATA": iRetval = (int)LuaType.LUA_TUSERDATA; break; case "LUA_TTHREAD": iRetval = (int)LuaType.LUA_TTHREAD; break; default: throw new ArgumentOutOfRangeException("szLuaType"); } return iRetval; } /// <summary> /// Convert string to LuaType /// (like "LUA_TNIL" to LuaType.LUA_TNIL) /// </summary> /// <param name="szLuaType"></param> /// <returns></returns> public static LuaType StringToLuaType(string szLuaType) { var lRetval = LuaType.LUA_TNONE; switch (szLuaType) { case "LUA_TNIL": lRetval = LuaType.LUA_TNIL; break; case "LUA_TBOOLEAN": lRetval = LuaType.LUA_TBOOLEAN; break; case "LUA_TLIGHTUSERDATA": lRetval = LuaType.LUA_TLIGHTUSERDATA; break; case "LUA_TNUMBER": lRetval = LuaType.LUA_TNUMBER; break; case "LUA_TSTRING": lRetval = LuaType.LUA_TSTRING; break; case "LUA_TTABLE": lRetval = LuaType.LUA_TTABLE; break; case "LUA_TFUNCTION": lRetval = LuaType.LUA_TFUNCTION; break; case "LUA_TUSERDATA": lRetval = LuaType.LUA_TUSERDATA; break; case "LUA_TTHREAD": lRetval = LuaType.LUA_TTHREAD; break; } return lRetval; } /// <summary> /// Convert LUA_T&lt;type&gt; integer to its string value /// (like -1 to "LUA_TNONE") /// </summary> /// <param name="iLuaType"></param> /// <returns></returns> public static string LuaTypeIntToString(int iLuaType) { return s_luaTypeStrings[iLuaType + 1]; } /// <summary> /// Convert LUA_T&lt;type&gt; LuaType to its string value /// (like LuaType.LUA_TNIL to "LUA_TNIL") /// </summary> /// <param name="luaType"></param> /// <returns></returns> public static string LuaTypeToString(LuaType luaType) { return LuaTypeIntToString((int)luaType); } /// <summary> /// Convert LUA_T&lt;type&gt; int to LuaType /// (like -1 to LuaType.LUA_TNONE) /// </summary> /// <param name="iLuaType"></param> /// <returns></returns> public static LuaType IntToLuaType(int iLuaType) { return (LuaType)iLuaType; } /// <summary> /// Convert LuaType to int /// (like LuaType.LUA_TNONE to -1) /// </summary> /// <param name="luaType"></param> /// <returns></returns> public static int LuaTypeToInt(LuaType luaType) { return (int)luaType; } private readonly static string[] s_luaTypeStrings = { Resource.LUA_TNONE, Resource.LUA_TNIL, Resource.LUA_TBOOLEAN, Resource.LUA_TLIGHTUSERDATA, Resource.LUA_TNUMBER, Resource.LUA_TSTRING, Resource.LUA_TTABLE, Resource.LUA_TFUNCTION, Resource.LUA_TUSERDATA, Resource.LUA_TTHREAD }; public static bool IsEditableLuaType(ISledLuaVarBaseType luaVar) { return IsEditableLuaType(luaVar.LuaType) && IsEditableLuaType((LuaType)luaVar.KeyType); } public static string GetFullHoverOvenToken(SledDocumentHoverOverTokenArgs args) { var bUseCache = (s_cachedArgs == args) && !string.IsNullOrEmpty(s_cachedFullToken); // Get full token string if (!bUseCache) s_cachedFullToken = FindAndConcatTokens(args); // Store for next run s_cachedArgs = args; return s_cachedFullToken; } private static bool IsEditableLuaType(LuaType type) { return (type == LuaType.LUA_TSTRING) || (type == LuaType.LUA_TBOOLEAN) || (type == LuaType.LUA_TNUMBER); } private static string FindAndConcatTokens(SledDocumentHoverOverTokenArgs args) { // Get full token string var szFullToken = FindAndConcatTokens(args.Args.Token, args.Document.Editor.GetTokens(args.Args.LineNumber)); if (string.IsNullOrEmpty(szFullToken)) return null; // Replace quotations szFullToken = szFullToken.Replace("\"", string.Empty); return szFullToken; } private static string s_cachedFullToken; private static SledDocumentHoverOverTokenArgs s_cachedArgs; private static string FindAndConcatTokens(Token hoverToken, Token[] lineTokens) { string szFullToken = null; // Check if the token the mouse is hovering over is valid or not if (IsInvalidToken(hoverToken)) return null; // Ignore whitespace the mouse is on if (hoverToken.TokenType == "WhitespaceToken") return null; var iIndex = -1; // Find the actual token the mouse is hovering over on the line for (var i = 0; (i < lineTokens.Length) && (iIndex == -1); i++) { if ((lineTokens[i].StartOffset == hoverToken.StartOffset) && (lineTokens[i].EndOffset == hoverToken.EndOffset)) iIndex = i; } // Concatenate together valid tokens if (iIndex != -1) { szFullToken = lineTokens[iIndex].Lexeme; //OutDevice.OutLine(MessageType.Info, "- [Index: " + iIndex.ToString() + "] of [Total: " + lineTokens.Length + "] [" + lineTokens[iIndex].Lexeme + "] [" + lineTokens[iIndex].TokenType + "]"); var bStop = false; for (var i = iIndex + 1; (i < lineTokens.Length) && !bStop; i++) { if (!IsInvalidToken(lineTokens[i])) szFullToken = szFullToken + lineTokens[i].Lexeme; else bStop = true; } bStop = false; for (var i = iIndex - 1; (i >= 0) && !bStop; i--) { if (!IsInvalidToken(lineTokens[i])) szFullToken = lineTokens[i].Lexeme + szFullToken; else bStop = true; } // Remove spaces szFullToken = szFullToken.Trim(); // Convert [ to . szFullToken = szFullToken.Replace('[', '.'); // Remove ] szFullToken = szFullToken.Replace("]", String.Empty); } return szFullToken; } /// <summary> /// Returns true or false if the token is valid or not (ie. it can /// be part of a Lua variable) /// <remarks>This isn't 100% accurate but returns a good enough /// result since the returned concatenated result still has to /// be looked up as a valid variable anyways.</remarks> /// </summary> /// <param name="token"></param> /// <returns></returns> private static bool IsInvalidToken(Token token) { var iHashCode = token.TokenType.GetHashCode(); // Special case for PunctuationToken if (iHashCode == -1613044712) { if (token.Lexeme != ".") return true; } return s_syntaxEditorTokenHashes.ContainsKey(iHashCode); } /// <summary> /// Holds hash codes for SyntaxEditor tokens /// </summary> private static readonly SortedList<int, string> s_syntaxEditorTokenHashes = new SortedList<int, string>(); /* Hash codes for tokens 1077052185 : LineTerminatorToken -561050543 : OpenParenthesisToken 1991237168 : CloseParenthesisToken 667020772 : OpenCurlyBraceToken 1139962090 : CloseCurlyBraceToken -1975386304 : ReservedWordToken -2076233560 : FunctionToken 1154245194 : OperatorToken 537949335 : RealNumberToken -1613044712 : PunctuationToken -1136125023 : SingleQuoteStringDefaultToken 1537402127 : SingleQuoteStringEscapedCharacterToken 1069267250 : SingleQuoteStringWhitespaceToken 1678979394 : SingleQuoteStringWordToken -63739884 : DoubleQuoteStringEscapedCharacterToken 1522906717 : LongBracketStringDefaultToken 615317892 : LongBracketStringStartToken -734326990 : LongBracketStringEndToken 201584444 : LongBracketStringWhitespaceToken -264903966 : LongBracketStringWordToken -1416924211 : CommentDefaultToken -1119709654 : CommentStartToken -674770501 : CommentStringEndToken -1611404732 : MultiLineCommentDefaultToken -1364531305 : MultiLineCommentStartToken -267688178 : MultiLineCommentEndToken -83712800 : MultiLineCommentWhitespaceToken 10191556 : MultiLineCommentLineTerminatorToken -1385349543 : MultiLineCommentWordToken */ /// <summary> /// List of all SyntaxEditor tokens SLED cares about /// </summary> private static readonly string[] s_syntaxEditorTokenStrings = { "LineTerminatorToken", "OpenParenthesisToken", "CloseParenthesisToken", "OpenCurlyBraceToken", "CloseCurlyBraceToken", "ReservedWordToken", "FunctionToken", "OperatorToken", "RealNumberToken", "PunctuationToken", "SingleQuoteStringDefaultToken", "SingleQuoteStringEscapedCharacterToken", "SingleQuoteStringWhitespaceToken", "SingleQuoteStringWordToken", "DoubleQuoteStringEscapedCharacterToken", "LongBracketStringDefaultToken", "LongBracketStringStartToken", "LongBracketStringEndToken", "LongBracketStringWhitespaceToken", "LongBracketStringWordToken", "CommentDefaultToken", "CommentStartToken", "CommentStringEndToken", "MultiLineCommentDefaultToken", "MultiLineCommentStartToken", "MultiLineCommentEndToken", "MultiLineCommentWhitespaceToken", "MultiLineCommentLineTerminatorToken", "MultiLineCommentWordToken" }; } static class SledLuaIcon { public const string ResourcePath = "Sled.Lua.Icons."; public const string Compile = ResourcePath + "Compile"; } class ProducerConsumerQueue : IDisposable { static ProducerConsumerQueue() { WorkerCount = Environment.ProcessorCount; } public ProducerConsumerQueue(int workerCount, SledUtil.BoolWrapper shouldCancel) { m_workers = new Thread[workerCount]; m_cancel = shouldCancel; for (var i = 0; i < workerCount; i++) { m_workers[i] = new Thread(ThreadRun) { Name = string.Format("SLED - PCQueue Thread:{0}", i), IsBackground = true, CurrentCulture = Thread.CurrentThread.CurrentCulture, CurrentUICulture = Thread.CurrentThread.CurrentUICulture }; m_workers[i].SetApartmentState(ApartmentState.STA); m_workers[i].Start(); } } #region Implementation of IDisposable public void Dispose() { // Signal for thread run funcs to quit foreach (var worker in m_workers) Enqueue(null); foreach (var worker in m_workers) worker.Join(); } #endregion public void EnqueueWorkItems(IEnumerable<IWork> items) { foreach (var item in items) { if (m_cancel.Value) return; Enqueue(item.WorkCallback); } } public interface IWork { void WorkCallback(); } public static int WorkerCount { get; private set; } #region Member Methods private void Enqueue(ThreadStart item) { lock (m_lock) { m_queue.Enqueue(item); Monitor.Pulse(m_lock); } } private void ThreadRun() { while (!m_cancel.Value) { ThreadStart item; lock (m_lock) { while (m_queue.Count == 0) Monitor.Wait(m_lock); item = m_queue.Dequeue(); } if (item == null) return; if (m_cancel.Value) return; item(); } } #endregion private volatile object m_lock = new object(); private readonly Thread[] m_workers; private readonly SledUtil.BoolWrapper m_cancel; private readonly Queue<ThreadStart> m_queue = new Queue<ThreadStart>(); } }
//------------------------------------------------------------------------------ // Symbooglix // // // Copyright 2014-2017 Daniel Liew // // This file is licensed under the MIT license. // See LICENSE.txt for details. //------------------------------------------------------------------------------ using Microsoft.Boogie; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using Symbooglix; namespace SymbooglixLibTests { [TestFixture(), Ignore("FIXME: Need way to easily get symbolics for a particular variable")] public class StateScheduling : SymbooglixTest { private void SimpleLoop(IStateScheduler scheduler) { p = LoadProgramFrom("programs/SimpleLoop.bpl"); e = GetExecutor(p, scheduler, GetSolver(), /*useConstantFolding=*/ true); var main = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First(); var boundsVar = main.InParams[0]; var entryBlock = main.Blocks[0]; Assert.AreEqual("entry", entryBlock.Label); var loopHead = main.Blocks[1]; Assert.AreEqual("loopHead", loopHead.Label); var loopBody = main.Blocks[2]; Assert.AreEqual("loopBody", loopBody.Label); var loopBodyAssume = loopBody.Cmds[0] as AssumeCmd; Assert.IsNotNull(loopBodyAssume); var loopExit = main.Blocks[3]; Assert.AreEqual("loopDone", loopExit.Label); var loopExitAssume = loopExit.Cmds[0] as AssumeCmd; Assert.IsNotNull(loopExitAssume); var exitBlock = main.Blocks[4]; Assert.AreEqual("exit", exitBlock.Label); var tc = new TerminationCounter(); tc.Connect(e); int change = 1; int contextChangeCount = 0; e.ContextChanged += delegate(object sender, Executor.ContextChangeEventArgs eventArgs) { ++contextChangeCount; // FIXME: //var symbolicForBound = eventArgs.Previous.Symbolics.Where( s => s.Origin.IsVariable && s.Origin.AsVariable == boundsVar).First(); SymbolicVariable symbolicForBound = null; // Just so we can compile if (change ==1) { // FIXME: The Executor shouldn't pop the last stack frame so we can check where we terminated successfully Assert.IsTrue(eventArgs.Previous.TerminationType.ExitLocation.IsTransferCmd); Assert.IsTrue(eventArgs.Previous.TerminationType.ExitLocation.AsTransferCmd is ReturnCmd); Assert.IsTrue(eventArgs.Previous.Finished()); Assert.AreEqual(3, eventArgs.Previous.Constraints.Count); var exitConstraint = eventArgs.Previous.Constraints.Constraints.Where( c => c.Origin.IsCmd && c.Origin.AsCmd == loopExitAssume); Assert.AreEqual(1, exitConstraint.Count()); Assert.AreEqual( symbolicForBound.Name + " <= 0", exitConstraint.First().Condition.ToString()); Assert.AreSame(loopBody, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Next.Constraints.Count); var bodyConstraint = eventArgs.Next.Constraints.Constraints.Where( c => c.Origin.IsCmd && c.Origin.AsCmd == loopBodyAssume); Assert.AreEqual(1, bodyConstraint.Count()); Assert.AreEqual("0 < " + symbolicForBound.Name, bodyConstraint.First().Condition.ToString()); } else if (change == 2) { Assert.IsTrue(eventArgs.Previous.Finished()); Assert.AreSame(loopBody, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(4, eventArgs.Previous.Constraints.Count); var exitConstraint = eventArgs.Previous.Constraints.Constraints.Where( c => c.Origin.IsCmd && c.Origin.AsCmd == loopExitAssume); Assert.AreEqual(1, exitConstraint.Count()); Assert.AreEqual( symbolicForBound.Name + " <= 1", exitConstraint.First().Condition.ToString()); Assert.AreSame(loopBody, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(3, eventArgs.Next.Constraints.Count); var bodyConstraints = eventArgs.Next.Constraints.Constraints.Where( c => c.Origin.IsCmd && c.Origin.AsCmd == loopBodyAssume).ToList(); Assert.AreEqual(2, bodyConstraints.Count()); Assert.AreEqual("0 < " + symbolicForBound.Name, bodyConstraints[0].Condition.ToString()); Assert.AreEqual("1 < " + symbolicForBound.Name, bodyConstraints[1].Condition.ToString()); } ++change; }; e.Run(main); Assert.AreEqual(3, tc.NumberOfTerminatedStates); Assert.AreEqual(3, tc.Sucesses); Assert.AreEqual(2, contextChangeCount); } [Test()] public void ExploreAllStatesDFS() { SimpleLoop(new DFSStateScheduler()); } [Test()] public void ExploreAllStatesUntilTerminationBFS() { SimpleLoop(new UntilTerminationBFSStateScheduler()); } [Test()] public void ExploreAllStatesBFS() { // TODO: SimpleLoop() assumes DFS can't use it //SimpleLoop(new BFSStateScheduler()); } private void ExploreOrderInit(IStateScheduler scheduler, out Implementation main, out Block entryBlock, out List<Block> l) { p = LoadProgramFrom("programs/StateScheduleTest.bpl"); e = GetExecutor(p, scheduler, GetSolver()); main = p.TopLevelDeclarations.OfType<Implementation>().Where(i => i.Name == "main").First(); entryBlock = main.Blocks[0]; Assert.AreEqual("entry", entryBlock.Label); // Collect "l<N>" blocks l = new List<Block>(); for (int index = 0; index <= 5; ++index) { l.Add(main.Blocks[index + 1]); Assert.AreEqual("l" + index, l[index].Label); } } [Test()] public void ExploreOrderDFS() { List<Block> l; Block entryBlock; Implementation main; ExploreOrderInit(new DFSStateScheduler(), out main, out entryBlock, out l); int changed = 0; e.ContextChanged += delegate(object sender, Executor.ContextChangeEventArgs eventArgs) { switch(changed) { case 0: Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[2],eventArgs.Previous.Mem.Stack[0].CurrentBlock); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[3],eventArgs.Next.GetCurrentBlock()); break; case 1: Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[3],eventArgs.Previous.Mem.Stack[0].CurrentBlock); /* FIXME: At a three way branch we schedule l0, l2, l1 rather than * l0, l1, l2. i.e. we aren't going left to right over the GotoCmd targets. * This is because the DFSScheduler executes the last added state first so it executes the ExecutionState * going to l2 before the state going to l1. * * I'm not sure this is desirable. */ Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[2],eventArgs.Next.GetCurrentBlock()); break; case 2: Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[2],eventArgs.Previous.GetCurrentBlock()); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[1],eventArgs.Next.GetCurrentBlock()); break; case 3: Assert.IsTrue(eventArgs.Previous.TerminationType is TerminatedWithoutError); Assert.AreSame(l[4],eventArgs.Previous.Mem.Stack[0].CurrentBlock); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[5],eventArgs.Next.GetCurrentBlock()); break; default: Assert.Fail("Too many context changes"); break; } ++changed; }; e.Run(main); Assert.AreEqual(4, changed); } [Test()] public void ExploreOrderUntilEndBFS() { List<Block> l; Block entryBlock; Implementation main; ExploreOrderInit(new UntilTerminationBFSStateScheduler(), out main, out entryBlock, out l); // Is this actually correct? int changed = 0; e.ContextChanged += delegate(object sender, Executor.ContextChangeEventArgs eventArgs) { switch(changed) { case 0: Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[2],eventArgs.Previous.Mem.Stack[0].CurrentBlock); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[1],eventArgs.Next.GetCurrentBlock()); break; case 1: Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[4],eventArgs.Previous.Mem.Stack[0].CurrentBlock); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[2],eventArgs.Next.GetCurrentBlock()); break; case 2: Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[2],eventArgs.Previous.GetCurrentBlock()); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[3],eventArgs.Next.GetCurrentBlock()); break; case 3: Assert.IsTrue(eventArgs.Previous.TerminationType is TerminatedWithoutError); Assert.AreSame(l[3],eventArgs.Previous.Mem.Stack[0].CurrentBlock); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[5],eventArgs.Next.GetCurrentBlock()); break; default: Assert.Fail("Too many context changes"); break; } ++changed; }; e.Run(main); Assert.AreEqual(4, changed); } [Test()] public void ExploreOrderBFS() { List<Block> l; Block entryBlock; Implementation main; ExploreOrderInit(new BFSStateScheduler(), out main, out entryBlock, out l); int changed = 0; int previousStateId = 0; e.ContextChanged += delegate(object sender, Executor.ContextChangeEventArgs eventArgs) { switch(changed) { case 0: Assert.IsFalse(eventArgs.Previous.Finished()); Assert.AreSame(l[0],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(1, eventArgs.Previous.ExplicitBranchDepth); /* Depth 0 explored */ Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[1],eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(1, eventArgs.Next.ExplicitBranchDepth); previousStateId = eventArgs.Next.Id; break; case 1: Assert.AreEqual(previousStateId, eventArgs.Previous.Id); Assert.IsFalse(eventArgs.Previous.Finished()); Assert.AreSame(l[4],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Previous.ExplicitBranchDepth); // Changing context because have gone deeper Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[2],eventArgs.Next.GetCurrentBlock()); previousStateId = eventArgs.Next.Id; break; case 2: Assert.AreEqual(previousStateId, eventArgs.Previous.Id); Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[2],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(1, eventArgs.Previous.ExplicitBranchDepth); Assert.IsFalse(eventArgs.Next.Finished()); // Now resuming execution of initial state Assert.AreSame(l[0],eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(1, eventArgs.Next.ExplicitBranchDepth); previousStateId = eventArgs.Next.Id; break; case 3: Assert.AreEqual(previousStateId, eventArgs.Previous.Id); Assert.IsFalse(eventArgs.Previous.Finished()); // Original state has made it to block l2 Assert.AreSame(l[2],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Previous.ExplicitBranchDepth); // Changing context because have gone deeper /* Depth 1 explored ? */ Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[5],eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Next.ExplicitBranchDepth); previousStateId = eventArgs.Next.Id; break; case 4: Assert.AreEqual(previousStateId, eventArgs.Previous.Id); Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[5],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Previous.ExplicitBranchDepth); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[4], eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Next.ExplicitBranchDepth); previousStateId = eventArgs.Next.Id; break; case 5: Assert.AreEqual(previousStateId, eventArgs.Previous.Id); Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[4],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Previous.ExplicitBranchDepth); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[3], eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Next.ExplicitBranchDepth); previousStateId = eventArgs.Next.Id; break; case 6: Assert.AreEqual(previousStateId, eventArgs.Previous.Id); Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(l[3],eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Previous.ExplicitBranchDepth); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(l[2], eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(2, eventArgs.Next.ExplicitBranchDepth); break; default: Assert.Fail("Too many context changes"); break; } ++changed; }; var tc = new TerminationCounter(); tc.Connect(e); e.Run(main); Assert.AreEqual(7, changed); Assert.AreEqual(5, tc.Sucesses); Assert.AreEqual(5, tc.NumberOfTerminatedStates); } [Test()] public void DepthBoundDFS() { var scheduler = new LimitExplicitDepthScheduler(new DFSStateScheduler(), 2); p = LoadProgramFrom("programs/SimpleLoop.bpl"); e = GetExecutor(p, scheduler, GetSolver()); var tc = new TerminationCounter(); tc.Connect(e); e.Run(GetMain(p)); Assert.AreEqual(3, tc.NumberOfTerminatedStates); Assert.AreEqual(2, tc.Sucesses); Assert.AreEqual(1, tc.DisallowedPathDepths); } [Test()] public void DepthBoundBFS() { var scheduler = new LimitExplicitDepthScheduler(new BFSStateScheduler(), 2); p = LoadProgramFrom("programs/SimpleLoop.bpl"); e = GetExecutor(p, scheduler, GetSolver()); var tc = new TerminationCounter(); tc.Connect(e); e.Run(GetMain(p)); Assert.AreEqual(3, tc.NumberOfTerminatedStates); Assert.AreEqual(2, tc.Sucesses); Assert.AreEqual(1, tc.DisallowedPathDepths); } [Test()] public void ExploreOrderLoopEscapingScheduler() { var scheduler = new LoopEscapingScheduler(new DFSStateScheduler()); p = LoadProgramFrom("programs/TestLoopEscaping.bpl"); // Get the blocks we need to refer to var main = GetMain(p); var loopBodyBlock = main.Blocks.Where(b => b.Label == "anon2_LoopBody").First(); var loopDoneBlock = main.Blocks.Where(b => b.Label == "anon2_LoopDone").First(); e = GetExecutor(p, scheduler, GetSolver(), /*useConstantFolding=*/ true); var tc = new TerminationCounter(); tc.Connect(e); int changed = 0; e.ContextChanged += delegate(object sender, Executor.ContextChangeEventArgs eventArgs) { switch (changed) { case 0: Assert.AreSame(loopBodyBlock, eventArgs.Previous.GetCurrentBlock()); Assert.IsFalse(eventArgs.Previous.Finished()); Assert.AreSame(loopDoneBlock, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(0, GetLoopCounter(eventArgs.Next)); Assert.IsFalse(eventArgs.Next.Finished()); break; case 1: Assert.AreSame(loopDoneBlock, eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(0, GetLoopCounter(eventArgs.Previous)); Assert.IsTrue(eventArgs.Previous.Finished()); Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); Assert.AreSame(loopBodyBlock, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(0, GetLoopCounter(eventArgs.Next)); Assert.IsFalse(eventArgs.Next.Finished()); break; case 2: Assert.AreSame(loopBodyBlock, eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(1, GetLoopCounter(eventArgs.Next)); Assert.IsFalse(eventArgs.Next.Finished()); Assert.AreSame(loopDoneBlock, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(1, GetLoopCounter(eventArgs.Next)); Assert.IsFalse(eventArgs.Next.Finished()); break; case 3: Assert.AreSame(loopDoneBlock, eventArgs.Previous.GetCurrentBlock()); Assert.AreEqual(1, GetLoopCounter(eventArgs.Previous)); Assert.IsTrue(eventArgs.Previous.Finished()); Assert.IsInstanceOf<TerminatedWithoutError>(eventArgs.Previous.TerminationType); // About to execute last possible execution of loop body Assert.AreSame(loopBodyBlock, eventArgs.Next.GetCurrentBlock()); Assert.AreEqual(1, GetLoopCounter(eventArgs.Next)); Assert.IsFalse(eventArgs.Next.Finished()); break; default: Assert.Fail("Too many context changes"); break; } ++changed; }; e.Run(main); Assert.AreEqual(3, tc.NumberOfTerminatedStates); Assert.AreEqual(3, tc.Sucesses); Assert.AreEqual(4, changed); } private int GetLoopCounter(ExecutionState state) { var pair = state.GetInScopeVariableAndExprByName("counter"); Assert.IsInstanceOf<LiteralExpr>(pair.Value); var value = pair.Value as LiteralExpr; Assert.IsTrue(value.isBigNum); return value.asBigNum.ToIntSafe; } } }
// 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.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class MinTests : EnumerableBasedTests { [Fact] public void EmptyInt32Source() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().AsQueryable().Min()); } [Fact] public void NullInt32Source() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Min()); } [Fact] public void Int32MinimumRepeated() { int[] source = { 6, 0, 9, 0, 10, 0 }; Assert.Equal(0, source.AsQueryable().Min()); } [Fact] public void EmptyInt64Source() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().AsQueryable().Min()); } [Fact] public void NullInt64Source() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Min()); } [Fact] public void Int64MinimumRepeated() { long[] source = { 6, -5, 9, -5, 10, -5 }; Assert.Equal(-5, source.AsQueryable().Min()); } [Fact] public void NullSingleSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Min()); } [Fact] public void EmptySingle() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().AsQueryable().Min()); } [Fact] public void SingleMinimumRepeated() { float[] source = { -5.5f, float.NegativeInfinity, 9.9f, float.NegativeInfinity }; Assert.True(float.IsNegativeInfinity(source.AsQueryable().Min())); } [Fact] public void EmptyDoubleSource() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().AsQueryable().Min()); } [Fact] public void NullDoubleSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Min()); } [Fact] public void DoubleMinimumRepeated() { double[] source = { -5.5, Double.NegativeInfinity, 9.9, Double.NegativeInfinity }; Assert.True(double.IsNegativeInfinity(source.AsQueryable().Min())); } [Fact] public void EmptyDecimalSource() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().AsQueryable().Min()); } [Fact] public void NullDecimalSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Min()); } [Fact] public void DecimalMinimumRepeated() { decimal[] source = { -5.5m, 0m, 9.9m, -5.5m, 5m }; Assert.Equal(-5.5m, source.AsQueryable().Min()); } [Fact] public void EmptyNullableInt32Source() { Assert.Null(Enumerable.Empty<int?>().AsQueryable().Min()); } [Fact] public void NullableInt32MinimumRepeated() { int?[] source = { 6, null, null, 0, 9, 0, 10, 0 }; Assert.Equal(0, source.AsQueryable().Min()); } [Fact] public void EmptyNullableInt64Source() { Assert.Null(Enumerable.Empty<long?>().AsQueryable().Min()); } [Fact] public void NullNullableInt64Source() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Min()); } [Fact] public void NullableInt64MinimumRepeated() { long?[] source = { 6, null, null, 0, 9, 0, 10, 0 }; Assert.Equal(0, source.AsQueryable().Min()); } [Fact] public void EmptyNullableSingleSource() { Assert.Null(Enumerable.Empty<float?>().AsQueryable().Min()); } [Fact] public void NullableSingleMinimumRepated() { float?[] source = { 6.4f, null, null, -0.5f, 9.4f, -0.5f, 10.9f, -0.5f }; Assert.Equal(-0.5f, source.AsQueryable().Min()); } [Fact] public void EmptyNullableDoubleSource() { Assert.Null(Enumerable.Empty<double?>().AsQueryable().Min()); } [Fact] public void NullNullableDoubleSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Min()); } [Fact] public void NullableDoubleMinimumRepeated() { double?[] source = { 6.4, null, null, -0.5, 9.4, -0.5, 10.9, -0.5 }; Assert.Equal(-0.5, source.AsQueryable().Min()); } [Fact] public void NullableDoubleNaNThenNulls() { double?[] source = { double.NaN, null, null, null }; Assert.True(double.IsNaN(source.Min().Value)); } [Fact] public void NullableDoubleNullsThenNaN() { double?[] source = { null, null, null, double.NaN }; Assert.True(double.IsNaN(source.Min().Value)); } [Fact] public void EmptyNullableDecimalSource() { Assert.Null(Enumerable.Empty<decimal?>().AsQueryable().Min()); } [Fact] public void NullNullableDecimalSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Min()); } [Fact] public void NullableDecimalMinimumRepeated() { decimal?[] source = { 6.4m, null, null, decimal.MinValue, 9.4m, decimal.MinValue, 10.9m, decimal.MinValue }; Assert.Equal(decimal.MinValue, source.AsQueryable().Min()); } [Fact] public void EmptyDateTimeSource() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().AsQueryable().Min()); } [Fact] public void NullNullableDateTimeSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime>)null).Min()); } [Fact] public void EmptyStringSource() { Assert.Null(Enumerable.Empty<string>().AsQueryable().Min()); } [Fact] public void NullStringSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<string>)null).Min()); } [Fact] public void StringMinimumRepeated() { string[] source = { "ooo", "www", "www", "ooo", "ooo", "ppp" }; Assert.Equal("ooo", source.AsQueryable().Min()); } [Fact] public void MinInt32WithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=10 }, new { name="John", num=-105 }, new { name="Bob", num=-30 } }; Assert.Equal(-105, source.AsQueryable().Min(e => e.num)); } [Fact] public void EmptyInt32WithSelector() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<int>().AsQueryable().Min(x => x)); } [Fact] public void NullInt32SourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int>)null).Min(i => i)); } [Fact] public void Int32SourceWithNullSelector() { Expression<Func<int, int>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int>().AsQueryable().Min(selector)); } [Fact] public void MinInt64WithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=10L }, new { name="John", num=long.MinValue }, new { name="Bob", num=-10L } }; Assert.Equal(long.MinValue, source.AsQueryable().Min(e => e.num)); } [Fact] public void EmptyInt64WithSelector() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<long>().AsQueryable().Min(x => x)); } [Fact] public void NullInt64SourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long>)null).Min(i => i)); } [Fact] public void Int64SourceWithNullSelector() { Expression<Func<long, long>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long>().AsQueryable().Min(selector)); } [Fact] public void EmptySingleWithSelector() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<float>().AsQueryable().Min(x => x)); } [Fact] public void NullSingleSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float>)null).Min(i => i)); } [Fact] public void MinSingleWithSelectorAccessingProperty() { var source = new []{ new { name="Tim", num=-45.5f }, new { name="John", num=-132.5f }, new { name="Bob", num=20.45f } }; Assert.Equal(-132.5f, source.AsQueryable().Min(e => e.num)); } [Fact] public void MinDoubleWithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=-45.5 }, new { name="John", num=-132.5 }, new { name="Bob", num=20.45 } }; Assert.Equal(-132.5, source.AsQueryable().Min(e => e.num)); } [Fact] public void EmptyDoubleWithSelector() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<double>().AsQueryable().Min(x => x)); } [Fact] public void NullDoubleSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double>)null).Min(i => i)); } [Fact] public void DoubleSourceWithNullSelector() { Expression<Func<double, double>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double>().AsQueryable().Min(selector)); } [Fact] public void MinDecimalWithSelectorAccessingProperty() { var source = new[]{ new {name="Tim", num=100.45m}, new {name="John", num=10.5m}, new {name="Bob", num=0.05m} }; Assert.Equal(0.05m, source.AsQueryable().Min(e => e.num)); } [Fact] public void EmptyDecimalWithSelector() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<decimal>().AsQueryable().Min(x => x)); } [Fact] public void NullDecimalSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal>)null).Min(i => i)); } [Fact] public void DecimalSourceWithNullSelector() { Expression<Func<decimal, decimal>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal>().AsQueryable().Min(selector)); } [Fact] public void MinNullableInt32WithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=(int?)10 }, new { name="John", num=default(int?) }, new { name="Bob", num=(int?)-30 } }; Assert.Equal(-30, source.AsQueryable().Min(e => e.num)); } [Fact] public void NullNullableInt32SourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<int?>)null).Min(i => i)); } [Fact] public void NullableInt32SourceWithNullSelector() { Expression<Func<int?, int?>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<int?>().AsQueryable().Min(selector)); } [Fact] public void MinNullableInt64WithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=default(long?) }, new { name="John", num=(long?)long.MinValue }, new { name="Bob", num=(long?)-10L } }; Assert.Equal(long.MinValue, source.AsQueryable().Min(e => e.num)); } [Fact] public void NullNullableInt64SourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<long?>)null).Min(i => i)); } [Fact] public void NullableInt64SourceWithNullSelector() { Expression<Func<long?, long?>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<long?>().AsQueryable().Min(selector)); } [Fact] public void MinNullableSingleWithSelectorAccessingProperty() { var source = new[]{ new {name="Tim", num=(float?)-45.5f}, new {name="John", num=(float?)-132.5f}, new {name="Bob", num=default(float?)} }; Assert.Equal(-132.5f, source.AsQueryable().Min(e => e.num)); } [Fact] public void NullNullableSingleSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<float?>)null).Min(i => i)); } [Fact] public void NullableSingleSourceWithNullSelector() { Expression<Func<float?, float?>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<float?>().AsQueryable().Min(selector)); } [Fact] public void MinNullableDoubleWithSelectorAccessingProperty() { var source = new[] { new { name="Tim", num=(double?)-45.5 }, new { name="John", num=(double?)-132.5 }, new { name="Bob", num=default(double?) } }; Assert.Equal(-132.5, source.AsQueryable().Min(e => e.num)); } [Fact] public void NullNullableDoubleSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<double?>)null).Min(i => i)); } [Fact] public void NullableDoubleSourceWithNullSelector() { Expression<Func<double?, double?>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<double?>().AsQueryable().Min(selector)); } [Fact] public void MinNullableDecimalWithSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=(decimal?)100.45m }, new { name="John", num=(decimal?)10.5m }, new { name="Bob", num=default(decimal?) } }; Assert.Equal(10.5m, source.AsQueryable().Min(e => e.num)); } [Fact] public void NullNullableDecimalSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<decimal?>)null).Min(i => i)); } [Fact] public void NullableDecimalSourceWithNullSelector() { Expression<Func<decimal?, decimal?>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<decimal?>().AsQueryable().Min(selector)); } [Fact] public void EmptyDateTimeWithSelector() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<DateTime>().AsQueryable().Min(x => x)); } [Fact] public void NullDateTimeSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<DateTime>)null).Min(i => i)); } [Fact] public void DateTimeSourceWithNullSelector() { Expression<Func<DateTime, DateTime>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<DateTime>().AsQueryable().Min(selector)); } [Fact] public void MinStringWitSelectorAccessingProperty() { var source = new[]{ new { name="Tim", num=100.45m }, new { name="John", num=10.5m }, new { name="Bob", num=0.05m } }; Assert.Equal("Bob", source.AsQueryable().Min(e => e.name)); } [Fact] public void NullStringSourceWithSelector() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IQueryable<string>)null).Min(i => i)); } [Fact] public void StringSourceWithNullSelector() { Expression<Func<string, string>> selector = null; AssertExtensions.Throws<ArgumentNullException>("selector", () => Enumerable.Empty<string>().AsQueryable().Min(selector)); } [Fact] public void EmptyBooleanSource() { Assert.Throws<InvalidOperationException>(() => Enumerable.Empty<bool>().AsQueryable().Min()); } [Fact] public void Min1() { var val = (new int[] { 0, 2, 1 }).AsQueryable().Min(); Assert.Equal(0, val); } [Fact] public void Min2() { var val = (new int[] { 0, 2, 1 }).AsQueryable().Min(n => n); Assert.Equal(0, val); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A car wash business. /// </summary> public class AutoWash_Core : TypeCore, IAutomotiveBusiness { public AutoWash_Core() { this._TypeId = 28; this._Id = "AutoWash"; this._Schema_Org_Url = "http://schema.org/AutoWash"; string label = ""; GetLabel(out label, "AutoWash", typeof(AutoWash_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,30}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{30}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Xml.Serialization; using System.IO; namespace Projeny.Internal { public class CoRoutineTimeoutException : Exception { } public class CoRoutineException : Exception { readonly List<Type> _objTrace; public CoRoutineException(List<Type> objTrace, Exception innerException) : base(CreateMessage(objTrace), innerException) { _objTrace = objTrace; } static string CreateMessage(List<Type> objTrace) { var result = new StringBuilder(); foreach (var objType in objTrace) { if (result.Length != 0) { result.Append(" -> "); } result.Append(objType.Name()); } result.AppendLine(); return "Coroutine Object Trace: " + result.ToString(); } public List<Type> ObjectTrace { get { return _objTrace; } } } // Wrapper class for IEnumerator coroutines to allow calling nested coroutines easily public class CoRoutine { readonly Stack<IEnumerator> _processStack; object _returnValue; public CoRoutine(IEnumerator enumerator) { _processStack = new Stack<IEnumerator>(); _processStack.Push(enumerator); } public object ReturnValue { get { Assert.That(_processStack.IsEmpty()); return _returnValue; } } public bool IsDone { get { return _processStack.IsEmpty(); } } public bool Pump() { Assert.That(!_processStack.IsEmpty()); Assert.IsNull(_returnValue); var finished = new List<IEnumerator>(); var topWorker = _processStack.Peek(); bool isFinished; try { isFinished = !topWorker.MoveNext(); } catch (CoRoutineException e) { var objectTrace = GenerateObjectTrace(finished.Concat(_processStack)); if (objectTrace.IsEmpty()) { throw e; } throw new CoRoutineException(objectTrace.Concat(e.ObjectTrace).ToList(), e.InnerException); } catch (Exception e) { var objectTrace = GenerateObjectTrace(finished.Concat(_processStack)); if (objectTrace.IsEmpty()) { throw e; } throw new CoRoutineException(objectTrace, e); } if (isFinished) { finished.Add(_processStack.Pop()); } if (topWorker.Current != null && topWorker.Current.GetType().DerivesFrom<IEnumerator>()) { _processStack.Push((IEnumerator)topWorker.Current); } if (_processStack.IsEmpty()) { _returnValue = topWorker.Current; } return !_processStack.IsEmpty(); } static List<Type> GenerateObjectTrace(IEnumerable<IEnumerator> enumerators) { var objTrace = new List<Type>(); foreach (var enumerator in enumerators) { var field = enumerator.GetType().GetField("<>4__this", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (field == null) { // Mono seems to use a different name field = enumerator.GetType().GetField("<>f__this", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (field == null) { continue; } } var obj = field.GetValue(enumerator); if (obj == null) { continue; } var objType = obj.GetType(); if (objTrace.IsEmpty() || objType != objTrace.Last()) { objTrace.Add(objType); } } objTrace.Reverse(); return objTrace; } public static IEnumerator<T> Wrap<T>(IEnumerator runner) { var coroutine = new CoRoutine(runner); while (coroutine.Pump()) { yield return default(T); } if (coroutine.ReturnValue != null) { Assert.That(coroutine.ReturnValue.GetType().DerivesFromOrEqual<T>(), "Unexpected type returned from coroutine! Expected '{0}' and found '{1}'", typeof(T).Name(), coroutine.ReturnValue.GetType().Name()); } yield return (T)coroutine.ReturnValue; } public static void SyncWait(IEnumerator runner) { var coroutine = new CoRoutine(runner); while (coroutine.Pump()) { } } public static void SyncWaitWithTimeout(IEnumerator runner, float timeout) { var startTime = DateTime.UtcNow; var coroutine = new CoRoutine(runner); while (coroutine.Pump()) { if ((DateTime.UtcNow - startTime).TotalSeconds > timeout) { throw new CoRoutineTimeoutException(); } } } public static T SyncWaitGet<T>(IEnumerator<T> runner) { var coroutine = new CoRoutine(runner); while (coroutine.Pump()) { } return (T)coroutine.ReturnValue; } public static T SyncWaitGet<T>(IEnumerator runner) { var coroutine = new CoRoutine(runner); while (coroutine.Pump()) { } return (T)coroutine.ReturnValue; } public static IEnumerator MakeParallelGroup(IEnumerable<IEnumerator> runners) { var runnerList = runners.Select(x => new CoRoutine(x)).ToList(); while (runnerList.Any()) { foreach (var runner in runnerList) { runner.Pump(); } foreach (var runner in runnerList.Where(x => x.IsDone).ToList()) { runnerList.Remove(runner); } yield return null; } } } }
using System; using System.Runtime.InteropServices; /* A large portion of this code was derived from another class I found online but can't relocate. If you're the author and recognize this, thank you! The code was modified from its original form to suit my needs. Only a few function calls, constants, delegates, and structs were added. */ namespace LightApp.ServiceProcess { ///<summary>A collection of Win32 API functions and structs for use with Win32 services.</summary> public class ServicesAPI { public delegate void ServiceCtrlHandlerProc(int Opcode); [DllImport("advapi32.dll")] public static extern IntPtr CreateService(IntPtr scHandle, //[MarshalAs(UnmanagedType.LPTStr)] string lpSvcName, //[MarshalAs(UnmanagedType.LPTStr)] string lpDisplayName, Attributes.ServiceAccessType dwDesiredAccess, Attributes.ServiceType dwServiceType, Attributes.ServiceStartType dwStartType, Attributes.ServiceErrorControl dwErrorControl, //[MarshalAs(UnmanagedType.LPTStr)] string lpPathName, //[MarshalAs(UnmanagedType.LPTStr)] string lpLoadOrderGroup, int lpdwTagId, //[MarshalAs(UnmanagedType.LPTStr)] string lpDependencies, //[MarshalAs(UnmanagedType.LPTStr)] string lpServiceStartName, //[MarshalAs(UnmanagedType.LPTStr)] string lpPassword); [DllImport("advapi32.dll")] public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, Attributes.ServiceAccessType dwDesiredAccess); [DllImport("advapi32.dll")] public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, int dwDesiredAccess); [DllImport("advapi32.dll")] public static extern int DeleteService(IntPtr svHandle); [DllImport("advapi32.dll", EntryPoint = "RegisterServiceCtrlHandler")] public static extern IntPtr RegisterServiceCtrlHandler(string lpServiceName, [MarshalAs(UnmanagedType.FunctionPtr)]ServiceCtrlHandlerProc lpHandlerProc); [DllImport("advapi32.dll", SetLastError = true)] public static extern int SetServiceStatus(IntPtr hServiceStatus, ref SERVICE_STATUS lpServiceStatus); [DllImport("advapi32.dll", EntryPoint = "StartServiceCtrlDispatcher", SetLastError = true)] public static extern int StartServiceCtrlDispatcher(SERVICE_TABLE_ENTRY[] lpServiceStartTable); [DllImport("advapi32.dll")] public static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword); [DllImport("advapi32.dll")] public static extern int LockServiceDatabase(int hSCManager); [DllImport("advapi32.dll")] public static extern bool UnlockServiceDatabase(int hSCManager); [DllImport("kernel32.dll")] public static extern void CopyMemory(IntPtr pDst, SC_ACTION[] pSrc, int ByteLen); [DllImport("advapi32.dll")] public static extern bool ChangeServiceConfigA( int hService, ServiceType dwServiceType, int dwStartType, int dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword, string lpDisplayName); [DllImport("advapi32.dll")] public static extern bool ChangeServiceConfig2A( int hService, InfoLevel dwInfoLevel, [MarshalAs(UnmanagedType.Struct)] ref SERVICE_DESCRIPTION lpInfo); [DllImport("advapi32.dll")] public static extern bool ChangeServiceConfig2A( int hService, InfoLevel dwInfoLevel, [MarshalAs(UnmanagedType.Struct)] ref SERVICE_FAILURE_ACTIONS lpInfo); [DllImport("advapi32.dll")] public static extern int OpenServiceA( int hSCManager, string lpServiceName, ACCESS_TYPE dwDesiredAccess); [DllImport("advapi32.dll", EntryPoint = "OpenService")] public static extern IntPtr OpenService(IntPtr hSCManager, string serviceName, ACCESS_TYPE desiredAccess); [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManagerA(string lpMachineName, string lpDatabaseName, ServiceControlManagerType dwDesiredAccess); [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManagerA(string lpMachineName, string lpSCDB, int scParameter); [DllImport("advapi32.dll")] public static extern bool CloseServiceHandle( int hSCObject); [DllImport("advapi32.dll")] public static extern bool CloseServiceHandle( IntPtr hSCObject); [DllImport("advapi32.dll")] public static extern bool QueryServiceConfigA( int hService, [MarshalAs(UnmanagedType.Struct)] ref QUERY_SERVICE_CONFIG lpServiceConfig, int cbBufSize, int pcbBytesNeeded); public const int STANDARD_RIGHTS_REQUIRED = 0xF0000; public const int GENERIC_READ = -2147483648; public const int ERROR_INSUFFICIENT_BUFFER = 122; public const int SERVICE_NO_CHANGE = -1; public const int GENERIC_WRITE = 0x40000000; public const int DELETE = 0x10000; public const int SERVICE_ACCEPT_STOP = 1; public const int SERVICE_ACCEPT_PAUSE_CONTINUE = 2; public const int SERVICE_ACCEPT_SHUTDOWN = 4; public const int SERVICE_STOPPED = 1; public const int SERVICE_START_PENDING = 2; public const int SERVICE_STOP_PENDING = 3; public const int SERVICE_RUNNING = 4; public const int SERVICE_CONTINUE_PENDING = 5; public const int SERVICE_PAUSE_PENDING = 6; public const int SERVICE_PAUSED = 7; public const int SERVICE_INTERROGATE = 0x80; public const int SERVICE_CONTROL_STOP = 1; public const int SERVICE_CONTROL_PAUSE = 2; public const int SERVICE_CONTROL_CONTINUE = 3; public const int SERVICE_CONTROL_INTERROGATE = 4; public const int SERVICE_CONTROL_SHUTDOWN = 5; public const int SERVICE_WIN32 = (int)(ServiceType.SERVICE_WIN32_OWN_PROCESS | ServiceType.SERVICE_WIN32_SHARE_PROCESS); public const int ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063; public const int ERROR_INVALID_DATA = 13; public const int ERROR_SERVICE_ALREADY_RUNNING = 1057; //public const int SERVICE_NO_CHANGE = 0xFFFF; public enum ServiceType { SERVICE_KERNEL_DRIVER = 0x1, SERVICE_FILE_SYSTEM_DRIVER = 0x2, SERVICE_WIN32_OWN_PROCESS = 0x10, SERVICE_WIN32_SHARE_PROCESS = 0x20, SERVICE_INTERACTIVE_PROCESS = 0x100, SERVICETYPE_NO_CHANGE = SERVICE_NO_CHANGE } public enum ServiceStartType : int { SERVICE_BOOT_START = 0x0, SERVICE_SYSTEM_START = 0x1, SERVICE_AUTO_START = 0x2, SERVICE_DEMAND_START = 0x3, SERVICE_DISABLED = 0x4, SERVICESTARTTYPE_NO_CHANGE = SERVICE_NO_CHANGE } public enum ServiceErrorControl : int { SERVICE_ERROR_IGNORE = 0x0, SERVICE_ERROR_NORMAL = 0x1, SERVICE_ERROR_SEVERE = 0x2, SERVICE_ERROR_CRITICAL = 0x3, msidbServiceInstallErrorControlVital = 0x8000, SERVICEERRORCONTROL_NO_CHANGE = SERVICE_NO_CHANGE } public enum ServiceStateRequest : int { SERVICE_ACTIVE = 0x1, SERVICE_INACTIVE = 0x2, SERVICE_STATE_ALL = (SERVICE_ACTIVE | SERVICE_INACTIVE) } public enum ServiceControlType : int { SERVICE_CONTROL_STOP = 0x1, SERVICE_CONTROL_PAUSE = 0x2, SERVICE_CONTROL_CONTINUE = 0x3, SERVICE_CONTROL_INTERROGATE = 0x4, SERVICE_CONTROL_SHUTDOWN = 0x5, SERVICE_CONTROL_PARAMCHANGE = 0x6, SERVICE_CONTROL_NETBINDADD = 0x7, SERVICE_CONTROL_NETBINDREMOVE = 0x8, SERVICE_CONTROL_NETBINDENABLE = 0x9, SERVICE_CONTROL_NETBINDDISABLE = 0xA, SERVICE_CONTROL_DEVICEEVENT = 0xB, SERVICE_CONTROL_HARDWAREPROFILECHANGE = 0xC, SERVICE_CONTROL_POWEREVENT = 0xD, SERVICE_CONTROL_SESSIONCHANGE = 0xE, } public enum ServiceState : int { SERVICE_STOPPED = 0x1, SERVICE_START_PENDING = 0x2, SERVICE_STOP_PENDING = 0x3, SERVICE_RUNNING = 0x4, SERVICE_CONTINUE_PENDING = 0x5, SERVICE_PAUSE_PENDING = 0x6, SERVICE_PAUSED = 0x7, } public enum ServiceControlAccepted : int { SERVICE_ACCEPT_STOP = 0x1, SERVICE_ACCEPT_PAUSE_CONTINUE = 0x2, SERVICE_ACCEPT_SHUTDOWN = 0x4, SERVICE_ACCEPT_PARAMCHANGE = 0x8, SERVICE_ACCEPT_NETBINDCHANGE = 0x10, SERVICE_ACCEPT_HARDWAREPROFILECHANGE = 0x20, SERVICE_ACCEPT_POWEREVENT = 0x40, SERVICE_ACCEPT_SESSIONCHANGE = 0x80 } public enum ServiceControlManagerType : int { SC_MANAGER_CONNECT = 0x1, SC_MANAGER_CREATE_SERVICE = 0x2, SC_MANAGER_ENUMERATE_SERVICE = 0x4, SC_MANAGER_LOCK = 0x8, SC_MANAGER_QUERY_LOCK_STATUS = 0x10, SC_MANAGER_MODIFY_BOOT_CONFIG = 0x20, SC_MANAGER_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE | SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_LOCK | SC_MANAGER_QUERY_LOCK_STATUS | SC_MANAGER_MODIFY_BOOT_CONFIG } public enum ACCESS_TYPE : int { SERVICE_QUERY_CONFIG = 0x1, SERVICE_CHANGE_CONFIG = 0x2, SERVICE_QUERY_STATUS = 0x4, SERVICE_ENUMERATE_DEPENDENTS = 0x8, SERVICE_START = 0x10, SERVICE_STOP = 0x20, SERVICE_PAUSE_CONTINUE = 0x40, SERVICE_INTERROGATE = 0x80, SERVICE_USER_DEFINED_CONTROL = 0x100, SERVICE_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_STATUS { public int dwServiceType; public int dwCurrentState; public int dwControlsAccepted; public int dwWin32ExitCode; public int dwServiceSpecificExitCode; public int dwCheckPoint; public int dwWaitHint; } [StructLayout(LayoutKind.Sequential)] public struct QUERY_SERVICE_CONFIG { public int dwServiceType; public int dwStartType; public int dwErrorControl; public string lpBinaryPathName; public string lpLoadOrderGroup; public int dwTagId; public string lpDependencies; public string lpServiceStartName; public string lpDisplayName; } public enum SC_ACTION_TYPE : int { SC_ACTION_NONE = 0, SC_ACTION_RESTART = 1, SC_ACTION_REBOOT = 2, SC_ACTION_RUN_COMMAND = 3, } public delegate void ServiceMainProc(int argc, [MarshalAs(UnmanagedType.LPArray)]string[] argv); public struct SERVICE_TABLE_ENTRY { public string lpServiceName; [MarshalAs(UnmanagedType.FunctionPtr)] public ServiceMainProc lpServiceProc; /*public SERVICE_TABLE_ENTRY(string Name, ServiceMainProc ServiceMainMethod) { this.lpServiceName = Name; this.lpServiceProc = ServiceMainMethod; this.lpServiceNameNull = null; this.lpServiceProcNull = null; }/**/ } [StructLayout(LayoutKind.Sequential)] public struct SC_ACTION { public SC_ACTION_TYPE SCActionType; public int Delay; } public enum InfoLevel : int { SERVICE_CONFIG_DESCRIPTION = 1, SERVICE_CONFIG_FAILURE_ACTIONS = 2 } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_DESCRIPTION { public string lpDescription; } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_FAILURE_ACTIONS { public int dwResetPeriod; public string lpRebootMsg; public string lpCommand; public int cActions; public int lpsaActions; } } }
using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="usedBy">Appends user agent header</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string usedBy = null ) { if (apiClient == null) ApiClient = ApiClient.Default; else ApiClient = apiClient; Username = username; Password = password; AccessToken = accessToken; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; UsedBy = usedBy; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { if (apiClient == null) ApiClient = ApiClient.Default; else ApiClient = apiClient; } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.0.0"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap.Add(key, value); } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix(string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Gets or sets additional agent information when a tool using SDK needs to be recognized /// </summary> public string UsedBy { get; set; } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Swagger) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 1.0\n"; report += " SDK Package Version: 1.0.0\n"; return report; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DirectoryObjectRequest. /// </summary> public partial class DirectoryObjectRequest : BaseRequest, IDirectoryObjectRequest { /// <summary> /// Constructs a new DirectoryObjectRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DirectoryObjectRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified DirectoryObject using POST. /// </summary> /// <param name="directoryObjectToCreate">The DirectoryObject to create.</param> /// <returns>The created DirectoryObject.</returns> public System.Threading.Tasks.Task<DirectoryObject> CreateAsync(DirectoryObject directoryObjectToCreate) { return this.CreateAsync(directoryObjectToCreate, CancellationToken.None); } /// <summary> /// Creates the specified DirectoryObject using POST. /// </summary> /// <param name="directoryObjectToCreate">The DirectoryObject to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DirectoryObject.</returns> public async System.Threading.Tasks.Task<DirectoryObject> CreateAsync(DirectoryObject directoryObjectToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<DirectoryObject>(directoryObjectToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified DirectoryObject. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified DirectoryObject. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<DirectoryObject>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified DirectoryObject. /// </summary> /// <returns>The DirectoryObject.</returns> public System.Threading.Tasks.Task<DirectoryObject> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified DirectoryObject. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The DirectoryObject.</returns> public async System.Threading.Tasks.Task<DirectoryObject> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<DirectoryObject>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified DirectoryObject using PATCH. /// </summary> /// <param name="directoryObjectToUpdate">The DirectoryObject to update.</param> /// <returns>The updated DirectoryObject.</returns> public System.Threading.Tasks.Task<DirectoryObject> UpdateAsync(DirectoryObject directoryObjectToUpdate) { return this.UpdateAsync(directoryObjectToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified DirectoryObject using PATCH. /// </summary> /// <param name="directoryObjectToUpdate">The DirectoryObject to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated DirectoryObject.</returns> public async System.Threading.Tasks.Task<DirectoryObject> UpdateAsync(DirectoryObject directoryObjectToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<DirectoryObject>(directoryObjectToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDirectoryObjectRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDirectoryObjectRequest Expand(Expression<Func<DirectoryObject, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDirectoryObjectRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDirectoryObjectRequest Select(Expression<Func<DirectoryObject, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="directoryObjectToInitialize">The <see cref="DirectoryObject"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(DirectoryObject directoryObjectToInitialize) { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Orleans.Core; using Orleans.GrainDirectory; using Orleans.Providers; using Orleans.Runtime.Configuration; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.Placement; using Orleans.Runtime.Scheduler; using Orleans.Storage; namespace Orleans.Runtime { internal class Catalog : SystemTarget, ICatalog, IPlacementContext, ISiloStatusListener { /// <summary> /// Exception to indicate that the activation would have been a duplicate so messages pending for it should be redirected. /// </summary> [Serializable] internal class DuplicateActivationException : Exception { public ActivationAddress ActivationToUse { get; private set; } public SiloAddress PrimaryDirectoryForGrain { get; private set; } // for diagnostics only! public DuplicateActivationException() : base("DuplicateActivationException") { } public DuplicateActivationException(string msg) : base(msg) { } public DuplicateActivationException(string message, Exception innerException) : base(message, innerException) { } public DuplicateActivationException(ActivationAddress activationToUse) : base("DuplicateActivationException") { ActivationToUse = activationToUse; } public DuplicateActivationException(ActivationAddress activationToUse, SiloAddress primaryDirectoryForGrain) : base("DuplicateActivationException") { ActivationToUse = activationToUse; PrimaryDirectoryForGrain = primaryDirectoryForGrain; } // Implementation of exception serialization with custom properties according to: // http://stackoverflow.com/questions/94488/what-is-the-correct-way-to-make-a-custom-net-exception-serializable protected DuplicateActivationException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info != null) { ActivationToUse = (ActivationAddress) info.GetValue("ActivationToUse", typeof (ActivationAddress)); PrimaryDirectoryForGrain = (SiloAddress) info.GetValue("PrimaryDirectoryForGrain", typeof (SiloAddress)); } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info != null) { info.AddValue("ActivationToUse", ActivationToUse, typeof (ActivationAddress)); info.AddValue("PrimaryDirectoryForGrain", PrimaryDirectoryForGrain, typeof (SiloAddress)); } // MUST call through to the base class to let it save its own state base.GetObjectData(info, context); } } [Serializable] internal class NonExistentActivationException : Exception { public ActivationAddress NonExistentActivation { get; private set; } public bool IsStatelessWorker { get; private set; } public NonExistentActivationException() : base("NonExistentActivationException") { } public NonExistentActivationException(string msg) : base(msg) { } public NonExistentActivationException(string message, Exception innerException) : base(message, innerException) { } public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker) : base(msg) { NonExistentActivation = nonExistentActivation; IsStatelessWorker = isStatelessWorker; } protected NonExistentActivationException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info != null) { NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress)); IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool)); } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info != null) { info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress)); info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool)); } // MUST call through to the base class to let it save its own state base.GetObjectData(info, context); } } public GrainTypeManager GrainTypeManager { get; private set; } public SiloAddress LocalSilo { get; private set; } internal ISiloStatusOracle SiloStatusOracle { get; set; } internal readonly ActivationCollector ActivationCollector; private readonly ILocalGrainDirectory directory; private readonly OrleansTaskScheduler scheduler; private readonly ActivationDirectory activations; private IStorageProviderManager storageProviderManager; private Dispatcher dispatcher; private readonly TraceLogger logger; private int collectionNumber; private int destroyActivationsNumber; private IDisposable gcTimer; private readonly GlobalConfiguration config; private readonly string localSiloName; private readonly CounterStatistic activationsCreated; private readonly CounterStatistic activationsDestroyed; private readonly CounterStatistic activationsFailedToActivate; private readonly IntValueStatistic inProcessRequests; private readonly CounterStatistic collectionCounter; private readonly IGrainRuntime grainRuntime; internal Catalog( GrainId grainId, SiloAddress silo, string siloName, ILocalGrainDirectory grainDirectory, GrainTypeManager typeManager, OrleansTaskScheduler scheduler, ActivationDirectory activationDirectory, ClusterConfiguration config, IGrainRuntime grainRuntime, out Action<Dispatcher> setDispatcher) : base(grainId, silo) { LocalSilo = silo; localSiloName = siloName; directory = grainDirectory; activations = activationDirectory; this.scheduler = scheduler; GrainTypeManager = typeManager; this.grainRuntime = grainRuntime; collectionNumber = 0; destroyActivationsNumber = 0; logger = TraceLogger.GetLogger("Catalog", TraceLogger.LoggerType.Runtime); this.config = config.Globals; setDispatcher = d => dispatcher = d; ActivationCollector = new ActivationCollector(config); GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false); IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count); activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED); activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED); activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE); collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS); inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () => { long counter = 0; lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; counter += data.GetRequestCount(); } } return counter; }); } internal void SetStorageManager(IStorageProviderManager storageManager) { storageProviderManager = storageManager; } internal void Start() { if (gcTimer != null) gcTimer.Dispose(); var t = GrainTimer.FromTaskCallback(OnTimer, null, TimeSpan.Zero, ActivationCollector.Quantum, "Catalog.GCTimer"); t.Start(); gcTimer = t; } private Task OnTimer(object _) { return CollectActivationsImpl(true); } public Task CollectActivations(TimeSpan ageLimit) { return CollectActivationsImpl(false, ageLimit); } private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan)) { var watch = new Stopwatch(); watch.Start(); var number = Interlocked.Increment(ref collectionNumber); long memBefore = GC.GetTotalMemory(false) / (1024 * 1024); logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.", number, memBefore, activations.Count, ActivationCollector.ToString()); List<ActivationData> list = scanStale ? ActivationCollector.ScanStale() : ActivationCollector.ScanAll(ageLimit); collectionCounter.Increment(); var count = 0; if (list != null && list.Count > 0) { count = list.Count; if (logger.IsVerbose) logger.Verbose("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId)); await DeactivateActivationsFromCollector(list); } long memAfter = GC.GetTotalMemory(false) / (1024 * 1024); watch.Stop(); logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.", number, memAfter, activations.Count, count, ActivationCollector.ToString(), watch.Elapsed); } public List<Tuple<GrainId, string, int>> GetGrainStatistics() { var counts = new Dictionary<string, Dictionary<GrainId, int>>(); lock (activations) { foreach (var activation in activations) { ActivationData data = activation.Value; if (data == null || data.GrainInstance == null) continue; // TODO: generic type expansion var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType); Dictionary<GrainId, int> grains; int n; if (!counts.TryGetValue(grainTypeName, out grains)) { counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } }); } else if (!grains.TryGetValue(data.Grain, out n)) grains[data.Grain] = 1; else grains[data.Grain] = n + 1; } } return counts .SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value))) .ToList(); } public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics() { return activations.GetSimpleGrainStatistics(); } public DetailedGrainReport GetDetailedGrainReport(GrainId grain) { var report = new DetailedGrainReport { Grain = grain, SiloAddress = LocalSilo, SiloName = localSiloName, LocalCacheActivationAddresses = directory.GetLocalCacheData(grain), LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses, PrimaryForGrain = directory.GetPrimaryForGrain(grain) }; try { PlacementStrategy unused; MultiClusterRegistrationStrategy unusedActivationStrategy; string grainClassName; GrainTypeManager.GetTypeInfo(grain.GetTypeCode(), out grainClassName, out unused, out unusedActivationStrategy); report.GrainClassTypeName = grainClassName; } catch (Exception exc) { report.GrainClassTypeName = exc.ToString(); } List<ActivationData> acts = activations.FindTargets(grain); report.LocalActivations = acts != null ? acts.Select(activationData => activationData.ToDetailedString()).ToList() : new List<string>(); return report; } #region MessageTargets /// <summary> /// Register a new object to which messages can be delivered with the local lookup table and scheduler. /// </summary> /// <param name="activation"></param> public void RegisterMessageTarget(ActivationData activation) { var context = new SchedulingContext(activation); scheduler.RegisterWorkContext(context); activations.RecordNewTarget(activation); activationsCreated.Increment(); } /// <summary> /// Unregister message target and stop delivering messages to it /// </summary> /// <param name="activation"></param> public void UnregisterMessageTarget(ActivationData activation) { activations.RemoveTarget(activation); // this should be removed once we've refactored the deactivation code path. For now safe to keep. ActivationCollector.TryCancelCollection(activation); activationsDestroyed.Increment(); scheduler.UnregisterWorkContext(new SchedulingContext(activation)); if (activation.GrainInstance == null) return; var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType); activations.DecrementGrainCounter(grainTypeName); activation.SetGrainInstance(null); } /// <summary> /// FOR TESTING PURPOSES ONLY!! /// </summary> /// <param name="grain"></param> internal int UnregisterGrainForTesting(GrainId grain) { var acts = activations.FindTargets(grain); if (acts == null) return 0; int numActsBefore = acts.Count; foreach (var act in acts) UnregisterMessageTarget(act); return numActsBefore; } #endregion #region Grains internal bool IsReentrantGrain(ActivationId running) { ActivationData target; GrainTypeData data; return TryGetActivationData(running, out target) && target.GrainInstance != null && GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) && data.IsReentrant; } public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null) { GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments); } #endregion #region Activations public int ActivationCount { get { return activations.Count; } } /// <summary> /// If activation already exists, use it /// Otherwise, create an activation of an existing grain by reading its state. /// Return immediately using a dummy that will queue messages. /// Concurrently start creating and initializing the real activation and replace it when it is ready. /// </summary> /// <param name="address">Grain's activation address</param> /// <param name="newPlacement">Creation of new activation was requested by the placement director.</param> /// <param name="grainType">The type of grain to be activated or created</param> /// <param name="genericArguments">Specific generic type of grain to be activated or created</param> /// <param name="activatedPromise"></param> /// <returns></returns> public ActivationData GetOrCreateActivation( ActivationAddress address, bool newPlacement, string grainType, string genericArguments, Dictionary<string, object> requestContextData, out Task activatedPromise) { ActivationData result; activatedPromise = TaskDone.Done; PlacementStrategy placement; lock (activations) { if (TryGetActivationData(address.Activation, out result)) { return result; } int typeCode = address.Grain.GetTypeCode(); string actualGrainType = null; MultiClusterRegistrationStrategy activationStrategy; if (typeCode != 0) { GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy); } else { // special case for Membership grain. placement = SystemPlacement.Singleton; activationStrategy = ClusterLocalRegistration.Singleton; } if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating()) { // create a dummy activation that will queue up messages until the real data arrives if (string.IsNullOrEmpty(grainType)) { grainType = actualGrainType; } // We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory. result = new ActivationData( address, genericArguments, placement, activationStrategy, ActivationCollector, config.Application.GetCollectionAgeLimit(grainType)); RegisterMessageTarget(result); } } // End lock // Did not find and did not start placing new if (result == null) { var msg = String.Format("Non-existent activation: {0}, grain type: {1}.", address.ToFullString(), grainType); if (logger.IsVerbose) logger.Verbose(ErrorCode.CatalogNonExistingActivation2, msg); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment(); throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement); } SetupActivationInstance(result, grainType, genericArguments); activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData); return result; } private void SetupActivationInstance(ActivationData result, string grainType, string genericInterface) { var genericArguments = String.IsNullOrEmpty(genericInterface) ? null : TypeUtils.GenericTypeArgsString(genericInterface); lock (result) { if (result.GrainInstance == null) { CreateGrainInstance(grainType, result, genericArguments); } } } private async Task InitActivation(ActivationData activation, string grainType, string genericInterface, Dictionary<string, object> requestContextData) { // We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly) // the operations required to turn the "dummy" activation into a real activation ActivationAddress address = activation.Address; int initStage = 0; // A chain of promises that will have to complete in order to complete the activation // Register with the grain directory, register with the store if necessary and call the Activate method on the new activation. try { initStage = 1; await RegisterActivationInGrainDirectoryAndValidate(activation); initStage = 2; await SetupActivationState(activation, grainType); initStage = 3; await InvokeActivate(activation, requestContextData); ActivationCollector.ScheduleCollection(activation); // Success!! Log the result, and start processing messages if (logger.IsVerbose) logger.Verbose("InitActivation is done: {0}", address); } catch (Exception ex) { lock (activation) { activation.SetState(ActivationState.Invalid); try { UnregisterMessageTarget(activation); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget4, String.Format("UnregisterMessageTarget failed on {0}.", activation), exc); } switch (initStage) { case 1: // failed to RegisterActivationInGrainDirectory ActivationAddress target = null; Exception dupExc; // Failure!! Could it be that this grain uses single activation placement, and there already was an activation? if (Utils.TryFindException(ex, typeof (DuplicateActivationException), out dupExc)) { target = ((DuplicateActivationException) dupExc).ActivationToUse; CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DUPLICATE_ACTIVATIONS) .Increment(); } activation.ForwardingAddress = target; if (target != null) { var primary = ((DuplicateActivationException)dupExc).PrimaryDirectoryForGrain; // If this was a duplicate, it's not an error, just a race. // Forward on all of the pending messages, and then forget about this activation. string logMsg = String.Format("Tried to create a duplicate activation {0}, but we'll use {1} instead. " + "GrainInstanceType is {2}. " + "{3}" + "Full activation address is {4}. We have {5} messages to forward.", address, target, activation.GrainInstanceType, primary != null ? "Primary Directory partition for this grain is " + primary + ". " : String.Empty, address.ToFullString(), activation.WaitingCount); if (activation.IsStatelessWorker) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_DuplicateActivation, logMsg); } else { logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg); } RerouteAllQueuedMessages(activation, target, "Duplicate activation", ex); } else { logger.Warn(ErrorCode.Runtime_Error_100064, String.Format("Failed to RegisterActivationInGrainDirectory for {0}.", activation), ex); // Need to undo the registration we just did earlier if (!activation.IsStatelessWorker) { scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address), SchedulingContext).Ignore(); } RerouteAllQueuedMessages(activation, null, "Failed RegisterActivationInGrainDirectory", ex); } break; case 2: // failed to setup persistent state logger.Warn(ErrorCode.Catalog_Failed_SetupActivationState, String.Format("Failed to SetupActivationState for {0}.", activation), ex); // Need to undo the registration we just did earlier if (!activation.IsStatelessWorker) { scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address), SchedulingContext).Ignore(); } RerouteAllQueuedMessages(activation, null, "Failed SetupActivationState", ex); break; case 3: // failed to InvokeActivate logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate, String.Format("Failed to InvokeActivate for {0}.", activation), ex); // Need to undo the registration we just did earlier if (!activation.IsStatelessWorker) { scheduler.RunOrQueueTask(() => directory.UnregisterAsync(address), SchedulingContext).Ignore(); } RerouteAllQueuedMessages(activation, null, "Failed InvokeActivate", ex); break; } } throw; } } /// <summary> /// Perform just the prompt, local part of creating an activation object /// Caller is responsible for registering locally, registering with store and calling its activate routine /// </summary> /// <param name="grainTypeName"></param> /// <param name="data"></param> /// <param name="genericArguments"></param> /// <returns></returns> private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments) { string grainClassName; var interfaceToClassMap = GrainTypeManager.GetGrainInterfaceToClassMap(); if (!interfaceToClassMap.TryGetValue(grainTypeName, out grainClassName)) { // Lookup from grain type code var typeCode = data.Grain.GetTypeCode(); if (typeCode != 0) { PlacementStrategy unused; MultiClusterRegistrationStrategy unusedActivationStrategy; GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments); } else { grainClassName = grainTypeName; } } GrainTypeData grainTypeData = GrainTypeManager[grainClassName]; Type grainType = grainTypeData.Type; // TODO: Change back to GetRequiredService after stable Microsoft.Framework.DependencyInjection is released and can be referenced here var services = Runtime.Silo.CurrentSilo.Services; var grain = services != null ? (Grain) services.GetService(grainType) : (Grain) Activator.CreateInstance(grainType); // Inject runtime hooks into grain instance grain.Runtime = grainRuntime; grain.Data = data; Type stateObjectType = grainTypeData.StateObjectType; object state = null; if (stateObjectType != null) { state = Activator.CreateInstance(stateObjectType); } lock (data) { grain.Identity = data.Identity; data.SetGrainInstance(grain); var statefulGrain = grain as IStatefulGrain; if (statefulGrain != null) { if (state != null) { SetupStorageProvider(data); statefulGrain.GrainState.State = state; statefulGrain.SetStorage(new GrainStateStorageBridge(data.GrainTypeName, statefulGrain, data.StorageProvider)); } } } activations.IncrementGrainCounter(grainClassName); if (logger.IsVerbose) logger.Verbose("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId); } private void SetupStorageProvider(ActivationData data) { var grainTypeName = data.GrainInstanceType.FullName; // Get the storage provider name, using the default if not specified. var attrs = data.GrainInstanceType.GetCustomAttributes(typeof(StorageProviderAttribute), true); var attr = attrs.FirstOrDefault() as StorageProviderAttribute; var storageProviderName = attr != null ? attr.ProviderName : Constants.DEFAULT_STORAGE_PROVIDER_NAME; IStorageProvider provider; if (storageProviderManager == null || storageProviderManager.GetNumLoadedProviders() == 0) { var errMsg = string.Format("No storage providers found loading grain type {0}", grainTypeName); logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_1, errMsg); throw new BadProviderConfigException(errMsg); } if (string.IsNullOrWhiteSpace(storageProviderName)) { // Use default storage provider provider = storageProviderManager.GetDefaultProvider(); } else { // Look for MemoryStore provider as special case name bool caseInsensitive = Constants.MEMORY_STORAGE_PROVIDER_NAME.Equals(storageProviderName, StringComparison.OrdinalIgnoreCase); storageProviderManager.TryGetProvider(storageProviderName, out provider, caseInsensitive); if (provider == null) { var errMsg = string.Format( "Cannot find storage provider with Name={0} for grain type {1}", storageProviderName, grainTypeName); logger.Error(ErrorCode.Provider_CatalogNoStorageProvider_2, errMsg); throw new BadProviderConfigException(errMsg); } } data.StorageProvider = provider; if (logger.IsVerbose2) { string msg = string.Format("Assigned storage provider with Name={0} to grain type {1}", storageProviderName, grainTypeName); logger.Verbose2(ErrorCode.Provider_CatalogStorageProviderAllocated, msg); } } private async Task SetupActivationState(ActivationData result, string grainType) { var statefulGrain = result.GrainInstance as IStatefulGrain; if (statefulGrain == null) { return; } var state = statefulGrain.GrainState; if (result.StorageProvider != null && state != null) { var sw = Stopwatch.StartNew(); var innerState = statefulGrain.GrainState.State; // Populate state data try { var grainRef = result.GrainReference; await scheduler.RunOrQueueTask(() => result.StorageProvider.ReadStateAsync(grainType, grainRef, state), new SchedulingContext(result)); sw.Stop(); StorageStatisticsGroup.OnStorageActivate(result.StorageProvider, grainType, result.GrainReference, sw.Elapsed); } catch (Exception ex) { StorageStatisticsGroup.OnStorageActivateError(result.StorageProvider, grainType, result.GrainReference); sw.Stop(); if (!(ex.GetBaseException() is KeyNotFoundException)) throw; statefulGrain.GrainState.State = innerState; // Just keep original empty state object } } } /// <summary> /// Try to get runtime data for an activation /// </summary> /// <param name="activationId"></param> /// <param name="data"></param> /// <returns></returns> public bool TryGetActivationData(ActivationId activationId, out ActivationData data) { data = null; if (activationId.IsSystem) return false; data = activations.FindTarget(activationId); return data != null; } private Task DeactivateActivationsFromCollector(List<ActivationData> list) { logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count); foreach (var activation in list) { lock (activation) { activation.PrepareForDeactivation(); // Don't accept any new messages } } return DestroyActivations(list); } // To be called fro within Activation context. // Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task. internal void DeactivateActivationOnIdle(ActivationData data) { bool promptly = false; bool alreadBeingDestroyed = false; lock (data) { if (data.State == ActivationState.Valid) { // Change the ActivationData state here, since we're about to give up the lock. data.PrepareForDeactivation(); // Don't accept any new messages ActivationCollector.TryCancelCollection(data); if (!data.IsCurrentlyExecuting) { promptly = true; } else // busy, so destroy later. { data.AddOnInactive(() => DestroyActivationVoid(data)); } } else if (data.State == ActivationState.Create) { throw new InvalidOperationException(String.Format( "Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.", data.ToString())); } else if (data.State == ActivationState.Activating) { throw new InvalidOperationException(String.Format( "Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.", data.ToString())); } else { alreadBeingDestroyed = true; } } logger.Info(ErrorCode.Catalog_ShutdownActivations_2, "DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle")); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE).Increment(); if (promptly) { DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed! } } /// <summary> /// Gracefully deletes activations, putting it into a shutdown state to /// complete and commit outstanding transactions before deleting it. /// To be called not from within Activation context, so can be awaited. /// </summary> /// <param name="list"></param> /// <returns></returns> internal async Task DeactivateActivations(List<ActivationData> list) { if (list == null || list.Count == 0) return; if (logger.IsVerbose) logger.Verbose("DeactivateActivations: {0} activations.", list.Count); List<ActivationData> destroyNow = null; List<MultiTaskCompletionSource> destroyLater = null; int alreadyBeingDestroyed = 0; foreach (var d in list) { var activationData = d; // capture lock (activationData) { if (activationData.State == ActivationState.Valid) { // Change the ActivationData state here, since we're about to give up the lock. activationData.PrepareForDeactivation(); // Don't accept any new messages ActivationCollector.TryCancelCollection(activationData); if (!activationData.IsCurrentlyExecuting) { if (destroyNow == null) { destroyNow = new List<ActivationData>(); } destroyNow.Add(activationData); } else // busy, so destroy later. { if (destroyLater == null) { destroyLater = new List<MultiTaskCompletionSource>(); } var tcs = new MultiTaskCompletionSource(1); destroyLater.Add(tcs); activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs)); } } else { alreadyBeingDestroyed++; } } } int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count; int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count; logger.Info(ErrorCode.Catalog_ShutdownActivations_3, "DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.", list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed); CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count); if (destroyNow != null && destroyNow.Count > 0) { await DestroyActivations(destroyNow); } if (destroyLater != null && destroyLater.Count > 0) { await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray()); } } public Task DeactivateAllActivations() { logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations."); var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList(); return DeactivateActivations(activationsToShutdown); } /// <summary> /// Deletes activation immediately regardless of active transactions etc. /// For use by grain delete, transaction abort, etc. /// </summary> /// <param name="activation"></param> private void DestroyActivationVoid(ActivationData activation) { StartDestroyActivations(new List<ActivationData> { activation }); } private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs) { StartDestroyActivations(new List<ActivationData> { activation }, tcs); } /// <summary> /// Forcibly deletes activations now, without waiting for any outstanding transactions to complete. /// Deletes activation immediately regardless of active transactions etc. /// For use by grain delete, transaction abort, etc. /// </summary> /// <param name="list"></param> /// <returns></returns> // Overall code flow: // Deactivating state was already set before, in the correct context under lock. // that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued) // Wait for all already scheduled ticks to finish // CallGrainDeactivate // when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks): // Unregister in the directory // when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest): // Set Invalid state // UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor). // InvalidateCacheEntry // Reroute pending private Task DestroyActivations(List<ActivationData> list) { var tcs = new MultiTaskCompletionSource(list.Count); StartDestroyActivations(list, tcs); return tcs.Task; } private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null) { int number = destroyActivationsNumber; destroyActivationsNumber++; try { logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count); // step 1 - WaitForAllTimersToFinish var tasks1 = new List<Task>(); foreach (var activation in list) { tasks1.Add(activation.WaitForAllTimersToFinish()); } try { await Task.WhenAll(tasks1); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc); } // step 2 - CallGrainDeactivate var tasks2 = new List<Tuple<Task, ActivationData>>(); foreach (var activation in list) { var activationData = activation; // Capture loop variable var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData), new SchedulingContext(activationData)); tasks2.Add(new Tuple<Task, ActivationData>(task, activationData)); } var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>(); asyncQueue.Queue(tasks2, tupleList => { FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs); GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe. }); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc); } } private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs) { try { //logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count); // step 3 - UnregisterManyAsync try { List<ActivationAddress> activationsToDeactivate = list. Where((ActivationData d) => !d.IsStatelessWorker). Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList(); if (activationsToDeactivate.Count > 0) { await scheduler.RunOrQueueTask(() => directory.UnregisterManyAsync(activationsToDeactivate), SchedulingContext); } } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc); } // step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate foreach (var activationData in list) { try { lock (activationData) { activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished } UnregisterMessageTarget(activationData); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc); } try { // IMPORTANT: no more awaits and .Ignore after that point. // Just use this opportunity to invalidate local Cache Entry as well. // If this silo is not the grain directory partition for this grain, it may have it in its cache. directory.InvalidateCacheEntry(activationData.Address); RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation"); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc); } } // step 5 - Resolve any waiting TaskCompletionSource if (tcs != null) { tcs.SetMultipleResults(list.Count); } logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count); }catch (Exception exc) { logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc); } } private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { lock (activation) { List<Message> msgs = activation.DequeueAllWaitingMessages(); if (msgs == null || msgs.Count <= 0) return; if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation)); dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc); } } private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData) { var grainTypeName = activation.GrainInstanceType.FullName; // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName); // Call OnActivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function try { RequestContext.Import(requestContextData); await activation.GrainInstance.OnActivateAsync(); if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName); lock (activation) { if (activation.State == ActivationState.Activating) { activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished } if (!activation.IsCurrentlyExecuting) { activation.RunOnInactive(); } // Run message pump to see if there is a new request is queued to be processed dispatcher.RunMessagePump(activation); } } catch (Exception exc) { logger.Error(ErrorCode.Catalog_ErrorCallingActivate, string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc); activation.SetState(ActivationState.Invalid); // Mark this activation as unusable activationsFailedToActivate.Increment(); throw; } } private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation) { try { var grainTypeName = activation.GrainInstanceType.FullName; // Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName); // Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function try { // just check in case this activation data is already Invalid or not here at all. ActivationData ignore; if (TryGetActivationData(activation.ActivationId, out ignore) && activation.State == ActivationState.Deactivating) { RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake. await activation.GrainInstance.OnDeactivateAsync(); } if (logger.IsVerbose) logger.Verbose(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName); } catch (Exception exc) { logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate, string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc); } if (activation.IsUsingStreams) { try { await activation.DeactivateStreamResources(); } catch (Exception exc) { logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc); } } } catch(Exception exc) { logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc); } return activation; } private async Task RegisterActivationInGrainDirectoryAndValidate(ActivationData activation) { ActivationAddress address = activation.Address; bool singleActivationMode = !activation.IsStatelessWorker; if (singleActivationMode) { var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext); if (address.Equals(result.Address)) return; SiloAddress primaryDirectoryForGrain = directory.GetPrimaryForGrain(address.Grain); throw new DuplicateActivationException(result.Address, primaryDirectoryForGrain); } else { StatelessWorkerPlacement stPlacement = activation.PlacedUsing as StatelessWorkerPlacement; int maxNumLocalActivations = stPlacement.MaxLocal; lock (activations) { List<ActivationData> local; if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations) return; var id = StatelessWorkerDirector.PickRandom(local).Address; throw new DuplicateActivationException(id); } } // We currently don't have any other case for multiple activations except for StatelessWorker. } #endregion #region Activations - private /// <summary> /// Invoke the activate method on a newly created activation /// </summary> /// <param name="activation"></param> /// <returns></returns> private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData) { // NOTE: This should only be called with the correct schedulering context for the activation to be invoked. lock (activation) { activation.SetState(ActivationState.Activating); } return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), new SchedulingContext(activation)); // Target grain's scheduler context); // ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest } #endregion #region IPlacementContext public TraceLogger Logger { get { return logger; } } public bool FastLookup(GrainId grain, out AddressesAndTag addresses) { return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0; // NOTE: only check with the local directory cache. // DO NOT check in the local activations TargetDirectory!!! // The only source of truth about which activation should be legit to is the state of the ditributed directory. // Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth"). // If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it, // thus volaiting the single-activation semantics and not converging even eventualy! } public Task<AddressesAndTag> FullLookup(GrainId grain) { return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext); } public bool LocalLookup(GrainId grain, out List<ActivationData> addresses) { addresses = activations.FindTargets(grain); return addresses != null; } public List<SiloAddress> AllActiveSilos { get { var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList(); if (result.Count > 0) return result; logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty"); return new List<SiloAddress> { LocalSilo }; } } #endregion #region Implementation of ICatalog public Task CreateSystemGrain(GrainId grainId, string grainType) { ActivationAddress target = ActivationAddress.NewActivationAddress(LocalSilo, grainId); Task activatedPromise; GetOrCreateActivation(target, true, grainType, null, null, out activatedPromise); return activatedPromise ?? TaskDone.Done; } public Task DeleteActivations(List<ActivationAddress> addresses) { return DestroyActivations(TryGetActivationDatas(addresses)); } private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses) { var datas = new List<ActivationData>(addresses.Count); foreach (var activationAddress in addresses) { ActivationData data; if (TryGetActivationData(activationAddress.Activation, out data)) datas.Add(data); } return datas; } #endregion #region Implementation of ISiloStatusListener public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // ignore joining events and also events on myself. if (updatedSilo.Equals(LocalSilo)) return; // We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states, // since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses, // thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified. // We may review the directory behaiviour in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well. if (!status.IsTerminating()) return; if (status == SiloStatus.Dead) { RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(updatedSilo); } var activationsToShutdown = new List<ActivationData>(); try { // scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner. lock (activations) { foreach (var activation in activations) { try { var activationData = activation.Value; if (!directory.GetPrimaryForGrain(activationData.Grain).Equals(updatedSilo)) continue; lock (activationData) { // adapted from InsideGarinClient.DeactivateOnIdle(). activationData.ResetKeepAliveRequest(); activationsToShutdown.Add(activationData); } } catch (Exception exc) { logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception, String.Format("Catalog has thrown an exception while executing SiloStatusChangeNotification of silo {0}.", updatedSilo.ToStringWithHashCode()), exc); } } } logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification, String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partiton to these grain ids.", activationsToShutdown.Count, updatedSilo.ToStringWithHashCode())); } finally { // outside the lock. if (activationsToShutdown.Count > 0) { DeactivateActivations(activationsToShutdown).Ignore(); } } } #endregion } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using MathNet.Numerics.Distributions; using MathNet.Numerics.Statistics; using QuantConnect.Logging; namespace QuantConnect.Statistics { /// <summary> /// Calculate all the statistics required from the backtest, based on the equity curve and the profit loss statement. /// </summary> /// <remarks>This is a particularly ugly class and one of the first ones written. It should be thrown out and re-written.</remarks> public class Statistics { /// <summary> /// Retrieve a static S-P500 Benchmark for the statistics calculations. Update the benchmark once per day. /// </summary> public static SortedDictionary<DateTime, decimal> YahooSPYBenchmark { get { var benchmark = new SortedDictionary<DateTime, decimal>(); var url = "http://real-chart.finance.yahoo.com/table.csv?s=SPY&a=11&b=31&c=1997&d=" + (DateTime.Now.Month - 1) + "&e=" + DateTime.Now.Day + "&f=" + DateTime.Now.Year + "&g=d&ignore=.csv"; using (var net = new WebClient()) { net.Proxy = WebRequest.GetSystemWebProxy(); var data = net.DownloadString(url); var first = true; using (var sr = new StreamReader(data.ToStream())) { while (sr.Peek() >= 0) { var line = sr.ReadLine(); if (first) { first = false; continue; } if (line == null) continue; var csv = line.Split(','); benchmark.Add(Parse.DateTime(csv[0]), csv[6].ConvertInvariant<decimal>()); } } } return benchmark; } } /// <summary> /// Convert the charting data into an equity array. /// </summary> /// <remarks>This is required to convert the equity plot into a usable form for the statistics calculation</remarks> /// <param name="points">ChartPoints Array</param> /// <returns>SortedDictionary of the equity decimal values ordered in time</returns> private static SortedDictionary<DateTime, decimal> ChartPointToDictionary(IEnumerable<ChartPoint> points) { var dictionary = new SortedDictionary<DateTime, decimal>(); try { foreach (var point in points) { var x = Time.UnixTimeStampToDateTime(point.x); if (!dictionary.ContainsKey(x)) { dictionary.Add(x, point.y); } else { dictionary[x] = point.y; } } } catch (Exception err) { Log.Error(err); } return dictionary; } /// <summary> /// Run a full set of orders and return a Dictionary of statistics. /// </summary> /// <param name="pointsEquity">Equity value over time.</param> /// <param name="profitLoss">profit loss from trades</param> /// <param name="pointsPerformance"> Daily performance</param> /// <param name="unsortedBenchmark"> Benchmark data as dictionary. Data does not need to be ordered</param> /// <param name="startingCash">Amount of starting cash in USD </param> /// <param name="totalFees">The total fees incurred over the life time of the algorithm</param> /// <param name="totalTrades">Total number of orders executed.</param> /// <param name="tradingDaysPerYear">Number of trading days per year</param> /// <returns>Statistics Array, Broken into Annual Periods</returns> public static Dictionary<string, string> Generate(IEnumerable<ChartPoint> pointsEquity, SortedDictionary<DateTime, decimal> profitLoss, IEnumerable<ChartPoint> pointsPerformance, Dictionary<DateTime, decimal> unsortedBenchmark, decimal startingCash, decimal totalFees, decimal totalTrades, double tradingDaysPerYear = 252 ) { //Initialise the response: double riskFreeRate = 0; decimal totalClosedTrades = 0; decimal totalWins = 0; decimal totalLosses = 0; decimal averageWin = 0; decimal averageLoss = 0; decimal averageWinRatio = 0; decimal winRate = 0; decimal lossRate = 0; decimal totalNetProfit = 0; double fractionOfYears = 1; decimal profitLossValue = 0, runningCash = startingCash; decimal algoCompoundingPerformance = 0; decimal finalBenchmarkCash = 0; decimal benchCompoundingPerformance = 0; var years = new List<int>(); var annualTrades = new SortedDictionary<int, int>(); var annualWins = new SortedDictionary<int, int>(); var annualLosses = new SortedDictionary<int, int>(); var annualLossTotal = new SortedDictionary<int, decimal>(); var annualWinTotal = new SortedDictionary<int, decimal>(); var annualNetProfit = new SortedDictionary<int, decimal>(); var statistics = new Dictionary<string, string>(); var dtPrevious = new DateTime(); var listPerformance = new List<double>(); var listBenchmark = new List<double>(); var equity = new SortedDictionary<DateTime, decimal>(); var performance = new SortedDictionary<DateTime, decimal>(); SortedDictionary<DateTime, decimal> benchmark = null; try { //Get array versions of the performance: performance = ChartPointToDictionary(pointsPerformance); equity = ChartPointToDictionary(pointsEquity); performance.Values.ToList().ForEach(i => listPerformance.Add((double)(i / 100))); benchmark = new SortedDictionary<DateTime, decimal>(unsortedBenchmark); // to find the delta in benchmark for first day, we need to know the price at the opening // moment of the day, but since we cannot find this, we cannot find the first benchmark's delta, // so we pad it with Zero. If running a short backtest this will skew results, longer backtests // will not be affected much listBenchmark.Add(0); //Get benchmark performance array for same period: benchmark.Keys.ToList().ForEach(dt => { if (dt >= equity.Keys.FirstOrDefault().AddDays(-1) && dt < equity.Keys.LastOrDefault()) { decimal previous; if (benchmark.TryGetValue(dtPrevious, out previous) && previous != 0) { var deltaBenchmark = (benchmark[dt] - previous)/previous; listBenchmark.Add((double)(deltaBenchmark)); } else { listBenchmark.Add(0); } dtPrevious = dt; } }); // TODO : if these lists are required to be the same length then we should create structure to pair the values, this way, by contract it will be enforced. //THIS SHOULD NEVER HAPPEN --> But if it does, log it and fail silently. while (listPerformance.Count < listBenchmark.Count) { listPerformance.Add(0); Log.Error("Statistics.Generate(): Padded Performance"); } while (listPerformance.Count > listBenchmark.Count) { listBenchmark.Add(0); Log.Error("Statistics.Generate(): Padded Benchmark"); } } catch (Exception err) { Log.Error(err, "Dic-Array Convert:"); } try { //Number of years in this dataset: fractionOfYears = (equity.Keys.LastOrDefault() - equity.Keys.FirstOrDefault()).TotalDays / 365; } catch (Exception err) { Log.Error(err, "Fraction of Years:"); } try { if (benchmark != null) { algoCompoundingPerformance = CompoundingAnnualPerformance(startingCash, equity.Values.LastOrDefault(), (decimal) fractionOfYears); finalBenchmarkCash = ((benchmark.Values.Last() - benchmark.Values.First())/benchmark.Values.First())*startingCash; benchCompoundingPerformance = CompoundingAnnualPerformance(startingCash, finalBenchmarkCash, (decimal) fractionOfYears); } } catch (Exception err) { Log.Error(err, "Compounding:"); } try { //Run over each equity day: foreach (var closedTrade in profitLoss.Keys) { profitLossValue = profitLoss[closedTrade]; //Check if this date is in the "years" array: var year = closedTrade.Year; if (!years.Contains(year)) { //Initialise a new year holder: years.Add(year); annualTrades.Add(year, 0); annualWins.Add(year, 0); annualWinTotal.Add(year, 0); annualLosses.Add(year, 0); annualLossTotal.Add(year, 0); } //Add another trade: annualTrades[year]++; //Profit loss tracking: if (profitLossValue > 0) { annualWins[year]++; annualWinTotal[year] += profitLossValue / runningCash; } else { annualLosses[year]++; annualLossTotal[year] += profitLossValue / runningCash; } //Increment the cash: runningCash += profitLossValue; } //Get the annual percentage of profit and loss: foreach (var year in years) { annualNetProfit[year] = (annualWinTotal[year] + annualLossTotal[year]); } //Sum the totals: try { if (profitLoss.Keys.Count > 0) { totalClosedTrades = annualTrades.Values.Sum(); totalWins = annualWins.Values.Sum(); totalLosses = annualLosses.Values.Sum(); totalNetProfit = (equity.Values.LastOrDefault() / startingCash) - 1; //-> Handle Div/0 Errors if (totalWins == 0) { averageWin = 0; } else { averageWin = annualWinTotal.Values.Sum() / totalWins; } if (totalLosses == 0) { averageLoss = 0; averageWinRatio = 0; } else { averageLoss = annualLossTotal.Values.Sum() / totalLosses; averageWinRatio = Math.Abs(averageWin / averageLoss); } if (totalTrades == 0) { winRate = 0; lossRate = 0; } else { winRate = Math.Round(totalWins / totalClosedTrades, 5); lossRate = Math.Round(totalLosses / totalClosedTrades, 5); } } } catch (Exception err) { Log.Error(err, "Second Half:"); } var profitLossRatio = ProfitLossRatio(averageWin, averageLoss); var profitLossRatioHuman = profitLossRatio.ToString(CultureInfo.InvariantCulture); if (profitLossRatio == -1) profitLossRatioHuman = "0"; //Add the over all results first, break down by year later: statistics = new Dictionary<string, string> { { "Total Trades", Math.Round(totalTrades, 0).ToStringInvariant() }, { "Average Win", Math.Round(averageWin * 100, 2).ToStringInvariant() + "%" }, { "Average Loss", Math.Round(averageLoss * 100, 2).ToStringInvariant() + "%" }, { "Compounding Annual Return", Math.Round(algoCompoundingPerformance * 100, 3).ToStringInvariant() + "%" }, { "Drawdown", (DrawdownPercent(equity, 3) * 100).ToStringInvariant() + "%" }, { "Expectancy", Math.Round((winRate * averageWinRatio) - (lossRate), 3).ToStringInvariant() }, { "Net Profit", Math.Round(totalNetProfit * 100, 3).ToStringInvariant() + "%"}, { "Sharpe Ratio", Math.Round(SharpeRatio(listPerformance, riskFreeRate), 3).ToStringInvariant() }, { "Loss Rate", Math.Round(lossRate * 100).ToStringInvariant() + "%" }, { "Win Rate", Math.Round(winRate * 100).ToStringInvariant() + "%" }, { "Profit-Loss Ratio", profitLossRatioHuman }, { "Alpha", Math.Round(Alpha(listPerformance, listBenchmark, riskFreeRate), 3).ToStringInvariant() }, { "Beta", Math.Round(Beta(listPerformance, listBenchmark), 3).ToStringInvariant() }, { "Annual Standard Deviation", Math.Round(AnnualStandardDeviation(listPerformance, tradingDaysPerYear), 3).ToStringInvariant() }, { "Annual Variance", Math.Round(AnnualVariance(listPerformance, tradingDaysPerYear), 3).ToStringInvariant() }, { "Information Ratio", Math.Round(InformationRatio(listPerformance, listBenchmark), 3).ToStringInvariant() }, { "Tracking Error", Math.Round(TrackingError(listPerformance, listBenchmark), 3).ToStringInvariant() }, { "Treynor Ratio", Math.Round(TreynorRatio(listPerformance, listBenchmark, riskFreeRate), 3).ToStringInvariant() }, { "Total Fees", "$" + totalFees.ToStringInvariant("0.00") } }; } catch (Exception err) { Log.Error(err); } return statistics; } /// <summary> /// Return profit loss ratio safely avoiding divide by zero errors. /// </summary> /// <param name="averageWin"></param> /// <param name="averageLoss"></param> /// <returns></returns> public static decimal ProfitLossRatio(decimal averageWin, decimal averageLoss) { if (averageLoss == 0) return -1; return Math.Round(averageWin / Math.Abs(averageLoss), 2); } /// <summary> /// Drawdown maximum percentage. /// </summary> /// <param name="equityOverTime"></param> /// <param name="rounding"></param> /// <returns></returns> public static decimal DrawdownPercent(SortedDictionary<DateTime, decimal> equityOverTime, int rounding = 2) { var dd = 0m; try { var lPrices = equityOverTime.Values.ToList(); var lDrawdowns = new List<decimal>(); var high = lPrices[0]; foreach (var price in lPrices) { if (price >= high) high = price; lDrawdowns.Add((price/high) - 1); } dd = Math.Round(Math.Abs(lDrawdowns.Min()), rounding); } catch (Exception err) { Log.Error(err); } return dd; } /// <summary> /// Drawdown maximum value /// </summary> /// <param name="equityOverTime">Array of portfolio value over time.</param> /// <param name="rounding">Round the drawdown statistics.</param> /// <returns>Draw down percentage over period.</returns> public static decimal DrawdownValue(SortedDictionary<DateTime, decimal> equityOverTime, int rounding = 2) { //Initialise: var priceMaximum = 0; var previousMinimum = 0; var previousMaximum = 0; try { var lPrices = equityOverTime.Values.ToList(); for (var id = 0; id < lPrices.Count; id++) { if (lPrices[id] >= lPrices[priceMaximum]) { priceMaximum = id; } else { if ((lPrices[priceMaximum] - lPrices[id]) > (lPrices[previousMaximum] - lPrices[previousMinimum])) { previousMaximum = priceMaximum; previousMinimum = id; } } } return Math.Round((lPrices[previousMaximum] - lPrices[previousMinimum]), rounding); } catch (Exception err) { Log.Error(err); } return 0; } // End Drawdown: /// <summary> /// Annual compounded returns statistic based on the final-starting capital and years. /// </summary> /// <param name="startingCapital">Algorithm starting capital</param> /// <param name="finalCapital">Algorithm final capital</param> /// <param name="years">Years trading</param> /// <returns>Decimal fraction for annual compounding performance</returns> public static decimal CompoundingAnnualPerformance(decimal startingCapital, decimal finalCapital, decimal years) { if (years == 0 || startingCapital == 0) { return 0; } var power = 1 / (double)years; var baseNumber = (double)finalCapital / (double)startingCapital; var result = Math.Pow(baseNumber, power) - 1; return result.IsNaNOrInfinity() ? 0 : result.SafeDecimalCast(); } /// <summary> /// Annualized return statistic calculated as an average of daily trading performance multiplied by the number of trading days per year. /// </summary> /// <param name="performance">Dictionary collection of double performance values</param> /// <param name="tradingDaysPerYear">Trading days per year for the assets in portfolio</param> /// <remarks>May be unaccurate for forex algorithms with more trading days in a year</remarks> /// <returns>Double annual performance percentage</returns> public static double AnnualPerformance(List<double> performance, double tradingDaysPerYear = 252) { return Math.Pow((performance.Average() + 1), tradingDaysPerYear) - 1; } /// <summary> /// Annualized variance statistic calculation using the daily performance variance and trading days per year. /// </summary> /// <param name="performance"></param> /// <param name="tradingDaysPerYear"></param> /// <remarks>Invokes the variance extension in the MathNet Statistics class</remarks> /// <returns>Annual variance value</returns> public static double AnnualVariance(List<double> performance, double tradingDaysPerYear = 252) { return (performance.Variance())*tradingDaysPerYear; } /// <summary> /// Annualized standard deviation /// </summary> /// <param name="performance">Collection of double values for daily performance</param> /// <param name="tradingDaysPerYear">Number of trading days for the assets in portfolio to get annualize standard deviation.</param> /// <remarks> /// Invokes the variance extension in the MathNet Statistics class. /// Feasibly the trading days per year can be fetched from the dictionary of performance which includes the date-times to get the range; if is more than 1 year data. /// </remarks> /// <returns>Value for annual standard deviation</returns> public static double AnnualStandardDeviation(List<double> performance, double tradingDaysPerYear = 252) { return Math.Sqrt(performance.Variance() * tradingDaysPerYear); } /// <summary> /// Algorithm "beta" statistic - the covariance between the algorithm and benchmark performance, divided by benchmark's variance /// </summary> /// <param name="algoPerformance">Collection of double values for algorithm daily performance.</param> /// <param name="benchmarkPerformance">Collection of double benchmark daily performance values.</param> /// <remarks>Invokes the variance and covariance extensions in the MathNet Statistics class</remarks> /// <returns>Value for beta</returns> public static double Beta(List<double> algoPerformance, List<double> benchmarkPerformance) { return algoPerformance.Covariance(benchmarkPerformance) / benchmarkPerformance.Variance(); } /// <summary> /// Algorithm "Alpha" statistic - abnormal returns over the risk free rate and the relationshio (beta) with the benchmark returns. /// </summary> /// <param name="algoPerformance">Collection of double algorithm daily performance values.</param> /// <param name="benchmarkPerformance">Collection of double benchmark daily performance values.</param> /// <param name="riskFreeRate">Risk free rate of return for the T-Bonds.</param> /// <returns>Value for alpha</returns> public static double Alpha(List<double> algoPerformance, List<double> benchmarkPerformance, double riskFreeRate) { return AnnualPerformance(algoPerformance) - (riskFreeRate + Beta(algoPerformance, benchmarkPerformance) * (AnnualPerformance(benchmarkPerformance) - riskFreeRate)); } /// <summary> /// Tracking error volatility (TEV) statistic - a measure of how closely a portfolio follows the index to which it is benchmarked /// </summary> /// <remarks>If algo = benchmark, TEV = 0</remarks> /// <param name="algoPerformance">Double collection of algorithm daily performance values</param> /// <param name="benchmarkPerformance">Double collection of benchmark daily performance values</param> /// <param name="tradingDaysPerYear">Number of trading days per year</param> /// <returns>Value for tracking error</returns> public static double TrackingError(List<double> algoPerformance, List<double> benchmarkPerformance, double tradingDaysPerYear = 252) { // Un-equal lengths will blow up other statistics, but this will handle the case here if (algoPerformance.Count() != benchmarkPerformance.Count()) { return 0.0; } var performanceDifference = new List<double>(); for (var i = 0; i < algoPerformance.Count(); i++) { performanceDifference.Add(algoPerformance[i] - benchmarkPerformance[i]); } return Math.Sqrt(AnnualVariance(performanceDifference, tradingDaysPerYear)); } /// <summary> /// Information ratio - risk adjusted return /// </summary> /// <param name="algoPerformance">Collection of doubles for the daily algorithm daily performance</param> /// <param name="benchmarkPerformance">Collection of doubles for the benchmark daily performance</param> /// <remarks>(risk = tracking error volatility, a volatility measures that considers the volatility of both algo and benchmark)</remarks> /// <seealso cref="TrackingError"/> /// <returns>Value for information ratio</returns> public static double InformationRatio(List<double> algoPerformance, List<double> benchmarkPerformance) { return (AnnualPerformance(algoPerformance) - AnnualPerformance(benchmarkPerformance)) / (TrackingError(algoPerformance, benchmarkPerformance)); } /// <summary> /// Sharpe ratio with respect to risk free rate: measures excess of return per unit of risk. /// </summary> /// <remarks>With risk defined as the algorithm's volatility</remarks> /// <param name="algoPerformance">Collection of double values for the algorithm daily performance</param> /// <param name="riskFreeRate"></param> /// <returns>Value for sharpe ratio</returns> public static double SharpeRatio(List<double> algoPerformance, double riskFreeRate) { return (AnnualPerformance(algoPerformance) - riskFreeRate) / (AnnualStandardDeviation(algoPerformance)); } /// <summary> /// Treynor ratio statistic is a measurement of the returns earned in excess of that which could have been earned on an investment that has no diversifiable risk /// </summary> /// <param name="algoPerformance">Collection of double algorithm daily performance values</param> /// <param name="benchmarkPerformance">Collection of double benchmark daily performance values</param> /// <param name="riskFreeRate">Risk free rate of return</param> /// <returns>double Treynor ratio</returns> public static double TreynorRatio(List<double> algoPerformance, List<double> benchmarkPerformance, double riskFreeRate) { return (AnnualPerformance(algoPerformance) - riskFreeRate) / (Beta(algoPerformance, benchmarkPerformance)); } /// <summary> /// Helper method to calculate the probabilistic sharpe ratio /// </summary> /// <param name="listPerformance">The list of algorithm performance values</param> /// <param name="benchmarkSharpeRatio">The benchmark sharpe ratio to use</param> /// <returns>Probabilistic Sharpe Ratio</returns> public static double ProbabilisticSharpeRatio(List<double> listPerformance, double benchmarkSharpeRatio) { var observedSharpeRatio = ObservedSharpeRatio(listPerformance); var skewness = listPerformance.Skewness(); var kurtosis = listPerformance.Kurtosis(); var operandA = skewness * observedSharpeRatio; var operandB = ((kurtosis - 1) / 4) * (Math.Pow(observedSharpeRatio, 2)); // Calculated standard deviation of point estimate var estimateStandardDeviation = Math.Pow((1 - operandA + operandB) / (listPerformance.Count - 1), 0.5); if (double.IsNaN(estimateStandardDeviation)) { return 0; } // Calculate PSR(benchmark) var value = estimateStandardDeviation.IsNaNOrZero() ? 0 : (observedSharpeRatio - benchmarkSharpeRatio) / estimateStandardDeviation; return (new Normal()).CumulativeDistribution(value); } /// <summary> /// Calculates the observed sharpe ratio /// </summary> /// <param name="listPerformance">The performance samples to use</param> /// <returns>The observed sharpe ratio</returns> public static double ObservedSharpeRatio(List<double> listPerformance) { var performanceAverage = listPerformance.Average(); var standardDeviation = listPerformance.StandardDeviation(); // we don't annualize it return standardDeviation.IsNaNOrZero() ? 0 : performanceAverage / standardDeviation; } /// <summary> /// Calculate the drawdown between a high and current value /// </summary> /// <param name="current">Current value</param> /// <param name="high">Latest maximum</param> /// <param name="roundingDecimals">Digits to round the result too</param> /// <returns>Drawdown percentage</returns> public static decimal DrawdownPercent(decimal current, decimal high, int roundingDecimals = 2) { if (high == 0) { throw new ArgumentException("High value must not be 0"); } var drawdownPercentage = ((current / high) - 1) * 100; return Math.Round(drawdownPercentage, roundingDecimals); } } // End of Statistics } // End of Namespace
// 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.IO; using System.Runtime.Serialization; // For SR using System.Text; namespace System.Xml { // This wrapper does not support seek. // Constructors consume/emit byte order mark. // Supports: UTF-8, Unicode, BigEndianUnicode // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. It can be done, it would just mean more buffers. // ASSUMPTION (Microsoft): The byte buffer is large enough to hold the declaration // ASSUMPTION (Microsoft): The buffer manipulation methods (FillBuffer/Compare/etc.) will only be used to parse the declaration // during construction. internal class EncodingStreamWrapper : Stream { private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly UTF8Encoding s_safeUTF8 = new UTF8Encoding(false, false); private static readonly UnicodeEncoding s_safeUTF16 = new UnicodeEncoding(false, false, false); private static readonly UnicodeEncoding s_safeBEUTF16 = new UnicodeEncoding(true, false, false); private static readonly UTF8Encoding s_validatingUTF8 = new UTF8Encoding(false, true); private static readonly UnicodeEncoding s_validatingUTF16 = new UnicodeEncoding(false, false, true); private static readonly UnicodeEncoding s_validatingBEUTF16 = new UnicodeEncoding(true, false, true); private const int BufferLength = 128; // UTF-8 is fastpath, so that's how these are stored // Compare methods adapt to Unicode. private static readonly byte[] s_encodingAttr = new byte[] { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g' }; private static readonly byte[] s_encodingUTF8 = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'8' }; private static readonly byte[] s_encodingUnicode = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6' }; private static readonly byte[] s_encodingUnicodeLE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'l', (byte)'e' }; private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; private SupportedEncoding _encodingCode; private Encoding _encoding; private readonly Encoder _enc; private readonly Decoder _dec; private readonly bool _isReading; private readonly Stream _stream; private char[] _chars; private byte[] _bytes; private int _byteOffset; private int _byteCount; private readonly byte[] _byteBuffer = new byte[1]; // Reading constructor public EncodingStreamWrapper(Stream stream, Encoding encoding) { try { _isReading = true; _stream = stream; // Decode the expected encoding SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); // Get the byte order mark so we can determine the encoding // May want to try to delay allocating everything until we know the BOM SupportedEncoding declEnc = ReadBOMEncoding(encoding == null); // Check that the expected encoding matches the decl encoding. if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); // Fastpath: UTF-8 BOM if (declEnc == SupportedEncoding.UTF8) { // Fastpath: UTF-8 BOM, No declaration FillBuffer(2); if (_bytes[_byteOffset + 1] != '?' || _bytes[_byteOffset] != '<') { return; } FillBuffer(BufferLength); CheckUTF8DeclarationEncoding(_bytes, _byteOffset, _byteCount, declEnc, expectedEnc); } else { // Convert to UTF-8 EnsureBuffers(); FillBuffer((BufferLength - 1) * 2); SetReadDocumentEncoding(declEnc); CleanupCharBreak(); int count = _encoding.GetChars(_bytes, _byteOffset, _byteCount, _chars, 0); _byteOffset = 0; _byteCount = s_validatingUTF8.GetBytes(_chars, 0, count, _bytes, 0); // Check for declaration if (_bytes[1] == '?' && _bytes[0] == '<') { CheckUTF8DeclarationEncoding(_bytes, 0, _byteCount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } } } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); _encodingCode = e; _encoding = GetEncoding(e); } private static Encoding GetEncoding(SupportedEncoding e) => e switch { SupportedEncoding.UTF8 => s_validatingUTF8, SupportedEncoding.UTF16LE => s_validatingUTF16, SupportedEncoding.UTF16BE => s_validatingBEUTF16, _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static Encoding GetSafeEncoding(SupportedEncoding e) => e switch { SupportedEncoding.UTF8 => s_safeUTF8, SupportedEncoding.UTF16LE => s_safeUTF16, SupportedEncoding.UTF16BE => s_safeBEUTF16, _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static string GetEncodingName(SupportedEncoding enc) => enc switch { SupportedEncoding.UTF8 => "utf-8", SupportedEncoding.UTF16LE => "utf-16LE", SupportedEncoding.UTF16BE => "utf-16BE", _ => throw new XmlException(SR.XmlEncodingNotSupported), }; private static SupportedEncoding GetSupportedEncoding(Encoding encoding) { if (encoding == null) return SupportedEncoding.None; else if (encoding.WebName == s_validatingUTF8.WebName) return SupportedEncoding.UTF8; else if (encoding.WebName == s_validatingUTF16.WebName) return SupportedEncoding.UTF16LE; else if (encoding.WebName == s_validatingBEUTF16.WebName) return SupportedEncoding.UTF16BE; else throw new XmlException(SR.XmlEncodingNotSupported); } // Writing constructor public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) { _isReading = false; _encoding = encoding; _stream = stream; // Set the encoding code _encodingCode = GetSupportedEncoding(encoding); if (_encodingCode != SupportedEncoding.UTF8) { EnsureBuffers(); _dec = s_validatingUTF8.GetDecoder(); _enc = _encoding.GetEncoder(); // Emit BOM if (emitBOM) { ReadOnlySpan<byte> bom = _encoding.Preamble; if (bom.Length > 0) _stream.Write(bom); } } } private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); int b3 = _stream.ReadByte(); int b4 = _stream.ReadByte(); // Premature end of stream if (b4 == -1) throw new XmlException(SR.UnexpectedEndOfFile); int preserve; SupportedEncoding e = ReadBOMEncoding((byte)b1, (byte)b2, (byte)b3, (byte)b4, notOutOfBand, out preserve); EnsureByteBuffer(); switch (preserve) { case 1: _bytes[0] = (byte)b4; break; case 2: _bytes[0] = (byte)b3; _bytes[1] = (byte)b4; break; case 4: _bytes[0] = (byte)b1; _bytes[1] = (byte)b2; _bytes[2] = (byte)b3; _bytes[3] = (byte)b4; break; } _byteCount = preserve; return e; } private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve) { SupportedEncoding e = SupportedEncoding.UTF8; // Default preserve = 0; if (b1 == '<' && b2 != 0x00) // UTF-8, no BOM { e = SupportedEncoding.UTF8; preserve = 4; } else if (b1 == 0xFF && b2 == 0xFE) // UTF-16 little endian { e = SupportedEncoding.UTF16LE; preserve = 2; } else if (b1 == 0xFE && b2 == 0xFF) // UTF-16 big endian { e = SupportedEncoding.UTF16BE; preserve = 2; } else if (b1 == 0x00 && b2 == '<') // UTF-16 big endian, no BOM { e = SupportedEncoding.UTF16BE; if (notOutOfBand && (b3 != 0x00 || b4 != '?')) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == '<' && b2 == 0x00) // UTF-16 little endian, no BOM { e = SupportedEncoding.UTF16LE; if (notOutOfBand && (b3 != '?' || b4 != 0x00)) throw new XmlException(SR.XmlDeclMissing); preserve = 4; } else if (b1 == 0xEF && b2 == 0xBB) // UTF8 with BOM { // Encoding error if (notOutOfBand && b3 != 0xBF) throw new XmlException(SR.XmlBadBOM); preserve = 1; } else // Assume UTF8 { preserve = 4; } return e; } private void FillBuffer(int count) { count -= _byteCount; while (count > 0) { int read = _stream.Read(_bytes, _byteOffset + _byteCount, count); if (read == 0) break; _byteCount += read; count -= read; } } private void EnsureBuffers() { EnsureByteBuffer(); if (_chars == null) _chars = new char[BufferLength]; } private void EnsureByteBuffer() { if (_bytes != null) return; _bytes = new byte[BufferLength * 4]; _byteOffset = 0; _byteCount = 0; } private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc) { byte quot = 0; int encEq = -1; int max = offset + Math.Min(count, BufferLength); // Encoding should be second "=", abort at first "?" int i = 0; int eq = 0; for (i = offset + 2; i < max; i++) // Skip the "<?" so we don't get caught by the first "?" { if (quot != 0) { if (buffer[i] == quot) { quot = 0; } continue; } if (buffer[i] == (byte)'\'' || buffer[i] == (byte)'"') { quot = buffer[i]; } else if (buffer[i] == (byte)'=') { if (eq == 1) { encEq = i; break; } eq++; } else if (buffer[i] == (byte)'?') // Not legal character in a decl before second "=" { break; } } // No encoding found if (encEq == -1) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } if (encEq < 28) // Earliest second "=" can appear throw new XmlException(SR.XmlMalformedDecl); // Back off whitespace for (i = encEq - 1; IsWhitespace(buffer[i]); i--) ; // Check for encoding attribute if (!Compare(s_encodingAttr, buffer, i - s_encodingAttr.Length + 1)) { if (e != SupportedEncoding.UTF8 && expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); return; } // Move ahead of whitespace for (i = encEq + 1; i < max && IsWhitespace(buffer[i]); i++) ; // Find the quotes if (buffer[i] != '\'' && buffer[i] != '"') throw new XmlException(SR.XmlMalformedDecl); quot = buffer[i]; int q = i; for (i = q + 1; buffer[i] != quot && i < max; ++i) ; if (buffer[i] != quot) throw new XmlException(SR.XmlMalformedDecl); int encStart = q + 1; int encCount = i - encStart; // lookup the encoding SupportedEncoding declEnc = e; if (encCount == s_encodingUTF8.Length && CompareCaseInsensitive(s_encodingUTF8, buffer, encStart)) { declEnc = SupportedEncoding.UTF8; } else if (encCount == s_encodingUnicodeLE.Length && CompareCaseInsensitive(s_encodingUnicodeLE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16LE; } else if (encCount == s_encodingUnicodeBE.Length && CompareCaseInsensitive(s_encodingUnicodeBE, buffer, encStart)) { declEnc = SupportedEncoding.UTF16BE; } else if (encCount == s_encodingUnicode.Length && CompareCaseInsensitive(s_encodingUnicode, buffer, encStart)) { if (e == SupportedEncoding.UTF8) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), s_safeUTF8.GetString(s_encodingUTF8, 0, s_encodingUTF8.Length)); } else { ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } if (e != declEnc) ThrowEncodingMismatch(s_safeUTF8.GetString(buffer, encStart, encCount), e); } private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] == buffer[offset + i]) continue; if (key[i] != char.ToLowerInvariant((char)buffer[offset + i])) return false; } return true; } private static bool Compare(byte[] key, byte[] buffer, int offset) { for (int i = 0; i < key.Length; i++) { if (key[i] != buffer[offset + i]) return false; } return true; } private static bool IsWhitespace(byte ch) { return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r'; } internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) { if (count < 4) throw new XmlException(SR.UnexpectedEndOfFile); try { int preserve; ArraySegment<byte> seg; SupportedEncoding expectedEnc = GetSupportedEncoding(encoding); SupportedEncoding declEnc = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve); if (expectedEnc != SupportedEncoding.None && expectedEnc != declEnc) ThrowExpectedEncodingMismatch(expectedEnc, declEnc); offset += 4 - preserve; count -= 4 - preserve; // Fastpath: UTF-8 char[] chars; byte[] bytes; Encoding localEnc; if (declEnc == SupportedEncoding.UTF8) { // Fastpath: No declaration if (buffer[offset + 1] != '?' || buffer[offset] != '<') { seg = new ArraySegment<byte>(buffer, offset, count); return seg; } CheckUTF8DeclarationEncoding(buffer, offset, count, declEnc, expectedEnc); seg = new ArraySegment<byte>(buffer, offset, count); return seg; } // Convert to UTF-8 localEnc = GetSafeEncoding(declEnc); int inputCount = Math.Min(count, BufferLength * 2); chars = new char[localEnc.GetMaxCharCount(inputCount)]; int ccount = localEnc.GetChars(buffer, offset, inputCount, chars, 0); bytes = new byte[s_validatingUTF8.GetMaxByteCount(ccount)]; int bcount = s_validatingUTF8.GetBytes(chars, 0, ccount, bytes, 0); // Check for declaration if (bytes[1] == '?' && bytes[0] == '<') { CheckUTF8DeclarationEncoding(bytes, 0, bcount, declEnc, expectedEnc); } else { // Declaration required if no out-of-band encoding if (expectedEnc == SupportedEncoding.None) throw new XmlException(SR.XmlDeclarationRequired); } seg = new ArraySegment<byte>(s_validatingUTF8.GetBytes(GetEncoding(declEnc).GetChars(buffer, offset, count))); return seg; } catch (DecoderFallbackException e) { throw new XmlException(SR.XmlInvalidBytes, e); } } private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc) { throw new XmlException(SR.Format(SR.XmlExpectedEncoding, GetEncodingName(expEnc), GetEncodingName(actualEnc))); } private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc) { ThrowEncodingMismatch(declEnc, GetEncodingName(enc)); } private static void ThrowEncodingMismatch(string declEnc, string docEnc) { throw new XmlException(SR.Format(SR.XmlEncodingMismatch, declEnc, docEnc)); } // This stream wrapper does not support duplex public override bool CanRead { get { if (!_isReading) return false; return _stream.CanRead; } } // The encoding conversion and buffering breaks seeking. public override bool CanSeek { get { return false; } } // This stream wrapper does not support duplex public override bool CanWrite { get { if (_isReading) return false; return _stream.CanWrite; } } // The encoding conversion and buffering breaks seeking. public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { if (_stream.CanWrite) { Flush(); } _stream.Dispose(); base.Dispose(disposing); } public override void Flush() { _stream.Flush(); } public override int ReadByte() { if (_byteCount == 0 && _encodingCode == SupportedEncoding.UTF8) return _stream.ReadByte(); if (Read(_byteBuffer, 0, 1) == 0) return -1; return _byteBuffer[0]; } public override int Read(byte[] buffer, int offset, int count) { try { if (_byteCount == 0) { if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); // Check for end of stream if (_byteCount == 0) return 0; // Fix up incomplete chars CleanupCharBreak(); // Change encoding int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) count = _byteCount; Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; } catch (DecoderFallbackException ex) { throw new XmlException(SR.XmlInvalidBytes, ex); } } private void CleanupCharBreak() { int max = _byteOffset + _byteCount; // Read on 2 byte boundaries if ((_byteCount % 2) != 0) { int b = _stream.ReadByte(); if (b < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b; _byteCount++; } // Don't cut off a surrogate character int w; if (_encodingCode == SupportedEncoding.UTF16LE) { w = _bytes[max - 2] + (_bytes[max - 1] << 8); } else { w = _bytes[max - 1] + (_bytes[max - 2] << 8); } if ((w & 0xDC00) != 0xDC00 && w >= 0xD800 && w <= 0xDBFF) // First 16-bit number of surrogate pair { int b1 = _stream.ReadByte(); int b2 = _stream.ReadByte(); if (b2 < 0) throw new XmlException(SR.UnexpectedEndOfFile); _bytes[max++] = (byte)b1; _bytes[max++] = (byte)b2; _byteCount += 2; } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void WriteByte(byte b) { if (_encodingCode == SupportedEncoding.UTF8) { _stream.WriteByte(b); return; } _byteBuffer[0] = b; Write(_byteBuffer, 0, 1); } public override void Write(byte[] buffer, int offset, int count) { // Optimize UTF-8 case if (_encodingCode == SupportedEncoding.UTF8) { _stream.Write(buffer, offset, count); return; } while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false); _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; } } // Delegate properties public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { return _stream.Length; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // Delegate methods public override void SetLength(long value) { throw new NotSupportedException(); } } // Add format exceptions // Do we need to modify the stream position/Seek to account for the buffer? // ASSUMPTION (Microsoft): This class will only be used for EITHER reading OR writing. }
//================================================================== // C# OpenGL Framework (http://www.csharpopenglframework.com) // Copyright (c) 2005-2006 devDept (http://www.devdept.com) // All rights reserved. // // For more information on this program, please visit: // http://www.csharpopenglframework.com // // For licensing information, please visit: // http://www.csharpopenglframework.com/licensing.html //================================================================== using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using OpenGL; using System.Runtime.InteropServices; using System.Drawing.Imaging; using System.Collections; using System.Globalization; namespace openglFramework { public partial class OpenGLControl : UserControl { protected Context renderingContext; public ArrayList entities = new ArrayList(); public ArrayList labels = new ArrayList(); // Lights Settings float[] ambientLight = {0.10f, 0.10f, 0.10f, 1.00f}; float[] mainLightDiffuse = {0.75f, 0.75f, 0.75f, 1.00f}; float[] sideLightDiffuse = {0.20f, 0.20f, 0.20f, 1.00f}; float[] mainLightPos = { -50.0f, +150.0f, +100.0f, 0.0f}; // x z y float[] sideLightPos = {+100.0f, -50.0f, +100.0f, 0.0f}; // x z y float[] specular = {0.75f, 0.75f, 0.75f, 1.00f}; float[] specref = {1.00f, 1.00f, 1.00f, 1.00f}; // Focus bool hasFocus = false; // Model extents protected float[] globalMin = new float[3]; protected float[] globalMax = new float[3]; // Model size protected float xSize; protected float ySize; protected float zSize; protected static float openglVersion; protected int stencilBits; protected bool lighting; protected bool heavyModel = false; // bounding rectangle (parallel projection) protected float globalLeft; protected float globalBottom; protected float globalRight; protected float globalTop; // true zooming TM protected RectangleF viewportRect, prevZoomRect, zoomRect; protected bool firstRedraw = true; public OpenGLControl() { InitializeStyles(); InitializeComponent(); backgroundTopColor = Color.FromArgb(0xff, 0x9e, 0x9b, 0x92); backgroundBottomColor = Color.FromArgb(0xff, 0xe3, 0xe1, 0xd4); renderingContext = new Context(this, 32, 16, 8); OpenGLSetup(); zoomCursor = new Cursor(GetType(), "zoom.cur"); panCursor = new Cursor(GetType(), "pan.cur"); rotateCursor = new Cursor(GetType(), "rotate.cur"); xUcsLabel = new Label("X"); yUcsLabel = new Label("Y"); zUcsLabel = new Label("Z"); originLabel = new Label("Origin"); cameraQuat = new Quaternion(0, 0, 0, 1.0f); entities = new ArrayList(); openglVersion = GetOpenGLVersion(); int[] stencil = new int[1]; gl.GetIntegerv(gl.STENCIL_BITS, stencil); stencilBits = stencil[0]; Console.WriteLine("Version : " + gl.GetString(gl.VERSION)); Console.WriteLine("Renderer : " + gl.GetString(gl.RENDERER)); Console.WriteLine("Vendor : " + gl.GetString(gl.VENDOR)); Console.WriteLine("Stencil bits : " + stencilBits); //zoomRect.X = 10; //zoomRect.Y = 10; //zoomRect.Width = 600; //zoomRect.Height = 600; } #region Properties public shadingType ShadingMode { get { return renderMode; } set { renderMode = value; } } public projectionType ProjectionMode { get { return projectionMode; } set { projectionMode = value; Invalidate(); } } public float FieldOfView { get { return fieldOfView; } set { fieldOfView = value; Invalidate(); } } public static float OpenglVersion { get { return OpenGLControl.openglVersion; } } [CategoryAttribute("Lighting")] public float[] AmbientLight { get { return ambientLight; } set { ambientLight = value; Invalidate(); } } [CategoryAttribute("Lighting")] public float[] MainLightDiffuse { get { return mainLightDiffuse; } set { mainLightDiffuse = value; Invalidate(); } } [CategoryAttribute("Lighting")] public float[] SideLightDiffuse { get { return sideLightDiffuse; } set { sideLightDiffuse = value; Invalidate(); } } public bool HeavyModel { get { return heavyModel; } } #endregion #region Events protected override void OnPaint(PaintEventArgs e) { if (this.DesignMode) { e.Graphics.Clear(this.BackColor); e.Graphics.Flush(); return; } if (renderingContext.DC == 0 || renderingContext.RC == 0) { MessageBox.Show("No device or rendering context available!"); return; } base.OnPaint(e); int errorCode = gl.NO_ERROR; // The GL error code errorCode = gl.GetError(); if (errorCode != gl.NO_ERROR) { switch (errorCode) { case gl.INVALID_ENUM: MessageBox.Show("GL_INVALID_ENUM - An unacceptable value has been specified for an enumerated argument. The offending function has been ignored.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; case gl.INVALID_VALUE: MessageBox.Show("GL_INVALID_VALUE - A numeric argument is out of range. The offending function has been ignored.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; case gl.INVALID_OPERATION: MessageBox.Show("GL_INVALID_OPERATION - The specified operation is not allowed in the current state. The offending function has been ignored.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; case gl.STACK_OVERFLOW: MessageBox.Show("GL_STACK_OVERFLOW - This function would cause a stack overflow. The offending function has been ignored.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; case gl.STACK_UNDERFLOW: MessageBox.Show("GL_STACK_UNDERFLOW - This function would cause a stack underflow. The offending function has been ignored.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; case gl.OUT_OF_MEMORY: MessageBox.Show("GL_OUT_OF_MEMORY - There is not enough memory left to execute the function. The state of OpenGL has been left undefined.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; default: MessageBox.Show("Unknown GL error. This should never happen.", "OpenGL Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); break; } } } protected override void OnPaintBackground(PaintEventArgs e) { } #endregion #region Setup protected virtual void OpenGLSetup() { gl.ClearColor(1, 1, 1, 1); gl.ShadeModel(gl.SMOOTH); gl.FrontFace(gl.CCW); // Correct illumination of the inside of the model gl.LightModeli(gl.LIGHT_MODEL_TWO_SIDE, (BackFaceCulling == false) ? gl.TRUE : gl.FALSE); // Setup and enable main light gl.Lightfv(gl.LIGHT0, gl.AMBIENT, ambientLight); gl.Lightfv(gl.LIGHT0, gl.DIFFUSE, mainLightDiffuse); gl.Lightfv(gl.LIGHT0, gl.SPECULAR, specular); gl.Lightfv(gl.LIGHT0, gl.POSITION, mainLightPos); gl.Enable( gl.LIGHT0); // Setup and enable side light gl.Lightfv(gl.LIGHT1, gl.AMBIENT, ambientLight); gl.Lightfv(gl.LIGHT1, gl.DIFFUSE, sideLightDiffuse); gl.Lightfv(gl.LIGHT1, gl.POSITION, sideLightPos); gl.Enable( gl.LIGHT1); // Enable color tracking gl.Enable(gl.COLOR_MATERIAL); // Set Material properties to follow glColor values gl.ColorMaterial(gl.FRONT_AND_BACK, gl.AMBIENT_AND_DIFFUSE); // All materials hereafter have full specular reflectivity // with a high shine gl.Materialfv(gl.FRONT, gl.SPECULAR, specref); gl.Materiali (gl.FRONT, gl.SHININESS, 128); FontMapping(); quadric = glu.NewQuadric(); glu.QuadricDrawStyle(quadric, glu.FILL); glu.QuadricNormals (quadric, gl.SMOOTH); glu.QuadricTexture (quadric, gl.TRUE); texNames = new uint[8]; // Generate 8 texture names gl.GenTextures(8, texNames); LoadTextureFromResources(texNames[0], "origin.jpg", gl.LINEAR); } #region dllimports [DllImport("gdi32.dll", EntryPoint = "SelectObject")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr bmp); #endregion protected void FontMapping() { Graphics g = this.CreateGraphics(); IntPtr hdc = new IntPtr(); hdc = g.GetHdc(); Font font = new Font("Tahoma", 8.25f); SelectObject(hdc, font.ToHfont()); if (wgl.UseFontBitmaps(hdc, 0, 255, 1000) == false) Console.WriteLine("wglUseFontBitmaps failed: font"); Font boldFont = new Font("Tahoma", 8.25f, FontStyle.Bold); SelectObject(hdc, boldFont.ToHfont()); if (wgl.UseFontBitmaps(hdc, 0, 255, 2000) == false) Console.WriteLine("wglUseFontBitmaps failed: boldFont"); Font welcomeFont = new Font("Georgia", 14.0f, FontStyle.Bold); SelectObject(hdc, welcomeFont.ToHfont()); if (wgl.UseFontBitmaps(hdc, 0, 255, 3000) == false) Console.WriteLine("wglUseFontBitmaps failed: welcomeFont"); g.ReleaseHdc(hdc); } private void ViewportSetup() { int w = this.Width; int h = this.Height; if (h == 0) h = 1; // Set Viewport to window dimensions gl.Viewport(0, 0, w, h); aspect = (float)w / (float)h; } protected void SceneSetup2D(float zNear, float zFar) { gl.Enable(gl.LIGHT0); gl.Enable(gl.LIGHT1); gl.MatrixMode(gl.PROJECTION); gl.LoadIdentity(); gl.Ortho(0, this.Width, 0, this.Height, zNear, zFar); } protected void SceneSetupOrtho3D() { gl.Enable(gl.LIGHT0); gl.Disable(gl.LIGHT1); gl.MatrixMode(gl.PROJECTION); gl.LoadIdentity(); ApplyZoom(); gl.Ortho(-this.Width/2, this.Width/2, -this.Height/2, this.Height/2, zNearOrtho, zFarOrtho); } protected void SceneSetupPerispective3D() { gl.Enable(gl.LIGHT0); gl.Disable(gl.LIGHT1); gl.MatrixMode(gl.PROJECTION); gl.LoadIdentity(); ApplyZoom(); glu.Perspective(fieldOfView, aspect, zNearPerspective, zFarPerspective); } void ApplyZoom() { int[] viewport = new int[4]; gl.GetIntegerv(gl.VIEWPORT, viewport); viewportRect.X = viewport[0]; viewportRect.Y = viewport[1]; viewportRect.Width = viewport[2]; viewportRect.Height = viewport[3]; if (firstRedraw) { zoomRect = viewportRect; firstRedraw = false; } float widthScale = viewportRect.Width / zoomRect.Width; float heightScale = viewportRect.Height / zoomRect.Height; if (widthScale < heightScale) { float prevHeight = zoomRect.Height; zoomRect.Height = zoomRect.Width / aspect; zoomRect.Y -= (zoomRect.Height - prevHeight) / 2; } else { float prevWidth = zoomRect.Width; zoomRect.Width = zoomRect.Height * aspect; zoomRect.X -= (zoomRect.Width - prevWidth) / 2; } if (zoomRect.Width < 0.1f) { zoomRect.Width = 0.1f; zoomRect.Height = zoomRect.Width / aspect; } if (zoomRect.Height < 0.1f) { zoomRect.Height = 0.1f; zoomRect.Width = zoomRect.Height * aspect; } glu.PickMatrix(zoomRect.X + zoomRect.Width / 2, zoomRect.Y + zoomRect.Height / 2, zoomRect.Width, zoomRect.Height, viewport); prevZoomRect = zoomRect; } // param can be gl.LINEAR or gl.NEAREST protected void LoadTextureFromResources(uint id, string name, int param) { gl.Enable(gl.TEXTURE_2D); using (Bitmap bitmap = new Bitmap(this.GetType(), name)) { bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY); Rectangle rectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); BitmapData bitmapData = bitmap.LockBits(rectangle, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb); gl.BindTexture(gl.TEXTURE_2D, id); gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, param); gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, param); gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGB8, bitmapData.Width, bitmapData.Height, 0, gl.BGR_EXT, gl.UNSIGNED_BYTE, bitmapData.Scan0); bitmap.UnlockBits(bitmapData); } gl.Disable(gl.TEXTURE_2D); } #endregion #region Focus handling protected override void OnLostFocus(EventArgs e) { hasFocus = false; action = actionType.None; Invalidate(); } protected override void OnGotFocus(EventArgs e) { hasFocus = true; Invalidate(); } #endregion #region Zoom/Pan/Rotate #endregion /// <summary> /// Make the OpenGLControl rendering context current, /// used when there are more OpenGLControls on the same form. /// </summary> public void MakeRenderingContextCurrent() { renderingContext.MakeCurrent(); } public float GetOpenGLVersion() { string versionString1 = gl.GetString(gl.VERSION); string versionString2 = versionString1.Substring(0, 3); float version = 0.0f; try { version = (float) Convert.ToDouble(versionString2); } catch (Exception ex) { version = 1.0f; Console.WriteLine(ex.Message); } return version; } private void InitializeStyles() { this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false); this.SetStyle(ControlStyles.Opaque, true); this.SetStyle(ControlStyles.ResizeRedraw, true); this.SetStyle(ControlStyles.UserPaint, true); } protected override CreateParams CreateParams { get { Int32 CS_VREDRAW = 0x1; Int32 CS_HREDRAW = 0x2; Int32 CS_OWNDC = 0x20; CreateParams cp = base.CreateParams; cp.ClassStyle = cp.ClassStyle | CS_VREDRAW | CS_HREDRAW | CS_OWNDC; return cp; } } public void SetZoomCursor() { if (zoomButtonDown) this.Cursor = zoomCursor; else this.Cursor = Cursors.Arrow; } public void SetPanCursor() { if (panButtonDown) this.Cursor = panCursor; else this.Cursor = Cursors.Arrow; } public void SetRotateCursor() { if (rotateButtonDown) this.Cursor = rotateCursor; else this.Cursor = Cursors.Arrow; } public void CheckModelWeight() { if (entities.Count > 512) heavyModel = true; } void DrawBoundingRect() { gl.PushMatrix(); gl.Color3ub(0xff, 0, 0); gl.LineStipple(1, 0x0808); gl.Enable(gl.LINE_STIPPLE); gl.Begin(gl.LINE_LOOP); gl.Vertex2f( globalLeft, globalBottom); gl.Vertex2f(globalRight, globalBottom); gl.Vertex2f(globalRight, globalTop); gl.Vertex2f( globalLeft, globalTop); gl.End(); gl.Disable(gl.LINE_STIPPLE); gl.PopMatrix(); } public void UpdateNormals() { foreach (Entity ent in entities) if (ent.GetType() == typeof(TriangularFace)) ent.ScaleNormal(scaleTo100); } protected void NormalizeBox(ref int x1, ref int y1, ref int x2, ref int y2) { int firstX; int firstY; int secondX; int secondY; firstX = Math.Min(x1, x2); secondX = Math.Max(x1, x2); firstY = Math.Min(y1, y2); secondY = Math.Max(y1, y2); x1 = firstX; y1 = firstY; x2 = secondX; y2 = secondY; } public virtual void ZoomFit() {} public virtual void ZoomWindow(int x1, int y1, int x2, int y2) {} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using Windows.Foundation; using Xunit; namespace Windows.UI.Xaml.Media.Media3D.Tests { public class Matrix3DTests { [Fact] public void Ctor_Default() { var matrix = new Matrix3D(); Assert.Equal(0, matrix.M11); Assert.Equal(0, matrix.M12); Assert.Equal(0, matrix.M13); Assert.Equal(0, matrix.M14); Assert.Equal(0, matrix.M21); Assert.Equal(0, matrix.M22); Assert.Equal(0, matrix.M23); Assert.Equal(0, matrix.M24); Assert.Equal(0, matrix.M31); Assert.Equal(0, matrix.M32); Assert.Equal(0, matrix.M33); Assert.Equal(0, matrix.M34); Assert.Equal(0, matrix.OffsetX); Assert.Equal(0, matrix.OffsetY); Assert.Equal(0, matrix.OffsetZ); Assert.Equal(0, matrix.M44); Assert.False(matrix.IsIdentity); } [Theory] [InlineData(-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, false, false)] [InlineData(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, false, false)] [InlineData(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, false, false)] [InlineData(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, true, true)] [InlineData(1, 2, 0, 0, 0, 1, 2, 0, 4, 0, 1, 2, 0, 4, 0, 1, false, true)] [InlineData(double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, false, true)] [InlineData(double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity, false, true)] [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, false, true)] public void Ctor_Values(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44, bool expectedIsIdentity, bool expectedHasInverse) { var matrix = new Matrix3D(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, offsetX, offsetY, offsetZ, m44); Assert.Equal(m11, matrix.M11); Assert.Equal(m12, matrix.M12); Assert.Equal(m13, matrix.M13); Assert.Equal(m14, matrix.M14); Assert.Equal(m21, matrix.M21); Assert.Equal(m22, matrix.M22); Assert.Equal(m23, matrix.M23); Assert.Equal(m24, matrix.M24); Assert.Equal(m31, matrix.M31); Assert.Equal(m32, matrix.M32); Assert.Equal(m33, matrix.M33); Assert.Equal(m34, matrix.M34); Assert.Equal(offsetX, matrix.OffsetX); Assert.Equal(offsetY, matrix.OffsetY); Assert.Equal(offsetZ, matrix.OffsetZ); Assert.Equal(m44, matrix.M44); Assert.Equal(expectedIsIdentity, matrix.IsIdentity); Assert.Equal(expectedHasInverse, matrix.HasInverse); } [Fact] public void Identity_Get_ReturnsExpected() { Matrix3D matrix = Matrix3D.Identity; Assert.Equal(1, matrix.M11); Assert.Equal(0, matrix.M12); Assert.Equal(0, matrix.M13); Assert.Equal(0, matrix.M14); Assert.Equal(0, matrix.M21); Assert.Equal(1, matrix.M22); Assert.Equal(0, matrix.M23); Assert.Equal(0, matrix.M24); Assert.Equal(0, matrix.M31); Assert.Equal(0, matrix.M32); Assert.Equal(1, matrix.M33); Assert.Equal(0, matrix.M34); Assert.Equal(0, matrix.OffsetX); Assert.Equal(0, matrix.OffsetY); Assert.Equal(0, matrix.OffsetZ); Assert.Equal(1, matrix.M44); Assert.True(matrix.IsIdentity); Assert.True(matrix.HasInverse); } public static IEnumerable<object[]> Values_TestData() { yield return new object[] { -1 }; yield return new object[] { 0 }; yield return new object[] { 1 }; yield return new object[] { float.NaN }; yield return new object[] { float.PositiveInfinity }; yield return new object[] { float.NegativeInfinity }; } [Theory] [MemberData(nameof(Values_TestData))] public void M11_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M11 = value }; Assert.Equal(value, matrix.M11); } [Theory] [MemberData(nameof(Values_TestData))] public void M12_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M12 = value }; Assert.Equal(value, matrix.M12); } [Theory] [MemberData(nameof(Values_TestData))] public void M13_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M13 = value }; Assert.Equal(value, matrix.M13); } [Theory] [MemberData(nameof(Values_TestData))] public void M14_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M14 = value }; Assert.Equal(value, matrix.M14); } [Theory] [MemberData(nameof(Values_TestData))] public void M21_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M21 = value }; Assert.Equal(value, matrix.M21); } [Theory] [MemberData(nameof(Values_TestData))] public void M22_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M22 = value }; Assert.Equal(value, matrix.M22); } [Theory] [MemberData(nameof(Values_TestData))] public void M23_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M23 = value }; Assert.Equal(value, matrix.M23); } [Theory] [MemberData(nameof(Values_TestData))] public void M24_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M24 = value }; Assert.Equal(value, matrix.M24); } [Theory] [MemberData(nameof(Values_TestData))] public void M31_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M31 = value }; Assert.Equal(value, matrix.M31); } [Theory] [MemberData(nameof(Values_TestData))] public void M32_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M32 = value }; Assert.Equal(value, matrix.M32); } [Theory] [MemberData(nameof(Values_TestData))] public void M33_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M33 = value }; Assert.Equal(value, matrix.M33); } [Theory] [MemberData(nameof(Values_TestData))] public void M34_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M34 = value }; Assert.Equal(value, matrix.M34); } [Theory] [MemberData(nameof(Values_TestData))] public void OffsetX_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { OffsetX = value }; Assert.Equal(value, matrix.OffsetX); } [Theory] [MemberData(nameof(Values_TestData))] public void OffsetY_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { OffsetY = value }; Assert.Equal(value, matrix.OffsetY); } [Theory] [MemberData(nameof(Values_TestData))] public void OffsetZ_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { OffsetZ = value }; Assert.Equal(value, matrix.OffsetZ); } [Theory] [MemberData(nameof(Values_TestData))] public void M44_Set_GetReturnsExpected(double value) { var matrix = new Matrix3D { M44 = value }; Assert.Equal(value, matrix.M44); } public static IEnumerable<object[]> Equals_TestData() { var matrix = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), true }; yield return new object[] { matrix, new Matrix3D(2, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 4, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 5, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 7, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 8, 8, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 9, 9, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 10, 10, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 11, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 12, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 13, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 14, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 15, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 16), false }; yield return new object[] { matrix, new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17), false }; yield return new object[] { Matrix3D.Identity, Matrix3D.Identity, true }; yield return new object[] { Matrix3D.Identity, new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), true }; yield return new object[] { Matrix3D.Identity, new Matrix3D(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), false }; yield return new object[] { Matrix3D.Identity, new object(), false }; yield return new object[] { Matrix3D.Identity, null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals_Object_ReturnsExpected(Matrix3D matrix, object other, bool expected) { Assert.Equal(expected, matrix.Equals(other)); if (other is Matrix3D otherMatrix) { Assert.Equal(expected, matrix.Equals(otherMatrix)); Assert.Equal(expected, matrix == otherMatrix); Assert.Equal(!expected, matrix != otherMatrix); Assert.Equal(expected, matrix.GetHashCode().Equals(otherMatrix.GetHashCode())); } } [Fact] public void Multiply_Matrices_ReturnsExpected() { var matrix1 = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); var matrix2 = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); Matrix3D result = matrix1 * matrix2; Assert.Equal(new Matrix3D(90, 100, 110, 120, 202, 228, 254, 280, 314, 356, 398, 440, 426, 484, 542, 600), result); Assert.False(result.IsIdentity); Assert.False(result.HasInverse); } [Fact] public void Invert_Affine_ReturnsExpected() { var matrix = new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); matrix.Invert(); Assert.Equal(new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), matrix); } [Fact] public void Invert_NonAffine_ReturnsExpected() { var matrix = new Matrix3D(1, 2, 0, 0, 0, 1, 2, 0, 4, 0, 1, 2, 0, 4, 0, 1); matrix.Invert(); string expected = ((IFormattable)new Matrix3D(0.515151515151515, -0.0606060606060606, 0.121212121212121, -0.242424242424242, 0.242424242424242, 0.0303030303030303, -0.0606060606060606, 0.121212121212121, -0.121212121212121, 0.484848484848485, 0.0303030303030303, -0.0606060606060606, -0.96969696969697, -0.121212121212121, 0.242424242424242, 0.515151515151515)).ToString("N2", null); Assert.Equal(expected, ((IFormattable)matrix).ToString("N2", null)); } [Fact] public void Invert_NotInvertible_ThrowsInvalidOperationException() { var matrix = new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); Assert.Throws<InvalidOperationException>(() => matrix.Invert()); } [Fact] public void Invert_AffineNotInvertible_ThrowsInvalidOperationException() { var matrix = new Matrix3D(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1); Assert.Throws<InvalidOperationException>(() => matrix.Invert()); } public static IEnumerable<object[]> ToString_TestData() { string cultureSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator; char decimalSeparator = cultureSeparator.Length > 0 && cultureSeparator[0] == ',' ? ';' : ','; yield return new object[] { Matrix3D.Identity, null, null, "Identity" }; yield return new object[] { Matrix3D.Identity, "InvalidFormat", CultureInfo.CurrentCulture, "Identity" }; yield return new object[] { new Matrix3D(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), null, null, $"1{decimalSeparator}2{decimalSeparator}3{decimalSeparator}4{decimalSeparator}5{decimalSeparator}6{decimalSeparator}7{decimalSeparator}8{decimalSeparator}9{decimalSeparator}10{decimalSeparator}11{decimalSeparator}12{decimalSeparator}13{decimalSeparator}14{decimalSeparator}15{decimalSeparator}16" }; var matrix = new Matrix3D(2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2, 2.2); var culture = new CultureInfo("en-US"); culture.NumberFormat.NumberDecimalSeparator = "|"; yield return new object[] { matrix, "abc", culture, "abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc,abc" }; yield return new object[] { matrix, "N4", culture, "2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000,2|2000" }; yield return new object[] { matrix, null, culture, "2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2,2|2" }; var commaCulture = new CultureInfo("en-US"); commaCulture.NumberFormat.NumberDecimalSeparator = ","; yield return new object[] { matrix, null, commaCulture, "2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2;2,2" }; yield return new object[] { matrix, null, null, $"{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}{decimalSeparator}{2.2.ToString()}" }; } [Theory] [MemberData(nameof(ToString_TestData))] public void ToString_Invoke_ReturnsExpected(Matrix3D matrix, string format, IFormatProvider formatProvider, string expected) { if (format == null) { if (formatProvider == null) { Assert.Equal(expected, matrix.ToString()); } Assert.Equal(expected, matrix.ToString(formatProvider)); } Assert.Equal(expected, ((IFormattable)matrix).ToString(format, formatProvider)); } } }
// 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.Runtime.InteropServices; using System.Security; namespace System.IO.Compression { /// <summary> /// This class provides declaration for constants and PInvokes as well as some basic tools for exposing the /// native CLRCompression.dll (effectively, ZLib) library to managed code. /// /// See also: How to choose a compression level (in comments to <code>CompressionLevel</code>. /// </summary> internal static partial class ZLibNative { // This is the NULL pointer for using with ZLib pointers; // we prefer it to IntPtr.Zero to mimic the definition of Z_NULL in zlib.h: internal static readonly IntPtr ZNullPtr = IntPtr.Zero; public enum FlushCode : int { NoFlush = 0, SyncFlush = 2, Finish = 4, } public enum ErrorCode : int { Ok = 0, StreamEnd = 1, StreamError = -2, DataError = -3, MemError = -4, BufError = -5, VersionError = -6 } /// <summary> /// <p>ZLib can accept any integer value between 0 and 9 (inclusive) as a valid compression level parameter: /// 1 gives best speed, 9 gives best compression, 0 gives no compression at all (the input data is simply copied a block at a time). /// <code>CompressionLevel.DefaultCompression</code> = -1 requests a default compromise between speed and compression /// (currently equivalent to level 6).</p> /// /// <p><strong>How to choose a compression level:</strong></p> /// /// <p>The names <code>NoCompression</code>, <code>BestSpeed</code>, <code>DefaultCompression</code> are taken over from the corresponding /// ZLib definitions, which map to our public NoCompression, Fastest, and Optimal respectively.</p> /// <p><em>Optimal Compression:</em></p> /// <p><code>ZLibNative.CompressionLevel compressionLevel = ZLibNative.CompressionLevel.DefaultCompression;</code> <br /> /// <code>int windowBits = 15; // or -15 if no headers required</code> <br /> /// <code>int memLevel = 8;</code> <br /> /// <code>ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;</code> </p> /// ///<p><em>Fastest compression:</em></p> ///<p><code>ZLibNative.CompressionLevel compressionLevel = ZLibNative.CompressionLevel.BestSpeed;</code> <br /> /// <code>int windowBits = 15; // or -15 if no headers required</code> <br /> /// <code>int memLevel = 8; </code> <br /> /// <code>ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;</code> </p> /// /// <p><em>No compression (even faster, useful for data that cannot be compressed such some image formats):</em></p> /// <p><code>ZLibNative.CompressionLevel compressionLevel = ZLibNative.CompressionLevel.NoCompression;</code> <br /> /// <code>int windowBits = 15; // or -15 if no headers required</code> <br /> /// <code>int memLevel = 7;</code> <br /> /// <code>ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;</code> </p> /// </summary> public enum CompressionLevel : int { NoCompression = 0, BestSpeed = 1, DefaultCompression = -1 } /// <summary> /// <p><strong>From the ZLib manual:</strong></p> /// <p><code>CompressionStrategy</code> is used to tune the compression algorithm.<br /> /// Use the value <code>DefaultStrategy</code> for normal data, <code>Filtered</code> for data produced by a filter (or predictor), /// <code>HuffmanOnly</code> to force Huffman encoding only (no string match), or <code>Rle</code> to limit match distances to one /// (run-length encoding). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the /// compression algorithm is tuned to compress them better. The effect of <code>Filtered</code> is to force more Huffman coding and] /// less string matching; it is somewhat intermediate between <code>DefaultStrategy</code> and <code>HuffmanOnly</code>. /// <code>Rle</code> is designed to be almost as fast as <code>HuffmanOnly</code>, but give better compression for PNG image data. /// The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set /// appropriately. <code>Fixed</code> prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications.</p> /// /// <p><strong>For NetFx use:</strong></p> /// <p>We have investigated compression scenarios for a bunch of different frequently occurring compression data and found that in all /// cases we investigated so far, <code>DefaultStrategy</code> provided best results</p> /// <p>See also: How to choose a compression level (in comments to <code>CompressionLevel</code>.</p> /// </summary> public enum CompressionStrategy : int { DefaultStrategy = 0 } /// <summary> /// In version 1.2.3, ZLib provides on the <code>Deflated</code>-<code>CompressionMethod</code>. /// </summary> public enum CompressionMethod : int { Deflated = 8 } /// <summary> /// <p><strong>From the ZLib manual:</strong></p> /// <p>ZLib's <code>windowBits</code> parameter is the base two logarithm of the window size (the size of the history buffer). /// It should be in the range 8..15 for this version of the library. Larger values of this parameter result in better compression /// at the expense of memory usage. The default value is 15 if deflateInit is used instead.<br /></p> /// <strong>Note</strong>: /// <code>windowBits</code> can also be -8..-15 for raw deflate. In this case, -windowBits determines the window size. /// <code>Deflate</code> will then generate raw deflate data with no ZLib header or trailer, and will not compute an adler32 check value.<br /> /// <p>See also: How to choose a compression level (in comments to <code>CompressionLevel</code>.</p> /// </summary> public const int Deflate_DefaultWindowBits = -15; // Legal values are 8..15 and -8..-15. 15 is the window size, // negative val causes deflate to produce raw deflate data (no zlib header). /// <summary> /// <p>Zlib's <code>windowBits</code> parameter is the base two logarithm of the window size (the size of the history buffer). /// For GZip header encoding, <code>windowBits</code> should be equal to a value between 8..15 (to specify Window Size) added to /// 16. The range of values for GZip encoding is therefore 24..31. /// <strong>Note</strong>: /// The GZip header will have no file name, no extra data, no comment, no modification time (set to zero), no header crc, and /// the operating system will be set based on the OS that the ZLib library was compiled to. <code>ZStream.adler</code> /// is a crc32 instead of an adler32.</p> /// </summary> public const int GZip_DefaultWindowBits = 31; /// <summary> /// <p><strong>From the ZLib manual:</strong></p> /// <p>The <code>memLevel</code> parameter specifies how much memory should be allocated for the internal compression state. /// <code>memLevel</code> = 1 uses minimum memory but is slow and reduces compression ratio; <code>memLevel</code> = 9 uses maximum /// memory for optimal speed. The default value is 8.</p> /// <p>See also: How to choose a compression level (in comments to <code>CompressionLevel</code>.</p> /// </summary> public const int Deflate_DefaultMemLevel = 8; // Memory usage by deflate. Legal range: [1..9]. 8 is ZLib default. // More is faster and better compression with more memory usage. public const int Deflate_NoCompressionMemLevel = 7; public const byte GZip_Header_ID1 = 31; public const byte GZip_Header_ID2 = 139; /** * Do not remove the nested typing of types inside of <code>System.IO.Compression.ZLibNative</code>. * This was done on purpose to: * * - Achieve the right encapsulation in a situation where <code>ZLibNative</code> may be compiled division-wide * into different assemblies that wish to consume <code>CLRCompression</code>. Since <code>internal</code> * scope is effectively like <code>public</code> scope when compiling <code>ZLibNative</code> into a higher * level assembly, we need a combination of inner types and <code>private</code>-scope members to achieve * the right encapsulation. * * - Achieve late dynamic loading of <code>CLRCompression.dll</code> at the right time. * The native assembly will not be loaded unless it is actually used since the loading is performed by a static * constructor of an inner type that is not directly referenced by user code. * * In Dev12 we would like to create a proper feature for loading native assemblies from user-specified * directories in order to PInvoke into them. This would preferably happen in the native interop/PInvoke * layer; if not we can add a Framework level feature. */ /// <summary> /// The <code>ZLibStreamHandle</code> could be a <code>CriticalFinalizerObject</code> rather than a /// <code>SafeHandleMinusOneIsInvalid</code>. This would save an <code>IntPtr</code> field since /// <code>ZLibStreamHandle</code> does not actually use its <code>handle</code> field. /// Instead it uses a <code>private ZStream zStream</code> field which is the actual handle data /// structure requiring critical finalization. /// However, we would like to take advantage if the better debugability offered by the fact that a /// <em>releaseHandleFailed MDA</em> is raised if the <code>ReleaseHandle</code> method returns /// <code>false</code>, which can for instance happen if the underlying ZLib <code>XxxxEnd</code> /// routines return an failure error code. /// </summary> public sealed class ZLibStreamHandle : SafeHandle { public enum State { NotInitialized, InitializedForDeflate, InitializedForInflate, Disposed } private ZStream _zStream; private volatile State _initializationState; public ZLibStreamHandle() : base(new IntPtr(-1), true) { _zStream = new ZStream(); _zStream.Init(); _initializationState = State.NotInitialized; SetHandle(IntPtr.Zero); } public override bool IsInvalid { get { return handle == new IntPtr(-1); } } public State InitializationState { get { return _initializationState; } } protected override bool ReleaseHandle() => InitializationState switch { State.NotInitialized => true, State.InitializedForDeflate => (DeflateEnd() == ErrorCode.Ok), State.InitializedForInflate => (InflateEnd() == ErrorCode.Ok), State.Disposed => true, _ => false, // This should never happen. Did we forget one of the State enum values in the switch? }; public IntPtr NextIn { get { return _zStream.nextIn; } set { _zStream.nextIn = value; } } public uint AvailIn { get { return _zStream.availIn; } set { _zStream.availIn = value; } } public IntPtr NextOut { get { return _zStream.nextOut; } set { _zStream.nextOut = value; } } public uint AvailOut { get { return _zStream.availOut; } set { _zStream.availOut = value; } } private void EnsureNotDisposed() { if (InitializationState == State.Disposed) throw new ObjectDisposedException(GetType().ToString()); } private void EnsureState(State requiredState) { if (InitializationState != requiredState) throw new InvalidOperationException("InitializationState != " + requiredState.ToString()); } public ErrorCode DeflateInit2_(CompressionLevel level, int windowBits, int memLevel, CompressionStrategy strategy) { EnsureNotDisposed(); EnsureState(State.NotInitialized); ErrorCode errC = Interop.zlib.DeflateInit2_(ref _zStream, level, CompressionMethod.Deflated, windowBits, memLevel, strategy); _initializationState = State.InitializedForDeflate; return errC; } public ErrorCode Deflate(FlushCode flush) { EnsureNotDisposed(); EnsureState(State.InitializedForDeflate); return Interop.zlib.Deflate(ref _zStream, flush); } public ErrorCode DeflateEnd() { EnsureNotDisposed(); EnsureState(State.InitializedForDeflate); ErrorCode errC = Interop.zlib.DeflateEnd(ref _zStream); _initializationState = State.Disposed; return errC; } public ErrorCode InflateInit2_(int windowBits) { EnsureNotDisposed(); EnsureState(State.NotInitialized); ErrorCode errC = Interop.zlib.InflateInit2_(ref _zStream, windowBits); _initializationState = State.InitializedForInflate; return errC; } public ErrorCode Inflate(FlushCode flush) { EnsureNotDisposed(); EnsureState(State.InitializedForInflate); return Interop.zlib.Inflate(ref _zStream, flush); } public ErrorCode InflateEnd() { EnsureNotDisposed(); EnsureState(State.InitializedForInflate); ErrorCode errC = Interop.zlib.InflateEnd(ref _zStream); _initializationState = State.Disposed; return errC; } // This can work even after XxflateEnd(). public string GetErrorMessage() => _zStream.msg != ZNullPtr ? Marshal.PtrToStringAnsi(_zStream.msg)! : string.Empty; } public static ErrorCode CreateZLibStreamForDeflate(out ZLibStreamHandle zLibStreamHandle, CompressionLevel level, int windowBits, int memLevel, CompressionStrategy strategy) { zLibStreamHandle = new ZLibStreamHandle(); return zLibStreamHandle.DeflateInit2_(level, windowBits, memLevel, strategy); } public static ErrorCode CreateZLibStreamForInflate(out ZLibStreamHandle zLibStreamHandle, int windowBits) { zLibStreamHandle = new ZLibStreamHandle(); return zLibStreamHandle.InflateInit2_(windowBits); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// TaskResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Taskrouter.V1.Workspace { public class TaskResource : Resource { public sealed class StatusEnum : StringEnum { private StatusEnum(string value) : base(value) {} public StatusEnum() {} public static implicit operator StatusEnum(string value) { return new StatusEnum(value); } public static readonly StatusEnum Pending = new StatusEnum("pending"); public static readonly StatusEnum Reserved = new StatusEnum("reserved"); public static readonly StatusEnum Assigned = new StatusEnum("assigned"); public static readonly StatusEnum Canceled = new StatusEnum("canceled"); public static readonly StatusEnum Completed = new StatusEnum("completed"); public static readonly StatusEnum Wrapping = new StatusEnum("wrapping"); } private static Request BuildFetchRequest(FetchTaskOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Tasks/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static TaskResource Fetch(FetchTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<TaskResource> FetchAsync(FetchTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task to fetch </param> /// <param name="pathSid"> The SID of the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static TaskResource Fetch(string pathWorkspaceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchTaskOptions(pathWorkspaceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task to fetch </param> /// <param name="pathSid"> The SID of the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<TaskResource> FetchAsync(string pathWorkspaceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchTaskOptions(pathWorkspaceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateTaskOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Tasks/" + options.PathSid + "", postParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static TaskResource Update(UpdateTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<TaskResource> UpdateAsync(UpdateTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task to update </param> /// <param name="pathSid"> The SID of the resource to update </param> /// <param name="attributes"> The JSON string that describes the custom attributes of the task </param> /// <param name="assignmentStatus"> The new status of the task </param> /// <param name="reason"> The reason that the Task was canceled or complete </param> /// <param name="priority"> The Task's new priority value </param> /// <param name="taskChannel"> When MultiTasking is enabled, specify the TaskChannel with the task to update </param> /// <param name="ifMatch"> The If-Match HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static TaskResource Update(string pathWorkspaceSid, string pathSid, string attributes = null, TaskResource.StatusEnum assignmentStatus = null, string reason = null, int? priority = null, string taskChannel = null, string ifMatch = null, ITwilioRestClient client = null) { var options = new UpdateTaskOptions(pathWorkspaceSid, pathSid){Attributes = attributes, AssignmentStatus = assignmentStatus, Reason = reason, Priority = priority, TaskChannel = taskChannel, IfMatch = ifMatch}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task to update </param> /// <param name="pathSid"> The SID of the resource to update </param> /// <param name="attributes"> The JSON string that describes the custom attributes of the task </param> /// <param name="assignmentStatus"> The new status of the task </param> /// <param name="reason"> The reason that the Task was canceled or complete </param> /// <param name="priority"> The Task's new priority value </param> /// <param name="taskChannel"> When MultiTasking is enabled, specify the TaskChannel with the task to update </param> /// <param name="ifMatch"> The If-Match HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<TaskResource> UpdateAsync(string pathWorkspaceSid, string pathSid, string attributes = null, TaskResource.StatusEnum assignmentStatus = null, string reason = null, int? priority = null, string taskChannel = null, string ifMatch = null, ITwilioRestClient client = null) { var options = new UpdateTaskOptions(pathWorkspaceSid, pathSid){Attributes = attributes, AssignmentStatus = assignmentStatus, Reason = reason, Priority = priority, TaskChannel = taskChannel, IfMatch = ifMatch}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteTaskOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Tasks/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: options.GetHeaderParams() ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static bool Delete(DeleteTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task to delete </param> /// <param name="pathSid"> The SID of the resource to delete </param> /// <param name="ifMatch"> The If-Match HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static bool Delete(string pathWorkspaceSid, string pathSid, string ifMatch = null, ITwilioRestClient client = null) { var options = new DeleteTaskOptions(pathWorkspaceSid, pathSid){IfMatch = ifMatch}; return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Task to delete </param> /// <param name="pathSid"> The SID of the resource to delete </param> /// <param name="ifMatch"> The If-Match HTTP request header </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathWorkspaceSid, string pathSid, string ifMatch = null, ITwilioRestClient client = null) { var options = new DeleteTaskOptions(pathWorkspaceSid, pathSid){IfMatch = ifMatch}; return await DeleteAsync(options, client); } #endif private static Request BuildReadRequest(ReadTaskOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Tasks", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static ResourceSet<TaskResource> Read(ReadTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<TaskResource>.FromJson("tasks", response.Content); return new ResourceSet<TaskResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<ResourceSet<TaskResource>> ReadAsync(ReadTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<TaskResource>.FromJson("tasks", response.Content); return new ResourceSet<TaskResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Tasks to read </param> /// <param name="priority"> The priority value of the Tasks to read </param> /// <param name="assignmentStatus"> Returns the list of all Tasks in the Workspace with the specified assignment_status /// </param> /// <param name="workflowSid"> The SID of the Workflow with the Tasks to read </param> /// <param name="workflowName"> The friendly name of the Workflow with the Tasks to read </param> /// <param name="taskQueueSid"> The SID of the TaskQueue with the Tasks to read </param> /// <param name="taskQueueName"> The friendly_name of the TaskQueue with the Tasks to read </param> /// <param name="evaluateTaskAttributes"> The task attributes of the Tasks to read </param> /// <param name="ordering"> Controls the order of the Tasks returned </param> /// <param name="hasAddons"> Whether to read Tasks with addons </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static ResourceSet<TaskResource> Read(string pathWorkspaceSid, int? priority = null, List<string> assignmentStatus = null, string workflowSid = null, string workflowName = null, string taskQueueSid = null, string taskQueueName = null, string evaluateTaskAttributes = null, string ordering = null, bool? hasAddons = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTaskOptions(pathWorkspaceSid){Priority = priority, AssignmentStatus = assignmentStatus, WorkflowSid = workflowSid, WorkflowName = workflowName, TaskQueueSid = taskQueueSid, TaskQueueName = taskQueueName, EvaluateTaskAttributes = evaluateTaskAttributes, Ordering = ordering, HasAddons = hasAddons, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Tasks to read </param> /// <param name="priority"> The priority value of the Tasks to read </param> /// <param name="assignmentStatus"> Returns the list of all Tasks in the Workspace with the specified assignment_status /// </param> /// <param name="workflowSid"> The SID of the Workflow with the Tasks to read </param> /// <param name="workflowName"> The friendly name of the Workflow with the Tasks to read </param> /// <param name="taskQueueSid"> The SID of the TaskQueue with the Tasks to read </param> /// <param name="taskQueueName"> The friendly_name of the TaskQueue with the Tasks to read </param> /// <param name="evaluateTaskAttributes"> The task attributes of the Tasks to read </param> /// <param name="ordering"> Controls the order of the Tasks returned </param> /// <param name="hasAddons"> Whether to read Tasks with addons </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<ResourceSet<TaskResource>> ReadAsync(string pathWorkspaceSid, int? priority = null, List<string> assignmentStatus = null, string workflowSid = null, string workflowName = null, string taskQueueSid = null, string taskQueueName = null, string evaluateTaskAttributes = null, string ordering = null, bool? hasAddons = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadTaskOptions(pathWorkspaceSid){Priority = priority, AssignmentStatus = assignmentStatus, WorkflowSid = workflowSid, WorkflowName = workflowName, TaskQueueSid = taskQueueSid, TaskQueueName = taskQueueName, EvaluateTaskAttributes = evaluateTaskAttributes, Ordering = ordering, HasAddons = hasAddons, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<TaskResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<TaskResource>.FromJson("tasks", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<TaskResource> NextPage(Page<TaskResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Taskrouter) ); var response = client.Request(request); return Page<TaskResource>.FromJson("tasks", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<TaskResource> PreviousPage(Page<TaskResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Taskrouter) ); var response = client.Request(request); return Page<TaskResource>.FromJson("tasks", response.Content); } private static Request BuildCreateRequest(CreateTaskOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Taskrouter, "/v1/Workspaces/" + options.PathWorkspaceSid + "/Tasks", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static TaskResource Create(CreateTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Task parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<TaskResource> CreateAsync(CreateTaskOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace that the new Task belongs to </param> /// <param name="timeout"> The amount of time in seconds the task can live before being assigned </param> /// <param name="priority"> The priority to assign the new task and override the default </param> /// <param name="taskChannel"> When MultiTasking is enabled specify the TaskChannel by passing either its unique_name /// or SID </param> /// <param name="workflowSid"> The SID of the Workflow that you would like to handle routing for the new Task </param> /// <param name="attributes"> A URL-encoded JSON string describing the attributes of the task </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Task </returns> public static TaskResource Create(string pathWorkspaceSid, int? timeout = null, int? priority = null, string taskChannel = null, string workflowSid = null, string attributes = null, ITwilioRestClient client = null) { var options = new CreateTaskOptions(pathWorkspaceSid){Timeout = timeout, Priority = priority, TaskChannel = taskChannel, WorkflowSid = workflowSid, Attributes = attributes}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace that the new Task belongs to </param> /// <param name="timeout"> The amount of time in seconds the task can live before being assigned </param> /// <param name="priority"> The priority to assign the new task and override the default </param> /// <param name="taskChannel"> When MultiTasking is enabled specify the TaskChannel by passing either its unique_name /// or SID </param> /// <param name="workflowSid"> The SID of the Workflow that you would like to handle routing for the new Task </param> /// <param name="attributes"> A URL-encoded JSON string describing the attributes of the task </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Task </returns> public static async System.Threading.Tasks.Task<TaskResource> CreateAsync(string pathWorkspaceSid, int? timeout = null, int? priority = null, string taskChannel = null, string workflowSid = null, string attributes = null, ITwilioRestClient client = null) { var options = new CreateTaskOptions(pathWorkspaceSid){Timeout = timeout, Priority = priority, TaskChannel = taskChannel, WorkflowSid = workflowSid, Attributes = attributes}; return await CreateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a TaskResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> TaskResource object represented by the provided JSON </returns> public static TaskResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<TaskResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The number of seconds since the Task was created /// </summary> [JsonProperty("age")] public int? Age { get; private set; } /// <summary> /// The current status of the Task's assignment /// </summary> [JsonProperty("assignment_status")] [JsonConverter(typeof(StringEnumConverter))] public TaskResource.StatusEnum AssignmentStatus { get; private set; } /// <summary> /// The JSON string with custom attributes of the work /// </summary> [JsonProperty("attributes")] public string Attributes { get; private set; } /// <summary> /// An object that contains the addon data for all installed addons /// </summary> [JsonProperty("addons")] public string Addons { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the Task entered the TaskQueue. /// </summary> [JsonProperty("task_queue_entered_date")] public DateTime? TaskQueueEnteredDate { get; private set; } /// <summary> /// Retrieve the list of all Tasks in the Workspace with the specified priority /// </summary> [JsonProperty("priority")] public int? Priority { get; private set; } /// <summary> /// The reason the Task was canceled or completed /// </summary> [JsonProperty("reason")] public string Reason { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the TaskQueue /// </summary> [JsonProperty("task_queue_sid")] public string TaskQueueSid { get; private set; } /// <summary> /// The friendly name of the TaskQueue /// </summary> [JsonProperty("task_queue_friendly_name")] public string TaskQueueFriendlyName { get; private set; } /// <summary> /// The SID of the TaskChannel /// </summary> [JsonProperty("task_channel_sid")] public string TaskChannelSid { get; private set; } /// <summary> /// The unique name of the TaskChannel /// </summary> [JsonProperty("task_channel_unique_name")] public string TaskChannelUniqueName { get; private set; } /// <summary> /// The amount of time in seconds that the Task can live before being assigned /// </summary> [JsonProperty("timeout")] public int? Timeout { get; private set; } /// <summary> /// The SID of the Workflow that is controlling the Task /// </summary> [JsonProperty("workflow_sid")] public string WorkflowSid { get; private set; } /// <summary> /// The friendly name of the Workflow that is controlling the Task /// </summary> [JsonProperty("workflow_friendly_name")] public string WorkflowFriendlyName { get; private set; } /// <summary> /// The SID of the Workspace that contains the Task /// </summary> [JsonProperty("workspace_sid")] public string WorkspaceSid { get; private set; } /// <summary> /// The absolute URL of the Task resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The URLs of related resources /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } private TaskResource() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Searches for resources in Assembly manifest, used ** for assembly-based resource lookup. ** ** ===========================================================*/ namespace System.Resources { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; using Microsoft.Win32; // // Note: this type is integral to the construction of exception objects, // and sometimes this has to be done in low memory situtations (OOM) or // to create TypeInitializationExceptions due to failure of a static class // constructor. This type needs to be extremely careful and assume that // any type it references may have previously failed to construct, so statics // belonging to that type may not be initialized. FrameworkEventSource.Log // is one such example. // internal class ManifestBasedResourceGroveler : IResourceGroveler { private ResourceManager.ResourceManagerMediator _mediator; public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { // here and below: convert asserts to preconditions where appropriate when we get // contracts story in place. Contract.Requires(mediator != null, "mediator shouldn't be null; check caller"); _mediator = mediator; } public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark) { Debug.Assert(culture != null, "culture shouldn't be null; check caller"); Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller"); ResourceSet rs = null; Stream stream = null; RuntimeAssembly satellite = null; // 1. Fixups for ultimate fallbacks CultureInfo lookForCulture = UltimateFallbackFixup(culture); // 2. Look for satellite assembly or main assembly, as appropriate if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { // don't bother looking in satellites in this case satellite = _mediator.MainAssembly; } #if RESOURCE_SATELLITE_CONFIG // If our config file says the satellite isn't here, don't ask for it. else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture)) { satellite = null; } #endif else { satellite = GetSatelliteAssembly(lookForCulture, ref stackMark); if (satellite == null) { bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)); // didn't find satellite, give error if necessary if (raiseException) { HandleSatelliteMissing(); } } } // get resource file name we'll search for. Note, be careful if you're moving this statement // around because lookForCulture may be modified from originally requested culture above. String fileName = _mediator.GetResourceFileName(lookForCulture); // 3. If we identified an assembly to search; look in manifest resource stream for resource file if (satellite != null) { // Handle case in here where someone added a callback for assembly load events. // While no other threads have called into GetResourceSet, our own thread can! // At that point, we could already have an RS in our hash table, and we don't // want to add it twice. lock (localResourceSets) { localResourceSets.TryGetValue(culture.Name, out rs); } stream = GetManifestResourceStream(satellite, fileName, ref stackMark); } // 4a. Found a stream; create a ResourceSet if possible if (createIfNotExists && stream != null && rs == null) { rs = CreateResourceSet(stream, satellite); } else if (stream == null && tryParents) { // 4b. Didn't find stream; give error if necessary bool raiseException = culture.HasInvariantCultureName; if (raiseException) { HandleResourceStreamMissing(fileName); } } return rs; } private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture) { CultureInfo returnCulture = lookForCulture; // If our neutral resources were written in this culture AND we know the main assembly // does NOT contain neutral resources, don't probe for this satellite. if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { returnCulture = CultureInfo.InvariantCulture; } else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { returnCulture = _mediator.NeutralResourcesCulture; } return returnCulture; } internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation) { Debug.Assert(a != null, "assembly != null"); string cultureName = null; short fallback = 0; if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref cultureName), out fallback)) { if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) { throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback)); } fallbackLocation = (UltimateResourceFallbackLocation)fallback; } else { fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } try { CultureInfo c = CultureInfo.GetCultureInfo(cultureName); return c; } catch (ArgumentException e) { // we should catch ArgumentException only. // Note we could go into infinite loops if mscorlib's // NeutralResourcesLanguageAttribute is mangled. If this assert // fires, please fix the build process for the BCL directory. if (a == typeof(Object).Assembly) { Debug.Assert(false, System.CoreLib.Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e); return CultureInfo.InvariantCulture; } throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e); } } // Constructs a new ResourceSet for a given file name. The logic in // here avoids a ReflectionPermission check for our RuntimeResourceSet // for perf and working set reasons. // Use the assembly to resolve assembly manifest resource references. // Note that is can be null, but probably shouldn't be. // This method could use some refactoring. One thing at a time. internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { Debug.Assert(store != null, "I need a Stream!"); // Check to see if this is a Stream the ResourceManager understands, // and check for the correct resource reader type. if (store.CanSeek && store.Length > 4) { long startPos = store.Position; // not disposing because we want to leave stream open BinaryReader br = new BinaryReader(store); // Look for our magic number as a little endian Int32. int bytes = br.ReadInt32(); if (bytes == ResourceManager.MagicNumber) { int resMgrHeaderVersion = br.ReadInt32(); String readerTypeName = null, resSetTypeName = null; if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber) { br.ReadInt32(); // We don't want the number of bytes to skip. readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); } else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber) { // Assume that the future ResourceManager headers will // have two strings for us - the reader type name and // resource set type name. Read those, then use the num // bytes to skip field to correct our position. int numBytesToSkip = br.ReadInt32(); long endPosition = br.BaseStream.Position + numBytesToSkip; readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString()); br.BaseStream.Seek(endPosition, SeekOrigin.Begin); } else { // resMgrHeaderVersion is older than this ResMgr version. // We should add in backwards compatibility support here. throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName())); } store.Position = startPos; // Perf optimization - Don't use Reflection for our defaults. // Note there are two different sets of strings here - the // assembly qualified strings emitted by ResourceWriter, and // the abbreviated ones emitted by InternalResGen. if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName)) { RuntimeResourceSet rs; #if LOOSELY_LINKED_RESOURCE_REFERENCE rs = new RuntimeResourceSet(store, assembly); #else rs = new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } else { // we do not want to use partial binding here. Type readerType = Type.GetType(readerTypeName, true); Object[] args = new Object[1]; args[0] = store; IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args); Object[] resourceSetArgs = #if LOOSELY_LINKED_RESOURCE_REFERENCE new Object[2]; #else new Object[1]; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[0] = reader; #if LOOSELY_LINKED_RESOURCE_REFERENCE resourceSetArgs[1] = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE Type resSetType; if (_mediator.UserResourceSet == null) { Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here."); resSetType = Type.GetType(resSetTypeName, true, false); } else resSetType = _mediator.UserResourceSet; ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, resourceSetArgs, null, null); return rs; } } else { store.Position = startPos; } } if (_mediator.UserResourceSet == null) { // Explicitly avoid CreateInstance if possible, because it // requires ReflectionPermission to call private & protected // constructors. #if LOOSELY_LINKED_RESOURCE_REFERENCE return new RuntimeResourceSet(store, assembly); #else return new RuntimeResourceSet(store); #endif // LOOSELY_LINKED_RESOURCE_REFERENCE } else { Object[] args = new Object[2]; args[0] = store; args[1] = assembly; try { ResourceSet rs = null; // Add in a check for a constructor taking in an assembly first. try { rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); return rs; } catch (MissingMethodException) { } args = new Object[1]; args[0] = store; rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); #if LOOSELY_LINKED_RESOURCE_REFERENCE rs.Assembly = assembly; #endif // LOOSELY_LINKED_RESOURCE_REFERENCE return rs; } catch (MissingMethodException e) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e); } } } private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(fileName != null, "fileName shouldn't be null; check caller"); // If we're looking in the main assembly AND if the main assembly was the person who // created the ResourceManager, skip a security check for private manifest resources. bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite) && (_mediator.CallingAssembly == _mediator.MainAssembly); Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark); if (stream == null) { stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); } return stream; } // Looks up a .resources file in the assembly manifest using // case-insensitive lookup rules. Yes, this is slow. The metadata // dev lead refuses to make all assembly manifest resource lookups case-insensitive, // even optionally case-insensitive. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name) { Contract.Requires(satellite != null, "satellite shouldn't be null; check caller"); Contract.Requires(name != null, "name shouldn't be null; check caller"); StringBuilder sb = new StringBuilder(); if (_mediator.LocationInfo != null) { String nameSpace = _mediator.LocationInfo.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) sb.Append(Type.Delimiter); } } sb.Append(name); String givenName = sb.ToString(); CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; String canonicalName = null; foreach (String existingName in satellite.GetManifestResourceNames()) { if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0) { if (canonicalName == null) { canonicalName = existingName; } else { throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString())); } } } if (canonicalName == null) { return null; } // If we're looking in the main assembly AND if the main // assembly was the person who created the ResourceManager, // skip a security check for private manifest resources. bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck); } private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } RuntimeAssembly satellite = null; String satAssemblyName = GetSatelliteAssemblyName(); // Look up the satellite assembly, but don't let problems // like a partially signed satellite assembly stop us from // doing fallback and displaying something to the user. // Yet also somehow log this error for a developer. try { satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark); } // Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback. catch (FileLoadException fle) { // Ignore cases where the loader gets an access // denied back from the OS. This showed up for // href-run exe's at one point. int hr = fle._HResult; if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED)) { Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle); } } // Don't throw for zero-length satellite assemblies, for compat with v1 catch (BadImageFormatException bife) { Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife); } return satellite; } // Perf optimization - Don't use Reflection for most cases with // our .resources files. This makes our code run faster and we can // creating a ResourceReader via Reflection. This would incur // a security check (since the link-time check on the constructor that // takes a String is turned into a full demand with a stack walk) // and causes partially trusted localized apps to fail. private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName) { Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller"); Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller"); if (_mediator.UserResourceSet != null) return false; // Ignore the actual version of the ResourceReader and // RuntimeResourceSet classes. Let those classes deal with // versioning themselves. AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName); if (readerTypeName != null) { if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib)) return false; } if (resSetTypeName != null) { if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib)) return false; } return true; } private String GetSatelliteAssemblyName() { String satAssemblyName = _mediator.MainAssembly.GetSimpleName(); satAssemblyName += ".resources"; return satAssemblyName; } private void HandleSatelliteMissing() { String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll"; if (_mediator.SatelliteContractVersion != null) { satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString(); } AssemblyName an = new AssemblyName(); an.SetPublicKey(_mediator.MainAssembly.GetPublicKey()); byte[] token = an.GetPublicKeyToken(); int iLen = token.Length; StringBuilder publicKeyTok = new StringBuilder(iLen * 2); for (int i = 0; i < iLen; i++) { publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture)); } satAssemName += ", PublicKeyToken=" + publicKeyTok; String missingCultureName = _mediator.NeutralResourcesCulture.Name; if (missingCultureName.Length == 0) { missingCultureName = "<invariant>"; } throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName); } private void HandleResourceStreamMissing(String fileName) { // Keep people from bothering me about resources problems if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name)) { // This would break CultureInfo & all our exceptions. Debug.Assert(false, "Couldn't get " + System.CoreLib.Name + ResourceManager.ResFileExtension + " from " + System.CoreLib.Name + "'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug."); // We cannot continue further - simply FailFast. string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!"; System.Environment.FailFast(mesgFailFast); } // We really don't think this should happen - we always // expect the neutral locale's resources to be present. String resName = String.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) resName = _mediator.LocationInfo.Namespace + Type.Delimiter; resName += fileName; throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName())); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class HashtableTests { [Fact] public static void Ctor_Empty() { var hash = new ComparableHashtable(); VerifyHashtable(hash, null, null); } [Fact] public static void Ctor_IDictionary() { // No exception var hash1 = new ComparableHashtable(new Hashtable()); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()))))); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2); VerifyHashtable(hash1, hash2, null); } [Fact] public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null)); // Dictionary is null } [Fact] public static void Ctor_IEqualityComparer() { // Null comparer var hash = new ComparableHashtable((IEqualityComparer)null); VerifyHashtable(hash, null, null); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(comparer); VerifyHashtable(hash, null, comparer); }); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] public static void Ctor_Int(int capacity) { var hash = new ComparableHashtable(capacity); VerifyHashtable(hash, null, null); } [Fact] public static void Ctor_Int_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1)); // Capacity < 0 Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue } [Fact] public static void Ctor_IDictionary_Int() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f); VerifyHashtable(hash1, hash2, null); } [Fact] public static void Ctor_IDictionary_Int_Invalid() { Assert.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f)); // Dictionary is null Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity)); // Load factor is infinity } [Fact] public static void Ctor_IDictionary_IEqualityComparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), null); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null); Assert.Equal(0, hash1.Count); // Null comparer Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, null); VerifyHashtable(hash1, hash2, null); // Custom comparer hash2 = Helpers.CreateIntHashtable(100); Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash1 = new ComparableHashtable(hash2, comparer); VerifyHashtable(hash1, hash2, comparer); }); } [Fact] public static void Ctor_IDictionary_IEqualityComparer_NullDictionary_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("d", () => new Hashtable(null, null)); // Dictionary is null } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public static void Ctor_Int_Int(int capacity, float loadFactor) { var hash = new ComparableHashtable(capacity, loadFactor); VerifyHashtable(hash, null, null); } [Fact] public static void Ctor_Int_Int_GenerateNewPrime() { // The ctor for Hashtable performs the following calculation: // rawSize = capacity / (loadFactor * 0.72) // If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime. // Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically // This test makes sure this works. int capacity = 8000000; float loadFactor = 0.1f / 0.72f; try { var hash = new ComparableHashtable(capacity, loadFactor); } catch (OutOfMemoryException) { // On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore. } } [Fact] public static void Ctor_Int_Int_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f)); // Capacity < 0 Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f)); // Load factor < 0.1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f)); // Load factor > 1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN)); // Load factor is NaN Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity)); // Load factor is infinity } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Ctor_Int_IEqualityComparer(int capacity) { // Null comparer var hash = new ComparableHashtable(capacity, null); VerifyHashtable(hash, null, null); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(capacity, comparer); VerifyHashtable(hash, null, comparer); }); } [Fact] public static void Ctor_Int_IEqualityComparer_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, null)); // Capacity < 0 Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue } [Fact] public static void Ctor_IDictionary_Int_IEqualityComparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f, null); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable( new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null); Assert.Equal(0, hash1.Count); // Null comparer Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f, null); VerifyHashtable(hash1, hash2, null); hash2 = Helpers.CreateIntHashtable(100); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash1 = new ComparableHashtable(hash2, 1f, comparer); VerifyHashtable(hash1, hash2, comparer); }); } [Fact] public static void Ctor_IDictionary_LoadFactor_IEqualityComparer_Invalid() { Assert.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f, null)); // Dictionary is null Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity, null)); // Load factor is infinity } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public static void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor) { // Null comparer var hash = new ComparableHashtable(capacity, loadFactor, null); VerifyHashtable(hash, null, null); Assert.Null(hash.EqualityComparer); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(capacity, loadFactor, comparer); VerifyHashtable(hash, null, comparer); }); } [Fact] public static void Ctor_Capacity_LoadFactor_IEqualityComparer_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f, null)); // Capacity < 0 Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f, null)); // Load factor > 1f Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN, null)); // Load factor is NaN Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity Assert.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity, null)); // Load factor is infinity } [Fact] public static void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable()); var hash = new Hashtable() { { "a", 1 }, { "b", 2 } }; DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash)); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public static void Add_ReferenceType() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { // Value is a reference var foo = new Foo(); hash2.Add("Key", foo); Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue); // Changing original object should change the object stored in the Hashtable foo.StringValue = "Goodbye"; Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue); }); } [Fact] public static void Add_ClearRepeatedly() { const int Iterations = 2; const int Count = 2; var hash = new Hashtable(); for (int i = 0; i < Iterations; i++) { for (int j = 0; j < Count; j++) { string key = "Key: i=" + i + ", j=" + j; string value = "Value: i=" + i + ", j=" + j; hash.Add(key, value); } Assert.Equal(Count, hash.Count); hash.Clear(); } } [Fact] [OuterLoop] public static void AddRemove_LargeAmountNumbers() { // Generate a random 100,000 array of ints as test data var inputData = new int[100000]; var random = new Random(341553); for (int i = 0; i < inputData.Length; i++) { inputData[i] = random.Next(7500000, int.MaxValue); } var hash = new Hashtable(); int count = 0; foreach (long number in inputData) { hash.Add(number, count++); } count = 0; foreach (long number in inputData) { Assert.Equal(hash[number], count); Assert.True(hash.ContainsKey(number)); count++; } foreach (long number in inputData) { hash.Remove(number); } Assert.Equal(0, hash.Count); } [Fact] public static void DuplicatedKeysWithInitialCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var hash = new Hashtable(200); const int Iterations = 1600; for (int i = 0; i < Iterations; i += 2) { hash.Add(new BadHashCode(i), i.ToString()); hash.Add(new BadHashCode(i + 1), (i + 1).ToString()); hash.Remove(new BadHashCode(i)); hash.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < Iterations; i++) { hash.Add(i.ToString(), i); } for (int i = 0; i < Iterations; i++) { Assert.Equal(i, hash[i.ToString()]); } } [Fact] public static void DuplicatedKeysWithDefaultCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var hash = new Hashtable(); const int Iterations = 1600; for (int i = 0; i < Iterations; i += 2) { hash.Add(new BadHashCode(i), i.ToString()); hash.Add(new BadHashCode(i + 1), (i + 1).ToString()); hash.Remove(new BadHashCode(i)); hash.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < Iterations; i++) { hash.Add(i.ToString(), i); } for (int i = 0; i < Iterations; i++) { Assert.Equal(i, hash[i.ToString()]); } } [Theory] [InlineData(0)] [InlineData(100)] public static void Clone(int count) { Hashtable hash1 = Helpers.CreateStringHashtable(count); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { Hashtable clone = (Hashtable)hash2.Clone(); Assert.Equal(hash2.Count, clone.Count); Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized); Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize); Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly); for (int i = 0; i < clone.Count; i++) { string key = "Key_" + i; string value = "Value_" + i; Assert.True(clone.ContainsKey(key)); Assert.True(clone.ContainsValue(value)); Assert.Equal(value, clone[key]); } }); } [Fact] public static void Clone_IsShallowCopy() { var hash = new Hashtable(); for (int i = 0; i < 10; i++) { hash.Add(i, new Foo()); } Hashtable clone = (Hashtable)hash.Clone(); for (int i = 0; i < clone.Count; i++) { Assert.Equal("Hello World", ((Foo)clone[i]).StringValue); Assert.Same(hash[i], clone[i]); } // Change object in original hashtable ((Foo)hash[1]).StringValue = "Goodbye"; Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue); // Removing an object from the original hashtable doesn't change the clone hash.Remove(0); Assert.True(clone.Contains(0)); } [Fact] public static void Clone_HashtableCastedToInterfaces() { // Try to cast the returned object from Clone() to different types Hashtable hash = Helpers.CreateIntHashtable(100); ICollection collection = (ICollection)hash.Clone(); Assert.Equal(hash.Count, collection.Count); IDictionary dictionary = (IDictionary)hash.Clone(); Assert.Equal(hash.Count, dictionary.Count); } [Fact] public static void ContainsKey() { Hashtable hash1 = Helpers.CreateStringHashtable(100); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { for (int i = 0; i < hash2.Count; i++) { string key = "Key_" + i; Assert.True(hash2.ContainsKey(key)); Assert.True(hash2.Contains(key)); } Assert.False(hash2.ContainsKey("Non Existent Key")); Assert.False(hash2.Contains("Non Existent Key")); Assert.False(hash2.ContainsKey(101)); Assert.False(hash2.Contains("Non Existent Key")); string removedKey = "Key_1"; hash2.Remove(removedKey); Assert.False(hash2.ContainsKey(removedKey)); Assert.False(hash2.Contains(removedKey)); }); } [Fact] public static void ContainsKey_EqualObjects() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { var foo1 = new Foo() { StringValue = "Goodbye" }; var foo2 = new Foo() { StringValue = "Goodbye" }; hash2.Add(foo1, 101); Assert.True(hash2.ContainsKey(foo2)); Assert.True(hash2.Contains(foo2)); int i1 = 0x10; int i2 = 0x100; long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode long l2 = (((long)i2) << 32) + i1; hash2.Add(l1, 101); hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set Assert.True(hash2.ContainsKey(l1)); Assert.True(hash2.Contains(l1)); hash2.Remove(l1); // Remove the first item Assert.False(hash2.ContainsKey(l1)); Assert.False(hash2.Contains(l1)); Assert.True(hash2.ContainsKey(l2)); Assert.True(hash2.Contains(l2)); }); } [Fact] public static void ContainsKey_NullKey_ThrowsArgumentNullException() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { Assert.Throws<ArgumentNullException>("key", () => hash2.ContainsKey(null)); // Key is null Assert.Throws<ArgumentNullException>("key", () => hash2.Contains(null)); // Key is null }); } [Fact] public static void ContainsValue() { Hashtable hash1 = Helpers.CreateStringHashtable(100); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { for (int i = 0; i < hash2.Count; i++) { string value = "Value_" + i; Assert.True(hash2.ContainsValue(value)); } Assert.False(hash2.ContainsValue("Non Existent Value")); Assert.False(hash2.ContainsValue(101)); Assert.False(hash2.ContainsValue(null)); hash2.Add("Key_101", null); Assert.True(hash2.ContainsValue(null)); string removedKey = "Key_1"; string removedValue = "Value_1"; hash2.Remove(removedKey); Assert.False(hash2.ContainsValue(removedValue)); }); } [Fact] public static void ContainsValue_EqualObjects() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { var foo1 = new Foo() { StringValue = "Goodbye" }; var foo2 = new Foo() { StringValue = "Goodbye" }; hash2.Add(101, foo1); Assert.True(hash2.ContainsValue(foo2)); }); } [Fact] public static void Keys_ModifyingHashtable_ModifiesCollection() { Hashtable hash = Helpers.CreateStringHashtable(100); ICollection keys = hash.Keys; // Removing a key from the hashtable should update the Keys ICollection. // This means that the Keys ICollection no longer contains the key. hash.Remove("Key_0"); IEnumerator enumerator = keys.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotEqual("Key_0", enumerator.Current); } } [Fact] public static void Remove_SameHashcode() { // We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable // does not expand but have to tread through collision bit set positions to insert the new elements. We do this // by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that // the hashtable does not expand as long as we have at most 7 elements at any given time? var hash = new Hashtable(); var arrList = new ArrayList(); for (int i = 0; i < 7; i++) { var hashConfuse = new BadHashCode(i); arrList.Add(hashConfuse); hash.Add(hashConfuse, i); } var rand = new Random(-55); int iCount = 7; for (int i = 0; i < 100; i++) { for (int j = 0; j < 7; j++) { Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value); } // Delete 3 elements from the hashtable for (int j = 0; j < 3; j++) { int iElement = rand.Next(6); hash.Remove(arrList[iElement]); Assert.False(hash.ContainsValue(null)); arrList.RemoveAt(iElement); int testInt = iCount++; var hashConfuse = new BadHashCode(testInt); arrList.Add(hashConfuse); hash.Add(hashConfuse, testInt); } } } [Fact] public static void SynchronizedProperties() { // Ensure Synchronized correctly reflects a wrapped hashtable var hash1 = Helpers.CreateStringHashtable(100); var hash2 = Hashtable.Synchronized(hash1); Assert.Equal(hash1.Count, hash2.Count); Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly); Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize); Assert.True(hash2.IsSynchronized); Assert.Equal(hash1.SyncRoot, hash2.SyncRoot); for (int i = 0; i < hash2.Count; i++) { Assert.Equal("Value_" + i, hash2["Key_" + i]); } } [Fact] public static void Synchronized_NullTable_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("table", () => Hashtable.Synchronized(null)); // Table is null } [Fact] public static void Values_ModifyingHashtable_ModifiesCollection() { Hashtable hash = Helpers.CreateStringHashtable(100); ICollection values = hash.Values; // Removing a value from the hashtable should update the Values ICollection. // This means that the Values ICollection no longer contains the value. hash.Remove("Key_0"); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotEqual("Value_0", enumerator.Current); } } private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc) { if (hash2 == null) { Assert.Equal(0, hash1.Count); } else { // Make sure that construtor imports all keys and values Assert.Equal(hash2.Count, hash1.Count); for (int i = 0; i < 100; i++) { Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } // Make sure the new and old hashtables are not linked hash2.Clear(); for (int i = 0; i < 100; i++) { Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } } Assert.Equal(ikc, hash1.EqualityComparer); Assert.False(hash1.IsFixedSize); Assert.False(hash1.IsReadOnly); Assert.False(hash1.IsSynchronized); // Make sure we can add to the hashtable int count = hash1.Count; for (int i = count; i < count + 100; i++) { hash1.Add(i, i); Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } } private class ComparableHashtable : Hashtable { public ComparableHashtable() : base() { } public ComparableHashtable(int capacity) : base(capacity) { } public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor) { } public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc) { } public ComparableHashtable(IEqualityComparer ikc) : base(ikc) { } public ComparableHashtable(IDictionary d) : base(d) { } public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor) { } public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc) { } public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc) { } public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc) { } public new IEqualityComparer EqualityComparer => base.EqualityComparer; } private class BadHashCode { public BadHashCode(int value) { Value = value; } public int Value { get; private set; } public override bool Equals(object o) { BadHashCode rhValue = o as BadHashCode; if (rhValue != null) { return Value.Equals(rhValue.Value); } else { throw new ArgumentException("is not BadHashCode type actual " + o.GetType(), nameof(o)); } } // Return 0 for everything to force hash collisions. public override int GetHashCode() => 0; public override string ToString() => Value.ToString(); } private class Foo { public string StringValue { get; set; } = "Hello World"; public override bool Equals(object obj) { Foo foo = obj as Foo; return foo != null && StringValue == foo.StringValue; } public override int GetHashCode() => StringValue.GetHashCode(); } } /// <summary> /// A hashtable can have a race condition: /// A read operation on hashtable has three steps: /// (1) calculate the hash and find the slot number. /// (2) compare the hashcode, if equal, go to step 3. Otherwise end. /// (3) compare the key, if equal, go to step 4. Otherwise end. /// (4) return the value contained in the bucket. /// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one /// in the same bukcet. In order to make this happen easily, I created two long with same hashcode. /// </summary> public class Hashtable_ItemThreadSafetyTests { private object _key1; private object _key2; private object _value1 = "value1"; private object _value2 = "value2"; private Hashtable _hash; private bool _errorOccurred = false; private bool _timeExpired = false; private const int MAX_TEST_TIME_MS = 10000; // 10 seconds [Fact] [OuterLoop] public void GetItem_ThreadSafety() { int i1 = 0x10; int i2 = 0x100; // Setup key1 and key2 so they are different values but have the same hashcode // To produce a hashcode long XOR's the first 32bits with the last 32 bits long l1 = (((long)i1) << 32) + i2; long l2 = (((long)i2) << 32) + i1; _key1 = l1; _key2 = l2; _hash = new Hashtable(3); // Just one item will be in the hashtable at a time int taskCount = 3; var readers1 = new Task[taskCount]; var readers2 = new Task[taskCount]; Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < readers1.Length; i++) { readers1[i] = Task.Run(new Action(ReaderFunction1)); } for (int i = 0; i < readers2.Length; i++) { readers2[i] = Task.Run(new Action(ReaderFunction2)); } Task writer = Task.Run(new Action(WriterFunction)); var spin = new SpinWait(); while (!_errorOccurred && !_timeExpired) { if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds) { _timeExpired = true; } spin.SpinOnce(); } Task.WaitAll(readers1); Task.WaitAll(readers2); writer.Wait(); Assert.False(_errorOccurred); } private void ReaderFunction1() { while (!_timeExpired) { object value = _hash[_key1]; if (value != null) { Assert.NotEqual(value, _value2); } } } private void ReaderFunction2() { while (!_errorOccurred && !_timeExpired) { object value = _hash[_key2]; if (value != null) { Assert.NotEqual(value, _value1); } } } private void WriterFunction() { while (!_errorOccurred && !_timeExpired) { _hash.Add(_key1, _value1); _hash.Remove(_key1); _hash.Add(_key2, _value2); _hash.Remove(_key2); } } } public class Hashtable_SynchronizedTests { private Hashtable _hash2; private int _iNumberOfElements = 20; [Fact] [OuterLoop] public void SynchronizedThreadSafety() { const int NumberOfWorkers = 3; // Synchronized returns a hashtable that is thread safe // We will try to test this by getting a number of threads to write some items // to a synchronized IList var hash1 = new Hashtable(); _hash2 = Hashtable.Synchronized(hash1); var workers = new Task[NumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; var task = new Action(() => AddElements(name)); workers[i] = Task.Run(task); } Task.WaitAll(workers); // Check time Assert.Equal(_hash2.Count, _iNumberOfElements * NumberOfWorkers); for (int i = 0; i < NumberOfWorkers; i++) { for (int j = 0; j < _iNumberOfElements; j++) { string strValue = "Thread worker " + i + "_" + j; Assert.True(_hash2.Contains(strValue)); } } // We cannot can make an assumption on the order of these items but // now we are going to remove all of these workers = new Task[NumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { string name = "Thread worker " + i; var task = new Action(() => RemoveElements(name)); workers[i] = Task.Run(task); } Task.WaitAll(workers); Assert.Equal(_hash2.Count, 0); } private void AddElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hash2.Add(strName + "_" + i, "string_" + i); } } private void RemoveElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hash2.Remove(strName + "_" + i); } } } public class Hashtable_SyncRootTests { private Hashtable _hashDaughter; private Hashtable _hashGrandDaughter; private const int NumberOfElements = 100; [Fact] public void SyncRoot() { // Different hashtables have different SyncRoots var hash1 = new Hashtable(); var hash2 = new Hashtable(); Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot); Assert.Equal(hash1.SyncRoot.GetType(), typeof(object)); // Cloned hashtables have different SyncRoots hash1 = new Hashtable(); hash2 = Hashtable.Synchronized(hash1); Hashtable hash3 = (Hashtable)hash2.Clone(); Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot); Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot); // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother Hashtable // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var hashMother = new Hashtable(); for (int i = 0; i < NumberOfElements; i++) { hashMother.Add("Key_" + i, "Value_" + i); } Hashtable hashSon = Hashtable.Synchronized(hashMother); _hashGrandDaughter = Hashtable.Synchronized(hashSon); _hashDaughter = Hashtable.Synchronized(hashMother); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); // We are going to rumble with the Hashtables with some threads int iNumberOfWorkers = 30; var workers = new Task[iNumberOfWorkers]; var ts2 = new Action(RemoveElements); for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2) { var name = "Thread_worker_" + iThreads; var ts1 = new Action(() => AddMoreElements(name)); workers[iThreads] = Task.Run(ts1); workers[iThreads + 1] = Task.Run(ts2); } Task.WaitAll(workers); // Check: // Either there should be some elements (the new ones we added and/or the original ones) or none var hshPossibleValues = new Hashtable(); for (int i = 0; i < NumberOfElements; i++) { hshPossibleValues.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < iNumberOfWorkers; i++) { hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } IDictionaryEnumerator idic = hashMother.GetEnumerator(); while (idic.MoveNext()) { Assert.True(hshPossibleValues.ContainsKey(idic.Key)); Assert.True(hshPossibleValues.ContainsValue(idic.Value)); } } private void AddMoreElements(string threadName) { _hashGrandDaughter.Add("Key_" + threadName, threadName); } private void RemoveElements() { _hashDaughter.Clear(); } } }
// 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.Diagnostics.Contracts; using System.Security; namespace System.IO { public sealed partial class DirectoryInfo : FileSystemInfo { [System.Security.SecuritySafeCritical] public DirectoryInfo(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); OriginalPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path; FullPath = Path.GetFullPath(path); DisplayPath = GetDisplayName(OriginalPath); } [System.Security.SecuritySafeCritical] internal DirectoryInfo(string fullPath, string originalPath) { Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = originalPath ?? Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath); } public override string Name { get { return GetDirName(FullPath); } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { string s = FullPath; // FullPath might end in either "parent\child" or "parent\child", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. if (!PathHelpers.IsRoot(s)) { s = PathHelpers.TrimEndingDirectorySeparator(s); } string parentName = Path.GetDirectoryName(s); return parentName != null ? new DirectoryInfo(parentName, null) : null; } } [System.Security.SecuritySafeCritical] public DirectoryInfo CreateSubdirectory(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path); } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(string path) { Debug.Assert(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); string newDirs = Path.Combine(FullPath, path); string fullPath = Path.GetFullPath(newDirs); if (0 != string.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path)); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } [System.Security.SecurityCritical] public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). [SecurityCritical] public FileInfo[] GetFiles(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). private FileInfo[] InternalGetFiles(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); return EnumerableHelpers.ToArray(enumerable); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); return EnumerableHelpers.ToArray(enumerable); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) { Debug.Assert(searchPattern != null); Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { string rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(string destDirName) { if (destDirName == null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); Contract.EndContractBlock(); string destination = Path.GetFullPath(destDirName); string destinationWithSeparator = destination; if (destinationWithSeparator[destinationWithSeparator.Length - 1] != Path.DirectorySeparatorChar) destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString; string fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; if (PathInternal.IsDirectoryTooLong(fullSourcePath)) throw new PathTooLongException(SR.IO_PathTooLong); if (PathInternal.IsDirectoryTooLong(destinationWithSeparator)) throw new PathTooLongException(SR.IO_PathTooLong); StringComparison pathComparison = PathInternal.StringComparison; if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); string sourceRoot = Path.GetPathRoot(fullSourcePath); string destinationRoot = Path.GetPathRoot(destinationWithSeparator); if (!string.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); // Windows will throw if the source file/directory doesn't exist, we preemptively check // to make sure our cross platform behavior matches NetFX behavior. if (!Exists && !FileSystem.Current.FileExists(FullPath)) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath)); if (FileSystem.Current.DirectoryExists(destinationWithSeparator)) throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator)); FileSystem.Current.MoveDirectory(FullPath, destination); FullPath = destinationWithSeparator; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath); // Flush any cached information about the directory. Invalidate(); } [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } /// <summary> /// Returns the original path. Use FullPath or Name properties for the path / directory name. /// </summary> public override string ToString() { return DisplayPath; } private static string GetDisplayName(string originalPath) { Debug.Assert(originalPath != null); // Desktop documents that the path returned by ToString() should be the original path. // For SL/Phone we only gave the directory name regardless of what was passed in. return PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ? "." : originalPath; } private static string GetDirName(string fullPath) { Debug.Assert(fullPath != null); return PathHelpers.IsRoot(fullPath) ? fullPath : Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath)); } } }
// 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; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate001.dlgate001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate001.dlgate001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression; // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E += new Dele(C.Foo); if (c.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate002.dlgate002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dlgate002.dlgate002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate creation expression; (no event accessor declaration) // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E += new Dele(C.Foo); if (c.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic001.dynamic001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic001.dynamic001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic002.dynamic002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic002.dynamic002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is dynamic runtime delegate: without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic003.dynamic003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic003.dynamic003; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public event Dele E; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic004.dynamic004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.dynamic004.dynamic004; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // lhs is static typed and rhs is dynamic runtime delegate: without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { C d = new C(); dynamic c = new C(); c.E += (Dele)C.Foo; d.E += c.E; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty001.fieldproperty001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty001.fieldproperty001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public event Dele E; public C() { field = C.Foo; } public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); //c.E += C.Foo; C c = new C(); d.E += c.field; if (d.DoEvent(9) != 9) return 1; d.E -= c.field; d.E += c.Field; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty002.fieldproperty002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.fieldproperty002.fieldproperty002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is field/property of delegate type : without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public Dele field; public Dele Field { get { return field; } set { field = value; } } public Dele E; public C() { field = C.Foo; } public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); //c.E += C.Foo; C c = new C(); d.E += c.field; if (d.DoEvent(9) != 9) return 1; d.E -= c.field; d.E += c.Field; if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null001.null001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null001.null001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // Negtive: rhs is null literal : lhs is not null // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.E += (Dele)C.Foo; c.E += null; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null002.null002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.null002.null002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // Negtive: rhs is null literal : lhs is null // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public event Dele E; public static int Foo(int i) { return i; } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); int result = 0; try { c.E += null; result += 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.AmbigBinaryOps, e.Message, "+=", "<null>", "<null>")) return 1; } return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return001.return001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return001.return001; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : with event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public static Dele Bar() { return C.Foo; } public event Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += C.Bar(); if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return002.return002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.context.operate.compound.evnt.pluseql.return002.return002; // <Area> Dynamic -- compound operator</Area> // <Title> compund operator +=/-= on event </Title> // <Description> // rhs is delegate invocation return delegate : without event accessor // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public delegate int Dele(int i); public class C { public static int Foo(int i) { return i; } public static Dele Bar() { return C.Foo; } public Dele E; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new C(); d.E += C.Bar(); if (d.DoEvent(9) != 9) return 1; return 0; } public int DoEvent(int arg) { return this.E(arg); } } // </Code> }
using System; using SystemEx.Html; using System.Runtime.CompilerServices; using System.Collections; using System.Html; namespace SystemEx.IO { public class FileInfo { public const char SeparatorChar = '/'; public const string Separator = "/"; //public const char PathSeparatorChar = ':'; //public const string PathSeparator = ":"; public static FileInfo Root = new FileInfo(""); private FileInfo _parent; private string _name; //private bool _absolute; [AlternateSignature] public extern FileInfo(string fileName); public FileInfo(string fileName, FileInfo parent) { while (fileName.EndsWith(Separator) && (fileName.Length > 0)) fileName = fileName.Substring(0, fileName.Length - 1); int cut = fileName.LastIndexOf(SeparatorChar); if (cut == -1) _name = fileName; else if (cut == 0) { _name = fileName.Substring(cut, fileName.Length); _parent = (_name == "" ? null : Root); } else { _name = fileName.Substring(cut + 1, fileName.Length); _parent = new FileInfo(fileName.Substring(0, cut)); } } public string Name { get { return _name; } } private string Parent { get { return (_parent == null ? "" : _parent.Path); } } private FileInfo ParentFileInfo { get { return _parent; } } public string Path { get { return (_parent == null ? _name : _parent.Path + SeparatorChar + _name); } } private bool IsRoot() { return ((_name == "") && (_parent == null)); } internal bool IsAbsolute() { if (IsRoot()) return true; if (_parent == null) return false; return _parent.IsAbsolute(); } internal string GetAbsolutePath() { string path = GetAbsoluteFile().Path; return (path.Length == 0 ? "/" : path); } internal FileInfo GetAbsoluteFile() { if (IsAbsolute()) return this; return new FileInfo(_name, _parent == null ? Root : _parent.GetAbsoluteFile()); } internal string GetCanonicalPath() { return GetCanonicalFile().GetAbsolutePath(); } internal FileInfo GetCanonicalFile() { FileInfo cParent = (_parent == null ? null : _parent.GetCanonicalFile()); if (_name == ".") return (cParent == null ? Root : cParent); if ((cParent != null) && (cParent._name == "")) cParent = null; if (_name == "..") { if (cParent == null) return Root; if (cParent._parent == null) return Root; return cParent._parent; } return new FileInfo(_name, (cParent == null) && (_name != "") ? Root : cParent); } internal bool Exists() { try { return (LocalStorage.GetItem(GetCanonicalPath()) != null); } catch (Exception e) { if (e.Message.StartsWith("IOException")) return false; throw e; } } internal bool IsFileInfo() { try { String s = LocalStorage.GetItem(GetCanonicalPath()); return ((s != null) && !s.StartsWith("{")); } catch (Exception e) { if (e.Message.StartsWith("IOException")) return false; throw e; } } public long Length { get { try { if (!Exists()) return 0; FileStream raf = new FileStream(null, FileMode.Append, FileAccess.Read, this); long length = raf.Length; raf.Close(); return length; } catch (Exception e) { if (e.Message.StartsWith("IOException")) return 0; throw e; } } } public bool CreateNewFile() { if (Exists() || !_parent.Exists()) return false; LocalStorage.SetItem(GetCanonicalPath(), WindowEx.Btoa("")); return true; } internal bool Delete_() { try { if (!Exists()) return false; LocalStorage.RemoveItem(GetCanonicalPath()); return true; } catch (Exception e) { if (e.Message.StartsWith("IOException")) return false; throw e; } } private bool MakeDirectory() { try { if ((_parent != null) && !_parent.Exists()) return false; if (Exists()) return false; // We may want to make this a JS map LocalStorage.SetItem(GetCanonicalPath(), "{}"); return true; } catch (Exception e) { if (e.Message.StartsWith("IOException")) return false; throw e; } } internal bool MakeDirectories() { if (_parent != null) _parent.MakeDirectories(); return MakeDirectory(); } #region List [AlternateSignature] public extern FileInfo[] ListFiles(); public IEnumerable ListFiles(FileInfoSearchPredicate predicate) { ArrayList files = new ArrayList(); try { String prefix = GetCanonicalPath(); if (!prefix.EndsWith(Separator)) prefix += SeparatorChar; int cut = prefix.Length; int count = LocalStorage.Length; for (int index = 0; index < count; index++) { String key = LocalStorage.Key(index); if (key.StartsWith(prefix) && (key.IndexOf(SeparatorChar, cut) == -1)) { String name = key.Substring(cut, key.Length); if ((predicate == null) || predicate(name, this)) files.Add(new FileInfo(name, this)); } } } catch (Exception) { } return files; } #endregion } }
// dnlib: See LICENSE.txt for more info using System; using System.Text; using dnlib.DotNet.MD; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the Constant table /// </summary> public abstract class Constant : IMDTokenProvider { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <inheritdoc/> public MDToken MDToken { get { return new MDToken(Table.Constant, rid); } } /// <inheritdoc/> public uint Rid { get { return rid; } set { rid = value; } } /// <summary> /// From column Constant.Type /// </summary> public ElementType Type { get { return type; } set { type = value; } } /// <summary/> protected ElementType type; /// <summary> /// From column Constant.Value /// </summary> public object Value { get { return value; } set { this.value = value; } } /// <summary/> protected object value; } /// <summary> /// A Constant row created by the user and not present in the original .NET file /// </summary> public class ConstantUser : Constant { /// <summary> /// Default constructor /// </summary> public ConstantUser() { } /// <summary> /// Constructor /// </summary> /// <param name="value">Value</param> public ConstantUser(object value) { this.type = GetElementType(value); this.value = value; } /// <summary> /// Constructor /// </summary> /// <param name="value">Value</param> /// <param name="type">Type</param> public ConstantUser(object value, ElementType type) { this.type = type; this.value = value; } static ElementType GetElementType(object value) { if (value == null) return ElementType.Class; switch (System.Type.GetTypeCode(value.GetType())) { case TypeCode.Boolean: return ElementType.Boolean; case TypeCode.Char: return ElementType.Char; case TypeCode.SByte: return ElementType.I1; case TypeCode.Byte: return ElementType.U1; case TypeCode.Int16: return ElementType.I2; case TypeCode.UInt16: return ElementType.U2; case TypeCode.Int32: return ElementType.I4; case TypeCode.UInt32: return ElementType.U4; case TypeCode.Int64: return ElementType.I8; case TypeCode.UInt64: return ElementType.U8; case TypeCode.Single: return ElementType.R4; case TypeCode.Double: return ElementType.R8; case TypeCode.String: return ElementType.String; default: return ElementType.Void; } } } /// <summary> /// Created from a row in the Constant table /// </summary> sealed class ConstantMD : Constant, IMDTokenProviderMD { readonly uint origRid; /// <inheritdoc/> public uint OrigRid { get { return origRid; } } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>Constant</c> row</param> /// <param name="rid">Row ID</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public ConstantMD(ModuleDefMD readerModule, uint rid) { #if DEBUG if (readerModule == null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.ConstantTable.IsInvalidRID(rid)) throw new BadImageFormatException(string.Format("Constant rid {0} does not exist", rid)); #endif this.origRid = rid; this.rid = rid; uint value = readerModule.TablesStream.ReadConstantRow(origRid, out this.type); this.value = GetValue(this.type, readerModule.BlobStream.ReadNoNull(value)); } static object GetValue(ElementType etype, byte[] data) { switch (etype) { case ElementType.Boolean: if (data == null || data.Length < 1) return false; return BitConverter.ToBoolean(data, 0); case ElementType.Char: if (data == null || data.Length < 2) return (char)0; return BitConverter.ToChar(data, 0); case ElementType.I1: if (data == null || data.Length < 1) return (sbyte)0; return (sbyte)data[0]; case ElementType.U1: if (data == null || data.Length < 1) return (byte)0; return data[0]; case ElementType.I2: if (data == null || data.Length < 2) return (short)0; return BitConverter.ToInt16(data, 0); case ElementType.U2: if (data == null || data.Length < 2) return (ushort)0; return BitConverter.ToUInt16(data, 0); case ElementType.I4: if (data == null || data.Length < 4) return (int)0; return BitConverter.ToInt32(data, 0); case ElementType.U4: if (data == null || data.Length < 4) return (uint)0; return BitConverter.ToUInt32(data, 0); case ElementType.I8: if (data == null || data.Length < 8) return (long)0; return BitConverter.ToInt64(data, 0); case ElementType.U8: if (data == null || data.Length < 8) return (ulong)0; return BitConverter.ToUInt64(data, 0); case ElementType.R4: if (data == null || data.Length < 4) return (float)0; return BitConverter.ToSingle(data, 0); case ElementType.R8: if (data == null || data.Length < 8) return (double)0; return BitConverter.ToDouble(data, 0); case ElementType.String: if (data == null) return string.Empty; return Encoding.Unicode.GetString(data, 0, data.Length / 2 * 2); case ElementType.Class: return null; default: return null; } } } }
using System; using System.Linq; using System.Linq.Expressions; using System.Reflection; using FluentNHibernate.Conventions; using FluentNHibernate.Conventions.Inspections; using FluentNHibernate.MappingModel; using FluentNHibernate.Utils; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.Inspection { [TestFixture, Category("Inspection DSL")] public class ManyToOneInspectorMapsToManyToOneMapping { private ManyToOneMapping mapping; private IManyToOneInspector inspector; [SetUp] public void CreateDsl() { mapping = new ManyToOneMapping(); inspector = new ManyToOneInspector(mapping); } [Test] public void AccessMapped() { mapping.Access = "field"; inspector.Access.ShouldEqual(Access.Field); } [Test] public void AccessIsSet() { mapping.Access = "field"; inspector.IsSet(Prop(x => x.Access)) .ShouldBeTrue(); } [Test] public void AccessIsNotSet() { inspector.IsSet(Prop(x => x.Access)) .ShouldBeFalse(); } [Test] public void CascadeMapped() { mapping.Cascade = "all"; inspector.Cascade.ShouldEqual(Cascade.All); } [Test] public void CascadeIsSet() { mapping.Cascade = "all"; inspector.IsSet(Prop(x => x.Cascade)) .ShouldBeTrue(); } [Test] public void CascadeIsNotSet() { inspector.IsSet(Prop(x => x.Cascade)) .ShouldBeFalse(); } [Test] public void ClassMapped() { mapping.Class = new TypeReference(typeof(string)); inspector.Class.ShouldEqual(new TypeReference(typeof(string))); } [Test] public void ClassIsSet() { mapping.Class = new TypeReference(typeof(string)); inspector.IsSet(Prop(x => x.Class)) .ShouldBeTrue(); } [Test] public void ClassIsNotSet() { inspector.IsSet(Prop(x => x.Class)) .ShouldBeFalse(); } [Test] public void ColumnsCollectionHasSameCountAsMapping() { mapping.AddColumn(new ColumnMapping()); inspector.Columns.Count().ShouldEqual(1); } [Test] public void ColumnsCollectionOfInspectors() { mapping.AddColumn(new ColumnMapping()); inspector.Columns.First().ShouldBeOfType<IColumnInspector>(); } [Test] public void ColumnsCollectionIsEmpty() { inspector.Columns.IsEmpty().ShouldBeTrue(); } [Test] public void FetchMapped() { mapping.Fetch = "join"; inspector.Fetch.ShouldEqual(Fetch.Join); } [Test] public void FetchIsSet() { mapping.Fetch = "join"; inspector.IsSet(Prop(x => x.Fetch)) .ShouldBeTrue(); } [Test] public void FetchIsNotSet() { inspector.IsSet(Prop(x => x.Fetch)) .ShouldBeFalse(); } [Test] public void ForeignKeyMapped() { mapping.ForeignKey = "key"; inspector.ForeignKey.ShouldEqual("key"); } [Test] public void ForeignKeyIsSet() { mapping.ForeignKey = "key"; inspector.IsSet(Prop(x => x.ForeignKey)) .ShouldBeTrue(); } [Test] public void ForeignKeyIsNotSet() { inspector.IsSet(Prop(x => x.ForeignKey)) .ShouldBeFalse(); } [Test] public void InsertMapped() { mapping.Insert = true; inspector.Insert.ShouldBeTrue(); } [Test] public void InsertIsSet() { mapping.Insert = true; inspector.IsSet(Prop(x => x.Insert)) .ShouldBeTrue(); } [Test] public void InsertIsNotSet() { inspector.IsSet(Prop(x => x.Insert)) .ShouldBeFalse(); } [Test] public void LazyLoadMapped() { mapping.Lazy = true; inspector.LazyLoad.ShouldEqual(true); } [Test] public void LazyLoadIsSet() { mapping.Lazy = true; inspector.IsSet(Prop(x => x.LazyLoad)) .ShouldBeTrue(); } [Test] public void LazyLoadIsNotSet() { inspector.IsSet(Prop(x => x.LazyLoad)) .ShouldBeFalse(); } [Test] public void NameMapped() { mapping.Name = "name"; inspector.Name.ShouldEqual("name"); } [Test] public void NameIsSet() { mapping.Name = "name"; inspector.IsSet(Prop(x => x.Name)) .ShouldBeTrue(); } [Test] public void NameIsNotSet() { inspector.IsSet(Prop(x => x.Name)) .ShouldBeFalse(); } [Test] public void NotFoundMapped() { mapping.NotFound = "exception"; inspector.NotFound.ShouldEqual(NotFound.Exception); } [Test] public void NotFoundIsSet() { mapping.NotFound = "exception"; inspector.IsSet(Prop(x => x.NotFound)) .ShouldBeTrue(); } [Test] public void NotFoundIsNotSet() { inspector.IsSet(Prop(x => x.NotFound)) .ShouldBeFalse(); } [Test] public void PropertyRefMapped() { mapping.PropertyRef = "ref"; inspector.PropertyRef.ShouldEqual("ref"); } [Test] public void PropertyRefIsSet() { mapping.PropertyRef = "ref"; inspector.IsSet(Prop(x => x.PropertyRef)) .ShouldBeTrue(); } [Test] public void PropertyRefIsNotSet() { inspector.IsSet(Prop(x => x.PropertyRef)) .ShouldBeFalse(); } [Test] public void UpdateMapped() { mapping.Update = true; inspector.Update.ShouldEqual(true); } [Test] public void UpdateIsSet() { mapping.Update = true; inspector.IsSet(Prop(x => x.Update)) .ShouldBeTrue(); } [Test] public void UpdateIsNotSet() { inspector.IsSet(Prop(x => x.Update)) .ShouldBeFalse(); } #region Helpers private PropertyInfo Prop(Expression<Func<IManyToOneInspector, object>> propertyExpression) { return ReflectionHelper.GetProperty(propertyExpression); } #endregion } }
using System; using UnityEngine; using UnityEditor; namespace Anima2D { public class TextureEditorWindow : EditorWindow { public Color textureColor = Color.white; protected class Styles { public readonly GUIStyle dragdot = "U2D.dragDot"; public readonly GUIStyle dragdotDimmed = "U2D.dragDotDimmed"; public readonly GUIStyle dragdotactive = "U2D.dragDotActive"; public readonly GUIStyle createRect = "U2D.createRect"; public readonly GUIStyle preToolbar = "preToolbar"; public readonly GUIStyle preButton = "preButton"; public readonly GUIStyle preLabel = "preLabel"; public readonly GUIStyle preSlider = "preSlider"; public readonly GUIStyle preSliderThumb = "preSliderThumb"; public readonly GUIStyle preBackground = "preBackground"; public readonly GUIStyle pivotdotactive = "U2D.pivotDotActive"; public readonly GUIStyle pivotdot = "U2D.pivotDot"; public readonly GUIStyle dragBorderdot = new GUIStyle(); public readonly GUIStyle dragBorderDotActive = new GUIStyle(); public readonly GUIStyle toolbar; public readonly GUIContent alphaIcon; public readonly GUIContent RGBIcon; public readonly GUIStyle notice; public readonly GUIContent smallMip; public readonly GUIContent largeMip; public readonly GUIContent spriteIcon; public readonly GUIContent showBonesIcon; Texture2D mShowBonesImage; Texture2D showBonesImage { get { if(!mShowBonesImage) { mShowBonesImage = EditorGUIUtility.Load("Anima2D/showBonesIcon.png") as Texture2D; mShowBonesImage.hideFlags = HideFlags.DontSave; } return mShowBonesImage; } } public Styles() { this.toolbar = new GUIStyle(EditorStyles.inspectorDefaultMargins); this.toolbar.margin.top = 0; this.toolbar.margin.bottom = 0; this.alphaIcon = EditorGUIUtility.IconContent("PreTextureAlpha"); this.RGBIcon = EditorGUIUtility.IconContent("PreTextureRGB"); this.preToolbar.border.top = 0; this.createRect.border = new RectOffset(3, 3, 3, 3); this.notice = new GUIStyle(GUI.skin.label); this.notice.alignment = TextAnchor.MiddleCenter; this.notice.normal.textColor = Color.yellow; this.dragBorderdot.fixedHeight = 5f; this.dragBorderdot.fixedWidth = 5f; this.dragBorderdot.normal.background = EditorGUIUtility.whiteTexture; this.dragBorderDotActive.fixedHeight = this.dragBorderdot.fixedHeight; this.dragBorderDotActive.fixedWidth = this.dragBorderdot.fixedWidth; this.dragBorderDotActive.normal.background = EditorGUIUtility.whiteTexture; this.smallMip = EditorGUIUtility.IconContent("PreTextureMipMapLow"); this.largeMip = EditorGUIUtility.IconContent("PreTextureMipMapHigh"); this.spriteIcon = EditorGUIUtility.IconContent("Sprite Icon"); this.spriteIcon.tooltip = "Reset Sprite"; this.showBonesIcon = new GUIContent(showBonesImage); this.showBonesIcon.tooltip = "Show Bones"; } } public static string s_NoSelectionWarning = "No sprite selected"; protected const float k_BorderMargin = 10f; protected const float k_ScrollbarMargin = 16f; protected const float k_InspectorWindowMargin = 8f; protected const float k_InspectorWidth = 330f; protected const float k_InspectorHeight = 148f; protected const float k_MinZoomPercentage = 0.9f; protected const float k_MaxZoom = 10f; protected const float k_WheelZoomSpeed = 0.03f; protected const float k_MouseZoomSpeed = 0.005f; protected static Styles s_Styles; protected Texture2D m_Texture; protected Rect m_TextureViewRect; protected Rect m_TextureRect; protected bool m_ShowAlpha; protected float m_Zoom = -1f; protected float m_MipLevel; protected Vector2 m_ScrollPosition = default(Vector2); private static Material s_HandleWireMaterial; private static Material s_HandleWireMaterial2D; static Material handleWireMaterial { get { if (!s_HandleWireMaterial) { s_HandleWireMaterial = (Material)EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat"); s_HandleWireMaterial2D = (Material)EditorGUIUtility.LoadRequired("SceneView/2DHandleLines.mat"); } return (!Camera.current) ? s_HandleWireMaterial2D : s_HandleWireMaterial; } } static Texture2D transparentCheckerTexture { get { if (EditorGUIUtility.isProSkin) { return EditorGUIUtility.LoadRequired("Previews/Textures/textureCheckerDark.png") as Texture2D; } return EditorGUIUtility.LoadRequired("Previews/Textures/textureChecker.png") as Texture2D; } } protected Rect maxScrollRect { get { float num = (float)this.m_Texture.width * 0.5f * this.m_Zoom; float num2 = (float)this.m_Texture.height * 0.5f * this.m_Zoom; return new Rect(-num, -num2, this.m_TextureViewRect.width + num * 2f, this.m_TextureViewRect.height + num2 * 2f); } } protected Rect maxRect { get { float num = this.m_TextureViewRect.width * 0.5f / this.GetMinZoom(); float num2 = this.m_TextureViewRect.height * 0.5f / this.GetMinZoom(); float left = -num; float top = -num2; float width = (float)this.m_Texture.width + num * 2f; float height = (float)this.m_Texture.height + num2 * 2f; return new Rect(left, top, width, height); } } protected void InitStyles() { if (s_Styles == null) { s_Styles = new Styles(); } } protected float GetMinZoom() { if (this.m_Texture == null) { return 1f; } return Mathf.Min(this.m_TextureViewRect.width / (float)this.m_Texture.width, this.m_TextureViewRect.height / (float)this.m_Texture.height) * 0.9f; } protected virtual void HandleZoom() { bool flag = Event.current.alt && Event.current.button == 1; if (flag) { EditorGUIUtility.AddCursorRect(this.m_TextureViewRect, MouseCursor.Zoom); } if (((Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown) && flag) || ((Event.current.type == EventType.KeyUp || Event.current.type == EventType.KeyDown) && Event.current.keyCode == KeyCode.LeftAlt)) { base.Repaint(); } if (Event.current.type == EventType.ScrollWheel || (Event.current.type == EventType.MouseDrag && Event.current.alt && Event.current.button == 1)) { float num = 1f - Event.current.delta.y * ((Event.current.type != EventType.ScrollWheel) ? -0.005f : 0.03f); float num2 = this.m_Zoom * num; float num3 = Mathf.Clamp(num2, this.GetMinZoom(), 10f); if (num3 != this.m_Zoom) { this.m_Zoom = num3; if (num2 != num3) { num /= num2 / num3; } this.m_ScrollPosition *= num; Event.current.Use(); } } } protected void HandlePanning() { bool flag = (!Event.current.alt && Event.current.button > 0) || (Event.current.alt && Event.current.button <= 0); if (flag && GUIUtility.hotControl == 0) { EditorGUIUtility.AddCursorRect(this.m_TextureViewRect, MouseCursor.Pan); if (Event.current.type == EventType.MouseDrag) { this.m_ScrollPosition -= Event.current.delta; Event.current.Use(); } } if (((Event.current.type == EventType.MouseUp || Event.current.type == EventType.MouseDown) && flag) || ((Event.current.type == EventType.KeyUp || Event.current.type == EventType.KeyDown) && Event.current.keyCode == KeyCode.LeftAlt)) { base.Repaint(); } } public void DrawLine(Vector3 p1, Vector3 p2) { GL.Vertex(p1); GL.Vertex(p2); } public void BeginLines(Color color) { handleWireMaterial.SetPass(0); GL.PushMatrix(); GL.MultMatrix(Handles.matrix); GL.Begin(1); GL.Color(color); } public void EndLines() { GL.End(); GL.PopMatrix(); } protected void DrawTexturespaceBackground() { float num = Mathf.Max(this.maxRect.width, this.maxRect.height); Vector2 b = new Vector2(this.maxRect.xMin, this.maxRect.yMin); float num2 = num * 0.5f; float a = (!EditorGUIUtility.isProSkin) ? 0.08f : 0.15f; float num3 = 8f; BeginLines(new Color(0f, 0f, 0f, a)); for (float num4 = 0f; num4 <= num; num4 += num3) { float x = -num2 + num4 + b.x; float y = num2 + num4 + b.y; Vector2 p1 = new Vector2(x,y); x = num2 + num4 + b.x; y = -num2 + num4 + b.y;; Vector2 p2 = new Vector2(x, y); DrawLine(p1, p2); } EndLines(); } private float Log2(float x) { return (float)(Math.Log((double)x) / Math.Log(2.0)); } protected void DrawTexture() { int num = Mathf.Max(this.m_Texture.width, 1); float num2 = Mathf.Min(this.m_MipLevel, (float)(m_Texture.mipmapCount - 1)); //float mipMapBias = this.m_Texture.mipMapBias; m_Texture.mipMapBias = (num2 - this.Log2((float)num / this.m_TextureRect.width)); //FilterMode filterMode = this.m_Texture.filterMode; //m_Texture.filterMode = FilterMode.Point; Rect r = m_TextureRect; r.position -= m_ScrollPosition; if (this.m_ShowAlpha) { EditorGUI.DrawTextureAlpha(r, this.m_Texture); } else { GUI.DrawTextureWithTexCoords(r, transparentCheckerTexture, new Rect(r.width * -0.5f / (float)transparentCheckerTexture.width, r.height * -0.5f / (float)transparentCheckerTexture.height, r.width / (float)transparentCheckerTexture.width, r.height / (float)transparentCheckerTexture.height), false); GUI.color = textureColor; GUI.DrawTexture(r, this.m_Texture); } //m_Texture.filterMode = filterMode; //m_Texture.mipMapBias = mipMapBias; } protected void DrawScreenspaceBackground() { if (Event.current.type == EventType.Repaint) { s_Styles.preBackground.Draw(this.m_TextureViewRect, false, false, false, false); } } protected void HandleScrollbars() { Rect position = new Rect(this.m_TextureViewRect.xMin, this.m_TextureViewRect.yMax, this.m_TextureViewRect.width, 16f); this.m_ScrollPosition.x = GUI.HorizontalScrollbar(position, this.m_ScrollPosition.x, this.m_TextureViewRect.width, this.maxScrollRect.xMin, this.maxScrollRect.xMax); Rect position2 = new Rect(this.m_TextureViewRect.xMax, this.m_TextureViewRect.yMin, 16f, this.m_TextureViewRect.height); this.m_ScrollPosition.y = GUI.VerticalScrollbar(position2, this.m_ScrollPosition.y, this.m_TextureViewRect.height, this.maxScrollRect.yMin, this.maxScrollRect.yMax); } protected void SetupHandlesMatrix() { Vector3 pos = new Vector3(this.m_TextureRect.x - m_ScrollPosition.x, this.m_TextureRect.yMax - m_ScrollPosition.y, 0f); Vector3 s = new Vector3(this.m_Zoom, -this.m_Zoom, 1f); Handles.matrix = Matrix4x4.TRS(pos, Quaternion.identity, s); } protected void DoAlphaZoomToolbarGUI() { this.m_ShowAlpha = GUILayout.Toggle(this.m_ShowAlpha, (!this.m_ShowAlpha) ? s_Styles.RGBIcon : s_Styles.alphaIcon, "toolbarButton", new GUILayoutOption[0]); this.m_Zoom = GUILayout.HorizontalSlider(this.m_Zoom, this.GetMinZoom(), 10f, s_Styles.preSlider, s_Styles.preSliderThumb, new GUILayoutOption[] { GUILayout.MaxWidth(64f) }); int num = 1; if (this.m_Texture != null) { num = Mathf.Max(num, m_Texture.mipmapCount); } EditorGUI.BeginDisabledGroup(num == 1); GUILayout.Box(s_Styles.smallMip, s_Styles.preLabel, new GUILayoutOption[0]); this.m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(this.m_MipLevel, (float)(num - 1), 0f, s_Styles.preSlider, s_Styles.preSliderThumb, new GUILayoutOption[] { GUILayout.MaxWidth(64f) })); GUILayout.Box(s_Styles.largeMip, s_Styles.preLabel, new GUILayoutOption[0]); EditorGUI.EndDisabledGroup(); } protected void DoTextureGUI() { if (m_Zoom < 0f) m_Zoom = GetMinZoom(); m_TextureRect = new Rect(m_TextureViewRect.width / 2f - (float)m_Texture.width * m_Zoom / 2f, m_TextureViewRect.height / 2f - (float)m_Texture.height * m_Zoom / 2f, (float)m_Texture.width * m_Zoom, (float)m_Texture.height * m_Zoom); HandleScrollbars(); SetupHandlesMatrix(); DrawScreenspaceBackground(); GUI.BeginGroup(m_TextureViewRect); HandleEvents(); if (Event.current.type == EventType.Repaint) { DrawTexturespaceBackground(); DrawTexture(); DrawGizmos(); } DoTextureGUIExtras(); GUI.EndGroup(); } protected virtual void HandleEvents() { } protected virtual void DoTextureGUIExtras() { } protected virtual void DrawGizmos() { } protected void SetNewTexture(Texture2D texture) { if (texture != this.m_Texture) { this.m_Texture = texture; this.m_Zoom = -1f; } } protected virtual void DoToolbarGUI() { } protected virtual void OnGUI() { if(m_Texture) { InitStyles(); EditorGUILayout.BeginHorizontal((GUIStyle) "Toolbar"); DoToolbarGUI(); EditorGUILayout.EndHorizontal(); m_TextureViewRect = new Rect(0f, 16f, base.position.width - 16f, base.position.height - 16f - 16f); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); DoTextureGUI(); EditorGUILayout.EndHorizontal(); } } } }
// 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.Diagnostics; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.Reflection; namespace Microsoft.CSharp.RuntimeBinder { internal static class BinderHelper { private static MethodInfo s_DoubleIsNaN; private static MethodInfo s_SingleIsNaN; internal static DynamicMetaObject Bind( DynamicMetaObjectBinder action, RuntimeBinder binder, DynamicMetaObject[] args, IEnumerable<CSharpArgumentInfo> arginfos, DynamicMetaObject onBindingError) { Expression[] parameters = new Expression[args.Length]; BindingRestrictions restrictions = BindingRestrictions.Empty; ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder; ParameterExpression tempForIncrement = null; IEnumerator<CSharpArgumentInfo> arginfosEnum = (arginfos ?? Array.Empty<CSharpArgumentInfo>()).GetEnumerator(); for (int index = 0; index < args.Length; ++index) { DynamicMetaObject o = args[index]; // Our contract with the DLR is such that we will not enter a bind unless we have // values for the meta-objects involved. if (!o.HasValue) { Debug.Assert(false, "The runtime binder is being asked to bind a metaobject without a value"); throw Error.InternalCompilerError(); } CSharpArgumentInfo info = arginfosEnum.MoveNext() ? arginfosEnum.Current : null; if (index == 0 && IsIncrementOrDecrementActionOnLocal(action)) { // We have an inc or a dec operation. Insert the temp local instead. // // We need to do this because for value types, the object will come // in boxed, and we'd need to unbox it to get the original type in order // to increment. The only way to do that is to create a new temporary. object value = o.Value; tempForIncrement = Expression.Variable(value != null ? value.GetType() : typeof(object), "t0"); parameters[0] = tempForIncrement; } else { parameters[index] = o.Expression; } BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info); restrictions = restrictions.Merge(r); // Here we check the argument info. If the argument info shows that the current argument // is a literal constant, then we also add an instance restriction on the value of // the constant. if (info != null && info.LiteralConstant) { if (o.Value is double && double.IsNaN((double)o.Value)) { MethodInfo isNaN = s_DoubleIsNaN ?? (s_DoubleIsNaN = typeof(double).GetMethod("IsNaN")); Expression e = Expression.Call(null, isNaN, o.Expression); restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e)); } else if (o.Value is float && float.IsNaN((float)o.Value)) { MethodInfo isNaN = s_SingleIsNaN ?? (s_SingleIsNaN = typeof(float).GetMethod("IsNaN")); Expression e = Expression.Call(null, isNaN, o.Expression); restrictions = restrictions.Merge(BindingRestrictions.GetExpressionRestriction(e)); } else { Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type)); r = BindingRestrictions.GetExpressionRestriction(e); restrictions = restrictions.Merge(r); } } } // Get the bound expression. try { DynamicMetaObject deferredBinding; Expression expression = binder.Bind(action, parameters, args, out deferredBinding); if (deferredBinding != null) { expression = ConvertResult(deferredBinding.Expression, action); restrictions = deferredBinding.Restrictions.Merge(restrictions); return new DynamicMetaObject(expression, restrictions); } if (tempForIncrement != null) { // If we have a ++ or -- payload, we need to do some temp rewriting. // We rewrite to the following: // // temp = (type)o; // temp++; // o = temp; // return o; DynamicMetaObject arg0 = args[0]; expression = Expression.Block( new[] {tempForIncrement}, Expression.Assign(tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())), expression, Expression.Assign(arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type))); } expression = ConvertResult(expression, action); return new DynamicMetaObject(expression, restrictions); } catch (RuntimeBinderException e) { if (onBindingError != null) { return onBindingError; } return new DynamicMetaObject( Expression.Throw( Expression.New( typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }), Expression.Constant(e.Message) ), GetTypeForErrorMetaObject(action, args.Length == 0 ? null : args[0]) ), restrictions ); } } ///////////////////////////////////////////////////////////////////////////////// private static bool IsTypeOfStaticCall( int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload) { return parameterIndex == 0 && callPayload != null && callPayload.StaticCall; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsComObject(object obj) { return obj != null && Marshal.IsComObject(obj); } #if ENABLECOMBINDER ///////////////////////////////////////////////////////////////////////////////// // Try to determine if this object represents a WindowsRuntime object - i.e. it either // is coming from a WinMD file or is derived from a class coming from a WinMD. // The logic here matches the CLR's logic of finding a WinRT object. internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj) { Type curType = obj?.RuntimeType; while (curType != null) { TypeAttributes attributes = curType.Attributes; if ((attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime) { // Found a WinRT COM object return true; } if ((attributes & TypeAttributes.Import) == TypeAttributes.Import) { // Found a class that is actually imported from COM but not WinRT // this is definitely a non-WinRT COM object return false; } curType = curType.BaseType; } return false; } #endif ///////////////////////////////////////////////////////////////////////////////// private static bool IsTransparentProxy(object obj) { // In the full framework, this checks: // return obj != null && RemotingServices.IsTransparentProxy(obj); // but transparent proxies don't exist in .NET Core. return false; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info) { // This detects situations where, although the argument has a value with // a given type, that type is insufficient to determine, statically, the // set of reference conversions that are going to exist at bind time for // different values. For instance, one __ComObject may allow a conversion // to IFoo while another does not. bool isDynamicObject = info != null && !info.UseCompileTimeType && (IsComObject(argument.Value) || IsTransparentProxy(argument.Value)); return isDynamicObject; } ///////////////////////////////////////////////////////////////////////////////// private static BindingRestrictions DeduceArgumentRestriction( int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload, DynamicMetaObject argument, CSharpArgumentInfo info) { // Here we deduce what predicates the DLR can apply to future calls in order to // determine whether to use the previously-computed-and-cached delegate, or // whether we need to bind the site again. Ideally we would like the // predicate to be as broad as is possible; if we can re-use analysis based // solely on the type of the argument, that is preferable to re-using analysis // based on object identity with a previously-analyzed argument. // The times when we need to restrict re-use to a particular instance, rather // than its type, are: // // * if the argument is a null reference then we have no type information. // // * if we are making a static call then the first argument is // going to be a Type object. In this scenario we should always check // for a specific Type object rather than restricting to the Type type. // // * if the argument was dynamic at compile time and it is a dynamic proxy // object that the runtime manages, such as COM RCWs and transparent // proxies. // // ** there is also a case for constant values (such as literals) to use // something like value restrictions, and that is accomplished in Bind(). bool useValueRestriction = argument.Value == null || IsTypeOfStaticCall(parameterIndex, callPayload) || IsDynamicallyTypedRuntimeProxy(argument, info); return useValueRestriction ? BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) : BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType); } ///////////////////////////////////////////////////////////////////////////////// private static Expression ConvertResult(Expression binding, DynamicMetaObjectBinder action) { // Need to handle the following cases: // (1) Call to a constructor: no conversions. // (2) Call to a void-returning method: return null iff result is discarded. // (3) Call to a value-type returning method: box to object. // // In all other cases, binding.Type should be equivalent or // reference assignable to resultType. var invokeConstructor = action as CSharpInvokeConstructorBinder; if (invokeConstructor != null) { // No conversions needed, the call site has the correct type. return binding; } if (binding.Type == typeof(void)) { var invoke = action as ICSharpInvokeOrInvokeMemberBinder; if (invoke != null && invoke.ResultDiscarded) { Debug.Assert(action.ReturnType == typeof(object)); return Expression.Block(binding, Expression.Default(action.ReturnType)); } else { throw Error.BindToVoidMethodButExpectResult(); } } if (binding.Type.IsValueType && !action.ReturnType.IsValueType) { Debug.Assert(action.ReturnType == typeof(object)); return Expression.Convert(binding, action.ReturnType); } return binding; } ///////////////////////////////////////////////////////////////////////////////// private static Type GetTypeForErrorMetaObject(DynamicMetaObjectBinder action, DynamicMetaObject arg0) { // This is similar to ConvertResult but has fewer things to worry about. var invokeConstructor = action as CSharpInvokeConstructorBinder; if (invokeConstructor != null) { Type result = arg0.Value as Type; if (result == null) { Debug.Assert(false); return typeof(object); } return result; } return action.ReturnType; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsIncrementOrDecrementActionOnLocal(DynamicMetaObjectBinder action) { CSharpUnaryOperationBinder operatorPayload = action as CSharpUnaryOperationBinder; return operatorPayload != null && (operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement); } ///////////////////////////////////////////////////////////////////////////////// internal static T[] Cons<T>(T sourceHead, T[] sourceTail) { if (sourceTail?.Length != 0) { T[] array = new T[sourceTail.Length + 1]; array[0] = sourceHead; sourceTail.CopyTo(array, 1); return array; } return new[] { sourceHead }; } internal static T[] Cons<T>(T sourceHead, T[] sourceMiddle, T sourceLast) { if (sourceMiddle?.Length != 0) { T[] array = new T[sourceMiddle.Length + 2]; array[0] = sourceHead; array[array.Length - 1] = sourceLast; sourceMiddle.CopyTo(array, 1); return array; } return new[] {sourceHead, sourceLast}; } ///////////////////////////////////////////////////////////////////////////////// internal static List<T> ToList<T>(IEnumerable<T> source) { if (source == null) { return new List<T>(); } return source.ToList(); } ///////////////////////////////////////////////////////////////////////////////// internal static CallInfo CreateCallInfo(IEnumerable<CSharpArgumentInfo> argInfos, int discard) { // This function converts the C# Binder's notion of argument information to the // DLR's notion. The DLR counts arguments differently than C#. Here are some // examples: // Expression Binder C# ArgInfos DLR CallInfo // // d.M(1, 2, 3); CSharpInvokeMemberBinder 4 3 // d(1, 2, 3); CSharpInvokeBinder 4 3 // d[1, 2] = 3; CSharpSetIndexBinder 4 2 // d[1, 2, 3] CSharpGetIndexBinder 4 3 // // The "discard" parameter tells this function how many of the C# arg infos it // should not count as DLR arguments. int argCount = 0; List<string> argNames = new List<string>(); foreach (CSharpArgumentInfo info in argInfos) { if (info.NamedArgument) { argNames.Add(info.Name); } ++argCount; } Debug.Assert(discard <= argCount); Debug.Assert(argNames.Count <= argCount - discard); return new CallInfo(argCount - discard, argNames); } internal static string GetCLROperatorName(this ExpressionType p) { switch (p) { default: return null; // Binary Operators case ExpressionType.Add: return SpecialNames.CLR_Add; case ExpressionType.Subtract: return SpecialNames.CLR_Subtract; case ExpressionType.Multiply: return SpecialNames.CLR_Multiply; case ExpressionType.Divide: return SpecialNames.CLR_Division; case ExpressionType.Modulo: return SpecialNames.CLR_Modulus; case ExpressionType.LeftShift: return SpecialNames.CLR_LShift; case ExpressionType.RightShift: return SpecialNames.CLR_RShift; case ExpressionType.LessThan: return SpecialNames.CLR_LT; case ExpressionType.GreaterThan: return SpecialNames.CLR_GT; case ExpressionType.LessThanOrEqual: return SpecialNames.CLR_LTE; case ExpressionType.GreaterThanOrEqual: return SpecialNames.CLR_GTE; case ExpressionType.Equal: return SpecialNames.CLR_Equality; case ExpressionType.NotEqual: return SpecialNames.CLR_Inequality; case ExpressionType.And: return SpecialNames.CLR_BitwiseAnd; case ExpressionType.ExclusiveOr: return SpecialNames.CLR_ExclusiveOr; case ExpressionType.Or: return SpecialNames.CLR_BitwiseOr; // "op_LogicalNot"; case ExpressionType.AddAssign: return SpecialNames.CLR_InPlaceAdd; case ExpressionType.SubtractAssign: return SpecialNames.CLR_InPlaceSubtract; case ExpressionType.MultiplyAssign: return SpecialNames.CLR_InPlaceMultiply; case ExpressionType.DivideAssign: return SpecialNames.CLR_InPlaceDivide; case ExpressionType.ModuloAssign: return SpecialNames.CLR_InPlaceModulus; case ExpressionType.AndAssign: return SpecialNames.CLR_InPlaceBitwiseAnd; case ExpressionType.ExclusiveOrAssign: return SpecialNames.CLR_InPlaceExclusiveOr; case ExpressionType.OrAssign: return SpecialNames.CLR_InPlaceBitwiseOr; case ExpressionType.LeftShiftAssign: return SpecialNames.CLR_InPlaceLShift; case ExpressionType.RightShiftAssign: return SpecialNames.CLR_InPlaceRShift; // Unary Operators case ExpressionType.Negate: return SpecialNames.CLR_UnaryNegation; case ExpressionType.UnaryPlus: return SpecialNames.CLR_UnaryPlus; case ExpressionType.Not: return SpecialNames.CLR_LogicalNot; case ExpressionType.OnesComplement: return SpecialNames.CLR_OnesComplement; case ExpressionType.IsTrue: return SpecialNames.CLR_True; case ExpressionType.IsFalse: return SpecialNames.CLR_False; case ExpressionType.Increment: return SpecialNames.CLR_PreIncrement; case ExpressionType.Decrement: return SpecialNames.CLR_PreDecrement; } } } }
using System; using System.IO; using System.Reflection; using System.Runtime.Versioning; using System.Text.RegularExpressions; using System.Threading; using Npgsql; using static System.Globalization.CultureInfo; using static Bullseye.Targets; using static SimpleExec.Command; using static Westwind.Utilities.FileUtils; namespace martenbuild { internal class MartenBuild { private const string DockerConnectionString = "Host=localhost;Port=5432;Database=marten_testing;Username=postgres;password=postgres"; private static void Main(string[] args) { var framework = GetFramework(); var configuration = GetEnvironmentVariable("config"); configuration = string.IsNullOrEmpty(configuration) ? "debug" : configuration; var disableTestParallelization = GetEnvironmentVariable("disable_test_parallelization"); Target("ci", DependsOn("connection", "default")); Target("default", DependsOn("mocha", "test", "storyteller")); Target("clean", () => EnsureDirectoriesDeleted("results", "artifacts")); Target("connection", () => File.WriteAllText("src/Marten.Testing/connection.txt", GetEnvironmentVariable("connection"))); Target("install", () => RunNpm("install")); Target("mocha", DependsOn("install"), () => RunNpm("run test")); Target("compile", DependsOn("clean"), () => { Run("dotnet", $"build src/Marten.Testing/Marten.Testing.csproj --framework {framework} --configuration {configuration}"); Run("dotnet", $"build src/Marten.Schema.Testing/Marten.Schema.Testing.csproj --framework {framework} --configuration {configuration}"); }); Target("compile-noda-time", DependsOn("clean"), () => Run("dotnet", $"build src/Marten.NodaTime.Testing/Marten.NodaTime.Testing.csproj --framework {framework} --configuration {configuration}")); Target("test-noda-time", DependsOn("compile-noda-time"), () => Run("dotnet", $"test src/Marten.NodaTime.Testing/Marten.NodaTime.Testing.csproj --framework {framework} --configuration {configuration} --no-build")); Target("compile-aspnetcore", DependsOn("clean"), () => Run("dotnet", $"build src/Marten.AspNetCore.Testing/Marten.AspNetCore.Testing.csproj --configuration {configuration}")); Target("test-aspnetcore", DependsOn("compile-aspnetcore"), () => Run("dotnet", $"test src/Marten.AspNetCore.Testing/Marten.AspNetCore.Testing.csproj --configuration {configuration} --no-build")); Target("test-schema", () => Run("dotnet", $"test src/Marten.Schema.Testing/Marten.Schema.Testing.csproj --framework {framework} --configuration {configuration} --no-build")); Target("test-commands", () => Run("dotnet", $"test src/Marten.CommandLine.Testing/Marten.CommandLine.Testing.csproj --framework {framework} --configuration {configuration} --no-build")); Target("test-codegen", () => { var projectPath = "src/CommandLineRunner"; Run("dotnet", $"run -- codegen delete", projectPath); Run("dotnet", $"run -- codegen write", projectPath); Run("dotnet", $"run -- test", projectPath); }); Target("test-marten", DependsOn("compile", "test-noda-time"), () => Run("dotnet", $"test src/Marten.Testing/Marten.Testing.csproj --framework {framework} --configuration {configuration} --no-build")); Target("test-plv8", DependsOn("compile"), () => Run("dotnet", $"test src/Marten.PLv8.Testing/Marten.PLv8.Testing.csproj --framework {framework} --configuration {configuration} --no-build")); Target("test", DependsOn("setup-test-parallelization", "test-marten", "test-noda-time", "test-commands", "test-schema", "test-plv8", "test-codegen", "test-aspnetcore")); Target("storyteller", DependsOn("compile"), () => Run("dotnet", $"run --framework {framework} --culture en-US", "src/Marten.Storyteller")); Target("open_st", DependsOn("compile"), () => Run("dotnet", $"storyteller open --framework {framework} --culture en-US", "src/Marten.Storyteller")); Target("install-mdsnippets", IgnoreIfFailed(() => Run("dotnet", $"tool install -g MarkdownSnippets.Tool") )); Target("docs", DependsOn("install", "install-mdsnippets"), () => { // Run docs site RunNpm("run docs"); }); Target("docs-build", DependsOn("install", "install-mdsnippets"), () => { // Run docs site RunNpm("run docs-build"); }); Target("docs-import-v3", DependsOn("docs-build"), () => { const string branchName = "gh-pages"; const string docTargetDir = "docs/.vitepress/dist/v3"; Run("git", $"clone -b {branchName} https://github.com/jasperfx/marten.git {InitializeDirectory(docTargetDir)}"); }); Target("clear-inline-samples", () => { var files = Directory.GetFiles("./docs", "*.md", SearchOption.AllDirectories); var pattern = @"<!-- snippet:(.+)-->[\s\S]*?<!-- endSnippet -->"; var replacePattern = $"<!-- snippet:$1-->{Environment.NewLine}<!-- endSnippet -->"; foreach (var file in files) { // Console.WriteLine(file); var content = File.ReadAllText(file); if (!content.Contains("<!-- snippet:")) { continue; } var updatedContent = Regex.Replace(content, pattern, replacePattern); File.WriteAllText(file, updatedContent); } }); Target("publish-docs-preview", DependsOn("docs-import-v3"), () => RunNpm("run deploy")); Target("publish-docs", DependsOn("docs-import-v3"), () => RunNpm("run deploy:prod")); Target("benchmarks", () => Run("dotnet", "run --project src/MartenBenchmarks --configuration Release")); Target("recordbenchmarks", () => { var profile = GetEnvironmentVariable("profile"); if (!string.IsNullOrEmpty(profile)) { CopyDirectory("BenchmarkDotNet.Artifacts/results", InitializeDirectory($"benchmarks/{profile}")); } }); Target("pack", DependsOn("compile"), ForEach("./src/Marten", "./src/Marten.CommandLine", "./src/Marten.NodaTime", "./src/Marten.PLv8", "./src/Marten.AspNetCore"), project => Run("dotnet", $"pack {project} -o ./artifacts --configuration Release")); Target("init-db", () => { Run("docker-compose", "up -d"); WaitForDatabaseToBeReady(); }); Target("setup-test-parallelization", () => { if (string.IsNullOrEmpty(disableTestParallelization)) { Console.WriteLine("disable_test_parallelization env var not set, this step is ignored."); return; } var test_projects = new string[] { "src/Marten.Testing", "src/Marten.Schema.Testing", "src/Marten.NodaTime.Testing" }; foreach (var item in test_projects) { var assemblyInfoFile = Path.Join(item, "AssemblyInfo.cs"); File.WriteAllText(assemblyInfoFile, $"using Xunit;{Environment.NewLine}[assembly: CollectionBehavior(DisableTestParallelization = {disableTestParallelization})]"); } }); RunTargetsAndExit(args); } private static void WaitForDatabaseToBeReady() { var attempt = 0; while (attempt < 10) try { using (var conn = new NpgsqlConnection(DockerConnectionString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "create extension if not exists plv8"; cmd.ExecuteNonQuery(); Console.WriteLine("Postgresql is up and ready!"); break; } } catch (Exception) { Thread.Sleep(250); attempt++; } } private static string InitializeDirectory(string path) { EnsureDirectoriesDeleted(path); Directory.CreateDirectory(path); return path; } private static void EnsureDirectoriesDeleted(params string[] paths) { foreach (var path in paths) { if (Directory.Exists(path)) { var dir = new DirectoryInfo(path); DeleteDirectory(dir); } } } private static void DeleteDirectory(DirectoryInfo baseDir) { baseDir.Attributes = FileAttributes.Normal; foreach (var childDir in baseDir.GetDirectories()) DeleteDirectory(childDir); foreach (var file in baseDir.GetFiles()) file.IsReadOnly = false; baseDir.Delete(true); } private static void RunNpm(string args) => Run("npm", args, windowsName: "cmd.exe", windowsArgs: $"/c npm {args}"); private static string GetEnvironmentVariable(string variableName) { var val = Environment.GetEnvironmentVariable(variableName); // Azure devops converts environment variable to upper case and dot to underscore // https://docs.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch // Attempt to fetch variable by updating it if (string.IsNullOrEmpty(val)) { val = Environment.GetEnvironmentVariable(variableName.ToUpper().Replace(".", "_")); } Console.WriteLine(val); return val; } private static string GetFramework() { var frameworkName = Assembly.GetEntryAssembly().GetCustomAttribute<TargetFrameworkAttribute>().FrameworkName; var version = float.Parse(frameworkName.Split('=')[1].Replace("v",""), InvariantCulture.NumberFormat); return version < 5.0 ? $"netcoreapp{version.ToString("N1", InvariantCulture.NumberFormat)}" : $"net{version.ToString("N1", InvariantCulture.NumberFormat)}"; } private static Action IgnoreIfFailed(Action action) { return () => { try { action(); } catch (Exception exception) { Console.WriteLine(exception.Message); } }; } } }
using System; using System.Collections.Generic; using BenchmarkDotNet.Attributes; using Robust.Shared.Utility; namespace Content.Benchmarks { [SimpleJob] public class ComponentFetchBenchmark { [Params(5000)] public int NEnt { get; set; } private readonly Dictionary<(EntityUid, Type), BComponent> _componentsFlat = new Dictionary<(EntityUid, Type), BComponent>(); private readonly Dictionary<Type, Dictionary<EntityUid, BComponent>> _componentsPart = new Dictionary<Type, Dictionary<EntityUid, BComponent>>(); private UniqueIndex<Type, BComponent> _allComponents = new UniqueIndex<Type, BComponent>(); private readonly List<EntityUid> _lookupEntities = new List<EntityUid>(); [GlobalSetup] public void Setup() { var random = new Random(); _componentsPart[typeof(BComponent1)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent2)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent3)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent4)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponentLookup)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent6)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent7)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent8)] = new Dictionary<EntityUid, BComponent>(); _componentsPart[typeof(BComponent9)] = new Dictionary<EntityUid, BComponent>(); for (var i = 0u; i < NEnt; i++) { var eId = new EntityUid(i); if (random.Next(1) == 0) { _lookupEntities.Add(eId); } var comps = new List<BComponent> { new BComponent1(), new BComponent2(), new BComponent3(), new BComponent4(), new BComponent6(), new BComponent7(), new BComponent8(), new BComponent9(), }; if (random.Next(1000) == 0) { comps.Add(new BComponentLookup()); } foreach (var comp in comps) { comp.Uid = eId; var type = comp.GetType(); _componentsPart[type][eId] = comp; _componentsFlat[(eId, type)] = comp; _allComponents.Add(type, comp); } } } // These two benchmarks are find "needles in haystack" components. // We try to look up a component that 0.1% of entities have on 1% of entities. // Examples of this in the engine are VisibilityComponent lookups during PVS. [Benchmark] public void FindPart() { foreach (var entityUid in _lookupEntities) { var d = _componentsPart[typeof(BComponentLookup)]; d.TryGetValue(entityUid, out _); } } [Benchmark] public void FindFlat() { foreach (var entityUid in _lookupEntities) { _componentsFlat.TryGetValue((entityUid, typeof(BComponentLookup)), out _); } } // Iteration benchmarks: // We try to iterate every instance of a single component (BComponent1) and see which is faster. [Benchmark] public void IterPart() { var list = _componentsPart[typeof(BComponent1)]; var arr = new BComponent[list.Count]; var i = 0; foreach (var c in list.Values) { arr[i++] = c; } } [Benchmark] public void IterFlat() { var list = _allComponents[typeof(BComponent1)]; var arr = new BComponent[list.Count]; var i = 0; foreach (var c in list) { arr[i++] = c; } } // We do the same as the iteration benchmarks but re-fetch the component every iteration. // This is what entity systems mostly do via entity queries because crappy code. [Benchmark] public void IterFetchPart() { var list = _componentsPart[typeof(BComponent1)]; var arr = new BComponent[list.Count]; var i = 0; foreach (var c in list.Values) { var eId = c.Uid; var d = _componentsPart[typeof(BComponent1)]; arr[i++] = d[eId]; } } [Benchmark] public void IterFetchFlat() { var list = _allComponents[typeof(BComponent1)]; var arr = new BComponent[list.Count]; var i = 0; foreach (var c in list) { var eId = c.Uid; arr[i++] = _componentsFlat[(eId, typeof(BComponent1))]; } } // Same as the previous benchmarks but with BComponentLookup instead. // Which is only on 1% of entities. [Benchmark] public void IterFetchPartRare() { var list = _componentsPart[typeof(BComponentLookup)]; var arr = new BComponent[list.Count]; var i = 0; foreach (var c in list.Values) { var eId = c.Uid; var d = _componentsPart[typeof(BComponentLookup)]; arr[i++] = d[eId]; } } [Benchmark] public void IterFetchFlatRare() { var list = _allComponents[typeof(BComponentLookup)]; var arr = new BComponent[list.Count]; var i = 0; foreach (var c in list) { var eId = c.Uid; arr[i++] = _componentsFlat[(eId, typeof(BComponentLookup))]; } } private readonly struct EntityUid : IEquatable<EntityUid> { public readonly uint Value; public EntityUid(uint value) { Value = value; } public bool Equals(EntityUid other) { return Value == other.Value; } public override bool Equals(object obj) { return obj is EntityUid other && Equals(other); } public override int GetHashCode() { return (int) Value; } public static bool operator ==(EntityUid left, EntityUid right) { return left.Equals(right); } public static bool operator !=(EntityUid left, EntityUid right) { return !left.Equals(right); } } private abstract class BComponent { public EntityUid Uid; } private class BComponent1 : BComponent { } private class BComponent2 : BComponent { } private class BComponent3 : BComponent { } private class BComponent4 : BComponent { } private class BComponentLookup : BComponent { } private class BComponent6 : BComponent { } private class BComponent7 : BComponent { } private class BComponent8 : BComponent { } private class BComponent9 : BComponent { } } }
// --------------------------------------------------------------------------- // <copyright file="DocumentSharingLocation.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the DocumentSharingLocation class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Autodiscover { using System.Collections.Generic; using System.Xml; using Microsoft.Exchange.WebServices.Data; /// <summary> /// Represents a sharing location. /// </summary> public sealed class DocumentSharingLocation { /// <summary> /// The URL of the web service to use to manipulate documents at the /// sharing location. /// </summary> private string serviceUrl; /// <summary> /// The URL of the sharing location (for viewing the contents in a web /// browser). /// </summary> private string locationUrl; /// <summary> /// The display name of the location. /// </summary> private string displayName; /// <summary> /// The set of file extensions that are allowed at the location. /// </summary> private IEnumerable<string> supportedFileExtensions; /// <summary> /// Indicates whether external users (outside the enterprise/tenant) /// can view documents at the location. /// </summary> private bool externalAccessAllowed; /// <summary> /// Indicates whether anonymous users can view documents at the location. /// </summary> private bool anonymousAccessAllowed; /// <summary> /// Indicates whether the user can modify permissions for documents at /// the location. /// </summary> private bool canModifyPermissions; /// <summary> /// Indicates whether this location is the user's default location. /// This will generally be their My Site. /// </summary> private bool isDefault; /// <summary> /// Gets the URL of the web service to use to manipulate /// documents at the sharing location. /// </summary> public string ServiceUrl { get { return this.serviceUrl; } private set { this.serviceUrl = value; } } /// <summary> /// Gets the URL of the sharing location (for viewing the /// contents in a web browser). /// </summary> public string LocationUrl { get { return this.locationUrl; } private set { this.locationUrl = value; } } /// <summary> /// Gets the display name of the location. /// </summary> public string DisplayName { get { return this.displayName; } private set { this.displayName = value; } } /// <summary> /// Gets the space-separated list of file extensions that are /// allowed at the location. /// </summary> /// <remarks> /// Example: "docx pptx xlsx" /// </remarks> public IEnumerable<string> SupportedFileExtensions { get { return this.supportedFileExtensions; } private set { this.supportedFileExtensions = value; } } /// <summary> /// Gets a flag indicating whether external users (outside the /// enterprise/tenant) can view documents at the location. /// </summary> public bool ExternalAccessAllowed { get { return this.externalAccessAllowed; } private set { this.externalAccessAllowed = value; } } /// <summary> /// Gets a flag indicating whether anonymous users can view /// documents at the location. /// </summary> public bool AnonymousAccessAllowed { get { return this.anonymousAccessAllowed; } private set { this.anonymousAccessAllowed = value; } } /// <summary> /// Gets a flag indicating whether the user can modify /// permissions for documents at the location. /// </summary> /// <remarks> /// This will be true for the user's "My Site," for example. However, /// documents at team and project sites will typically be ACLed by the /// site owner, so the user will not be able to modify permissions. /// This will most likely by false even if the caller is the owner, /// to avoid surprises. They should go to SharePoint to modify /// permissions for team and project sites. /// </remarks> public bool CanModifyPermissions { get { return this.canModifyPermissions; } private set { this.canModifyPermissions = value; } } /// <summary> /// Gets a flag indicating whether this location is the user's /// default location. This will generally be their My Site. /// </summary> public bool IsDefault { get { return this.isDefault; } private set { this.isDefault = value; } } /// <summary> /// Initializes a new instance of the <see cref="DocumentSharingLocation"/> class. /// </summary> private DocumentSharingLocation() { } /// <summary> /// Loads DocumentSharingLocation instance from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>DocumentSharingLocation.</returns> internal static DocumentSharingLocation LoadFromXml(EwsXmlReader reader) { DocumentSharingLocation location = new DocumentSharingLocation(); do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case XmlElementNames.ServiceUrl: location.ServiceUrl = reader.ReadElementValue<string>(); break; case XmlElementNames.LocationUrl: location.LocationUrl = reader.ReadElementValue<string>(); break; case XmlElementNames.DisplayName: location.DisplayName = reader.ReadElementValue<string>(); break; case XmlElementNames.SupportedFileExtensions: List<string> fileExtensions = new List<string>(); reader.Read(); while (reader.IsStartElement(XmlNamespace.Autodiscover, XmlElementNames.FileExtension)) { string extension = reader.ReadElementValue<string>(); fileExtensions.Add(extension); reader.Read(); } location.SupportedFileExtensions = fileExtensions; break; case XmlElementNames.ExternalAccessAllowed: location.ExternalAccessAllowed = reader.ReadElementValue<bool>(); break; case XmlElementNames.AnonymousAccessAllowed: location.AnonymousAccessAllowed = reader.ReadElementValue<bool>(); break; case XmlElementNames.CanModifyPermissions: location.CanModifyPermissions = reader.ReadElementValue<bool>(); break; case XmlElementNames.IsDefault: location.IsDefault = reader.ReadElementValue<bool>(); break; default: break; } } } while (!reader.IsEndElement(XmlNamespace.Autodiscover, XmlElementNames.DocumentSharingLocation)); return location; } } }
/* VRPhysicsConstraintHinge * MiddleVR * (c) MiddleVR */ using UnityEngine; using System; using System.Collections; using MiddleVR_Unity3D; [AddComponentMenu("MiddleVR/Physics/Constraints/Hinge")] [RequireComponent(typeof(VRPhysicsBody))] public class VRPhysicsConstraintHinge : MonoBehaviour { #region Member Variables [SerializeField] private GameObject m_ConnectedBody = null; [SerializeField] private Vector3 m_Anchor = new Vector3(0.0f, 0.0f, 0.0f); [SerializeField] private Vector3 m_Axis = new Vector3(1.0f, 0.0f, 0.0f); [SerializeField] private VRPhysicsJointLimits m_Limits = new VRPhysicsJointLimits(-360.0, +360.0); [SerializeField] private double m_ZeroPosition = 0.0; [SerializeField] private float m_GizmoSphereRadius = 0.1f; [SerializeField] private float m_GizmoLineLength = 1.0f; private vrPhysicsConstraintHinge m_PhysicsConstraint = null; private string m_PhysicsConstraintName = ""; private vrEventListener m_MVREventListener = null; #endregion #region Member Properties public vrPhysicsConstraintHinge PhysicsConstraint { get { return m_PhysicsConstraint; } } public string PhysicsConstraintName { get { return m_PhysicsConstraintName; } } public GameObject ConnectedBody { get { return m_ConnectedBody; } set { m_ConnectedBody = value; } } public Vector3 Anchor { get { return m_Anchor; } set { m_Anchor = value; } } public Vector3 Axis { get { return m_Axis; } set { m_Axis= value; } } public VRPhysicsJointLimits Limits { get { return m_Limits; } set { m_Limits = value; } } public double ReferencePosition { get { return m_ZeroPosition; } set { m_ZeroPosition = value; } } #endregion #region MonoBehaviour Member Functions protected void Start() { if (MiddleVR.VRClusterMgr.IsCluster() && !MiddleVR.VRClusterMgr.IsServer()) { enabled = false; return; } if (MiddleVR.VRPhysicsMgr == null) { MiddleVRTools.Log(0, "No PhysicsManager found when creating a hinge constraint."); return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return; } if (m_PhysicsConstraint == null) { m_PhysicsConstraint = physicsEngine.CreateConstraintHingeWithUniqueName(name); if (m_PhysicsConstraint == null) { MiddleVRTools.Log(0, "[X] Could not create a hinge physics constraint for '" + name + "'."); } else { GC.SuppressFinalize(m_PhysicsConstraint); m_MVREventListener = new vrEventListener(OnMVRNodeDestroy); m_PhysicsConstraint.AddEventListener(m_MVREventListener); m_PhysicsConstraintName = m_PhysicsConstraint.GetName(); AddConstraint(); } } } protected void OnDrawGizmosSelected() { if (enabled) { Gizmos.color = Color.green; Vector3 origin = transform.TransformPoint(m_Anchor); Vector3 axisDir = transform.TransformDirection(m_Axis); axisDir.Normalize(); Gizmos.DrawSphere(origin, m_GizmoSphereRadius); Gizmos.DrawLine(origin, origin + m_GizmoLineLength * axisDir); } } protected void OnDestroy() { if (m_PhysicsConstraint == null) { return; } if (MiddleVR.VRPhysicsMgr == null) { return; } vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return; } physicsEngine.DestroyConstraint(m_PhysicsConstraintName); m_PhysicsConstraint = null; m_PhysicsConstraintName = ""; } #endregion #region VRPhysicsConstraintHinge Functions protected bool AddConstraint() { vrPhysicsEngine physicsEngine = MiddleVR.VRPhysicsMgr.GetPhysicsEngine(); if (physicsEngine == null) { return false; } if (m_PhysicsConstraint == null) { return false; } bool addedToSimulation = false; // Cannot fail since we require this component. VRPhysicsBody body0 = GetComponent<VRPhysicsBody>(); VRPhysicsBody body1 = null; if (m_ConnectedBody != null) { body1 = m_ConnectedBody.GetComponent<VRPhysicsBody>(); } if (body0.PhysicsBody != null) { m_PhysicsConstraint.SetPosition(MiddleVRTools.FromUnity(Anchor)); m_PhysicsConstraint.SetAxis(MiddleVRTools.FromUnity(Axis)); m_PhysicsConstraint.SetLowerLimit(m_Limits.Min); m_PhysicsConstraint.SetUpperLimit(m_Limits.Max); m_PhysicsConstraint.SetReferencePosition(m_ZeroPosition); m_PhysicsConstraint.SetBody(0, body0.PhysicsBody); m_PhysicsConstraint.SetBody(1, body1 != null ? body1.PhysicsBody : null); addedToSimulation = physicsEngine.AddConstraint(m_PhysicsConstraint); if (addedToSimulation) { MiddleVRTools.Log(3, "[ ] The constraint '" + m_PhysicsConstraint.GetName() + "' was added to the physics simulation."); } else { MiddleVRTools.Log(3, "[X] Failed to add the constraint '" + m_PhysicsConstraintName + "' to the physics simulation."); } } else { MiddleVRTools.Log(0, "[X] The PhysicsBody of '" + name + "' for the hinge physics constraint '" + m_PhysicsConstraintName + "' is null."); } return addedToSimulation; } private bool OnMVRNodeDestroy(vrEvent iBaseEvt) { vrObjectEvent e = vrObjectEvent.Cast(iBaseEvt); if (e != null) { if (e.ComesFrom(m_PhysicsConstraint)) { if (e.eventType == (int)VRObjectEventEnum.VRObjectEvent_Destroy) { // Killed in MiddleVR so delete it in C#. m_PhysicsConstraint.Dispose(); } } } return true; } #endregion }
namespace LL.MDE.Components.Qvt.Transformation.EA2FMEA { using System; using System.Collections.Generic; using System.Linq; using LL.MDE.Components.Qvt.Common; using LL.MDE.DataModels.EnAr; using LL.MDE.DataModels.XML; public class RelationProduct2Structure { private readonly IMetaModelInterface editor; private readonly TransformationEA2FMEA transformation; private Dictionary<CheckOnlyDomains, EnforceDomains> traceabilityMap = new Dictionary<CheckOnlyDomains, EnforceDomains>(); public RelationProduct2Structure(IMetaModelInterface editor , TransformationEA2FMEA transformation ) { this.editor = editor;this.transformation = transformation; } public EnforceDomains FindPreviousResult(LL.MDE.DataModels.EnAr.Package productP,LL.MDE.DataModels.XML.Tag fmStructureRefs,LL.MDE.DataModels.XML.Tag fmStructureElements) { CheckOnlyDomains input = new CheckOnlyDomains(productP,fmStructureRefs,fmStructureElements); return traceabilityMap.ContainsKey(input) ? traceabilityMap[input] : null; } internal static ISet<CheckResultProduct2Structure> Check( LL.MDE.DataModels.EnAr.Package productP,LL.MDE.DataModels.XML.Tag fmStructureRefs,LL.MDE.DataModels.XML.Tag fmStructureElements ) { ISet<CheckResultProduct2Structure> result = new HashSet<CheckResultProduct2Structure>();ISet<MatchDomainProductP> matchDomainProductPs = CheckDomainProductP(productP);ISet<MatchDomainFmStructureRefs> matchDomainFmStructureRefss = CheckDomainFmStructureRefs(fmStructureRefs);ISet<MatchDomainFmStructureElements> matchDomainFmStructureElementss = CheckDomainFmStructureElements(fmStructureElements);foreach (MatchDomainProductP matchDomainProductP in matchDomainProductPs ) {foreach (MatchDomainFmStructureRefs matchDomainFmStructureRefs in matchDomainFmStructureRefss ) {foreach (MatchDomainFmStructureElements matchDomainFmStructureElements in matchDomainFmStructureElementss ) {string productName = matchDomainProductP.productName; LL.MDE.DataModels.EnAr.Element productPE = matchDomainProductP.productPE; string productID = matchDomainProductP.productID; CheckResultProduct2Structure checkonlysMatch = new CheckResultProduct2Structure () {matchDomainProductP = matchDomainProductP,matchDomainFmStructureRefs = matchDomainFmStructureRefs,matchDomainFmStructureElements = matchDomainFmStructureElements,}; result.Add(checkonlysMatch); } // End foreach } // End foreach } // End foreach return result; } internal static ISet<MatchDomainFmStructureElements> CheckDomainFmStructureElements(LL.MDE.DataModels.XML.Tag fmStructureElements) { ISet<MatchDomainFmStructureElements> result = new HashSet<MatchDomainFmStructureElements>(); MatchDomainFmStructureElements match = new MatchDomainFmStructureElements() { fmStructureElements = fmStructureElements, }; result.Add(match); return result; } internal static ISet<MatchDomainFmStructureRefs> CheckDomainFmStructureRefs(LL.MDE.DataModels.XML.Tag fmStructureRefs) { ISet<MatchDomainFmStructureRefs> result = new HashSet<MatchDomainFmStructureRefs>(); MatchDomainFmStructureRefs match = new MatchDomainFmStructureRefs() { fmStructureRefs = fmStructureRefs, }; result.Add(match); return result; } internal static ISet<MatchDomainProductP> CheckDomainProductP(LL.MDE.DataModels.EnAr.Package productP) { ISet<MatchDomainProductP> result = new HashSet<MatchDomainProductP>(); string productName = productP.Name; LL.MDE.DataModels.EnAr.Element productPE = productP.Element; string productID = productPE.ElementGUID; if (productPE.ElementPackage() == productP) { MatchDomainProductP match = new MatchDomainProductP() { productP = productP, productName = productName, productPE = productPE, productID = productID, }; result.Add(match); } return result; } internal void CheckAndEnforce(LL.MDE.DataModels.EnAr.Package productP,LL.MDE.DataModels.XML.Tag fmStructureRefs,LL.MDE.DataModels.XML.Tag fmStructureElements,LL.MDE.DataModels.XML.Tag fmStructures ) { CheckOnlyDomains input = new CheckOnlyDomains(productP,fmStructureRefs,fmStructureElements); EnforceDomains output = new EnforceDomains(fmStructures); if (traceabilityMap.ContainsKey(input) && !traceabilityMap[input].Equals(output)) { throw new Exception("This relation has already been used with different enforced parameters!"); } if (!traceabilityMap.ContainsKey(input)) { ISet<CheckResultProduct2Structure> result = Check (productP,fmStructureRefs,fmStructureElements); Enforce(result, fmStructures); traceabilityMap[input] = output; } } internal void Enforce(ISet<CheckResultProduct2Structure> result, LL.MDE.DataModels.XML.Tag fmStructures ) { foreach (CheckResultProduct2Structure match in result) { // Extracting variables binded in source domains LL.MDE.DataModels.EnAr.Package productP = match.matchDomainProductP.productP; string productName = match.matchDomainProductP.productName; LL.MDE.DataModels.EnAr.Element productPE = match.matchDomainProductP.productPE; string productID = match.matchDomainProductP.productID; LL.MDE.DataModels.XML.Tag fmStructureRefs = match.matchDomainFmStructureRefs.fmStructureRefs; LL.MDE.DataModels.XML.Tag fmStructureElements = match.matchDomainFmStructureElements.fmStructureElements; // Assigning variables binded in the where clause // Enforcing each enforced domain MatchDomainFmStructures targetMatchDomainFmStructures = EnforceFmStructures(productID,productName, fmStructures ); // Retrieving variables binded in the enforced domains LL.MDE.DataModels.XML.Tag fmStructure = targetMatchDomainFmStructures.fmStructure; LL.MDE.DataModels.XML.Attribute structureId = targetMatchDomainFmStructures.structureId; LL.MDE.DataModels.XML.Tag longName1 = targetMatchDomainFmStructures.longName1; LL.MDE.DataModels.XML.Tag l41 = targetMatchDomainFmStructures.l41; LL.MDE.DataModels.XML.Attribute lAttr1 = targetMatchDomainFmStructures.lAttr1; // Calling other relations as defined in the where clause new RelationCreateProjectStructureLink(editor,transformation).CheckAndEnforce(structureId,fmStructureRefs);new RelationAddStructureRoot(editor,transformation).CheckAndEnforce(productP,fmStructure,fmStructureElements);} } internal MatchDomainFmStructures EnforceFmStructures(string productID,string productName, LL.MDE.DataModels.XML.Tag fmStructures) { MatchDomainFmStructures match = new MatchDomainFmStructures(); // Contructing fmStructures LL.MDE.DataModels.XML.Tag fmStructure = null; fmStructure = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(fmStructures, "childTags"); // Contructing fmStructure editor.AddOrSetInField(fmStructure, "tagname", "FM-STRUCTURE" ); LL.MDE.DataModels.XML.Attribute structureId = null; structureId = (LL.MDE.DataModels.XML.Attribute) editor.CreateNewObjectInField(fmStructure, "attributes"); LL.MDE.DataModels.XML.Tag longName1 = null; longName1 = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(fmStructure, "childTags"); // Contructing structureId editor.AddOrSetInField(structureId, "name", "ID" ); editor.AddOrSetInField(structureId, "value", productID ); // Contructing longName1 editor.AddOrSetInField(longName1, "tagname", "LONG-NAME" ); LL.MDE.DataModels.XML.Tag l41 = null; l41 = (LL.MDE.DataModels.XML.Tag) editor.CreateNewObjectInField(longName1, "childTags"); // Contructing l41 editor.AddOrSetInField(l41, "tagname", "L-4" ); editor.AddOrSetInField(l41, "value", productName ); LL.MDE.DataModels.XML.Attribute lAttr1 = null; lAttr1 = (LL.MDE.DataModels.XML.Attribute) editor.CreateNewObjectInField(l41, "attributes"); // Contructing lAttr1 editor.AddOrSetInField(lAttr1, "name", "L" ); editor.AddOrSetInField(lAttr1, "value", "Product2Structure" ); // Return newly binded variables match.fmStructures = fmStructures; match.fmStructure = fmStructure; match.structureId = structureId; match.longName1 = longName1; match.l41 = l41; match.lAttr1 = lAttr1; return match; } public class CheckOnlyDomains : Tuple<Package,Tag,Tag> { public CheckOnlyDomains(Package productP,Tag fmStructureRefs,Tag fmStructureElements) : base(productP,fmStructureRefs,fmStructureElements) { } public Tag fmStructureElements { get { return Item3; } } public Tag fmStructureRefs { get { return Item2; } } public Package productP { get { return Item1; } } } public class EnforceDomains : Tuple<Tag> { public EnforceDomains(Tag fmStructures) : base(fmStructures) { } public Tag fmStructures { get { return Item1; } } } internal class CheckResultProduct2Structure { public MatchDomainFmStructureElements matchDomainFmStructureElements; public MatchDomainFmStructureRefs matchDomainFmStructureRefs; public MatchDomainProductP matchDomainProductP; } internal class MatchDomainFmStructureElements { public LL.MDE.DataModels.XML.Tag fmStructureElements; } internal class MatchDomainFmStructureRefs { public LL.MDE.DataModels.XML.Tag fmStructureRefs; } internal class MatchDomainFmStructures { public LL.MDE.DataModels.XML.Tag fmStructure; public LL.MDE.DataModels.XML.Tag fmStructures; public LL.MDE.DataModels.XML.Tag l41; public LL.MDE.DataModels.XML.Attribute lAttr1; public LL.MDE.DataModels.XML.Tag longName1; public LL.MDE.DataModels.XML.Attribute structureId; } internal class MatchDomainProductP { public string productID; public string productName; public LL.MDE.DataModels.EnAr.Package productP; public LL.MDE.DataModels.EnAr.Element productPE; } } }
// 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.Linq; using System.Reactive.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Its.Domain.Serialization; using Microsoft.Its.Domain.Testing; using Microsoft.Its.Recipes; using NUnit.Framework; using Sample.Domain; using Sample.Domain.Ordering; using Sample.Domain.Ordering.Commands; using Sample.Domain.Projections; using Assert = NUnit.Framework.Assert; using Its.Log.Instrumentation; namespace Microsoft.Its.Domain.Sql.Tests { [TestFixture] public class ReadModelCatchupTests : ReadModelCatchupTest { } [Category("Catchups")] [TestFixture] public abstract class ReadModelCatchupTest : EventStoreDbTest { private readonly TimeSpan MaxWaitTime = TimeSpan.FromSeconds(5); [Test] public async Task ReadModelCatchup_only_queries_events_since_the_last_consumed_event_id() { var bus = new FakeEventBus(); var repository = new SqlEventSourcedRepository<Order>(bus); // save the order with no projectors running var order = new Order(); order.Apply(new AddItem { Price = 1m, ProductName = "Widget" }); await repository.Save(order); // subscribe one projector for catchup var projector1 = new Projector1(); using (var catchup = CreateReadModelCatchup(projector1)) { catchup.Progress.ForEachAsync(s => Console.WriteLine(s)); await catchup.Run(); } order.Apply(new AddItem { Price = 1m, ProductName = "Widget" }); await repository.Save(order); // subscribe both projectors var projector2 = new Projector2(); using (var catchup = CreateReadModelCatchup(projector1, projector2)) { catchup.Progress.ForEachAsync(s => Console.WriteLine(s)); await catchup.Run(); } projector1.CallCount.Should().Be(2, "A given event should only be passed to a given projector once"); projector2.CallCount.Should().Be(2, "A projector should be passed events it has not previously seen."); } [Test] public async Task ReadModelCatchup_does_not_query_events_that_no_subscribed_projector_is_interested_in() { Events.Write(100, _ => Events.Any()); Events.Write(1, _ => new Order.Created()); var projector2 = Projector.Create<CustomerAccount.Created>(e => { }); StorableEvent extraneousEvent = null; using (var catchup = CreateReadModelCatchup(projector2)) using (var eventStore = new EventStoreDbContext()) { var eventsQueried = 0; catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { var eventId = s.CurrentEventId; var @event = eventStore.Events.Single(e => e.Id == eventId); if (@event.StreamName != "CustomerAccount" || @event.Type != "Created") { extraneousEvent = @event; catchup.Dispose(); } eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } if (extraneousEvent != null) { Assert.Fail(string.Format("Found an event that should not have been queried from the event store: {0}:{1} (#{2})", extraneousEvent.StreamName, extraneousEvent.Type, extraneousEvent.Id)); } } [Test] public async Task ReadModelCatchup_queries_events_that_match_both_aggregate_and_event_type() { const int numOfOrderCreatedEvents = 5; Events.Write(numOfOrderCreatedEvents, _ => new Order.Created()); Events.Write(7, _ => new CustomerAccount.Created()); Events.Write(8, _ => new Order.Cancelled()); var projector = new DuckTypeProjector<Order.Created>(e => { }); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } eventsQueried.Should().Be(numOfOrderCreatedEvents); } [Test] public async Task ReadModelCatchup_queries_all_events_if_IEvent_is_subscribed() { Events.Write(100, _ => Events.Any()); var projector = Projector.Create<IEvent>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } eventsQueried.Should().Be(100); } [Test] public async Task ReadModelCatchup_queries_all_events_if_Event_is_subscribed() { Events.Write(100, _ => Events.Any()); var projector = Projector.Create<Event>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } eventsQueried.Should().Be(100); } [Test] public async Task ReadModelCatchup_queries_all_events_for_the_aggregate_if_IEvent_T_is_subscribed() { var orderEvents = 0; Events.Write(100, _ => { var @event = Events.Any(); if (@event.AggregateType() == typeof (Order)) { orderEvents++; } return @event; }); var projector = Projector.Create<IEvent<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } eventsQueried.Should().Be(orderEvents); } [Test] public async Task ReadModelCatchup_queries_all_events_for_the_aggregate_if_Event_T_is_subscribed() { var orderEvents = 0; Events.Write(100, _ => { var @event = Events.Any(); if (@event.AggregateType() == typeof (Order)) { orderEvents++; } return @event; }); var projector = Projector.Create<IEvent<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } eventsQueried.Should().Be(orderEvents); } [Test] public async Task ReadModelCatchup_queries_event_subtypes_correctly() { var subclassedEventsWritten = 0; Events.Write(100, _ => { var @event = Any.Bool() ? Events.Any() : new CustomerAccount.OrderShipConfirmationEmailSent(); if (@event is EmailSent) { subclassedEventsWritten++; } return @event; }); var projector = Projector.Create<EmailSent>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } eventsQueried.Should().Be(subclassedEventsWritten); } [Test] public async Task ReadModelCatchup_queries_scheduled_commands_if_IScheduledCommand_is_subscribed() { var scheduledCommandsWritten = 0; var scheduledCommandsQueried = 0; Events.Write(50, _ => { if (Any.Bool()) { return Events.Any(); } scheduledCommandsWritten++; return new CommandScheduled<Order> { Command = new Ship(), DueTime = DateTimeOffset.UtcNow }; }); var projector = Projector.Create<CommandScheduled<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) using (var eventStore = new EventStoreDbContext()) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { var eventId = s.CurrentEventId; var @event = eventStore.Events.Single(e => e.Id == eventId); if (@event.Type.StartsWith("Scheduled:")) { scheduledCommandsQueried++; } eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } scheduledCommandsQueried.Should().Be(scheduledCommandsWritten); } [Test] public async Task ReadModelCatchup_queries_scheduled_commands_if_IScheduledCommandT_is_subscribed() { var scheduledCommandsWritten = 0; var scheduledCommandsQueried = 0; Events.Write(50, _ => { if (Any.Bool()) { return Events.Any(); } scheduledCommandsWritten++; return new CommandScheduled<Order> { Command = new Ship(), DueTime = DateTimeOffset.UtcNow }; }); var projector = Projector.Create<CommandScheduled<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) using (var eventStore = new EventStoreDbContext()) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { var eventId = s.CurrentEventId; var @event = eventStore.Events.Single(e => e.Id == eventId); if (@event.Type.StartsWith("Scheduled:")) { scheduledCommandsQueried++; } eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } scheduledCommandsQueried.Should().Be(scheduledCommandsWritten); } [Test] public async Task ReadModelCatchup_queries_scheduled_commands_if_CommandScheduled_is_subscribed() { var scheduledCommandsWritten = 0; var scheduledCommandsQueried = 0; Events.Write(50, _ => { if (Any.Bool()) { return Events.Any(); } scheduledCommandsWritten++; return new CommandScheduled<Order> { Command = new Ship(), DueTime = DateTimeOffset.UtcNow }; }); var projector = Projector.Create<CommandScheduled<Order>>(e => { }).Named(MethodBase.GetCurrentMethod().Name); var eventsQueried = 0; using (var catchup = CreateReadModelCatchup(projector)) using (var eventStore = new EventStoreDbContext()) { catchup.Progress .Where(s => !s.IsStartOfBatch) .ForEachAsync(s => { var eventId = s.CurrentEventId; var @event = eventStore.Events.Single(e => e.Id == eventId); if (@event.Type.StartsWith("Scheduled:")) { scheduledCommandsQueried++; } eventsQueried++; }); await catchup.Run() .ContinueWith(r => catchup.Dispose()); Console.WriteLine(new { eventsQueried }); } scheduledCommandsQueried.Should().Be(scheduledCommandsWritten); } [Test] public async Task ReadModelCatchup_StartAtEventId_can_be_used_to_avoid_requery_of_previous_events() { var lastEventId = Events.Write(50, _ => Events.Any()); var eventsProjected = 0; var projector = Projector.Create<Event>(e => { eventsProjected++; }) .Named(MethodBase.GetCurrentMethod().Name); using (var catchup = new ReadModelCatchup(projector) { StartAtEventId = lastEventId - 20 }) { await catchup.Run(); } eventsProjected.Should().Be(21); } [Test] public async Task When_Run_is_called_while_already_running_then_it_skips_the_run() { var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus()); await repository.Save(new Order()); var mre = new ManualResetEventSlim(); var barrier = new Barrier(2); var progress = new List<ReadModelCatchupStatus>(); Events.Write(10); var projector = new Projector<Order.ItemAdded>(() => new ReadModelDbContext()) { OnUpdate = (work, e) => { barrier.SignalAndWait(1000); mre.Wait(5000); } }; using (var catchup = CreateReadModelCatchup(projector)) using (catchup.Progress.Subscribe(s => { progress.Add(s); Console.WriteLine("progress: " + s); })) { #pragma warning disable 4014 // don't await Task.Run(() => catchup.Run()); #pragma warning restore 4014 // make sure the first catchup is blocked inside the projector barrier.SignalAndWait(1000); // try to start another catchup var result = await catchup.Run(); result.Should().Be(ReadModelCatchupResult.CatchupAlreadyInProgress); await Task.Delay(2000); } mre.Set(); progress.Should().ContainSingle(s => s.IsStartOfBatch); } [Test] public async Task When_a_projector_update_fails_then_an_entry_is_added_to_EventHandlingErrors() { // arrange var errorMessage = Any.Paragraph(10); var productName = Any.Paragraph(); var projector = new Projector<Order.ItemAdded>(() => new ReadModelDbContext()) { OnUpdate = (work, e) => { throw new Exception(errorMessage); } }; var order = new Order(); var repository = new SqlEventSourcedRepository<Order>(); order.Apply(new AddItem { Price = 1m, ProductName = productName }); await repository.Save(order); // act using (var catchup = CreateReadModelCatchup(projector)) { await catchup.Run(); } // assert using (var db = new ReadModelDbContext()) { var error = db.Set<EventHandlingError>().Single(e => e.AggregateId == order.Id); error.StreamName.Should().Be("Order"); error.EventTypeName.Should().Be("ItemAdded"); error.SerializedEvent.Should().Contain(productName); error.Error.Should().Contain(errorMessage); } } [Test] public async Task Events_that_cannot_be_deserialized_to_the_expected_type_are_logged_as_EventHandlingErrors() { var badEvent = new StorableEvent { Actor = Any.Email(), StreamName = typeof (Order).Name, Type = typeof (Order.ItemAdded).Name, Body = new { Price = "oops this is not a number" }.ToJson(), SequenceNumber = Any.PositiveInt(), AggregateId = Any.Guid(), UtcTime = DateTime.UtcNow }; using (var eventStore = new EventStoreDbContext()) { eventStore.Events.Add(badEvent); await eventStore.SaveChangesAsync(); } using (var catchup = CreateReadModelCatchup(new Projector1())) { await catchup.Run(); } using (var readModels = new ReadModelDbContext()) { var failure = readModels.Set<EventHandlingError>() .OrderByDescending(e => e.Id) .First(e => e.AggregateId == badEvent.AggregateId); failure.Error.Should().Contain("JsonReaderException"); failure.SerializedEvent.Should().Contain(badEvent.Body); failure.Actor.Should().Be(badEvent.Actor); failure.OriginalId.Should().Be(badEvent.Id); failure.AggregateId.Should().Be(badEvent.AggregateId); failure.SequenceNumber.Should().Be(badEvent.SequenceNumber); failure.StreamName.Should().Be(badEvent.StreamName); failure.EventTypeName.Should().Be(badEvent.Type); } } [Test] public async Task When_an_exception_is_thrown_during_a_read_model_update_then_it_is_logged_on_its_bus() { var projector = new Projector<Order.ItemAdded>(() => new ReadModelDbContext()) { OnUpdate = (work, e) => { throw new Exception("oops!"); } }; var itemAdded = new Order.ItemAdded { AggregateId = Any.Guid(), SequenceNumber = 1, ProductName = Any.AlphanumericString(10, 20), Price = Any.Decimal(0.01m), Quantity = 100 }; var errors = new List<Domain.EventHandlingError>(); using (var catchup = CreateReadModelCatchup(projector)) using (var db = new EventStoreDbContext()) { db.Events.Add(itemAdded.ToStorableEvent()); db.SaveChanges(); catchup.EventBus.Errors.Subscribe(errors.Add); await catchup.Run(); } var error = errors.Single(e => e.AggregateId == itemAdded.AggregateId); error.SequenceNumber .Should() .Be(itemAdded.SequenceNumber); error.Event .SequenceNumber .Should() .Be(itemAdded.SequenceNumber); } [Ignore("Test needs rebuilding")] [Test] public async Task Database_command_timeouts_during_catchup_do_not_interrupt_catchup() { // reset read model tracking to 0 new ReadModelDbContext().DisposeAfter(c => { var projectorName = ReadModelInfo.NameForProjector(new Projector<Order.CustomerInfoChanged>(() => new ReadModelDbContext())); c.Set<ReadModelInfo>() .SingleOrDefault(i => i.Name == projectorName) .IfNotNull() .ThenDo(i => { i.CurrentAsOfEventId = 0; }); c.SaveChanges(); }); var exceptions = new Stack<Exception>(Enumerable.Range(1, 2) .Select(_ => new InvalidOperationException("Invalid attempt to call IsDBNull when reader is closed."))); var count = 0; var flakyEvents = new FlakyEventStream( Enumerable.Range(1, 1000) .Select(i => new StorableEvent { AggregateId = Any.Guid(), Body = new Order.CustomerInfoChanged { CustomerName = i.ToString() }.ToJson(), SequenceNumber = i, StreamName = typeof (Order).Name, Timestamp = DateTimeOffset.Now, Type = typeof (Order.CustomerInfoChanged).Name, Id = i }).ToArray(), startFlakingOnEnumeratorNumber: 2, doSomethingFlaky: i => { if (count++ > 50) { count = 0; if (exceptions.Any()) { throw exceptions.Pop(); } } }); var names = new HashSet<string>(); var projector = new Projector<Order.CustomerInfoChanged>(() => new ReadModelDbContext()) { OnUpdate = (work, e) => names.Add(e.CustomerName) }; using (var catchup = CreateReadModelCatchup(projector)) { await catchup.Run(); } projector.CallCount.Should().Be(1000); names.Count.Should().Be(1000); } [Test] public async Task Insertion_of_new_events_during_catchup_does_not_interrupt_catchup() { var barrier = new Barrier(2); // preload some events for the catchup. replay will hit the barrier on the last one. var order = new Order(); Action addEvent = () => order.Apply(new AddItem { Quantity = 1, ProductName = "Penny candy", Price = .01m }); Enumerable.Range(1, 100).ForEach(_ => addEvent()); var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus()); await repository.Save(order); // queue the catchup on a background task #pragma warning disable 4014 // don't await Task.Run(() => #pragma warning restore 4014 { var projector = new Projector1 { OnUpdate = (work, e) => { if (e.SequenceNumber == 10) { Console.WriteLine("pausing read model catchup"); barrier.SignalAndWait(MaxWaitTime); //1 barrier.SignalAndWait(MaxWaitTime); //2 Console.WriteLine("resuming read model catchup"); } } }; using (var db = new EventStoreDbContext()) using (var catchup = CreateReadModelCatchup(projector)) { var events = db.Events.Where(e => e.Id > HighestEventId); Console.WriteLine(string.Format("starting read model catchup for {0} events", events.Count())); catchup.Run().Wait(); Console.WriteLine("done with read model catchup"); barrier.SignalAndWait(MaxWaitTime); //3 } }); Console.WriteLine("queued read model catchup task"); barrier.SignalAndWait(MaxWaitTime); //1 new EventStoreDbContext().DisposeAfter(c => { Console.WriteLine("adding one more event, bypassing read model tracking"); c.Events.Add(new Order.ItemAdded { AggregateId = Guid.NewGuid(), SequenceNumber = 1 }.ToStorableEvent()); c.SaveChanges(); Console.WriteLine("done adding one more event"); }); barrier.SignalAndWait(MaxWaitTime); //2 barrier.SignalAndWait(MaxWaitTime); //3 // check that everything worked: var projector2 = new Projector1(); var projectorName = ReadModelInfo.NameForProjector(projector2); using (var readModels = new ReadModelDbContext()) { var readModelInfo = readModels.Set<ReadModelInfo>().Single(i => i.Name == projectorName); readModelInfo.CurrentAsOfEventId.Should().Be(HighestEventId + 101); using (var catchup = CreateReadModelCatchup(projector2)) { await catchup.Run(); } readModels.Entry(readModelInfo).Reload(); readModelInfo.CurrentAsOfEventId.Should().Be(HighestEventId + 102); } } [Test] public async Task When_not_using_Update_then_failed_writes_do_not_interrupt_catchup() { // arrange // preload some events for the catchup. replay will hit the barrier on the last one. var order = new Order(); var productName = Any.Paragraph(3); Action addEvent = () => order.Apply(new AddItem { Quantity = 1, ProductName = productName, Price = .01m }); Enumerable.Range(1, 30).ForEach(_ => addEvent()); var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus()); await repository.Save(order); var count = 0; var projector = new Projector1 { OnUpdate = (work, e) => { using (var db = new ReadModelDbContext()) { // throw one exception in the middle if (count++ == 15) { throw new Exception("drat!"); } db.SaveChanges(); } } }; // act using (var catchup = CreateReadModelCatchup(projector)) { await catchup.Run(); } // assert count.Should().Be(30); } [Test] public async Task When_using_Update_then_failed_writes_do_not_interrupt_catchup() { // preload some events for the catchup. replay will hit the barrier on the last one. var order = new Order(); var productName = Any.Paragraph(4); Action addEvent = () => order.Apply(new AddItem { Quantity = 1, ProductName = productName, Price = .01m }); Enumerable.Range(1, 30).ForEach(_ => addEvent()); var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus()); await repository.Save(order); var count = 0; Projector1 projector = null; projector = new Projector1 { OnUpdate = (_, e) => { using (var work = projector.Update()) { var db = work.Resource<ReadModelDbContext>(); if (count++ == 15) { // do something that will trigger a db exception when the UnitOfWork is committed var inventory = db.Set<ProductInventory>(); inventory.Add(new ProductInventory { ProductName = e.ProductName, QuantityReserved = e.Quantity }); inventory.Add(new ProductInventory { ProductName = e.ProductName, QuantityReserved = e.Quantity }); } work.VoteCommit(); } } }; // act using (var catchup = CreateReadModelCatchup(projector)) { await catchup.Run(); } // assert count.Should().Be(30); } [Test] public async Task When_using_Update_then_failed_writes_are_logged_to_EventHandlingErrors() { // preload some events for the catchup. replay will hit the barrier on the last one. var order = new Order(); var productName = Any.Paragraph(4); order.Apply(new AddItem { Quantity = 1, ProductName = productName, Price = .01m }); var repository = new SqlEventSourcedRepository<Order>(new FakeEventBus()); await repository.Save(order); Projector1 projector = null; projector = new Projector1 { OnUpdate = (_, e) => { using (var work = projector.Update()) { var db = work.Resource<ReadModelDbContext>(); // do something that will trigger a db exception when the UnitOfWork is committed var inventory = db.Set<ProductInventory>(); inventory.Add(new ProductInventory { ProductName = e.ProductName, QuantityReserved = e.Quantity }); inventory.Add(new ProductInventory { ProductName = e.ProductName, QuantityReserved = e.Quantity }); work.VoteCommit(); } } }; // act using (var catchup = CreateReadModelCatchup(projector)) { await catchup.Run(); } // assert using (var db = new ReadModelDbContext()) { var error = db.Set<EventHandlingError>().Single(e => e.AggregateId == order.Id); error.Error.Should() .Contain( string.Format( "Violation of PRIMARY KEY constraint 'PK_dbo.ProductInventories'. Cannot insert duplicate key in object 'dbo.ProductInventories'. The duplicate key value is ({0})", productName)); } } [Test] public void When_using_a_custom_DbContext_then_it_is_available_in_UnitOfWork_resources() { var projector = new Projector<Order.CreditCardCharged>(() => new ReadModels1DbContext()) { OnUpdate = (work, charged) => { work.Resource<ReadModels1DbContext>().Should().NotBeNull(); } }; projector.UpdateProjection(new Order.CreditCardCharged { Amount = Any.PositiveInt() }); } [Test] public void When_two_projectors_have_the_same_name_then_the_catchup_throws_on_creation() { var projector1 = Projector.Create<Order.Cancelled>(e => { }); var projector2 = Projector.Create<Order.Cancelled>(e => { }); Action create = () => CreateReadModelCatchup(projector1, projector2); create.ShouldThrow<ArgumentException>() .And .Message.Should().Contain(string.Format("Duplicate read model names:\n{0}", EventHandler.FullName(projector1))); } [Test] public async Task Run_returns_CatchupRanAndHandledNewEvents_if_the_catchup_was_not_currently_running() { Events.Write(5); using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { }))) { (await catchup.Run()).Should().Be(ReadModelCatchupResult.CatchupRanAndHandledNewEvents); } } [Test] public async Task Run_returns_CatchupRanAndHandledNewEvents_if_the_catchup_was_not_currently_running_and_there_were_no_events() { using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { }))) { (await catchup.Run()).Should().Be(ReadModelCatchupResult.CatchupRanButNoNewEvents); } } [Test] public async Task Run_returns_CatchupAlreadyInProgress_if_the_catchup_was_currently_running() { Events.Write(1); var barrier = new Barrier(2); using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { barrier.SignalAndWait(1000); }))) { #pragma warning disable 4014 // don't await catchup Task.Run(() => catchup.Run()); #pragma warning restore 4014 barrier.SignalAndWait(500); (await catchup.Run()).Should().Be(ReadModelCatchupResult.CatchupAlreadyInProgress); } } [Test] public async Task When_Progress_is_awaited_then_it_completes_when_the_catchup_is_disposed() { Events.Write(5); long lastEventId = 0; using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { }))) { catchup.Progress.Subscribe(s => { Console.WriteLine(s); lastEventId = s.CurrentEventId; }); #pragma warning disable 4014 // don't await Task.Run(() => catchup.Run()) .ContinueWith(r => catchup.Dispose()); #pragma warning restore 4014 await catchup.Progress; } lastEventId.Should().Be(HighestEventId + 5); } [Test] public async Task SingleBatchAsync_can_be_used_to_observe_the_status_during_a_single_catchup_batch() { Events.Write(5); using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { }))) { var statuses = await catchup.SingleBatchAsync().ToArray(); var ids = statuses.Select(s => s.CurrentEventId).ToArray(); Console.WriteLine(new { ids }.ToLogString()); ids.ShouldBeEquivalentTo(new[] { HighestEventId + 1, HighestEventId + 1, HighestEventId + 2, HighestEventId + 3, HighestEventId + 4, HighestEventId + 5 }); } } [Test] public async Task A_non_running_catchup_can_be_run_by_awaiting_SingleBatchAsync() { Events.Write(10); using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { }))) { var status = await catchup.SingleBatchAsync(); Console.WriteLine(status); status.IsEndOfBatch.Should().BeTrue(); status.BatchCount.Should().Be(10); status.CurrentEventId.Should().Be(HighestEventId + 10); } } [Test] public async Task A_single_catchup_batch_can_be_triggered_and_awaited_using_SingleBatchAsync() { Events.Write(10); using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { }))) { var status = await catchup.SingleBatchAsync().Do(s => Console.WriteLine(s)); status.IsEndOfBatch.Should().BeTrue(); status.BatchCount.Should().Be(10); status.CurrentEventId.Should().Be(HighestEventId + 10); } } [Test] public async Task The_current_batch_in_progress_can_be_awaited_using_SingleBatchAsync() { Events.Write(10); using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { // slow this down just enough for the batch to still be running when we await below Thread.Sleep(1000); }))) { #pragma warning disable 4014 // don't await Task.Run(() => catchup.Run()); #pragma warning restore 4014 Thread.Sleep(1000); var status = await catchup.SingleBatchAsync(); status.IsEndOfBatch.Should().BeTrue(); status.BatchCount.Should().Be(10); status.CurrentEventId.Should().Be(HighestEventId + 10); } } [Test] public async Task When_a_Progress_subscriber_throws_then_catchup_continues() { Events.Write(10); var projectedEventCount = 0; using (var catchup = CreateReadModelCatchup(Projector.Create<IEvent>(e => { projectedEventCount++; }))) { catchup.Progress.Subscribe(e => { throw new Exception("oops!"); }); await catchup.Run(); } projectedEventCount.Should().Be(10); } [Test] public async Task Two_different_projectors_can_catch_up_to_two_different_event_stores_using_separate_catchups() { // arrange var projector1CallCount = 0; var projector2CallCount = 0; var projector1 = Projector.Create<Order.ItemAdded>(e => projector1CallCount++).Named(MethodBase.GetCurrentMethod().Name + "1"); var projector2 = Projector.Create<Order.ItemAdded>(e => projector2CallCount++).Named(MethodBase.GetCurrentMethod().Name + "2"); var startProjector2AtId = new OtherEventStoreDbContext().DisposeAfter(db => GetHighestEventId(db)) + 1; Events.Write(5, createEventStore: () => new EventStoreDbContext()); Events.Write(5, createEventStore: () => new OtherEventStoreDbContext()); using ( var eventStoreCatchup = new ReadModelCatchup(projector1) { StartAtEventId = HighestEventId + 1, Name = "eventStoreCatchup", CreateEventStoreDbContext = () => new EventStoreDbContext() }) using ( var otherEventStoreCatchup = new ReadModelCatchup(projector2) { StartAtEventId = startProjector2AtId, Name = "otherEventStoreCatchup", CreateEventStoreDbContext = () => new OtherEventStoreDbContext() }) { // act await eventStoreCatchup.SingleBatchAsync(); await otherEventStoreCatchup.SingleBatchAsync(); } // assert projector1CallCount.Should().Be(5, "projector1 should get all events from event stream"); projector2CallCount.Should().Be(5, "projector2 should get all events from event stream"); } public class Projector1 : IUpdateProjectionWhen<Order.ItemAdded> { public int CallCount { get; set; } public void UpdateProjection(Order.ItemAdded @event) { using (var work = this.Update()) { CallCount++; OnUpdate(work, @event); work.VoteCommit(); } } public Action<UnitOfWork<ReadModelUpdate>, Order.ItemAdded> OnUpdate = (work, e) => { }; } public class Projector2 : IUpdateProjectionWhen<Order.ItemAdded> { public int CallCount { get; set; } public void UpdateProjection(Order.ItemAdded @event) { using (var work = this.Update()) { CallCount++; OnUpdate(work, @event); work.VoteCommit(); } } public Action<UnitOfWork<ReadModelUpdate>, Order.ItemAdded> OnUpdate = (work, e) => { }; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias Scripting; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion.FileSystem; using Microsoft.CodeAnalysis.Editor.Implementation.Interactive; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.Hosting; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Interactive { using RelativePathResolver = Scripting::Microsoft.CodeAnalysis.RelativePathResolver; internal abstract class InteractiveEvaluator : IInteractiveEvaluator, ICurrentWorkingDirectoryDiscoveryService { private const string CommandPrefix = "#"; // full path or null private readonly string _responseFilePath; private readonly InteractiveHost _interactiveHost; private readonly string _initialWorkingDirectory; private string _initialScriptFileOpt; private readonly IContentType _contentType; private readonly InteractiveWorkspace _workspace; private IInteractiveWindow _currentWindow; private ImmutableArray<MetadataReference> _responseFileReferences; private ImmutableArray<string> _responseFileImports; private MetadataReferenceResolver _metadataReferenceResolver; private SourceReferenceResolver _sourceReferenceResolver; private ProjectId _previousSubmissionProjectId; private ProjectId _currentSubmissionProjectId; private readonly IViewClassifierAggregatorService _classifierAggregator; private readonly IInteractiveWindowCommandsFactory _commandsFactory; private readonly ImmutableArray<IInteractiveWindowCommand> _commands; private IInteractiveWindowCommands _interactiveCommands; private ITextBuffer _currentSubmissionBuffer; /// <remarks> /// This is a set because the same buffer might be re-added when the content type is changed. /// </remarks> private readonly HashSet<ITextBuffer> _submissionBuffers = new HashSet<ITextBuffer>(); private int _submissionCount = 0; private readonly EventHandler<ContentTypeChangedEventArgs> _contentTypeChangedHandler; public ImmutableArray<string> ReferenceSearchPaths { get; private set; } public ImmutableArray<string> SourceSearchPaths { get; private set; } public string WorkingDirectory { get; private set; } internal InteractiveEvaluator( IContentType contentType, HostServices hostServices, IViewClassifierAggregatorService classifierAggregator, IInteractiveWindowCommandsFactory commandsFactory, ImmutableArray<IInteractiveWindowCommand> commands, string responseFilePath, string initialWorkingDirectory, string interactiveHostPath, Type replType) { Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath)); _contentType = contentType; _responseFilePath = responseFilePath; _workspace = new InteractiveWorkspace(this, hostServices); _contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged); _classifierAggregator = classifierAggregator; _initialWorkingDirectory = initialWorkingDirectory; _commandsFactory = commandsFactory; _commands = commands; // The following settings will apply when the REPL starts without .rsp file. // They are discarded once the REPL is reset. ReferenceSearchPaths = ImmutableArray<string>.Empty; SourceSearchPaths = ImmutableArray<string>.Empty; WorkingDirectory = initialWorkingDirectory; var metadataService = _workspace.CurrentSolution.Services.MetadataService; _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory); _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory); _interactiveHost = new InteractiveHost(replType, interactiveHostPath, initialWorkingDirectory); _interactiveHost.ProcessStarting += ProcessStarting; } public IContentType ContentType { get { return _contentType; } } public IInteractiveWindow CurrentWindow { get { return _currentWindow; } set { if (value == null) { throw new ArgumentNullException(); } if (_currentWindow != null) { throw new NotSupportedException(InteractiveEditorFeaturesResources.The_CurrentWindow_property_may_only_be_assigned_once); } _currentWindow = value; _interactiveHost.Output = _currentWindow.OutputWriter; _interactiveHost.ErrorOutput = _currentWindow.ErrorOutputWriter; _currentWindow.SubmissionBufferAdded += SubmissionBufferAdded; _interactiveCommands = _commandsFactory.CreateInteractiveCommands(_currentWindow, CommandPrefix, _commands); } } protected abstract string LanguageName { get; } protected abstract CompilationOptions GetSubmissionCompilationOptions(string name, MetadataReferenceResolver metadataReferenceResolver, SourceReferenceResolver sourceReferenceResolver, ImmutableArray<string> imports); protected abstract ParseOptions ParseOptions { get; } protected abstract CommandLineParser CommandLineParser { get; } #region Initialization public string GetConfiguration() { return null; } private IInteractiveWindow GetCurrentWindowOrThrow() { var window = _currentWindow; if (window == null) { throw new InvalidOperationException(EditorFeaturesResources.Engine_must_be_attached_to_an_Interactive_Window); } return window; } public Task<ExecutionResult> InitializeAsync() { var window = GetCurrentWindowOrThrow(); _interactiveHost.Output = window.OutputWriter; _interactiveHost.ErrorOutput = window.ErrorOutputWriter; return ResetAsyncWorker(); } public void Dispose() { _workspace.Dispose(); _interactiveHost.Dispose(); if (_currentWindow != null) { _currentWindow.SubmissionBufferAdded -= SubmissionBufferAdded; } } /// <summary> /// Invoked by <see cref="InteractiveHost"/> when a new process is being started. /// </summary> private void ProcessStarting(bool initialize) { var textView = GetCurrentWindowOrThrow().TextView; var dispatcher = ((FrameworkElement)textView).Dispatcher; if (!dispatcher.CheckAccess()) { dispatcher.BeginInvoke(new Action(() => ProcessStarting(initialize))); return; } // Freeze all existing classifications and then clear the list of submission buffers we have. _submissionBuffers.Remove(_currentSubmissionBuffer); // if present foreach (var textBuffer in _submissionBuffers) { InertClassifierProvider.CaptureExistingClassificationSpans(_classifierAggregator, textView, textBuffer); } _submissionBuffers.Clear(); // We always start out empty _workspace.ClearSolution(); _currentSubmissionProjectId = null; _previousSubmissionProjectId = null; var metadataService = _workspace.CurrentSolution.Services.MetadataService; var mscorlibRef = metadataService.GetReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly); var interactiveHostObjectRef = metadataService.GetReference(typeof(InteractiveScriptGlobals).Assembly.Location, Script.HostAssemblyReferenceProperties); _responseFileReferences = ImmutableArray.Create<MetadataReference>(mscorlibRef, interactiveHostObjectRef); _responseFileImports = ImmutableArray<string>.Empty; _initialScriptFileOpt = null; ReferenceSearchPaths = ImmutableArray<string>.Empty; SourceSearchPaths = ImmutableArray<string>.Empty; if (initialize && File.Exists(_responseFilePath)) { // The base directory for relative paths is the directory that contains the .rsp file. // Note that .rsp files included by this .rsp file will share the base directory (Dev10 behavior of csc/vbc). var responseFileDirectory = Path.GetDirectoryName(_responseFilePath); var args = this.CommandLineParser.Parse(new[] { "@" + _responseFilePath }, responseFileDirectory, RuntimeEnvironment.GetRuntimeDirectory(), null); if (args.Errors.Length == 0) { var metadataResolver = CreateMetadataReferenceResolver(metadataService, args.ReferencePaths, responseFileDirectory); var sourceResolver = CreateSourceReferenceResolver(args.SourcePaths, responseFileDirectory); // ignore unresolved references, they will be reported in the interactive window: var responseFileReferences = args.ResolveMetadataReferences(metadataResolver).Where(r => !(r is UnresolvedMetadataReference)); _initialScriptFileOpt = args.SourceFiles.IsEmpty ? null : args.SourceFiles[0].Path; ReferenceSearchPaths = args.ReferencePaths; SourceSearchPaths = args.SourcePaths; _responseFileReferences = _responseFileReferences.AddRange(responseFileReferences); _responseFileImports = CommandLineHelpers.GetImports(args); } } _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory); _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory); // create the first submission project in the workspace after reset: if (_currentSubmissionBuffer != null) { AddSubmission(_currentSubmissionBuffer, this.LanguageName); } } private static MetadataReferenceResolver CreateMetadataReferenceResolver(IMetadataService metadataService, ImmutableArray<string> searchPaths, string baseDirectory) { return new RuntimeMetadataReferenceResolver( new RelativePathResolver(searchPaths, baseDirectory), null, GacFileResolver.IsAvailable ? new GacFileResolver(preferredCulture: CultureInfo.CurrentCulture) : null, (path, properties) => metadataService.GetReference(path, properties)); } private static SourceReferenceResolver CreateSourceReferenceResolver(ImmutableArray<string> searchPaths, string baseDirectory) { return new SourceFileResolver(searchPaths, baseDirectory); } #endregion #region Workspace private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs args) { AddSubmission(args.NewBuffer, this.LanguageName); } // The REPL window might change content type to host command content type (when a host command is typed at the beginning of the buffer). private void LanguageBufferContentTypeChanged(object sender, ContentTypeChangedEventArgs e) { // It's not clear whether this situation will ever happen, but just in case. if (e.BeforeContentType == e.AfterContentType) { return; } var buffer = e.Before.TextBuffer; var contentTypeName = this.ContentType.TypeName; var afterIsLanguage = e.AfterContentType.IsOfType(contentTypeName); var afterIsInteractiveCommand = e.AfterContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); var beforeIsLanguage = e.BeforeContentType.IsOfType(contentTypeName); var beforeIsInteractiveCommand = e.BeforeContentType.IsOfType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName); Debug.Assert((afterIsLanguage && beforeIsInteractiveCommand) || (beforeIsLanguage && afterIsInteractiveCommand)); // We're switching between the target language and the Interactive Command "language". // First, remove the current submission from the solution. var oldSolution = _workspace.CurrentSolution; var newSolution = oldSolution; foreach (var documentId in _workspace.GetRelatedDocumentIds(buffer.AsTextContainer())) { Debug.Assert(documentId != null); newSolution = newSolution.RemoveDocument(documentId); // TODO (tomat): Is there a better way to remove mapping between buffer and document in REPL? // Perhaps TrackingWorkspace should implement RemoveDocumentAsync? _workspace.ClearOpenDocument(documentId); } // Next, remove the previous submission project and update the workspace. newSolution = newSolution.RemoveProject(_currentSubmissionProjectId); _workspace.SetCurrentSolution(newSolution); // Add a new submission with the correct language for the current buffer. var languageName = afterIsLanguage ? this.LanguageName : InteractiveLanguageNames.InteractiveCommand; AddSubmission(buffer, languageName); } private void AddSubmission(ITextBuffer subjectBuffer, string languageName) { var solution = _workspace.CurrentSolution; Project project; ImmutableArray<string> imports; ImmutableArray<MetadataReference> references; if (_previousSubmissionProjectId != null) { // only the first project needs imports and references imports = ImmutableArray<string>.Empty; references = ImmutableArray<MetadataReference>.Empty; } else if (_initialScriptFileOpt != null) { // insert a project for initialization script listed in .rsp: project = CreateSubmissionProject(solution, languageName, _responseFileImports, _responseFileReferences); var documentId = DocumentId.CreateNewId(project.Id, debugName: _initialScriptFileOpt); solution = project.Solution.AddDocument(documentId, Path.GetFileName(_initialScriptFileOpt), new FileTextLoader(_initialScriptFileOpt, defaultEncoding: null)); _previousSubmissionProjectId = project.Id; imports = ImmutableArray<string>.Empty; references = ImmutableArray<MetadataReference>.Empty; } else { imports = _responseFileImports; references = _responseFileReferences; } // project for the new submission: project = CreateSubmissionProject(solution, languageName, imports, references); // Keep track of this buffer so we can freeze the classifications for it in the future. _submissionBuffers.Add(subjectBuffer); SetSubmissionDocument(subjectBuffer, project); _currentSubmissionProjectId = project.Id; if (_currentSubmissionBuffer != null) { _currentSubmissionBuffer.ContentTypeChanged -= _contentTypeChangedHandler; } subjectBuffer.ContentTypeChanged += _contentTypeChangedHandler; subjectBuffer.Properties[typeof(ICurrentWorkingDirectoryDiscoveryService)] = this; _currentSubmissionBuffer = subjectBuffer; } private Project CreateSubmissionProject(Solution solution, string languageName, ImmutableArray<string> imports, ImmutableArray<MetadataReference> references) { var name = "Submission#" + (_submissionCount++); // Grab a local copy so we aren't closing over the field that might change. The // collection itself is an immutable collection. var localCompilationOptions = GetSubmissionCompilationOptions(name, _metadataReferenceResolver, _sourceReferenceResolver, imports); var localParseOptions = ParseOptions; var projectId = ProjectId.CreateNewId(debugName: name); solution = solution.AddProject( ProjectInfo.Create( projectId, VersionStamp.Create(), name: name, assemblyName: name, language: languageName, compilationOptions: localCompilationOptions, parseOptions: localParseOptions, documents: null, projectReferences: null, metadataReferences: references, hostObjectType: typeof(InteractiveScriptGlobals), isSubmission: true)); if (_previousSubmissionProjectId != null) { solution = solution.AddProjectReference(projectId, new ProjectReference(_previousSubmissionProjectId)); } return solution.GetProject(projectId); } private void SetSubmissionDocument(ITextBuffer buffer, Project project) { var documentId = DocumentId.CreateNewId(project.Id, debugName: project.Name); var solution = project.Solution .AddDocument(documentId, project.Name, buffer.CurrentSnapshot.AsText()); _workspace.SetCurrentSolution(solution); // opening document will start workspace listening to changes in this text container _workspace.OpenDocument(documentId, buffer.AsTextContainer()); } #endregion #region IInteractiveEngine public virtual bool CanExecuteCode(string text) { if (_interactiveCommands != null && _interactiveCommands.InCommand) { return true; } return false; } public Task<ExecutionResult> ResetAsync(bool initialize = true) { var window = GetCurrentWindowOrThrow(); Debug.Assert(_interactiveCommands.CommandPrefix == CommandPrefix); window.AddInput(CommandPrefix + ResetCommand.CommandName); window.WriteLine(InteractiveEditorFeaturesResources.Resetting_execution_engine); window.FlushOutput(); return ResetAsyncWorker(initialize); } private async Task<ExecutionResult> ResetAsyncWorker(bool initialize = true) { try { var options = new InteractiveHostOptions( initializationFile: initialize ? _responseFilePath : null, culture: CultureInfo.CurrentUICulture); var result = await _interactiveHost.ResetAsync(options).ConfigureAwait(false); if (result.Success) { UpdateResolvers(result); } return new ExecutionResult(result.Success); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } public async Task<ExecutionResult> ExecuteCodeAsync(string text) { try { if (_interactiveCommands.InCommand) { var cmdResult = _interactiveCommands.TryExecuteCommand(); if (cmdResult != null) { return await cmdResult.ConfigureAwait(false); } } var result = await _interactiveHost.ExecuteAsync(text).ConfigureAwait(false); if (result.Success) { // We are not executing a command (the current content type is not "Interactive Command"), // so the source document should not have been removed. Debug.Assert(_workspace.CurrentSolution.GetProject(_currentSubmissionProjectId).HasDocuments); // only remember the submission if we compiled successfully, otherwise we // ignore it's id so we don't reference it in the next submission. _previousSubmissionProjectId = _currentSubmissionProjectId; // update local search paths - remote paths has already been updated UpdateResolvers(result); } return new ExecutionResult(result.Success); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } public void AbortExecution() { // TODO (https://github.com/dotnet/roslyn/issues/4725) } public string FormatClipboard() { // keep the clipboard content as is return null; } #endregion #region Paths, Resolvers private void UpdateResolvers(RemoteExecutionResult result) { UpdateResolvers(result.ChangedReferencePaths.AsImmutableOrNull(), result.ChangedSourcePaths.AsImmutableOrNull(), result.ChangedWorkingDirectory); } private void UpdateResolvers(ImmutableArray<string> changedReferenceSearchPaths, ImmutableArray<string> changedSourceSearchPaths, string changedWorkingDirectory) { if (changedReferenceSearchPaths.IsDefault && changedSourceSearchPaths.IsDefault && changedWorkingDirectory == null) { return; } var solution = _workspace.CurrentSolution; // Maybe called after reset, when no submissions are available. var optionsOpt = (_currentSubmissionProjectId != null) ? solution.GetProjectState(_currentSubmissionProjectId).CompilationOptions : null; if (changedWorkingDirectory != null) { WorkingDirectory = changedWorkingDirectory; } if (!changedReferenceSearchPaths.IsDefault) { ReferenceSearchPaths = changedReferenceSearchPaths; } if (!changedSourceSearchPaths.IsDefault) { SourceSearchPaths = changedSourceSearchPaths; } if (!changedReferenceSearchPaths.IsDefault || changedWorkingDirectory != null) { _metadataReferenceResolver = CreateMetadataReferenceResolver(_workspace.CurrentSolution.Services.MetadataService, ReferenceSearchPaths, WorkingDirectory); if (optionsOpt != null) { optionsOpt = optionsOpt.WithMetadataReferenceResolver(_metadataReferenceResolver); } } if (!changedSourceSearchPaths.IsDefault || changedWorkingDirectory != null) { _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, WorkingDirectory); if (optionsOpt != null) { optionsOpt = optionsOpt.WithSourceReferenceResolver(_sourceReferenceResolver); } } if (optionsOpt != null) { _workspace.SetCurrentSolution(solution.WithProjectCompilationOptions(_currentSubmissionProjectId, optionsOpt)); } } public async Task SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string workingDirectory) { try { var result = await _interactiveHost.SetPathsAsync(referenceSearchPaths.ToArray(), sourceSearchPaths.ToArray(), workingDirectory).ConfigureAwait(false); UpdateResolvers(result); } catch (Exception e) when (FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } public string GetPrompt() { var buffer = GetCurrentWindowOrThrow().CurrentLanguageBuffer; return buffer != null && buffer.CurrentSnapshot.LineCount > 1 ? ". " : "> "; } #endregion } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.Serialization; namespace Pathfinding { /** Basic point graph. * \ingroup graphs * The point graph is the most basic graph structure, it consists of a number of interconnected points in space called nodes or waypoints.\n * The point graph takes a Transform object as "root", this Transform will be searched for child objects, every child object will be treated as a node. * If #recursive is enabled, it will also search the child objects of the children recursively. * 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 are treated as being set to infinity if they are set to 0 (zero). \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 * * Alternatively, a tag can be used to search for nodes. * \see http://docs.unity3d.com/Manual/Tags.html * * For larger graphs, it can take quite some time to scan the graph with the default settings. * If you have the pro version you can enable 'optimizeForSparseGraph' which will in most cases reduce the calculation times * drastically. If your graph is essentially only in the XZ plane (note, not XY), you can enable #optimizeFor2D (called 'Optimize For XZ Plane' in the inspector). * * \note Does not support linecast because of obvious reasons. * * \shadowimage{pointgraph_graph.png} * \shadowimage{pointgraph_inspector.png} * */ [JsonOptIn] public class PointGraph : NavGraph { /** Childs of this transform are treated as nodes */ [JsonMember] public Transform root; /** If no #root is set, all nodes with the tag is used as nodes */ [JsonMember] public string searchTag; /** 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. */ [JsonMember] public float maxDistance; /** Max distance along the axis for a connection to be valid. 0 = infinity */ [JsonMember] public Vector3 limits; /** Use raycasts to check connections */ [JsonMember] public bool raycast = true; /** Use the 2D Physics API */ [JsonMember] public bool use2DPhysics; /** Use thick raycast */ [JsonMember] public bool thickRaycast; /** Thick raycast radius */ [JsonMember] public float thickRaycastRadius = 1; /** Recursively search for child nodes to the #root */ [JsonMember] public bool recursive = true; /** Layer mask to use for raycast */ [JsonMember] public LayerMask mask; /** 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 */ public int nodeCount { get; protected set; } public override int CountNodes () { return 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) { 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; } } var 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; } struct GetNearestHelper { public Vector3 position; public float minDist, minConstDist, maxDistSqr; public PointNode minNode, minConstNode; NNConstraint constraint; Dictionary<Int3, PointNode> nodeLookup; public GetNearestHelper(Vector3 position, float maxDistSqr, NNConstraint constraint, Dictionary<Int3, PointNode> nodeLookup) { this.position = position; this.maxDistSqr = maxDistSqr; this.constraint = constraint; this.nodeLookup = nodeLookup; minDist = float.PositiveInfinity; minConstDist = float.PositiveInfinity; minNode = minConstNode = null; } public void Search (Int3 p) { PointNode node; if (nodeLookup.TryGetValue(p, out node)) { while (node != null) { 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; } node = node.next; } } } } /** Add a node to the graph at the specified position. * \note Vector3 can be casted to Int3 using (Int3)myVector. * * \note This needs to be called when it is safe to update nodes, which is * - when scanning * - during a graph update * - inside a callback registered using AstarPath.RegisterSafeUpdate */ 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. * * \param node 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. * \param position The node will be set to this position. * \note Vector3 can be casted to Int3 using (Int3)myVector. * * \note This needs to be called when it is safe to update nodes, which is * - when scanning * - during a graph update * - inside a callback registered using AstarPath.RegisterSafeUpdate * * \see AstarPath.RegisterSafeUpdate */ public T AddNode<T>(T node, Int3 position) where T : PointNode { if (nodes == null || nodeCount == nodes.Length) { var 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; } node.SetPosition(position); node.GraphIndex = graphIndex; node.Walkable = true; nodes[nodeCount] = node; nodeCount++; AddToLookup(node); return node; } /** Recursively counds children of a transform */ protected 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 */ protected void AddChildren (ref int c, Transform tr) { foreach (Transform child in tr) { nodes[c].SetPosition((Int3)child.position); nodes[c].Walkable = true; nodes[c].gameObject = 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 } 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 = searchTag != null ? GameObject.FindGameObjectsWithTag(searchTag) : null; 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); for (int i = 0; i < gos.Length; i++) { nodes[i].SetPosition((Int3)gos[i].transform.position); nodes[i].Walkable = true; nodes[i].gameObject = gos[i].gameObject; } } 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); int c = 0; foreach (Transform child in root) { nodes[c].SetPosition((Int3)child.position); nodes[c].Walkable = true; nodes[c].gameObject = 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)); int startID = 0; AddChildren(ref startID, root); } } if (maxDistance >= 0) { //To avoid too many allocations, these lists are reused for each node var connections = new List<PointNode>(3); var 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; 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(); } } } /** 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; var dir = (Vector3)(b.position-a.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) { var ray = new Ray((Vector3)a.position, dir); var invertRay = new Ray((Vector3)b.position, -dir); if (use2DPhysics) { if (thickRaycast) { return !Physics2D.CircleCast(ray.origin, thickRaycastRadius, ray.direction, dist, mask) && !Physics2D.CircleCast(invertRay.origin, thickRaycastRadius, invertRay.direction, dist, mask); } else { return !Physics2D.Linecast((Vector2)(Vector3)a.position, (Vector2)(Vector3)b.position, mask) && !Physics2D.Linecast((Vector2)(Vector3)b.position, (Vector2)(Vector3)a.position, mask); } } else { if (thickRaycast) { return !Physics.SphereCast(ray, thickRaycastRadius, dist, mask) && !Physics.SphereCast(invertRay, thickRaycastRadius, dist, mask); } else { return !Physics.Linecast((Vector3)a.position, (Vector3)b.position, mask) && !Physics.Linecast((Vector3)b.position, (Vector3)a.position, mask); } } } 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 DeserializeSettingsCompatibility (GraphSerializationContext ctx) { base.DeserializeSettingsCompatibility(ctx); root = ctx.DeserializeUnityObject() as Transform; searchTag = ctx.reader.ReadString(); maxDistance = ctx.reader.ReadSingle(); limits = ctx.DeserializeVector3(); raycast = ctx.reader.ReadBoolean(); use2DPhysics = ctx.reader.ReadBoolean(); thickRaycast = ctx.reader.ReadBoolean(); thickRaycastRadius = ctx.reader.ReadSingle(); recursive = ctx.reader.ReadBoolean(); ctx.reader.ReadBoolean(); // Deprecated field mask = (LayerMask)ctx.reader.ReadInt32(); } public override void SerializeExtraInfo (GraphSerializationContext ctx) { // Serialize node data if (nodes == null) ctx.writer.Write(-1); // Length prefixed array of nodes ctx.writer.Write(nodeCount); for (int i = 0; i < nodeCount; i++) { // -1 indicates a null field 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); } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.Common { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using NLog.Common; using NLog.Time; using Xunit; public class InternalLoggerTests : NLogTestBase, IDisposable { /// <summary> /// Test the return values of all Is[Level]Enabled() methods. /// </summary> [Fact] public void IsEnabledTests() { // Setup LogLevel to minimum named level. InternalLogger.LogLevel = LogLevel.Trace; Assert.True(InternalLogger.IsTraceEnabled); Assert.True(InternalLogger.IsDebugEnabled); Assert.True(InternalLogger.IsInfoEnabled); Assert.True(InternalLogger.IsWarnEnabled); Assert.True(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Setup LogLevel to maximum named level. InternalLogger.LogLevel = LogLevel.Fatal; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.True(InternalLogger.IsFatalEnabled); // Switch off the internal logging. InternalLogger.LogLevel = LogLevel.Off; Assert.False(InternalLogger.IsTraceEnabled); Assert.False(InternalLogger.IsDebugEnabled); Assert.False(InternalLogger.IsInfoEnabled); Assert.False(InternalLogger.IsWarnEnabled); Assert.False(InternalLogger.IsErrorEnabled); Assert.False(InternalLogger.IsFatalEnabled); } [Fact] public void WriteToStringWriterTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, writer2); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, () => "WWW"); InternalLogger.Log(LogLevel.Error, () => "EEE"); InternalLogger.Log(LogLevel.Fatal, () => "FFF"); InternalLogger.Log(LogLevel.Trace, () => "TTT"); InternalLogger.Log(LogLevel.Debug, () => "DDD"); InternalLogger.Log(LogLevel.Info, () => "III"); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } [Fact] public void WriteToStringWriterWithArgsTests() { try { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW 0\nError EEE 0, 1\nFatal FFF 0, 1, 2\nTrace TTT 0, 1, 2\nDebug DDD 0, 1\nInfo III 0\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; { StringWriter writer1 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer1; // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW {0}", 0); InternalLogger.Error("EEE {0}, {1}", 0, 1); InternalLogger.Fatal("FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Trace("TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Debug("DDD {0}, {1}", 0, 1); InternalLogger.Info("III {0}", 0); TestWriter(expected, writer1); } { // // Reconfigure the LogWriter. StringWriter writer2 = new StringWriter() { NewLine = "\n" }; InternalLogger.LogWriter = writer2; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW {0}", 0); InternalLogger.Log(LogLevel.Error, "EEE {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Fatal, "FFF {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Trace, "TTT {0}, {1}, {2}", 0, 1, 2); InternalLogger.Log(LogLevel.Debug, "DDD {0}, {1}", 0, 1); InternalLogger.Log(LogLevel.Info, "III {0}", 0); TestWriter(expected, writer2); } } finally { InternalLogger.Reset(); } } /// <summary> /// Test output van een textwriter /// </summary> /// <param name="expected"></param> /// <param name="writer"></param> private static void TestWriter(string expected, StringWriter writer) { writer.Flush(); var writerOutput = writer.ToString(); Assert.Equal(expected, writerOutput); } [Fact] public void WriteToConsoleOutTests() { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; using (var loggerScope = new InternalLoggerScope(true)) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsole = true; { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, consoleOutWriter1); } // // Redirect the console output to another StringWriter. { StringWriter consoleOutWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleOutput(consoleOutWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, consoleOutWriter2); } //lambdas { StringWriter consoleOutWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleOutput(consoleOutWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn(() => "WWW"); InternalLogger.Error(() => "EEE"); InternalLogger.Fatal(() => "FFF"); InternalLogger.Trace(() => "TTT"); InternalLogger.Debug(() => "DDD"); InternalLogger.Info(() => "III"); TestWriter(expected, consoleOutWriter1); } } } [Fact] public void WriteToConsoleErrorTests() { using (var loggerScope = new InternalLoggerScope(true)) { // Expected result is the same for both types of method invocation. const string expected = "Warn WWW\nError EEE\nFatal FFF\nTrace TTT\nDebug DDD\nInfo III\n"; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogToConsoleError = true; { StringWriter consoleWriter1 = new StringWriter() { NewLine = "\n" }; // Redirect the console output to a StringWriter. loggerScope.SetConsoleError(consoleWriter1); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } { // // Redirect the console output to another StringWriter. StringWriter consoleWriter2 = new StringWriter() { NewLine = "\n" }; loggerScope.SetConsoleError(consoleWriter2); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); TestWriter(expected, loggerScope.ConsoleErrorWriter); } } } [Fact] public void WriteToFileTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; var tempFile = Path.GetTempFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; InternalLogger.LogFile = tempFile; // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFile, expected, Encoding.UTF8); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } } } /// <summary> /// <see cref="TimeSource"/> that returns always the same time, /// passed into object constructor. /// </summary> private class FixedTimeSource : TimeSource { private readonly DateTime _time; public FixedTimeSource(DateTime time) { _time = time; } public override DateTime Time => _time; public override DateTime FromSystemTime(DateTime systemTime) { return _time; } } [Fact] public void TimestampTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = true; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; // Set fixed time source to test time output TimeSource.Current = new FixedTimeSource(DateTime.Now); // Named (based on LogLevel) public methods. InternalLogger.Warn("WWW"); InternalLogger.Error("EEE"); InternalLogger.Fatal("FFF"); InternalLogger.Trace("TTT"); InternalLogger.Debug("DDD"); InternalLogger.Info("III"); string expectedDateTime = TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture); var strings = consoleOutWriter.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var str in strings) { Assert.Contains(expectedDateTime + ".", str); } } } /// <summary> /// Test exception overloads /// </summary> [Fact] public void ExceptionTests() { using (new InternalLoggerScope()) { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; var ex1 = new Exception("e1"); var ex2 = new Exception("e2", new Exception("inner")); var ex3 = new NLogConfigurationException("config error"); var ex4 = new NLogConfigurationException("config error", ex2); var ex5 = new PathTooLongException(); ex5.Data["key1"] = "value1"; Exception ex6 = null; const string prefix = " Exception: "; { string expected = "Warn WWW1" + prefix + ex1 + Environment.NewLine + "Error EEE1" + prefix + ex2 + Environment.NewLine + "Fatal FFF1" + prefix + ex3 + Environment.NewLine + "Trace TTT1" + prefix + ex4 + Environment.NewLine + "Debug DDD1" + prefix + ex5 + Environment.NewLine + "Info III1" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, "WWW1"); InternalLogger.Error(ex2, "EEE1"); InternalLogger.Fatal(ex3, "FFF1"); InternalLogger.Trace(ex4, "TTT1"); InternalLogger.Debug(ex5, "DDD1"); InternalLogger.Info(ex6, "III1"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW2" + prefix + ex1 + Environment.NewLine + "Error EEE2" + prefix + ex2 + Environment.NewLine + "Fatal FFF2" + prefix + ex3 + Environment.NewLine + "Trace TTT2" + prefix + ex4 + Environment.NewLine + "Debug DDD2" + prefix + ex5 + Environment.NewLine + "Info III2" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Warn(ex1, () => "WWW2"); InternalLogger.Error(ex2, () => "EEE2"); InternalLogger.Fatal(ex3, () => "FFF2"); InternalLogger.Trace(ex4, () => "TTT2"); InternalLogger.Debug(ex5, () => "DDD2"); InternalLogger.Info(ex6, () => "III2"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW3" + prefix + ex1 + Environment.NewLine + "Error EEE3" + prefix + ex2 + Environment.NewLine + "Fatal FFF3" + prefix + ex3 + Environment.NewLine + "Trace TTT3" + prefix + ex4 + Environment.NewLine + "Debug DDD3" + prefix + ex5 + Environment.NewLine + "Info III3" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, "WWW3"); InternalLogger.Log(ex2, LogLevel.Error, "EEE3"); InternalLogger.Log(ex3, LogLevel.Fatal, "FFF3"); InternalLogger.Log(ex4, LogLevel.Trace, "TTT3"); InternalLogger.Log(ex5, LogLevel.Debug, "DDD3"); InternalLogger.Log(ex6, LogLevel.Info, "III3"); consoleOutWriter.Flush(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } { string expected = "Warn WWW4" + prefix + ex1 + Environment.NewLine + "Error EEE4" + prefix + ex2 + Environment.NewLine + "Fatal FFF4" + prefix + ex3 + Environment.NewLine + "Trace TTT4" + prefix + ex4 + Environment.NewLine + "Debug DDD4" + prefix + ex5 + Environment.NewLine + "Info III4" + Environment.NewLine; StringWriter consoleOutWriter = new StringWriter() { NewLine = Environment.NewLine }; // Redirect the console output to a StringWriter. InternalLogger.LogWriter = consoleOutWriter; // Named (based on LogLevel) public methods. InternalLogger.Log(ex1, LogLevel.Warn, () => "WWW4"); InternalLogger.Log(ex2, LogLevel.Error, () => "EEE4"); InternalLogger.Log(ex3, LogLevel.Fatal, () => "FFF4"); InternalLogger.Log(ex4, LogLevel.Trace, () => "TTT4"); InternalLogger.Log(ex5, LogLevel.Debug, () => "DDD4"); InternalLogger.Log(ex6, LogLevel.Info, () => "III4"); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } } } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_log(string rawLogLevel, int count) { Action log = () => { InternalLogger.Log(LogLevel.Fatal, "L1"); InternalLogger.Log(LogLevel.Error, "L2"); InternalLogger.Log(LogLevel.Warn, "L3"); InternalLogger.Log(LogLevel.Info, "L4"); InternalLogger.Log(LogLevel.Debug, "L5"); InternalLogger.Log(LogLevel.Trace, "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal("L1"); InternalLogger.Error("L2"); InternalLogger.Warn("L3"); InternalLogger.Info("L4"); InternalLogger.Debug("L5"); InternalLogger.Trace("L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } [Theory] [InlineData("trace", 6)] [InlineData("debug", 5)] [InlineData("info", 4)] [InlineData("warn", 3)] [InlineData("error", 2)] [InlineData("fatal", 1)] [InlineData("off", 0)] public void TestMinLevelSwitch_lambda(string rawLogLevel, int count) { Action log = () => { InternalLogger.Fatal(() => "L1"); InternalLogger.Error(() => "L2"); InternalLogger.Warn(() => "L3"); InternalLogger.Info(() => "L4"); InternalLogger.Debug(() => "L5"); InternalLogger.Trace(() => "L6"); }; TestMinLevelSwitch_inner(rawLogLevel, count, log); } private static void TestMinLevelSwitch_inner(string rawLogLevel, int count, Action log) { try { //set minimal InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; StringWriter consoleOutWriter = new StringWriter() { NewLine = ";" }; InternalLogger.LogWriter = consoleOutWriter; var expected = ""; var logLevel = LogLevel.Fatal.Ordinal; for (int i = 0; i < count; i++, logLevel--) { expected += LogLevel.FromOrdinal(logLevel) + " L" + (i + 1) + ";"; } log(); var strings = consoleOutWriter.ToString(); Assert.Equal(expected, strings); } finally { InternalLogger.Reset(); } } [Theory] [InlineData("trace", true)] [InlineData("debug", true)] [InlineData("info", true)] [InlineData("warn", true)] [InlineData("error", true)] [InlineData("fatal", true)] [InlineData("off", false)] public void CreateDirectoriesIfNeededTests(string rawLogLevel, bool shouldCreateDirectory) { var tempPath = Path.GetTempPath(); var tempFileName = Path.GetRandomFileName(); var randomSubDirectory = Path.Combine(tempPath, Path.GetRandomFileName()); string tempFile = Path.Combine(randomSubDirectory, tempFileName); try { InternalLogger.LogLevel = LogLevel.FromString(rawLogLevel); InternalLogger.IncludeTimestamp = false; if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } Assert.False(Directory.Exists(randomSubDirectory)); // Set the log file, which will only create the needed directories InternalLogger.LogFile = tempFile; Assert.Equal(Directory.Exists(randomSubDirectory), shouldCreateDirectory); Assert.False(File.Exists(tempFile)); InternalLogger.Log(LogLevel.FromString(rawLogLevel), "File and Directory created."); Assert.Equal(File.Exists(tempFile), shouldCreateDirectory); } finally { InternalLogger.Reset(); if (File.Exists(tempFile)) { File.Delete(tempFile); } if (Directory.Exists(randomSubDirectory)) { Directory.Delete(randomSubDirectory); } } } [Fact] public void CreateFileInCurrentDirectoryTests() { string expected = "Warn WWW" + Environment.NewLine + "Error EEE" + Environment.NewLine + "Fatal FFF" + Environment.NewLine + "Trace TTT" + Environment.NewLine + "Debug DDD" + Environment.NewLine + "Info III" + Environment.NewLine; // Store off the previous log file string previousLogFile = InternalLogger.LogFile; var tempFileName = Path.GetRandomFileName(); try { InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; Assert.False(File.Exists(tempFileName)); // Set the log file, which only has a filename InternalLogger.LogFile = tempFileName; Assert.False(File.Exists(tempFileName)); // Invoke Log(LogLevel, string) for every log level. InternalLogger.Log(LogLevel.Warn, "WWW"); InternalLogger.Log(LogLevel.Error, "EEE"); InternalLogger.Log(LogLevel.Fatal, "FFF"); InternalLogger.Log(LogLevel.Trace, "TTT"); InternalLogger.Log(LogLevel.Debug, "DDD"); InternalLogger.Log(LogLevel.Info, "III"); AssertFileContents(tempFileName, expected, Encoding.UTF8); Assert.True(File.Exists(tempFileName)); } finally { InternalLogger.Reset(); if (File.Exists(tempFileName)) { File.Delete(tempFileName); } } } [Fact] public void TestReceivedLogEventTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var receivedArgs = new List<InternalLoggerMessageEventArgs>(); var logFactory = new LogFactory(); logFactory.Setup().SetupInternalLogger(s => { EventHandler<InternalLoggerMessageEventArgs> eventHandler = (sender, e) => receivedArgs.Add(e); s.AddLogSubscription(eventHandler); s.RemoveLogSubscription(eventHandler); s.AddLogSubscription(eventHandler); }); var exception = new Exception(); // Act InternalLogger.Info(exception, "Hello {0}", "it's me!"); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Info, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal("Hello it's me!", logEventArgs.Message); } } [Fact] public void TestReceivedLogEventThrowingTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var receivedArgs = new List<InternalLoggerMessageEventArgs>(); InternalLogger.LogMessageReceived += (sender, e) => { receivedArgs.Add(e); throw new ApplicationException("I'm a bad programmer"); }; var exception = new Exception(); // Act InternalLogger.Info(exception, "Hello {0}", "it's me!"); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Info, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal("Hello it's me!", logEventArgs.Message); } } [Fact] public void TestReceivedLogEventContextTest() { using (var loggerScope = new InternalLoggerScope()) { // Arrange var targetContext = new NLog.Targets.DebugTarget() { Name = "Ugly" }; var receivedArgs = new List<InternalLoggerMessageEventArgs>(); InternalLogger.LogMessageReceived += (sender, e) => { receivedArgs.Add(e); }; var exception = new Exception(); // Act NLog.Internal.ExceptionHelper.MustBeRethrown(exception, targetContext); // Assert Assert.Single(receivedArgs); var logEventArgs = receivedArgs.Single(); Assert.Equal(LogLevel.Error, logEventArgs.Level); Assert.Equal(exception, logEventArgs.Exception); Assert.Equal(targetContext.GetType(), logEventArgs.SenderType); } } public void Dispose() { TimeSource.Current = new FastLocalTimeSource(); InternalLogger.Reset(); } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Gallio.UI.ProgressMonitoring; namespace Gallio.Icarus { partial class Main { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main)); WeifenLuo.WinFormsUI.Docking.DockPanelSkin dockPanelSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPanelSkin(); WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin autoHideStripSkin1 = new WeifenLuo.WinFormsUI.Docking.AutoHideStripSkin(); WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient1 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin dockPaneStripSkin1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripSkin(); WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient dockPaneStripGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient2 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient2 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient3 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient dockPaneStripToolWindowGradient1 = new WeifenLuo.WinFormsUI.Docking.DockPaneStripToolWindowGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient4 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient5 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); WeifenLuo.WinFormsUI.Docking.DockPanelGradient dockPanelGradient3 = new WeifenLuo.WinFormsUI.Docking.DockPanelGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient6 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); WeifenLuo.WinFormsUI.Docking.TabGradient tabGradient7 = new WeifenLuo.WinFormsUI.Docking.TabGradient(); this.menuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openProjectMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.saveProjectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveProjectAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.recentProjectsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.fileExit = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.projectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.addFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeAllFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.reloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.testsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.startTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.startWithDebuggerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.stopTestsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.resetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.reportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showOnlineHelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.aboutMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripProgressBar = new Gallio.UI.ProgressMonitoring.ToolStripProgressBar(); this.projectToolStrip = new System.Windows.Forms.ToolStrip(); this.newProjectToolStripButton = new System.Windows.Forms.ToolStripButton(); this.openProjectToolStripButton = new System.Windows.Forms.ToolStripButton(); this.saveProjectToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripContainer = new System.Windows.Forms.ToolStripContainer(); this.dockPanel = new WeifenLuo.WinFormsUI.Docking.DockPanel(); this.testsToolStrip = new System.Windows.Forms.ToolStrip(); this.startButton = new System.Windows.Forms.ToolStripButton(); this.startTestsWithDebuggerButton = new System.Windows.Forms.ToolStripButton(); this.stopButton = new System.Windows.Forms.ToolStripButton(); this.filesToolStrip = new System.Windows.Forms.ToolStrip(); this.addFilesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.removeAllFilesToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.reloadToolbarButton = new System.Windows.Forms.ToolStripButton(); this.menuStrip.SuspendLayout(); this.statusStrip.SuspendLayout(); this.projectToolStrip.SuspendLayout(); this.toolStripContainer.ContentPanel.SuspendLayout(); this.toolStripContainer.TopToolStripPanel.SuspendLayout(); this.toolStripContainer.SuspendLayout(); this.testsToolStrip.SuspendLayout(); this.filesToolStrip.SuspendLayout(); this.SuspendLayout(); // // menuStrip // this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.viewToolStripMenuItem, this.projectToolStripMenuItem, this.testsToolStripMenuItem, this.reportToolStripMenuItem, this.toolsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.ShowItemToolTips = true; this.menuStrip.Size = new System.Drawing.Size(1003, 24); this.menuStrip.TabIndex = 0; this.menuStrip.Text = "Main Menu"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newProjectToolStripMenuItem, this.openProjectMenuItem, this.toolStripSeparator3, this.saveProjectToolStripMenuItem, this.saveProjectAsToolStripMenuItem, this.toolStripSeparator4, this.recentProjectsToolStripMenuItem, this.toolStripSeparator12, this.fileExit}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "&File"; // // newProjectToolStripMenuItem // this.newProjectToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("newProjectToolStripMenuItem.Image"))); this.newProjectToolStripMenuItem.Name = "newProjectToolStripMenuItem"; this.newProjectToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.newProjectToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.newProjectToolStripMenuItem.Text = "&New Project"; this.newProjectToolStripMenuItem.Click += new System.EventHandler(this.newProjectToolStripMenuItem_Click); // // openProjectMenuItem // this.openProjectMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("openProjectMenuItem.Image"))); this.openProjectMenuItem.Name = "openProjectMenuItem"; this.openProjectMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.openProjectMenuItem.Size = new System.Drawing.Size(186, 22); this.openProjectMenuItem.Text = "&Open Project"; this.openProjectMenuItem.Click += new System.EventHandler(this.openProject_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(183, 6); // // saveProjectToolStripMenuItem // this.saveProjectToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveProjectToolStripMenuItem.Image"))); this.saveProjectToolStripMenuItem.Name = "saveProjectToolStripMenuItem"; this.saveProjectToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.saveProjectToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.saveProjectToolStripMenuItem.Text = "&Save Project"; this.saveProjectToolStripMenuItem.Click += new System.EventHandler(this.saveProjectToolStripMenuItem_Click); // // saveProjectAsToolStripMenuItem // this.saveProjectAsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("saveProjectAsToolStripMenuItem.Image"))); this.saveProjectAsToolStripMenuItem.Name = "saveProjectAsToolStripMenuItem"; this.saveProjectAsToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.saveProjectAsToolStripMenuItem.Text = "Save Project &As..."; this.saveProjectAsToolStripMenuItem.Click += new System.EventHandler(this.saveProjectAsToolStripMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(183, 6); // // recentProjectsToolStripMenuItem // this.recentProjectsToolStripMenuItem.Name = "recentProjectsToolStripMenuItem"; this.recentProjectsToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.recentProjectsToolStripMenuItem.Text = "Recent Projects"; // // toolStripSeparator12 // this.toolStripSeparator12.Name = "toolStripSeparator12"; this.toolStripSeparator12.Size = new System.Drawing.Size(183, 6); // // fileExit // this.fileExit.Name = "fileExit"; this.fileExit.Size = new System.Drawing.Size(186, 22); this.fileExit.Text = "E&xit"; this.fileExit.Click += new System.EventHandler(this.fileExit_Click); // // viewToolStripMenuItem // this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; this.viewToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.viewToolStripMenuItem.Text = "View"; // // projectToolStripMenuItem // this.projectToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addFilesToolStripMenuItem, this.removeAllFilesToolStripMenuItem, this.toolStripSeparator8, this.reloadToolStripMenuItem}); this.projectToolStripMenuItem.Name = "projectToolStripMenuItem"; this.projectToolStripMenuItem.Size = new System.Drawing.Size(56, 20); this.projectToolStripMenuItem.Text = "&Project"; // // addFilesToolStripMenuItem // this.addFilesToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("addFilesToolStripMenuItem.Image"))); this.addFilesToolStripMenuItem.Name = "addFilesToolStripMenuItem"; this.addFilesToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A))); this.addFilesToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.addFilesToolStripMenuItem.Text = "&Add Files..."; this.addFilesToolStripMenuItem.Click += new System.EventHandler(this.addFilesToolStripMenuItem_Click); // // removeAllFilesToolStripMenuItem // this.removeAllFilesToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("removeAllFilesToolStripMenuItem.Image"))); this.removeAllFilesToolStripMenuItem.Name = "removeAllFilesToolStripMenuItem"; this.removeAllFilesToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.R))); this.removeAllFilesToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.removeAllFilesToolStripMenuItem.Text = "&Remove All Files"; this.removeAllFilesToolStripMenuItem.Click += new System.EventHandler(this.removeAllFiles_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; this.toolStripSeparator8.Size = new System.Drawing.Size(198, 6); // // reloadToolStripMenuItem // this.reloadToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("reloadToolStripMenuItem.Image"))); this.reloadToolStripMenuItem.Name = "reloadToolStripMenuItem"; this.reloadToolStripMenuItem.Size = new System.Drawing.Size(201, 22); this.reloadToolStripMenuItem.Text = "R&eload"; this.reloadToolStripMenuItem.Click += new System.EventHandler(this.reloadToolbarButton_Click); // // testsToolStripMenuItem // this.testsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.startTestsToolStripMenuItem, this.startWithDebuggerToolStripMenuItem, this.stopTestsToolStripMenuItem, this.resetToolStripMenuItem}); this.testsToolStripMenuItem.Name = "testsToolStripMenuItem"; this.testsToolStripMenuItem.Size = new System.Drawing.Size(46, 20); this.testsToolStripMenuItem.Text = "Tests"; // // startTestsToolStripMenuItem // this.startTestsToolStripMenuItem.Enabled = false; this.startTestsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("startTestsToolStripMenuItem.Image"))); this.startTestsToolStripMenuItem.Name = "startTestsToolStripMenuItem"; this.startTestsToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F5; this.startTestsToolStripMenuItem.Size = new System.Drawing.Size(227, 22); this.startTestsToolStripMenuItem.Text = "Start"; this.startTestsToolStripMenuItem.Click += new System.EventHandler(this.startTestsToolStripMenuItem_Click); // // startWithDebuggerToolStripMenuItem // this.startWithDebuggerToolStripMenuItem.Name = "startWithDebuggerToolStripMenuItem"; this.startWithDebuggerToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F5))); this.startWithDebuggerToolStripMenuItem.Size = new System.Drawing.Size(227, 22); this.startWithDebuggerToolStripMenuItem.Text = "Start With Debugger"; this.startWithDebuggerToolStripMenuItem.Click += new System.EventHandler(this.startWithDebuggerToolStripMenuItem_Click); // // stopTestsToolStripMenuItem // this.stopTestsToolStripMenuItem.Enabled = false; this.stopTestsToolStripMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("stopTestsToolStripMenuItem.Image"))); this.stopTestsToolStripMenuItem.Name = "stopTestsToolStripMenuItem"; this.stopTestsToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Shift | System.Windows.Forms.Keys.F5))); this.stopTestsToolStripMenuItem.Size = new System.Drawing.Size(227, 22); this.stopTestsToolStripMenuItem.Text = "Stop"; this.stopTestsToolStripMenuItem.Click += new System.EventHandler(this.stopToolStripMenuItem_Click); // // resetToolStripMenuItem // this.resetToolStripMenuItem.Name = "resetToolStripMenuItem"; this.resetToolStripMenuItem.Size = new System.Drawing.Size(227, 22); this.resetToolStripMenuItem.Text = "Reset"; this.resetToolStripMenuItem.Click += new System.EventHandler(this.resetToolStripMenuItem_Click); // // reportToolStripMenuItem // this.reportToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.viewAsToolStripMenuItem}); this.reportToolStripMenuItem.Name = "reportToolStripMenuItem"; this.reportToolStripMenuItem.Size = new System.Drawing.Size(54, 20); this.reportToolStripMenuItem.Text = "Report"; // // viewAsToolStripMenuItem // this.viewAsToolStripMenuItem.Name = "viewAsToolStripMenuItem"; this.viewAsToolStripMenuItem.Size = new System.Drawing.Size(115, 22); this.viewAsToolStripMenuItem.Text = "View As"; // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.optionsMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(48, 20); this.toolsToolStripMenuItem.Text = "&Tools"; // // optionsMenuItem // this.optionsMenuItem.Image = ((System.Drawing.Image)(resources.GetObject("optionsMenuItem.Image"))); this.optionsMenuItem.Name = "optionsMenuItem"; this.optionsMenuItem.Size = new System.Drawing.Size(125, 22); this.optionsMenuItem.Text = "&Options..."; this.optionsMenuItem.Click += new System.EventHandler(this.optionsMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.showOnlineHelpToolStripMenuItem, this.toolStripSeparator5, this.aboutMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "&Help"; // // showOnlineHelpToolStripMenuItem // this.showOnlineHelpToolStripMenuItem.Name = "showOnlineHelpToolStripMenuItem"; this.showOnlineHelpToolStripMenuItem.ShortcutKeys = System.Windows.Forms.Keys.F1; this.showOnlineHelpToolStripMenuItem.Size = new System.Drawing.Size(156, 22); this.showOnlineHelpToolStripMenuItem.Text = "Online &Help"; this.showOnlineHelpToolStripMenuItem.Click += new System.EventHandler(this.showOnlineHelpToolStripMenuItem_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(153, 6); // // aboutMenuItem // this.aboutMenuItem.Name = "aboutMenuItem"; this.aboutMenuItem.Size = new System.Drawing.Size(156, 22); this.aboutMenuItem.Text = "&About..."; this.aboutMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click); // // statusStrip // this.statusStrip.AutoSize = false; this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel, this.toolStripProgressBar}); this.statusStrip.Location = new System.Drawing.Point(0, 685); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(1003, 22); this.statusStrip.TabIndex = 2; this.statusStrip.Text = "statusStrip"; // // toolStripStatusLabel // this.toolStripStatusLabel.AutoSize = false; this.toolStripStatusLabel.Name = "toolStripStatusLabel"; this.toolStripStatusLabel.Size = new System.Drawing.Size(886, 17); this.toolStripStatusLabel.Spring = true; this.toolStripStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // toolStripProgressBar // this.toolStripProgressBar.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripProgressBar.Name = "toolStripProgressBar"; this.toolStripProgressBar.Size = new System.Drawing.Size(100, 16); // // projectToolStrip // this.projectToolStrip.Dock = System.Windows.Forms.DockStyle.None; this.projectToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newProjectToolStripButton, this.openProjectToolStripButton, this.saveProjectToolStripButton}); this.projectToolStrip.Location = new System.Drawing.Point(272, 25); this.projectToolStrip.Name = "projectToolStrip"; this.projectToolStrip.Size = new System.Drawing.Size(81, 25); this.projectToolStrip.TabIndex = 3; this.projectToolStrip.Text = "Project"; // // newProjectToolStripButton // this.newProjectToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.newProjectToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newProjectToolStripButton.Image"))); this.newProjectToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.newProjectToolStripButton.Name = "newProjectToolStripButton"; this.newProjectToolStripButton.Size = new System.Drawing.Size(23, 22); this.newProjectToolStripButton.Text = "New Project"; this.newProjectToolStripButton.ToolTipText = "New Project"; this.newProjectToolStripButton.Click += new System.EventHandler(this.newProjectToolStripButton_Click); // // openProjectToolStripButton // this.openProjectToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.openProjectToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openProjectToolStripButton.Image"))); this.openProjectToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.openProjectToolStripButton.Name = "openProjectToolStripButton"; this.openProjectToolStripButton.Size = new System.Drawing.Size(23, 22); this.openProjectToolStripButton.Text = "Open Project"; this.openProjectToolStripButton.ToolTipText = "Open Project"; this.openProjectToolStripButton.Click += new System.EventHandler(this.openProject_Click); // // saveProjectToolStripButton // this.saveProjectToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.saveProjectToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveProjectToolStripButton.Image"))); this.saveProjectToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveProjectToolStripButton.Name = "saveProjectToolStripButton"; this.saveProjectToolStripButton.Size = new System.Drawing.Size(23, 22); this.saveProjectToolStripButton.Text = "Save Project"; this.saveProjectToolStripButton.Click += new System.EventHandler(this.saveProjectToolStripButton_Click); // // toolStripContainer // // // toolStripContainer.ContentPanel // this.toolStripContainer.ContentPanel.Controls.Add(this.dockPanel); this.toolStripContainer.ContentPanel.Size = new System.Drawing.Size(1003, 611); this.toolStripContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer.Location = new System.Drawing.Point(0, 24); this.toolStripContainer.Name = "toolStripContainer"; this.toolStripContainer.Size = new System.Drawing.Size(1003, 661); this.toolStripContainer.TabIndex = 5; // // toolStripContainer.TopToolStripPanel // this.toolStripContainer.TopToolStripPanel.Controls.Add(this.projectToolStrip); this.toolStripContainer.TopToolStripPanel.Controls.Add(this.filesToolStrip); this.toolStripContainer.TopToolStripPanel.Controls.Add(this.testsToolStrip); // // dockPanel // this.dockPanel.ActiveAutoHideContent = null; this.dockPanel.AllowDrop = true; this.dockPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.dockPanel.DockBackColor = System.Drawing.SystemColors.Control; this.dockPanel.DockLeftPortion = 0.33D; this.dockPanel.DockRightPortion = 0.33D; this.dockPanel.DockTopPortion = 0.15D; this.dockPanel.DocumentStyle = WeifenLuo.WinFormsUI.Docking.DocumentStyle.DockingWindow; this.dockPanel.Location = new System.Drawing.Point(0, 0); this.dockPanel.Name = "dockPanel"; this.dockPanel.Size = new System.Drawing.Size(1003, 611); dockPanelGradient1.EndColor = System.Drawing.SystemColors.ControlLight; dockPanelGradient1.StartColor = System.Drawing.SystemColors.ControlLight; autoHideStripSkin1.DockStripGradient = dockPanelGradient1; tabGradient1.EndColor = System.Drawing.SystemColors.Control; tabGradient1.StartColor = System.Drawing.SystemColors.Control; tabGradient1.TextColor = System.Drawing.SystemColors.ControlDarkDark; autoHideStripSkin1.TabGradient = tabGradient1; autoHideStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F); dockPanelSkin1.AutoHideStripSkin = autoHideStripSkin1; tabGradient2.EndColor = System.Drawing.SystemColors.ControlLightLight; tabGradient2.StartColor = System.Drawing.SystemColors.ControlLightLight; tabGradient2.TextColor = System.Drawing.SystemColors.ControlText; dockPaneStripGradient1.ActiveTabGradient = tabGradient2; dockPanelGradient2.EndColor = System.Drawing.SystemColors.Control; dockPanelGradient2.StartColor = System.Drawing.SystemColors.Control; dockPaneStripGradient1.DockStripGradient = dockPanelGradient2; tabGradient3.EndColor = System.Drawing.SystemColors.ControlLight; tabGradient3.StartColor = System.Drawing.SystemColors.ControlLight; tabGradient3.TextColor = System.Drawing.SystemColors.ControlText; dockPaneStripGradient1.InactiveTabGradient = tabGradient3; dockPaneStripSkin1.DocumentGradient = dockPaneStripGradient1; dockPaneStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F); tabGradient4.EndColor = System.Drawing.SystemColors.ActiveCaption; tabGradient4.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; tabGradient4.StartColor = System.Drawing.SystemColors.GradientActiveCaption; tabGradient4.TextColor = System.Drawing.SystemColors.ActiveCaptionText; dockPaneStripToolWindowGradient1.ActiveCaptionGradient = tabGradient4; tabGradient5.EndColor = System.Drawing.SystemColors.Control; tabGradient5.StartColor = System.Drawing.SystemColors.Control; tabGradient5.TextColor = System.Drawing.SystemColors.ControlText; dockPaneStripToolWindowGradient1.ActiveTabGradient = tabGradient5; dockPanelGradient3.EndColor = System.Drawing.SystemColors.ControlLight; dockPanelGradient3.StartColor = System.Drawing.SystemColors.ControlLight; dockPaneStripToolWindowGradient1.DockStripGradient = dockPanelGradient3; tabGradient6.EndColor = System.Drawing.SystemColors.InactiveCaption; tabGradient6.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; tabGradient6.StartColor = System.Drawing.SystemColors.GradientInactiveCaption; tabGradient6.TextColor = System.Drawing.SystemColors.InactiveCaptionText; dockPaneStripToolWindowGradient1.InactiveCaptionGradient = tabGradient6; tabGradient7.EndColor = System.Drawing.Color.Transparent; tabGradient7.StartColor = System.Drawing.Color.Transparent; tabGradient7.TextColor = System.Drawing.SystemColors.ControlDarkDark; dockPaneStripToolWindowGradient1.InactiveTabGradient = tabGradient7; dockPaneStripSkin1.ToolWindowGradient = dockPaneStripToolWindowGradient1; dockPanelSkin1.DockPaneStripSkin = dockPaneStripSkin1; this.dockPanel.Skin = dockPanelSkin1; this.dockPanel.TabIndex = 8; // // testsToolStrip // this.testsToolStrip.Dock = System.Windows.Forms.DockStyle.None; this.testsToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.startButton, this.startTestsWithDebuggerButton, this.stopButton}); this.testsToolStrip.Location = new System.Drawing.Point(3, 0); this.testsToolStrip.Name = "testsToolStrip"; this.testsToolStrip.Size = new System.Drawing.Size(176, 25); this.testsToolStrip.TabIndex = 12; this.testsToolStrip.Text = "Tests"; // // startButton // this.startButton.Enabled = false; this.startButton.Image = ((System.Drawing.Image)(resources.GetObject("startButton.Image"))); this.startButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.startButton.Name = "startButton"; this.startButton.Size = new System.Drawing.Size(51, 22); this.startButton.Text = "Start"; this.startButton.ToolTipText = "Start Tests"; this.startButton.Click += new System.EventHandler(this.startButton_Click); // // startTestsWithDebuggerButton // this.startTestsWithDebuggerButton.Enabled = false; this.startTestsWithDebuggerButton.Image = ((System.Drawing.Image)(resources.GetObject("startTestsWithDebuggerButton.Image"))); this.startTestsWithDebuggerButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.startTestsWithDebuggerButton.Name = "startTestsWithDebuggerButton"; this.startTestsWithDebuggerButton.Size = new System.Drawing.Size(62, 22); this.startTestsWithDebuggerButton.Text = "Debug"; this.startTestsWithDebuggerButton.ToolTipText = "Start Tests With Debugger"; this.startTestsWithDebuggerButton.Click += new System.EventHandler(this.startWithDebuggerToolStripMenuItem_Click); // // stopButton // this.stopButton.Enabled = false; this.stopButton.Image = ((System.Drawing.Image)(resources.GetObject("stopButton.Image"))); this.stopButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.stopButton.Name = "stopButton"; this.stopButton.Size = new System.Drawing.Size(51, 22); this.stopButton.Text = "Stop"; this.stopButton.ToolTipText = "Stop Tests"; this.stopButton.Click += new System.EventHandler(this.stopButton_Click); // // filesToolStrip // this.filesToolStrip.Dock = System.Windows.Forms.DockStyle.None; this.filesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.addFilesToolStripButton, this.removeAllFilesToolStripButton, this.toolStripSeparator1, this.reloadToolbarButton}); this.filesToolStrip.Location = new System.Drawing.Point(3, 25); this.filesToolStrip.Name = "filesToolStrip"; this.filesToolStrip.Size = new System.Drawing.Size(269, 25); this.filesToolStrip.TabIndex = 11; this.filesToolStrip.Text = "Files"; // // addFilesToolStripButton // this.addFilesToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("addFilesToolStripButton.Image"))); this.addFilesToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.addFilesToolStripButton.Name = "addFilesToolStripButton"; this.addFilesToolStripButton.Size = new System.Drawing.Size(75, 22); this.addFilesToolStripButton.Text = "Add Files"; this.addFilesToolStripButton.Click += new System.EventHandler(this.addFilesToolStripButton_Click); // // removeAllFilesToolStripButton // this.removeAllFilesToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("removeAllFilesToolStripButton.Image"))); this.removeAllFilesToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.removeAllFilesToolStripButton.Name = "removeAllFilesToolStripButton"; this.removeAllFilesToolStripButton.Size = new System.Drawing.Size(113, 22); this.removeAllFilesToolStripButton.Text = "Remove All Files"; this.removeAllFilesToolStripButton.Click += new System.EventHandler(this.removeAllFiles_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // reloadToolbarButton // this.reloadToolbarButton.Image = ((System.Drawing.Image)(resources.GetObject("reloadToolbarButton.Image"))); this.reloadToolbarButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.reloadToolbarButton.Name = "reloadToolbarButton"; this.reloadToolbarButton.Size = new System.Drawing.Size(63, 22); this.reloadToolbarButton.Text = "Reload"; this.reloadToolbarButton.Click += new System.EventHandler(this.reloadToolbarButton_Click); // // Main // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1003, 707); this.Controls.Add(this.toolStripContainer); this.Controls.Add(this.statusStrip); this.Controls.Add(this.menuStrip); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.IsMdiContainer = true; this.MainMenuStrip = this.menuStrip; this.Name = "Main"; this.Text = "Gallio Icarus {0}.{1}.{2} build {3}"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing); this.Load += new System.EventHandler(this.Form_Load); this.SizeChanged += new System.EventHandler(this.Main_SizeChanged); this.menuStrip.ResumeLayout(false); this.menuStrip.PerformLayout(); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.projectToolStrip.ResumeLayout(false); this.projectToolStrip.PerformLayout(); this.toolStripContainer.ContentPanel.ResumeLayout(false); this.toolStripContainer.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer.TopToolStripPanel.PerformLayout(); this.toolStripContainer.ResumeLayout(false); this.toolStripContainer.PerformLayout(); this.testsToolStrip.ResumeLayout(false); this.testsToolStrip.PerformLayout(); this.filesToolStrip.ResumeLayout(false); this.filesToolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fileExit; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutMenuItem; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel; private System.Windows.Forms.ToolStrip projectToolStrip; private System.Windows.Forms.ToolStripButton newProjectToolStripButton; private System.Windows.Forms.ToolStripButton openProjectToolStripButton; private System.Windows.Forms.ToolStripMenuItem projectToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem newProjectToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openProjectMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem saveProjectToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveProjectAsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem addFilesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem removeAllFilesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem reloadToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem showOnlineHelpToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripContainer toolStripContainer; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsMenuItem; private ToolStripProgressBar toolStripProgressBar; private System.Windows.Forms.ToolStripMenuItem testsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem startTestsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem stopTestsToolStripMenuItem; private WeifenLuo.WinFormsUI.Docking.DockPanel dockPanel; private System.Windows.Forms.ToolStripMenuItem viewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem resetToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator8; private System.Windows.Forms.ToolStripMenuItem reportToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem viewAsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem startWithDebuggerToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem recentProjectsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator12; private System.Windows.Forms.ToolStripButton saveProjectToolStripButton; private System.Windows.Forms.ToolStrip filesToolStrip; private System.Windows.Forms.ToolStripButton addFilesToolStripButton; private System.Windows.Forms.ToolStripButton removeAllFilesToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton reloadToolbarButton; private System.Windows.Forms.ToolStrip testsToolStrip; private System.Windows.Forms.ToolStripButton startButton; private System.Windows.Forms.ToolStripButton startTestsWithDebuggerButton; private System.Windows.Forms.ToolStripButton stopButton; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace AtTheMovies.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// // System.Runtime.Remoting.RemotingServices NUnit V2.0 test class // // Author Jean-Marc ANDRE (jean-marc.andre@polymtl.ca) // // ToDo: I didn't write test functions for the method not yep // implemented by Mono using System; using System.Collections; using NUnit.Framework; using System.Reflection; using System.Runtime.Remoting; using System.Threading; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; namespace MonoTests.System.Runtime.Remoting.RemotingServicesInternal { // We need our own proxy to intercept messages to remote object // and forward them using RemotingServices.ExecuteMessage public class MyProxy: RealProxy { MarshalByRefObject target; IMessageSink _sink; MethodBase _mthBase; bool methodOverloaded = false; public MethodBase MthBase { get{ return _mthBase;} } public bool IsMethodOverloaded { get{return methodOverloaded;} } public MyProxy(Type serverType, MarshalByRefObject target): base(serverType) { this.target = target; IChannel[] registeredChannels = ChannelServices.RegisteredChannels; string ObjectURI; // A new IMessageSink chain has to be created // since the RemotingServices.GetEnvoyChainForProxy() is not yet // implemented. foreach(IChannel channel in registeredChannels) { IChannelSender channelSender = channel as IChannelSender; if(channelSender != null) { _sink = (IMessageSink) channelSender.CreateMessageSink(RemotingServices.GetObjectUri(target), null, out ObjectURI); } } } // Messages will be intercepted here and redirected // to another object. public override IMessage Invoke(IMessage msg) { try { if(msg is IConstructionCallMessage) { IActivator remActivator = (IActivator) RemotingServices.Connect(typeof(IActivator), "tcp://localhost:1234/RemoteActivationService.rem"); IConstructionReturnMessage crm = remActivator.Activate((IConstructionCallMessage)msg); return crm; } else { methodOverloaded = RemotingServices.IsMethodOverloaded((IMethodMessage)msg); _mthBase = RemotingServices.GetMethodBaseFromMethodMessage((IMethodMessage)msg); MethodCallMessageWrapper mcm = new MethodCallMessageWrapper((IMethodCallMessage) msg); mcm.Uri = RemotingServices.GetObjectUri((MarshalByRefObject)target); MarshalByRefObject objRem = (MarshalByRefObject)Activator.CreateInstance(GetProxiedType()); RemotingServices.ExecuteMessage((MarshalByRefObject)objRem, (IMethodCallMessage)msg); IMessage rtnMsg = null; try { rtnMsg = _sink.SyncProcessMessage(msg); } catch(Exception e) { Console.WriteLine(e.Message); } Console.WriteLine ("RR:" + rtnMsg); return rtnMsg; } } catch (Exception ex) { Console.WriteLine (ex); return null; } } } // end MyProxy // This class is used to create "CAO" public class MarshalObjectFactory: MarshalByRefObject { public MarshalObject GetNewMarshalObject() { return new MarshalObject(); } } // A class used by the tests public class MarshalObject: ContextBoundObject { public MarshalObject() { } public MarshalObject(int id, string uri) { this.id = id; this.uri = uri; } public int Id { get{return id;} set{id = value;} } public string Uri { get{return uri;} } public void Method1() { _called++; methodOneWay = RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()); } public void Method2() { methodOneWay = RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()); } public void Method2(int i) { methodOneWay = RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()); } [OneWay()] public void Method3() { methodOneWay = RemotingServices.IsOneWay(MethodBase.GetCurrentMethod()); } public static int Called { get{return _called;} } public static bool IsMethodOneWay { get{return methodOneWay;} } private static int _called; private int id = 0; private string uri; private static bool methodOneWay = false; } // Another class used by the tests public class DerivedMarshalObject: MarshalObject { public DerivedMarshalObject(){} public DerivedMarshalObject(int id, string uri): base(id, uri) {} } interface A { } interface B: A { } public class CC: MarshalByRefObject { } public class DD: MarshalByRefObject { } } // namespace MonoTests.System.Runtime.Remoting.RemotingServicesInternal namespace MonoTests.Remoting { using MonoTests.System.Runtime.Remoting.RemotingServicesInternal; // The main test class [TestFixture] public class RemotingServicesTest : Assertion { private static int MarshalObjectId = 0; public RemotingServicesTest() { MarshalObjectId = 0; } // Helper function that create a new // MarshalObject with an unique ID private static MarshalObject NewMarshalObject() { string uri = "MonoTests.System.Runtime.Remoting.RemotingServicesTest.MarshalObject" + MarshalObjectId.ToString(); MarshalObject objMarshal = new MarshalObject(MarshalObjectId, uri); MarshalObjectId++; return objMarshal; } // Another helper function private DerivedMarshalObject NewDerivedMarshalObject() { string uri = "MonoTests.System.Runtime.Remoting.RemotingServicesTest.DerivedMarshalObject" + MarshalObjectId.ToString(); DerivedMarshalObject objMarshal = new DerivedMarshalObject(MarshalObjectId, uri); MarshalObjectId++; return objMarshal; } // The two folling method test RemotingServices.Marshal() [Test] public void Marshal1() { MarshalObject objMarshal = NewMarshalObject(); ObjRef objRef = RemotingServices.Marshal(objMarshal); Assert("#A01", objRef.URI != null); MarshalObject objRem = (MarshalObject) RemotingServices.Unmarshal(objRef); AssertEquals("#A02", objMarshal.Id, objRem.Id); objRem.Id = 2; AssertEquals("#A03", objMarshal.Id, objRem.Id); // TODO: uncomment when RemotingServices.Disconnect is implemented //RemotingServices.Disconnect(objMarshal); objMarshal = NewMarshalObject(); objRef = RemotingServices.Marshal(objMarshal, objMarshal.Uri); Assert("#A04", objRef.URI.EndsWith(objMarshal.Uri)); // TODO: uncomment when RemotingServices.Disconnect is implemented //RemotingServices.Disconnect(objMarshal); } [Test] public void Marshal2() { DerivedMarshalObject derivedObjMarshal = NewDerivedMarshalObject(); ObjRef objRef = RemotingServices.Marshal(derivedObjMarshal, derivedObjMarshal.Uri, typeof(MarshalObject)); // Check that the type of the marshaled object is MarshalObject Assert("#A05", objRef.TypeInfo.TypeName.StartsWith((typeof(MarshalObject)).ToString())); // TODO: uncomment when RemotingServices.Disconnect is implemented //RemotingServices.Disconnect(derivedObjMarshal); } // Tests RemotingServices.GetObjectUri() [Test] public void GetObjectUri() { MarshalObject objMarshal = NewMarshalObject(); Assert("#A06", RemotingServices.GetObjectUri(objMarshal) == null); RemotingServices.Marshal(objMarshal); Assert("#A07", RemotingServices.GetObjectUri(objMarshal) != null); // TODO: uncomment when RemotingServices.Disconnect is implemented //RemotingServices.Disconnect(objMarshal); } // Tests RemotingServices.Connect [Test] public void Connect() { MarshalObject objMarshal = NewMarshalObject(); IDictionary props = new Hashtable(); props["name"] = objMarshal.Uri; props["port"] = 1236; TcpChannel chn = new TcpChannel(props, null, null); ChannelServices.RegisterChannel(chn); RemotingServices.Marshal(objMarshal,objMarshal.Uri); MarshalObject objRem = (MarshalObject) RemotingServices.Connect(typeof(MarshalObject), "tcp://localhost:1236/" + objMarshal.Uri); Assert("#A08", RemotingServices.IsTransparentProxy(objRem)); ChannelServices.UnregisterChannel(chn); RemotingServices.Disconnect(objMarshal); } // Tests RemotingServices.Marshal() [Test] [ExpectedException(typeof(RemotingException))] public void MarshalThrowException() { MarshalObject objMarshal = NewMarshalObject(); IDictionary props = new Hashtable(); props["name"] = objMarshal.Uri; props["port"] = 1237; TcpChannel chn = new TcpChannel(props, null, null); ChannelServices.RegisterChannel(chn); RemotingServices.Marshal(objMarshal,objMarshal.Uri); MarshalObject objRem = (MarshalObject) RemotingServices.Connect(typeof(MarshalObject), "tcp://localhost:1237/" + objMarshal.Uri); // This line sould throw a RemotingException // It is forbidden to export an object which is not // a real object try { RemotingServices.Marshal(objRem, objMarshal.Uri); } catch(Exception e) { ChannelServices.UnregisterChannel(chn); // TODO: uncomment when RemotingServices.Disconnect is implemented //RemotingServices.Disconnect(objMarshal); throw e; } } // Tests RemotingServices.ExecuteMessage() // also tests GetMethodBaseFromMessage() // IsMethodOverloaded() [Test] public void ExecuteMessage() { TcpChannel chn = null; try { chn = new TcpChannel(1235); ChannelServices.RegisterChannel(chn); MarshalObject objMarshal = NewMarshalObject(); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MarshalObject), objMarshal.Uri, WellKnownObjectMode.SingleCall); // use a proxy to catch the Message MyProxy proxy = new MyProxy(typeof(MarshalObject), (MarshalObject) Activator.GetObject(typeof(MarshalObject), "tcp://localhost:1235/" + objMarshal.Uri)); MarshalObject objRem = (MarshalObject) proxy.GetTransparentProxy(); objRem.Method1(); // Tests RemotingServices.GetMethodBaseFromMethodMessage() AssertEquals("#A09","Method1",proxy.MthBase.Name); Assert("#A09.1", !proxy.IsMethodOverloaded); objRem.Method2(); Assert("#A09.2", proxy.IsMethodOverloaded); // Tests RemotingServices.ExecuteMessage(); // If ExecuteMessage does it job well, Method1 should be called 2 times AssertEquals("#A10", 2, MarshalObject.Called); } finally { if(chn != null) ChannelServices.UnregisterChannel(chn); } } // Tests the IsOneWay method [Test] public void IsOneWay() { TcpChannel chn = null; try { chn = new TcpChannel(1238); ChannelServices.RegisterChannel(chn); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MarshalObject), "MarshalObject.rem", WellKnownObjectMode.Singleton); MarshalObject objRem = (MarshalObject) Activator.GetObject(typeof(MarshalObject), "tcp://localhost:1238/MarshalObject.rem"); Assert("#A10.1", RemotingServices.IsTransparentProxy(objRem)); objRem.Method1(); Thread.Sleep(20); Assert("#A10.2", !MarshalObject.IsMethodOneWay); objRem.Method3(); Thread.Sleep(20); Assert("#A10.3", MarshalObject.IsMethodOneWay); } finally { if(chn != null) ChannelServices.UnregisterChannel(chn); } } [Test] public void GetObjRefForProxy() { TcpChannel chn = null; try { chn = new TcpChannel(1239); ChannelServices.RegisterChannel(chn); // Register le factory as a SAO RemotingConfiguration.RegisterWellKnownServiceType(typeof(MarshalObjectFactory), "MonoTests.System.Runtime.Remoting.RemotingServicesTest.Factory.soap", WellKnownObjectMode.Singleton); MarshalObjectFactory objFactory = (MarshalObjectFactory) Activator.GetObject(typeof(MarshalObjectFactory), "tcp://localhost:1239/MonoTests.System.Runtime.Remoting.RemotingServicesTest.Factory.soap"); // Get a new "CAO" MarshalObject objRem = objFactory.GetNewMarshalObject(); ObjRef objRefRem = RemotingServices.GetObjRefForProxy((MarshalByRefObject)objRem); Assert("#A11", objRefRem != null); } finally { if(chn != null) ChannelServices.UnregisterChannel(chn); } } // Tests GetRealProxy [Test] public void GetRealProxy() { TcpChannel chn = null; try { chn = new TcpChannel(1241); ChannelServices.RegisterChannel(chn); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MarshalObject), "MonoTests.System.Runtime.Remoting.RemotingServicesTest.MarshalObject.soap", WellKnownObjectMode.Singleton); MyProxy proxy = new MyProxy(typeof(MarshalObject), (MarshalByRefObject)Activator.GetObject(typeof(MarshalObject), "tcp://localhost:1241/MonoTests.System.Runtime.Remoting.RemotingServicesTest.MarshalObject.soap")); MarshalObject objRem = (MarshalObject) proxy.GetTransparentProxy(); RealProxy rp = RemotingServices.GetRealProxy(objRem); Assert("#A12", rp != null); AssertEquals("#A13", "MonoTests.System.Runtime.Remoting.RemotingServicesInternal.MyProxy", rp.GetType().ToString()); } finally { if(chn != null) ChannelServices.UnregisterChannel(chn); } } // Tests SetObjectUriForMarshal() [Test] public void SetObjectUriForMarshal() { TcpChannel chn = null; try { chn = new TcpChannel(1242); ChannelServices.RegisterChannel(chn); MarshalObject objRem = NewMarshalObject(); RemotingServices.SetObjectUriForMarshal(objRem, objRem.Uri); RemotingServices.Marshal(objRem); objRem = (MarshalObject) Activator.GetObject(typeof(MarshalObject), "tcp://localhost:1242/"+objRem.Uri); Assert("#A14", objRem != null); } finally { if(chn != null) ChannelServices.UnregisterChannel(chn); } } // Tests GetServeurTypeForUri() [Test] public void GetServeurTypeForUri() { TcpChannel chn = null; Type type = typeof(MarshalObject); try { chn = new TcpChannel(1243); ChannelServices.RegisterChannel(chn); MarshalObject objRem = NewMarshalObject(); RemotingServices.SetObjectUriForMarshal(objRem, objRem.Uri); RemotingServices.Marshal(objRem); Type typeRem = RemotingServices.GetServerTypeForUri(RemotingServices.GetObjectUri(objRem)); AssertEquals("#A15", type, typeRem); } finally { if(chn != null) ChannelServices.UnregisterChannel(chn); } } // Tests IsObjectOutOfDomain // Tests IsObjectOutOfContext [Test] public void IsObjectOutOf() { TcpChannel chn = null; try { chn = new TcpChannel(1245); ChannelServices.RegisterChannel(chn); RemotingConfiguration.RegisterWellKnownServiceType(typeof(MarshalObject), "MarshalObject2.rem", WellKnownObjectMode.Singleton); MarshalObject objRem = (MarshalObject) Activator.GetObject(typeof(MarshalObject), "tcp://localhost:1245/MarshalObject2.rem"); Assert("#A16", RemotingServices.IsObjectOutOfAppDomain(objRem)); Assert("#A17", RemotingServices.IsObjectOutOfContext(objRem)); MarshalObject objMarshal = new MarshalObject(); Assert("#A18", !RemotingServices.IsObjectOutOfAppDomain(objMarshal)); Assert("#A19", !RemotingServices.IsObjectOutOfContext(objMarshal)); } finally { ChannelServices.UnregisterChannel(chn); } } [Test] public void ConnectProxyCast () { object o; RemotingConfiguration.Configure (null); o = RemotingServices.Connect (typeof(MarshalByRefObject), "tcp://localhost:3434/ff1.rem"); Assert ("#m1", o is DD); Assert ("#m2", o is A); Assert ("#m3", o is B); Assert ("#m4", !(o is CC)); o = RemotingServices.Connect (typeof(A), "tcp://localhost:3434/ff3.rem"); Assert ("#a1", o is DD); Assert ("#a2", o is A); Assert ("#a3", o is B); Assert ("#a4", !(o is CC)); o = RemotingServices.Connect (typeof(DD), "tcp://localhost:3434/ff4.rem"); Assert ("#d1", o is DD); Assert ("#d2", o is A); Assert ("#d3", o is B); Assert ("#d4", !(o is CC)); o = RemotingServices.Connect (typeof(CC), "tcp://localhost:3434/ff5.rem"); Assert ("#c1", !(o is DD)); Assert ("#c2", o is A); Assert ("#c3", o is B); Assert ("#c4", o is CC); } } // end class RemotingServicesTest } // end of namespace MonoTests.Remoting
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfileTrafficAccelerationBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileULong))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))] public partial class LocalLBProfileTrafficAcceleration : iControlInterface { public LocalLBProfileTrafficAcceleration() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void create( string [] profile_names ) { this.Invoke("create", new object [] { profile_names}); } public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { profile_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_profiles //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void delete_all_profiles( ) { this.Invoke("delete_all_profiles", new object [0]); } public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState); } public void Enddelete_all_profiles(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void delete_profile( string [] profile_names ) { this.Invoke("delete_profile", new object [] { profile_names}); } public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_profile", new object[] { profile_names}, callback, asyncState); } public void Enddelete_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_all_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics get_all_statistics( ) { object [] results = this.Invoke("get_all_statistics", new object [0]); return ((LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics)(results[0])); } public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState); } public LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics Endget_all_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics)(results[0])); } //----------------------------------------------------------------------- // get_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_default_profile( string [] profile_names ) { object [] results = this.Invoke("get_default_profile", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_default_profile", new object[] { profile_names}, callback, asyncState); } public string [] Endget_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_description( string [] profile_names ) { object [] results = this.Invoke("get_description", new object [] { profile_names}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_description", new object[] { profile_names}, callback, asyncState); } public string [] Endget_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_idle_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_idle_timeout( string [] profile_names ) { object [] results = this.Invoke("get_idle_timeout", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_idle_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_idle_timeout", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_idle_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics get_statistics( string [] profile_names ) { object [] results = this.Invoke("get_statistics", new object [] { profile_names}); return ((LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics)(results[0])); } public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics Endget_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics)(results[0])); } //----------------------------------------------------------------------- // get_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { object [] results = this.Invoke("get_statistics_by_virtual", new object [] { profile_names, virtual_names}); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileStatisticsByVirtual)(results[0])); } //----------------------------------------------------------------------- // get_tcp_handshake_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_tcp_handshake_timeout( string [] profile_names ) { object [] results = this.Invoke("get_tcp_handshake_timeout", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_tcp_handshake_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_tcp_handshake_timeout", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_tcp_handshake_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_time_wait_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public LocalLBProfileULong [] get_time_wait_timeout( string [] profile_names ) { object [] results = this.Invoke("get_time_wait_timeout", new object [] { profile_names}); return ((LocalLBProfileULong [])(results[0])); } public System.IAsyncResult Beginget_time_wait_timeout(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_time_wait_timeout", new object[] { profile_names}, callback, asyncState); } public LocalLBProfileULong [] Endget_time_wait_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((LocalLBProfileULong [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // is_base_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_base_profile( string [] profile_names ) { object [] results = this.Invoke("is_base_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_base_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_base_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // is_system_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public bool [] is_system_profile( string [] profile_names ) { object [] results = this.Invoke("is_system_profile", new object [] { profile_names}); return ((bool [])(results[0])); } public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("is_system_profile", new object[] { profile_names}, callback, asyncState); } public bool [] Endis_system_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((bool [])(results[0])); } //----------------------------------------------------------------------- // reset_statistics //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void reset_statistics( string [] profile_names ) { this.Invoke("reset_statistics", new object [] { profile_names}); } public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics", new object[] { profile_names}, callback, asyncState); } public void Endreset_statistics(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // reset_statistics_by_virtual //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void reset_statistics_by_virtual( string [] profile_names, string [] [] virtual_names ) { this.Invoke("reset_statistics_by_virtual", new object [] { profile_names, virtual_names}); } public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("reset_statistics_by_virtual", new object[] { profile_names, virtual_names}, callback, asyncState); } public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_default_profile //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void set_default_profile( string [] profile_names, string [] defaults ) { this.Invoke("set_default_profile", new object [] { profile_names, defaults}); } public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_default_profile", new object[] { profile_names, defaults}, callback, asyncState); } public void Endset_default_profile(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void set_description( string [] profile_names, string [] descriptions ) { this.Invoke("set_description", new object [] { profile_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { profile_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_idle_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void set_idle_timeout( string [] profile_names, LocalLBProfileULong [] values ) { this.Invoke("set_idle_timeout", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_idle_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_idle_timeout", new object[] { profile_names, values}, callback, asyncState); } public void Endset_idle_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_tcp_handshake_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void set_tcp_handshake_timeout( string [] profile_names, LocalLBProfileULong [] values ) { this.Invoke("set_tcp_handshake_timeout", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_tcp_handshake_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_tcp_handshake_timeout", new object[] { profile_names, values}, callback, asyncState); } public void Endset_tcp_handshake_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_time_wait_timeout //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfileTrafficAcceleration", RequestNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration", ResponseNamespace="urn:iControl:LocalLB/ProfileTrafficAcceleration")] public void set_time_wait_timeout( string [] profile_names, LocalLBProfileULong [] values ) { this.Invoke("set_time_wait_timeout", new object [] { profile_names, values}); } public System.IAsyncResult Beginset_time_wait_timeout(string [] profile_names,LocalLBProfileULong [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_time_wait_timeout", new object[] { profile_names, values}, callback, asyncState); } public void Endset_time_wait_timeout(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileTrafficAcceleration.TrafficAccelerationProfileStatisticEntry", Namespace = "urn:iControl")] public partial class LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatisticEntry { private string profile_nameField; public string profile_name { get { return this.profile_nameField; } set { this.profile_nameField = value; } } private CommonStatistic [] statisticsField; public CommonStatistic [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfileTrafficAcceleration.TrafficAccelerationProfileStatistics", Namespace = "urn:iControl")] public partial class LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatistics { private LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatisticEntry [] statisticsField; public LocalLBProfileTrafficAccelerationTrafficAccelerationProfileStatisticEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; }